<jupyter_start><jupyter_text>1. Exception Handlinga) Create a text file and manually add some data to the fileb) WritePythoncodeto• open the file for write only access• attempt to read the contents of the filec) Note the type of Error that has been raised.d) Modifyyourcodeto• use a try / except / finally construct that will catch the exception, print a user-friendly error message, and clean up the file resourcee) Investigate how you would create your own Exception class. Then create your own Exception class and use it in your code from the previous exercise.<jupyter_code># 1.a
f = open("demo.txt", "w")
f.write("<NAME>, 34, <EMAIL>, manager \n")
f.write("<NAME>, 45, <EMAIL>, sales \n")
f.close()<jupyter_output><empty_output><jupyter_text>open the file read<jupyter_code>f = open("demo.txt", "r")
print(f.read())
f.close()<jupyter_output><empty_output><jupyter_text>b) Write Python code to- open the file for write only access    - attempt to read the contents of the file<jupyter_code>f = open("demo.txt", "w")
print(f.read())
f.close()<jupyter_output><empty_output><jupyter_text>c) Note the type of Error that has been raised. that is UnsupportedOperation  d) Modify your code to- use a try / except / finally construct that will catch the exception, - print a user-friendly error message, and clean up the file resource<jupyter_code>import sys
import io

try:
    f = open("demo.txt", "w")
    print(f.read())    
except io.UnsupportedOperation:
    print("A type of 'UnsupportedOperation' exception was triggered.\nThis is because you have opened your file in a write mode, while you are trying to read it !")
except:
    ("Other type of error " + sys.exc_info()[2])
finally:
    f.close()<jupyter_output><empty_output><jupyter_text>e) Investigate how you would create your own Exception class. Then create your own Exception class and use it in your code from the previous exercise.<jupyter_code>class MyCustomException(io.UnsupportedOperation):
    pass


try:
    f = open("demo.txt", "w")
    
    raise MyCustomException('You have opened your file in an incompatible mode')    
    print(f.read())    
    
except io.UnsupportedOperation:
     print("Handled by '{}': {}".format(sys.exc_info()[0], sys.exc_info()[1]))
except:
    print("Other type of error {}".format(sys.exc_info()[2]))
finally:
    f.close()<jupyter_output><empty_output><jupyter_text>2. Numpy Exercise Aa) Create an array with the arange function and reshape the array as follows: b = arange(24).reshape(2,3,4)This gives us a 3-dimensional data structure – you can think of it as being like 2 spreadsheet sheets where each sheet contains 3 rows of data and each row contains 4 columns.Using indexing and slicing perform the following tasks:i) Choose the first set of 3 rows and 4 columns of dataii) Choose the second row of data from the second set of 3 rows of dataiii) Choose all the data from the second column for both the first and secondsets of rows and columns of datab) Use the ravel function to flatten the data.What’s the difference between ravel and flatten?c) Reshape the data so that there are 6 rows of 4 columns per row.d) Getthetransposeofthenewdatastructure.e) Restack the rows of the transposed data structure in reverse order (hint: look atthe row_stack function).f) Split the resulting data structure horizontally (hint: look at the hsplit function).<jupyter_code># 2.a
import numpy as np
b = np.arange(24).reshape(2,3,4)
print(f"2.a.i => {b[0]}")
print(f"2.a.ii => {b[1,1,:]}")
print(f"2.a.iii => {b[:,1,:]}")
# 2.b
b = b.ravel()
print(f"2.b => {b}")
# 2.c
b = b.reshape(6,4)
print(f"2.c => {b}")
#2.d
b = b.T
print(f"2.d => {b}")
# 2.e
b = np.flip(b)
print(f"2.e => {b}")
# 2.f
b = np.hsplit(b,2)
print(f"2.f => {b}")<jupyter_output>2.a.i => [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
2.a.ii => [16 17 18 19]
2.a.iii => [[ 4  5  6  7]
 [16 17 18 19]]
2.b => [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
2.c => [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]]
2.d => [[ 0  4  8 12 16 20]
 [ 1  5  9 13 17 21]
 [ 2  6 10 14 18 22]
 [ 3  7 11 15 19 23]]
2.e => [[23 19 15 11  7  3]
 [22 18 14 10  6  2]
 [21 17 13  9  5  1]
 [20 16 12  8  4  0]]
2.f => [array([[23, 19, 15],
       [22, 18, 14],
       [21, 17, 13],
       [20, 16, 12]]), array([[11,  7,  3],
       [10,  6,  2],
       [ 9,  5,  1],
       [ 8,  4,  0]])]<jupyter_text>3. NumPy Exercise BNOTE:The AAPL.csv contains some stock price data for Apple. The MSFT.csv contains some stock price data for Microsoft.a) Use the loadtxt command to load data from AAPL.csv from columns 5 and 7 (i.e., the close price and the volume).b) Based on thedataprovided,calculatethevolumeweightedaveragepriceforthe stock (i.e., calculate the average price using the volume as weight values).c) Calculate the median value of the closing prices (hint: use the median function).d) Calculatethevariancevalueoftheclosingprices.e) Again, use the loadtxt command to load data from columns 3 and 4 (i.e., the highprices and the low prices).f) Use the max and min functions to get the highest high and the lowest low value.g) Load data from column 5 of AAPL.csv. Also, load data from column 5 of MSFT.csv.h) CalculatethecovariancematrixoftheclosingpricesofAAPLandMSFT(hint:usethe cov function).i) View the values on the diagonal (hint: diagonal).j) Calculate the correlation coefficient of the closing prices of AAPL and MSFT (hint:corrcoef).<jupyter_code>import numpy as np
