Skip to content

Circle class assignment #97

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions students/robert/Python 200/Session 1/echo_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#!/usr/bin/env_python

import socket
import sys


def client(msg, log_buffer=sys.stderr):
server_address = ('localhost', 10000)
# TODO: Replace the following line with your code which will instantiate
# a TCP socket with IPv4 Addressing, call the socket you make 'sock'
# sock = None
sock = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
print('connecting to {0} port {1}'.format(*server_address), file=log_buffer)

# TODO: connect your socket to the server here.
sock.connect(('127.0.0.1', 10000))

# you can use this variable to accumulate the entire message received back
# from the server
received_message = ''

# this try/finally block exists purely to allow us to close the socket
# when we are finished with it
try:
print('sending "{0}"'.format(msg), file=log_buffer)
# TODO: send your message to the server here.
# strToSend = 'Hey, can you hear me?'
sock.sendall(msg.encode('utf8'))
strLen = len(msg)
# TODO: the server should be sending you back your message as a series
# of 16-byte chunks. Accumulate the chunks you get to build the
# entire reply from the server. Make sure that you have received
# the entire message and then you can break the loop.
#
# Log each chunk you receive. Use the print statement below to
# do it. This will help in debugging problems
buffer_size = 16
strReceivedLen = 0
while True:
chunk = sock.recv(buffer_size)
print('received "{0}"'.format(chunk.decode('utf8')), file=log_buffer)
received_message += chunk
strReceivedLen += len(chunk)
if strLen == strReceivedLen:
break

finally:
# TODO: after you break out of the loop receiving echoed chunks from
# the server you will want to close your client socket.
sock.close()
print('closing socket', file=log_buffer)

# TODO: when all is said and done, you should return the entire reply
# you received from the server as the return value of this function.
return received_message

if __name__ == '__main__':
if len(sys.argv) != 2:
usage = '\nusage: python echo_client.py "this is my message"\n'
# print(usage, file=sys.stderr)
sys.exit(1)

msg = sys.argv[1]
client(msg)
94 changes: 94 additions & 0 deletions students/robert/Python 200/Session 1/echo_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
#!/usr/bin/env_python

import socket
import sys


def server(log_buffer=sys.stderr):
# set an address for our server
address = ('127.0.0.1', 10000)
# TODO: Replace the following line with your code which will instantiate
# a TCP socket with IPv4 Addressing, call the socket you make 'sock'
# sock = None
sock = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
# TODO: You may find that if you repeatedly run the server script it fails,
# claiming that the port is already used. You can set an option on
# your socket that will fix this problem. We DID NOT talk about this
# in class. Find the correct option by reading the very end of the
# socket library documentation:
# http://docs.python.org/3/library/socket.html#example
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# log that we are building a server
print("making a server on {0}:{1}".format(*address), file=log_buffer)

# TODO: bind your new sock 'sock' to the address above and begin to listen
# for incoming connections
sock.bind(address)
sock.listen(1)

try:
# the outer loop controls the creation of new connection sockets. The
# server will handle each incoming connection one at a time.
while True:
print('waiting for a connection', file=log_buffer)

# TODO: make a new socket when a client connects, call it 'conn',
# at the same time you should be able to get the address of
# the client so we can report it below. Replace the
# following line with your code. It is only here to prevent
# syntax errors
# addr = ('bar', 'baz')
conn, addr = sock.accept()
try:
print('connection - {0}:{1}'.format(*addr), file=log_buffer)
# the inner loop will receive messages sent by the client in
# buffers. When a complete message has been received, the
# loop will exit
while True:
# TODO: receive 16 bytes of data from the client. Store
# the data you receive as 'data'. Replace the
# following line with your code. It's only here as
# a placeholder to prevent an error in string
# formatting
# data = b''
# print('received "{0}"'.format(data.decode('utf8')))
buffer_size = 16
data = conn.recv(buffer_size)
print('received "{0}"'.format(data.decode('utf8')))
# TODO: Send the data you received back to the client, log
# the fact using the print statement here. It will help in
# debugging problems.
conn.sendall(data)
# .encode('utf8'))
print('sent "{0}"'.format(data.decode('utf8')))
# TODO: Check here to see if the message you've received is
# complete. If it is, break out of this inner loop.
if not data:
break

finally:
# TODO: When the inner loop exits, this 'finally' clause will
# be hit. Use that opportunity to close the socket you
# created above when a client connected.
conn.close()
print(
'echo complete, client connection closed', file=log_buffer
)