# 3.a
aapl = np.loadtxt(fname="/Users/sobil/Documents/MSC/Sem 1/Database & Analytical Programming/Lab/Lab - 4/AAPL.csv", delimiter=",", usecols=(4,6), skiprows=1)
print(f"3.a :: aapl[5,7] => {aapl[0:5,:]}")
# 3.b
aapl_weighted_price = np.average(aapl[:,0], axis= 0, weights= aapl[:,1])
print(f"3.b :: aapl_weighted_price => {aapl_weighted_price}")

# 3.c
print(f"3.c :: median => {np.median(aapl[:,0])}")

# 3.d
print(f"3.d :: variance => {np.var(aapl[:,0])}")

# 3.e
aapl = np.loadtxt("/Users/sobil/Documents/MSC/Sem 1/Database & Analytical Programming/Lab/Lab - 4/AAPL.csv", delimiter=",", usecols=(2,3), skiprows=1)
print(f"3.e :: aapl[3,4] => {aapl[0:5,:]}")

# 3.f
print(f"3.f :: highest high => {np.max(aapl[:,0])}")
print(f"3.f :: & lowest low => {np.min(aapl[:,1])}")

# 3.g
aapl = np.loadtxt(fname="/Users/sobil/Documents/MSC/Sem 1/Database & Analytical Programming/Lab/Lab - 4/AAPL.csv", delimiter=",", usecols=(4), skiprows=1)
msft = aapl = np.loadtxt(fname="/Users/sobil/Documents/MSC/Sem 1/Database & Analytical Programming/Lab/Lab - 4/MSFT.csv", delimiter=",", usecols=(4), skiprows=1)
print(f"3.g :: aapl[5] => {aapl[0:5]}")
print(f"3.g :: & msft[5] => {aapl[0:5]}")

# 3.h
print(f"3.h :: covariance => {np.cov(aapl,msft)}")

# 3.i
print(f"3.i :: diagnol => {np.cov(aapl,msft).diagonal()}")

# 3.j
print(f"3.h :: correlation => {np.cov(aapl,msft)}")<jupyter_output>3.a :: aapl[5,7] => [[2.23770004e+02 2.96639000e+07]
 [2.26869995e+02 2.68910000e+07]
 [2.16360001e+02 4.19906000e+07]
 [2.14449997e+02 5.31244000e+07]
 [2.22110001e+02 4.03379000e+07]]
3.b :: aapl_weighted_price => 190.02952578964312
3.c :: median => 197.0
3.d :: variance => 432.8804568188714
3.e :: aapl[3,4] => [[224.800003 220.199997]
 [227.270004 222.25    ]
 [226.350006 216.050003]
 [219.5      212.320007]
 [222.880005 216.839996]]
3.f :: highest high => 229.929993
3.f :: & lowest low => 142.0
3.g :: aapl[5] => [110.849998 112.260002 106.160004 105.910004 109.57    ]
3.g :: & msft[5] => [110.849998 112.260002 106.160004 105.910004 109.57    ]
3.h :: covariance => [[184.73421932 184.73421932]
 [184.73421932 184.73421932]]
3.i :: diagnol => [184.73421932 184.73421932]<jupyter_text>4. Regular ExpresssionsWrite a Python program that will identify URLs using regular expressions.<jupyter_code>import re
regex = r"http[s]?:\/\/\w+\.com?"
testData = "https://google.comhttp://google.comhtts://google.comhttp:/google.com"
x = re.findall(regex, testData)
print(x)<jupyter_output>['https://google.com', 'http://google.com']
{'fraction_non_alphanumeric': 0.1504247876061969, 'fraction_numerical': 0.09470264867566217, 'mean_word_length': 4.095480585614259, 'pattern_counts': {'":': 0, '<': 34, '<?xml version=': 0, '>': 73, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '139411', 'license': 'MIT', 'n_tokens_mistral': 3492, 'n_tokens_neox': 2978, 'n_words': 946, 'path': 'DAP_Lab4/.ipynb_checkpoints/DAP_Lab4-checkpoint.ipynb', 'repo_name': 'sobil-dalal/Database-Analytical-Programming', 'size': '8032'}