except KeyboardInterrupt:
# TODO: Use the python KeyboardInterrupt exception as a signal to
# close the server socket and exit from the server function.
# Replace the call to `pass` below, which is only there to
# prevent syntax problems
# pass
sock.close()
print('quitting echo server', file=log_buffer)


if __name__ == '__main__':
server()
sys.exit(0)
23 changes: 23 additions & 0 deletions students/robert/Python 200/Session 1/socket_tools.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#!/usr/bin/env_python

import socket


def get_constants(prefix):
return {getattr(socket, n): n for n in dir(socket) if n.startswith(prefix)}


families = get_constants('AF_')
types = get_constants('SOCK_')
protocols = get_constants('IPPROTO_')


def get_address_info(host, port):
for response in socket.getaddrinfo(host, port):
fam, typ, pro, nam, add = response
print('family: {}'.format(families[fam]))
print('type: {}'.format(types[typ]))
print('protocol: {}'.format(protocols[pro]))
print('canonical name: {}'.format(nam))
print('socket address: {}'.format(add))
print()
47 changes: 47 additions & 0 deletions students/robert/Python 200/Session 1/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#!/usr/bin/env_python

from echo_client import client
import socket
import unittest


class EchoTestCase(unittest.TestCase):
"""tests for the echo server and client"""

def send_message(self, message):
"""Attempt to send a message using the client
In case of a socket error, fail and report the problem
"""
try:
reply = client(message)
except socket.error as e:
if e.errno == 61:
msg = "Error: {0}, is the server running?"
self.fail(msg.format(e.strerror))
else:
self.fail("Unexpected Error: {0}".format(str(e)))
return reply

def test_short_message_echo(self):
"""test that a message short than 16 bytes echoes cleanly"""
expected = "short message"
actual = self.send_message(expected)
self.assertEqual(
expected,
actual,
"expected {0}, got {1}".format(expected, actual)
)

def test_long_message_echo(self):
"""test that a message longer than 16 bytes echoes in 16-byte chunks"""
expected = "Four score and seven years ago our fathers did stuff"
actual = self.send_message(expected)
self.assertEqual(
expected,
actual,
"expected {0}, got {1}".format(expected, actual)
)


if __name__ == '__main__':
unittest.main()
95 changes: 95 additions & 0 deletions students/robert/Session 8/Circle_Class.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
#!/usr/bin/env python

import math

class Circle(object):

# radius = None
def __init__ (self,radius):
self.radius = float(radius)
self.diameter = float(radius*2)



# @property
# def radius(self):
# return int(self.radius)

# @radius.setter
# def radius(self,value):
# print('In radius setter')
# self.radius = int(value)

@property
def diameter(self):
return float(self.radius*2)

@diameter.setter
def diameter(self,value):
self.radius = float(value/2)

@property
def area(self):
return round((math.pi*(self.radius**2)),6)

@area.setter
def area(self,value):
# how to just return AttributeError? -- Step 4
print(AttributeError)

# from_diameter() missing 1 required positional argument 'Value' -- Step 5
@classmethod
def from_diameter(cls,value):
# cls.radius = int(value/2)
return cls(float(value/2))

def __str__(self):
return('Circle with radius: {}'.format(round(self.radius*2,6)))

def __repr__(self):
return 'Circle(diameter={})'.format(self.radius*2)

def __add__(self,other):
total = (self.diameter+other.diameter)/4
return Circle(total)


def __mul__(self,other):
mul = self.diameter/4*other
return Circle(mul)

def __rmul__(self,other):
rmul = self.diameter/4*other
return Circle(rmul)

def __eq__(self,other):
return self.diameter/4 == other.diameter/4

def __gt__(self,other):
return self.diameter/4 > other.diameter/4

def __lt__(self,other):
return self.diameter/4 < other.diameter/4























35 changes: 35 additions & 0 deletions students/robert/Session 8/Circle_Class_Test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/usr/bin/env python


from Circle_Class import Circle

import pytest

from math import pi


import unittest
#from Circle_Class import Circle

def test_init():
Circle(3)

def test_radius():
c = Circle(3)
assert c.radius == 3



# class Test():

# def setUp(self):
# pass

# def TestCase(self):
# c = Circle(4)
# self.assertEqual(c.radius,float(4))


# if __name__ == '__main__':
# unittest.main()

22 changes: 22 additions & 0 deletions students/robert/Session 8/Lambda.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python

# Using Lambda

def function_builder(n):

l = []

for i in range(n):
l.append(lambda x, e=i: x + e)

return l

# Using List Comprehensions

def function_builder(n):

l = [lambda x, e=i: x+e for i in range(n)]

return l


Loading