<file_sep>import java.util.Scanner;
import java.util.Random;

public class rps {
   
   public static String userInput;
   public static String computerInput;
   public static int computerNumber;
   
   public static void main(String[] args) {
      // <NAME>, CSC 120 Final, Rock Paper Scissors Game
      
      Scanner input = new Scanner(System.in);
      Random random = new Random();

      System.out.println("This is a game of rock paper scissors,");
      
      System.out.println("Enter 'rock', 'paper', 'scissors'");
      String userInput = input.nextLine();

      computerNumber = random.nextInt(3) + 1;

      switch (computerNumber) {
         case 1:
            computerInput = "rock";
            break;
         case 2:
            computerInput = "paper";
            break;
         default:
            computerInput = "scissors";
            break;
      }


      System.out.println("The user picked "+ userInput);
      System.out.println("The computer picked " + computerInput);

      if ((userInput.equals("scissors") && computerInput.equals("paper")) || (userInput.equals("rock") && computerInput.equals("scissors")) || (userInput.equals("paper") && computerInput.equals("rock")) ) {
         System.out.println("User wins!");
      } else if ((userInput.equals("rock") && computerInput.equals("paper")) || (userInput.equals("paper") && computerInput.equals("scissors")) || (userInput.equals("scissors") && computerInput.equals("rock")) ) {
         System.out.println("Computer wins!");
      } else {
         System.out.println("The game is a tie!");
      }
      
   } 
}<file_sep>from javax.servlet.http import HttpServlet
from string import Template 

class hello(HttpServlet):
	def doGet(self, request, response):
		response.contentType = "text/html"
		out  = response.writer
		a = ['joe','sally','sue']
		s1 = a[0]
		s2 = a[1]
		for s in a:
			out.print(s + '-')
		
		buff = "<html><head></head><body>"
		buff += "<h1>Greetings from a jylet</h1>"
		x = 10
		if x == 10: 
			buff += '<h4>x is 10</h4>'
		
		s = Template('$who likes $what')
		d = dict(who='tim',what='money')
		d['who'] = 'fred'
		d['what'] = 'euros'
		
		d = {'who': 'James', 'what': 'francs'}
		buff += "<h3>" + s.substitute(d) + "</h3>"
		buff += "</body></html>"
		out.print(  buff )
	
	
<file_sep>import pandas as pd
import numpy as np
import datasist as ds

train_df = pd.read_csv("train_data.csv")
test_df = pd.read_csv("test_data.csv")

# 1
# print(train_df)
# print(train_df.head(10))
# print(ds.structdata.describe(train_df))

# 2
# ds.structdata.check_train_test_set(train_df, 
#                                     test_df, 
#                                     index='Customer Id', 
#                                     col='Building Dimension')

# print(ds.structdata.check_train_test_set(train_df))                     


# 3
# print(ds.structdata.display_missing(train_df))

# 4
cat_feats = ds.structdata.get_cat_feats(train_df)
num_feats = ds.structdata.get_num_feats(train_df)

print(cat_feats + num_feats)
# print(num_feats)


# 5 This one does not work
# unique_count = ds.structdata.get_unique_counts(train_df)
# print(unique_count)

# 6
# all_data, ntrain, ntest = ds.structdata.join_train_and_test(train_df, test_df)
# print("New size of combined data {}".format(all_data.shape))
# print("Old size of train data: {}".format(ntrain))
# print("Old size of test data: {}".format(ntest))
# print(all_data)

# train = all_data[:ntrain]
# test = all_data[ntrain:]<file_sep># <NAME>, CSC 110, <NAME>, 10/21/19
# Assignment 5
#

def main():

    def instructions():
        print('This program reads race time in minutes and seconds for a runner.')
        print('It then computes and prints the speed in feet/second and meters/second.')


    def feetPerSecond(min, sec):
        _fps = (5280 / ((min * 60) + sec))
        return _fps
        # print('feet/sec')
        # print('')
        # print('{:.2f}'.format(fps))

    def metersPerSecond(min, sec):
        _mps = 1609.34 / ((min * 60) + sec)
        return _mps
        # print('meters/second')
        # print('')
        # print('{:.2f}'.format(mps))



    instructions();


    for i in range(1, 5):
        x = input("Press 'Y' or 'y' to continue, anything else to exit: ")

        while x == 'y' or x == 'Y':
            name = input('Enter first name: ')
            min = int(input('Enter minutes: '))
            sec = float(input('Enter seconds: '))

            fps = feetPerSecond(min, sec);
            mps = metersPerSecond(min, sec);

            print(' ')
            print('{:^10}'.format('feet/sec'), ' '.center(10), '{:^10}'.format('meters/sec'))
            print()
            print('{:^10,.2f}'.format(fps), '     ', '{:^20,.2f}'.format(mps))

            x = input("Press 'Y' or 'y' to continue, anything else to exit: ")
        else:
            break;




main();


# def no_return(x,y):
#     c = x + y
#     return c
#
# res = no_return(4,5)
# print(res)



# <NAME>, CSC 110, <NAME>, 10/21/19
# Assignment 5
#

# import sys
#
# def main():
#
#     def instructions():
#         print('This program reads race time in minutes and seconds for a runner.')
#         print('It then computes and prints the speed in feet/second and meters/second.')
#         x = input("Press 'Y' or 'y' to continue, anything else to exit: ")
#
#         # if x == 'y' or x == 'Y':
#         #     return
#         # else:
#         #     sys.exit()
#
#         while x == 'y' or x == 'Y':
#             break
#         else:
#             sys.exit()
#
#     instructions();
#
#     name = input('Enter first name:')
#     min = int(input('Enter minutes: '))
#     sec = float(input('Enter seconds: '))
#
#     def feetPerSecond():
#         fps = 5280 / ((min * 60) + sec)
#         print('feet/sec')
#         print('')
#         print('{:.2f}'.format(fps))
#
#     def metersPerSecond():
#         mps = 1609.34 / ((min * 60) + sec)
#         print('meters/second')
#         print('')
#         print('{:.2f}'.format(mps))
#
#     # print('feet/sec     meters/sec')
#     # print()
#     # print('{:.2f}'.format(fps), '     ', '{:.2f}'.format(mps))
#
#
#
#
#     feetPerSecond();
#     metersPerSecond();
#
#
#
# main();
#
#
# #
# # x = 'y' or x == 'Y'
# # while x == 'y' or x == 'Y':
# #     print('toads')
# #     x = input()
<file_sep># <NAME> , CSC 110, 9/27/19
# EXTRA CREDIT
#

#---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
### Version 1
### Automated Version, Cleaner syntax
### Only works when the column headers are iterating by 1 (ie: 2000, 2001, 2002, 2003...)

import pandas as pd

x = 'Year'
y = 2000

# df = pd.read_csv('/Users/Ryan/Desktop/pre.csv')
df = pd.read_csv('pre.csv')

while y <= 2018:
    df.rename(columns={str(y): x + ' ' + str(y)}, inplace=True)

    #print(str(y))
    y += 1

    #header = ['Team', x + ' ' + str(y), x + ' ' + str(y), x + ' ' + str(y)]

#df.rename(columns={'2000': x + ' 2000', '2001': x + ' 2001', '2002': x + ' 2002', '2003': x + ' 2003', '2004': x + ' 2004', '2005': x + ' 2005'}, inplace=True)

header = ['Team', 'Year 2000', 'Year 2001', 'Year 2002', 'Year 2003', 'Year 2004', 'Year 2005', 'Year 2006', 'Year 2007', 'Year 2008', 'Year 2009', 'Year 2010',
'Year 2011', 'Year 2012', 'Year 2013', 'Year 2014', 'Year 2015', 'Year 2016', 'Year 2017', 'Year 2018']

#list(df)

#df.to_csv('/Users/Ryan/Desktop/test.csv', header=[col1, col2])
# df.to_csv('/Users/Ryan/Desktop/post.csv', columns=(header))
df.to_csv('post.csv', columns=(header))

#---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
### Version 2
### Messy Version, Specifically referencing each column header in pre.csv
### 100% functionality for only pre.csv

import pandas as pd

x = 'Year'
# df = pd.read_csv('/Users/Ryan/Desktop/pre.csv')
df = pd.read_csv('pre.csv')

df.rename(columns={'2000': x + ' 2000', '2001': x + ' 2001', '2002': x + ' 2002', '2003': x + ' 2003', '2004': x + ' 2004', '2005': x + ' 2005', '2005': x + ' 2005',
'2006': x + ' 2006', '2007': x + ' 2007', '2008': x + ' 2008', '2009': x + ' 2009', '2010': x + ' 2010', '2011': x + ' 2011', '2012': x + ' 2012', '2013': x + ' 2013',
'2014': x + ' 2014', '2015': x + ' 2015', '2016': x + ' 2016', '2017': x + ' 2017', '2018': x + ' 2018'}, inplace=True)

header = ['Team', 'Year 2000', 'Year 2001', 'Year 2002', 'Year 2003', 'Year 2004', 'Year 2005', 'Year 2006', 'Year 2007', 'Year 2008', 'Year 2009', 'Year 2010',
'Year 2011', 'Year 2012', 'Year 2013', 'Year 2014', 'Year 2015', 'Year 2016', 'Year 2017', 'Year 2018']

#list(df)

#df.to_csv('/Users/Ryan/Desktop/test.csv', header=[col1, col2])
# df.to_csv('/Users/Ryan/Desktop/post.csv', columns=(header))
df.to_csv('post.csv', columns=(header))

#---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
# Do not run this code w/ the assignment. Automatically erases post.csv after run
# Truncates document immediately

# post = '/Users/Ryan/Desktop/post.csv'
# f = open(post, 'w+')
# f.close()
<file_sep># <NAME>, CSC 110, Prof Ali, 10/26/19
#

# This is not apart of the lab? Just doing what he wants us to do in class

infile = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/numbers.txt', 'w')

for i in range(21):
    number = str(i)
    infile.write(number + '\n')

infile.close()

infile = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/numbers.txt', 'r')
c = 0

for line in infile:
    number = float(line)
    print('{:.2f}'.format(number))
    c += number
    print(c)
infile.close()

# End of inclass version. Notice different way of converting string -> int / float


##############################################################################
# Task 02

def main():

    x = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/numbers.txt', 'r')
    c = 0

    for line in x:

        # Empty "objects" such as lines are considered false in boolean context
        # Therefore, will iterate until it gets to an empty line.
        # https://stackoverflow.com/questions/17264226/what-does-if-x-strip-mean
        if line.strip():
            n = int(line)
            c += n
    print(c)

    x.close();
main();


##############################################################################
# Task 02

def main():

    x = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/numbers.txt', 'r')
    c = i = 0

    for line in x:

        if line.strip():
            n = int(line)
            c += n
            i += 1
    # print('{:.3f}'.format(c/n))
    print(c/n)

    x.close()
main();
<file_sep>#This tutorial originally created by <NAME> <EMAIL> and modified by Dr. Ali for educational purpose
# at Rider University

import pandas as pd
import datasist as ds  #import datasist library
import numpy as np


train_df = pd.read_csv('train_data.csv')
test_df = pd.read_csv('test_data.csv')

# _________________________________Working with the structdata module___________________________________________________
# The structdata module contains numerous functions for working with structured data mostly in the Pandas DataFrame format.
# That is, you can use these functions to easily manipulate and analyze DataFrames.

#describe: We all know the describe function in Pandas

#print(train_df) #print all
#print(train_df.head()) #print the first 5 rows
#print(train_df.head(10))  # print the first n rows

# we decided to extend it to support full description of a dataset at a glance using datasist.
#print(ds.structdata.describe(train_df))

# check_train_test_set: This function is used to check the sampling strategy of two dataset.
# pass in the two dataset (train_df and test_df ), a common index (customer_id) and finally any feature or column present in both dataset.

#ds.structdata.check_train_test_set(train_df, test_df, index='Customer Id',  col='Building Dimension')

# display_missing: You can check for the missing values in your dataset and
# display the result in the well formatted DataFrame using this function.

# print(ds.structdata.display_missing(train_df))

# get_cat_feats and get_num_feats: Just like their names,
# you can retrieve categorical and numerical features respectively as a Python list.

cat_feats = ds.structdata.get_cat_feats(train_df)
#print(cat_feats)
num_feats = ds.structdata.get_num_feats(train_df)
#print(num_feats)

# get_unique_counts: Ever wanted to check the number of unique classes in your categorical features before you decide what encoding scheme to use?
# well, you can use the get_unique_count function to easily do that.

#unique_count=ds.structdata.get_unique_counts(train_df)
#print(unique_count) #Will not work in Pycharm. Try in Jupyter.

# join_train_and_test: Most of the time when prototyping, you may want to concatenate both train and test set,
# and then apply some transformations to it. You can use the join_train_and_test function for that.
# It returns a concatenated dataset and the size of the train and test set for future splitting.
all_data, ntrain, ntest = ds.structdata.join_train_and_test(train_df, test_df)
#print("New size of combined data {}".format(all_data.shape))
#print("Old size of train data: {}".format(ntrain))
#print("Old size of test data: {}".format(ntest))

#later splitting after transformations
train = all_data[:ntrain]
test = all_data[ntrain:]

#____________________________________ Feature engineering with datasist.________________________________________________
# Feature Engineering is the act of extracting important features from raw data and
# transforming them into formats that are suitable for machine learning models.
# drop_missing: This function drops columns/features with a specified percentage of missing values.

#print(ds.structdata.display_missing(train_df))
# we’ll drop the column with 7.1 percent missing values (Date_of_Occupancy).
# Note: You should not drop a column/feature with so little missing values. The ideal thing to do is to fill it. We drop it here, just for demonstration purpose.

#new_train_df = ds.feature_engineering.drop_missing(train_df, percent=7.0)
#print(ds.structdata.display_missing(new_train_df))

# drop_redundant: This function is used to remove features with low or no variance.
# That is, features that contain the same value all through.
# We show a simple example using an artificial dataset.
df = pd.DataFrame({'a': [1,1,1,1,1,1,1], 'b': [2,3,4,5,6,7,8]})
#print(df)

# column a is redundant, that is it has the same value all through.
# We can drop this column automatically by just passing in the dataset to the drop_redundant function.

#df = ds.feature_engineering.drop_redundant(df)
#print(df)

# convert_dtypes: This function takes a DataFrame as argument and
# automatically type-cast the features to their correct data types.

data = {'Name':['Tom', 'nick', 'jack'],
        'Age':['20', '21', '19'],
        'Date of Birth': ['1999-11-17','20 Sept 1998','Wed Sep 19 14:55:02 2000']}
df = pd.DataFrame(data)
#print(df)

#let’s check the data types…
#print(df.dtypes)

# The features Age and Date of Birth are supposed to be integer and DateTime respectively,
# by passing this dataset to the convert_dtype function, this can be fixed automatically.

#df = ds.feature_engineering.convert_dtype(df)
#print(df.dtypes)

# fill_missing_cats: As the name implies, this function takes a DataFrame,
# and automatically detects categorical columns with missing values.
# It fills them using the mode. # From the dataset,
# we have two categorical features with missing values, these are Garden and Geo_Code.

#df = ds.feature_engineering.fill_missing_cats(train_df)
#print (ds.structdata.display_missing(df))

# fill_missing_nums: This is similar to the fill_missing_cats, except it works on numerical features and
# you can specify a filling strategy (mean, mode or median).
# From the dataset, we have two numerical features with missing values,
# these are Building Dimension and Date_of_Occupancy.

#df = ds.feature_engineering.fill_missing_num(train_df)
#print(ds.structdata.display_missing(df))

# log_transform: This function can help you log transform a set of features.
# It also display the before and after plot with level of skewness to help you
# decide if log transforming feature is what you really want.
# The feature Building Dimension is a right skewed, and we can transform it.
# Note: Columns passed to the log_transform function
# should not contain missing values, else it will throw an error.

#df = ds.feature_engineering.fill_missing_num(train_df)
#df = ds.feature_engineering.log_transform(df, columns=['Building Dimension'])

#_____________________________________WORKING WITH TIME BASED FEATURES__________________________________________________
# extract_dates: This function can extract specified features like day of the week,
# day of the year, hour, min and second of the day from a specified date feature.
new_train = pd.read_csv("Train.csv")
#print(new_train.head(3).T)

# Let’s demonstrate how easy it is to extract information from
# Placement — Time, Arrival at Destination — Time features using the extract_dates function.
# We specify that we want to extract just day of the week (dow) and hour of the day (hr).

date_cols = ['Placement - Time', 'Arrival at Destination - Time']
df = ds.timeseries.extract_dates(new_train, date_cols=date_cols, subset=['dow', 'hr'])
#print(df.head(3).T)
#dff=pd.DataFrame(df)
#dff.to_csv('Train_modified.csv')

# You will instead of 'Placement - Time', 'Arrival at Destination - Time' column, four new column:Placement - Time_dow ,
# Placement - Time_hr, Arrival at Destination - Time_dow, Arrival at Destination - Time_hr

# timeplot: The timeplot function can help you visualize a set features against a particular time feature.
# This can help you identify trends and patterns. To use this function, you can pass a set of numerical columns,
# and then specify the Date feature you want to plot against.

num_cols = ['Time from Pickup to Arrival', 'Destination Long',  'Pickup Long','Platform Type', 'Temperature']
# ds.timeseries.timeplot(new_train, num_cols=num_cols,  time_col='Placement - Time')

# _______________________________Visualization__________________
# VISUALIZATION FOR CATEGORICAL FEATURES
# boxplot: This function makes a box plot of all numerical features against a specified categorical target column.
# A box plot (or box-and-whisker plot) shows the distribution of quantitative data in a way that
# facilitates comparisons between variables or across levels of a categorical variable

#ds.visualizations.boxplot(train_df, target='Claim')


# VISUALIZATION FOR NUMERICAL FEATURES
# histogram: This function makes a histogram plot of all numerical features in a dataset.
# This helps to show distribution of the features.

#fill the missing values first
#df = ds.feature_engineering.fill_missing_num(train_df)
#ds.visualizations.histogram(df)
# scatterplot: This function makes a scatter plot of all numerical features in a
# dataset against a specified numerical target. It helps to show the correlation between features.

#feats = ['Insured_Period', 'Residential', 'Building Dimension', 'Building_Type', 'Date_of_Occupancy']
#ds.visualizations.scatterplot(train_df,num_features=feats, target='Building Dimension',save_fig='ali.png')

#__________________Testing and comparing machine learning models with datasist____________
#import libraries and datasets
'''
import pandas as pd
import numpy as np
import datasist as ds

train = pd.read_csv('train_data.csv')
#test = pd.read_csv('test_data.csv')


# Next, we do some processing. First, we drop the ID column (Customer Id) and
# then we fill missing numerical and categorical features.

#drop the id column
train.drop(columns='Customer Id', axis=1, inplace=True)
#test.drop(columns='Customer Id', axis=1, inplace=True)

#fill missing values
train = ds.feature_engineering.fill_missing_cats(train)
train = ds.feature_engineering.fill_missing_num(train)

#test = ds.feature_engineering.fill_missing_cats(test)
#test = ds.feature_engineering.fill_missing_num(test)

#check the unique classes in each categorical feature
ds.structdata.class_count(train)

# We will label encode Geo_Code, since the unique classes is large, and one-hot-encode the rest.

import category_encoders as ce

# drop target column
target = train['Claim'].values
train.drop(columns='Claim', axis=1, inplace=True)

enc = ce.OrdinalEncoder(cols=['Geo_Code'])
enc.fit(train)
train_enc = enc.transform(train)
#test_enc = enc.transform(test)


#one-hot-encode the rest categorical features
hot_enc = ce.OneHotEncoder()
hot_enc.fit(train_enc)
train_enc = hot_enc.transform(train_enc)
#test_enc = hot_enc.transform(test_enc)


# Now we will split the

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split


Xtrain, Xtest, ytrain, ytest = train_test_split(train_enc, target, test_size=0.3, random_state=1)
rf_classifier = RandomForestClassifier(n_estimators=20, max_depth=4)
rf_model=rf_classifier.fit(Xtrain,ytrain)
pred=rf_model.predict(Xtest)
ds.model.get_classification_report(pred,ytest)
'''

'''
# For Example I want to compare three ML models such as naive bayes, decision trees and svm
# compare_model: This model takes as argument multiple machine learning models
# and returns a plot showing each model’s performance.
# Now, let’s see this function in action. We will be comparing three models


from sklearn.naive_bayes import GaussianNB
from sklearn.svm import LinearSVC

Xtrain, Xtest, ytrain, ytest = train_test_split(train_enc, target, test_size=0.3, random_state=1)
rf_classifier = RandomForestClassifier(n_estimators=20, max_depth=4)
nb_classifier = GaussianNB()
svm_classifier = LinearSVC()
classifiers = [rf_classifier, nb_classifier, svm_classifier]
models, scores = ds.model.compare_model(models_list=classifiers, x_train=Xtrain, y_train=ytrain, scoring_metric='accuracy')
'''<file_sep># import os

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import torch
from torch.autograd import Variable
import torch.nn as nn
# import warnings
# warnings.filterwarnings("ignore")

# Defining car prices
car_prices_array = [3, 4, 5, 6, 7, 8, 9]
car_prices_np = np.array(car_prices_array, dtype=np.float32)

# https://stackoverflow.com/questions/18691084/what-does-1-mean-in-numpy-reshape
car_prices_np = car_prices_np.reshape(-1, 1)
car_price_tensor = Variable(torch.from_numpy(car_prices_np))

#Defining car sales
number_of_car_sell_array = [7.5, 7, 6.5, 6, 5.5, 5, 4.5]
number_of_car_sell_np = np.array(number_of_car_sell_array, dtype=np.float32)
number_of_car_sell_np = number_of_car_sell_np.reshape(-1, 1)
number_of_car_sell_tensor = Variable(torch.from_numpy(car_prices_np))

# plt.scatter(car_prices_array, number_of_car_sell_array)
# plt.xlabel("Car Price $")
# plt.ylabel("Number of Car Sales")
# plt.title("Car Price VS # of Car Sales")
# plt.show()

class LinearRegression(nn.Module):
   def __init__(self, input_size, output_size):
      super(LinearRegression, self).__init__()
      self.linear = nn.Linear(input_dim, output_dim)

   def forward(self, x):
      return self.linear(x)

# Model architecture
input_dim = 1
output_dim = 1
model = LinearRegression(input_dim, output_dim)

# MSE / Cost function
mse = nn.MSELoss()

# Optimization
learning_rate = 0.02
optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)

#train model
lost_list = []
iteration_number = 301
for iteration in range(iteration_number):
   # Optimization
   optimizer.zero_grad()
   # Forward to get output
   results = model(car_price_tensor)
   # Calculate Loss
   loss = mse(results, number_of_car_sell_tensor)
   # Backward prop
   loss.backward()
   # Updating parameters
   optimizer.step()
   # Store loss
   lost_list.append(loss.data)
   # Print loss
   if (iteration % 50 == 0):
      print('epoch {}, loss {}'.format(iteration, loss.data))

# plt.plot(range(iteration_number), lost_list)
# plt.xlabel("Number of Iterations")
# plt.ylabel("Loss")
# plt.show()

# Predict car price
predicted = model(car_price_tensor).data.numpy()
plt.scatter(car_prices_array, number_of_car_sell_array, label="original data", color="red")
plt.scatter(car_prices_array, predicted, label="predicted data", color="blue")

plt.legend()
plt.xlabel("Car Price $")
plt.ylabel("Number of Car Sell")
plt.title("Original vs Predicted values")
plt.show()


class One():
   def __init__(self, x, y, z):
      self.x = x
      self.y = y
      self.z = z

   def oneMethod(self, j):
      return self.x + j

oneI = One(2, 5, 7)
print(oneI.x)

class Three():
   def __init__(self, j = 20):
      self.j = j

   def returnJ(self):
      return self.j

class Two(One):
   def __init__(self, x, y, z, l):
      super().__init__(x, y, z)
      self.l = 9
      self.t = Three(3)

   def twoMethod(self):
      return self.x + self.y + self.z + self.l
   
   def printParam(self):
      print(self.x, self.y, self.z, self.l)

two = Two(1, 2, 3, 4)
print(two.t.returnJ())

class Net():
    def __init__(self):

      # First 2D convolutional layer, taking in 1 input channel (image),
      # outputting 32 convolutional features, with a square kernel size of 3
      self.conv1 = 1
      # Second 2D convolutional layer, taking in the 32 input layers,
      # outputting 64 convolutional features, with a square kernel size of 3
      self.conv2 = 2

      # Designed to ensure that adjacent pixels are either all 0s or all active
      # with an input probability
      self.dropout1 = 3
      self.dropout2 = 4
      # First fully connected layer
      self.fc1 = 5
      # Second fully connected layer that outputs our 10 labels
      self.fc2 = 6

test = Net()
print(test.conv1)<file_sep>public class sandbox {

    public static void main(String[] args) {
        
        short totalPay, basePay = 500, bonus = 1000;
        
        totalPay = (short)(basePay + bonus);
        
        System.out.println(totalPay);
        
        //        Challenge #2
        System.out.println("Challenge #2 ########################################");
        
        float alexa;
        double siri = 3.5;
        
        alexa = (float)(siri);
        
        System.out.println(alexa + "toads");
        
        //      Programming Challenge #2 - 
        System.out.println("Programming Challenge #2 ########################################");

        int fullPrice = 59;
        double sale = 0.2;

        System.out.println("The retail business sells product x at $" + fullPrice);
        System.out.println("The retail business sells product x at $" + (fullPrice - (fullPrice * 0.2)) + " after the 20% sale");
        System.out.println(fullPrice - (fullPrice * sale));

//      Programming Challenge #2 - Sales Prediction
        System.out.println("Programming Challenge #2 - Sales Prediction ########################################");

        double percentOfTotalSales = 0.62;
        double companyTotalSales = 4600000;

        System.out.println("The total predicted sales of the east coast company is: " + (companyTotalSales * percentOfTotalSales));

//      Programming Challenge #2 - Land Calculation
        System.out.println("Programming Challenge #2 - Land Calculation ########################################");
        int acre = 43560;
        int totalLand = 389767;

        System.out.println(totalLand / acre);

        



    }
}
<file_sep># <NAME>, CSC 110, Prof Ali, 10/24/19
# Task 01

def main():

    # x = open('filename.txt', 'w')
    x = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/filename.txt', 'w')
    x.write('<NAME>')
    x.close()

    # print(type(x))

main();

####################################################################################
# Task 02

def main():

    x = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/filename.txt', 'r')
    print(x.read())
    x.close()

main();


####################################################################################
# Task 03

def main():

    x = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/names.txt', 'r')
    i = 0
    n1 = x.readline()

    while n1 != '':
        i += 1
        n1 = x.readline()

    print(i)

    x.close()
main();


# x = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/numbers.txt', 'r')
# n1 = int(x.readline())
# n2 = int(x.readline())
# n3 = int(x.readline())
# n4 = int(x.readline())
#
# print(n1, n2, n3, n4)



######
# Task 03 Redo
#
# x = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/names.txt', 'r')
#
# y = x.readline()
#
# for i in :
#
#     y = x.readline();
#
#     i+=1
#
# print(i)
<file_sep>me());
      // System.out.println(testOne.getDepartment());
      // System.out.println(testOne.getId<file_sep>#!/usr/bin/env python
# coding: utf-8

# ### Load Programs

# In[1]:


import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# ### File Upload

# In[4]:


# Label File Tag
# file = 'Rider University B (40.283093852918036 -74.74257493436426) Primary 06_01_2019 08_31_2019'

# import file
PA = pd.read_csv("data.csv")
date=[]
time=[]
B=[]
C=[]
D=[]
E=[]
F=[]
G=[]
H=[]
I=[]
J=[]

for index, row in PA.iterrows():
    split=row['created_at'].split()
    date.append(split[0])
    time.append(split[1])
    B.append(row['entry_id'])
    C.append(row['PM1.0_CF_ATM_ug/m3'])
    D.append(row['PM2.5_CF_ATM_ug/m3'])
    E.append(row['PM10.0_CF_ATM_ug/m3'])
    F.append(row['UptimeMinutes'])
    G.append(row['ADC'])
    H.append(row['Temperature_F'])
    I.append(row['Humidity_%'])
    J.append(row['PM2.5_CF_1_ug/m3'])
data_modify={'date':date, 'time':time,'entry_id':B, 'PM1.0_CF_ATM_ug/m3':C,'PM2.5_CF_ATM_ug/m3':D, 'PM10.0_CF_ATM_ug/m3':E,'UptimeMinutes':F,'ADC':G,'Temperature_F':H,'Humidity_%':I,'PM2.5_CF_1_ug/m3':J}
df=pd.DataFrame(data_modify)
df.to_csv('data_modified.csv')

PB = pd.read_csv("data_modified.csv")


# show data with limited rows called head
PB.head(5)

# ### Histogram

# In[50]:


# bin data
bins = [0, 1, 2.5, 5, 7.5, 10, 15, 20, 25, 35, 40]

# build Histogram for Column Heading in csv
plt.hist(PB['PM1.0_CF_ATM_ug/m3'], bins=bins, color='#C73354')
# plt.hist(PA['PM2.5_CF_ATM_ug/m3'], bins=bins, color='#C73354')
# plt.hist(PA['PM10.0_CF_ATM_ug/m3'], bins=bins, color='#C73354')


# plot title and formatting
plt.title('PM1.0 Distribution', fontdict={'fontweight': 'bold', 'fontsize': 18})

# Adding a x and y axis label
plt.xlabel('Concentration ug m-3', fontdict={'fontname': 'Times New Roman', 'fontsize': 18})
plt.ylabel('Frequency of Concentrations', fontdict={'fontname': 'Times New Roman', 'fontsize': 18})

# show the begnning and end by intervals of an value
plt.xticks()
plt.yticks()
# [0,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000])

# plot legend
# plt.legend()

plt.show()

# In[53]:


# bin data
bins = [0, 1, 2.5, 5, 7.5, 10, 15, 20, 25, 35, 40]

# build Histogram for Column Heading in csv
# plt.hist(PA['PM1.0_CF_ATM_ug/m3'], bins=bins, color='#C73354')
plt.hist(PB['PM2.5_CF_ATM_ug/m3'], bins=bins, color='#C73354')
# plt.hist(PA['PM10.0_CF_ATM_ug/m3'], bins=bins, color='#C73354')


# plot title and formatting
plt.title('PM2.5 Distribution', fontdict={'fontweight': 'bold', 'fontsize': 18})

# Adding a x and y axis label
plt.xlabel('Concentration ug m-3', fontdict={'fontname': 'Times New Roman', 'fontsize': 18})
plt.ylabel('Frequency of Concentrations', fontdict={'fontname': 'Times New Roman', 'fontsize': 18})

# show the begnning and end by intervals of an value
plt.xticks()
plt.yticks()
# [0,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000])

# plot legend
# plt.legend()

plt.show()

# In[3]:


# bin data
bins = [0, 1, 2.5, 5, 7.5, 10, 15, 20, 25, 35, 40]

# build Histogram for Column Heading in csv
# plt.hist(PA['PM1.0_CF_ATM_ug/m3'], bins=bins, color='#C73354')
# plt.hist(PA['PM2.5_CF_ATM_ug/m3'], bins=bins, color='#C73354')
plt.hist(PB['PM10.0_CF_ATM_ug/m3'], bins=bins, color='#C73354')

# plot title and formatting
plt.title('PM10.0 Distribution', fontdict={'fontweight': 'bold', 'fontsize': 18})

# Adding a x and y axis label
plt.xlabel('Concentration ug m-3', fontdict={'fontname': 'Times New Roman', 'fontsize': 18})
plt.ylabel('Frequency of Concentrations', fontdict={'fontname': 'Times New Roman', 'fontsize': 18})

# show the begnning and end by intervals of an value
plt.xticks()
plt.yticks()
# [0,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000])

# plot legend
# plt.legend()

plt.show()




<file_sep># Acadamia
### CS & a bit more

Centralization of academic & hobby work

Not the best way to organize, but it gets the job done.<file_sep># <NAME> | CSC 101 | 9/18/19
# Updated 9/24/19

import turtle

t = turtle.Turtle()
t.hideturtle()
t.begin_fill()
t.penup()

t.goto(300, 0)
t.goto(300, 130)
t.goto(130, 130)
t.goto(130, 260)
t.goto(0, 260)
t.goto(0, 0)


# t.goto(300, 0)
# t.goto(300,200)
# t.goto(0, 200)
# t.goto(0, 0)
t.fillcolor('#4b99e0')
t.end_fill()

turtle.exitonclick()
<file_sep># <NAME>, <NAME>, 11/7/19, Test 2
#


def main():

    def instruction():
        print('This program ask user for an integer number and checks the given number is prime or not.')
    instruction();

    x = input("Press 'y' or 'Y' to continue, anything else to exit: ")

    while x == 'y' or x == 'Y':
        y = int(input('Enter an integer number: '))

        def prime_function(x):
            for i in range(2, x):
                if x % i == 0:
                    print(x ,'is not a prime number')
                    break;
                else:
                    print(x, 'is a prime number')
                    break;

        prime_function(y)

        x = input("Press 'y' or 'Y' to continue, anything else to exit: ")


main();

# Bad because I can input 9 and it will output as both prime and not prime
# because 9 % 3 = 0.
<file_sep>str = "this is string example....wow!!!"
print ("str.center(40, 'a') : ", str.center(60, 'a'))

<file_sep>/**
 * a1
 * 
 * <NAME>, CSC 120, Assignment 1
 * 
 */

import java.util.Scanner;

public class a1 {
   
   public static void main(final String[] args) {

      /**
       * Test Average section of Assignment 1 - Section 1
       */
      
      int testOne, testTwo, testThree;
      
      final Scanner keyboard = new Scanner(System.in);

      System.out.println("Test 1 score:");
      testOne = keyboard.nextInt();

      System.out.println("Test 2 score:");
      testTwo = keyboard.nextInt();

      System.out.println("Test 1 score:");
      testThree = keyboard.nextInt();

      System.out.printf("Test one score: %d%nTest two score: %d%nTest three score: %d%n", testOne, testTwo, testThree);
      System.out.println("The average test score is: " + ((testOne + testTwo + testThree) / 3) );



      stringManipulator();
      restaurantBill();
      wordGame();
   }

   public static void stringManipulator() {

      /**
       * String Manipulator section of Assignment 1 - Section 2
       */

      String favCity;

      final Scanner keyboard = new Scanner(System.in);     

      System.out.println("Enter the name of your favorite city:");
      favCity = keyboard.nextLine();

      System.out.println("Length: " + favCity.length());
      System.out.println("Uppercase: " + favCity.toUpperCase());
      System.out.println("Lowercase: " + favCity.toLowerCase());
      System.out.println("First letter: " + favCity.charAt(0));

   }

   public static void restaurantBill() {

      /**
       * Restaurant Bill section of Assignment 1 - Section 3
       */
      
      double bill, totalBill, tax, tip;
      final double taxRate = 0.565, tipRate = 0.2;

      final Scanner keyboard = new Scanner(System.in);

      System.out.println("Enter the bill: ");
      bill = keyboard.nextDouble();

      tax = bill * taxRate;
      tip = (bill + tax) * tipRate;
      totalBill = bill + tax + tip;

      System.out.println("Your tax is: " + tax);
      System.out.println("Your tip is: " + tip);
      System.out.println("Your total bill is: " + totalBill);

   }

   public static void wordGame() {

      /**
       * Word Game section of Assignment 1 - Section 4
       */
      
      int age;
      String name, nameOfCity, nameOfCollege, profession, animal, petName;

      final Scanner keyboard = new Scanner(System.in);

      System.out.println("Enter a name: ");
      name = keyboard.nextLine();
      
      System.out.println("Enter an age: ");
      age = keyboard.nextInt();

      // Scanner.nextInt() does not consume '\n' character
      keyboard.nextLine(); 
      
      System.out.println("Enter a name of a city: ");
      nameOfCity = keyboard.nextLine();
      
      System.out.println("Enter a name of a college: ");
      nameOfCollege = keyboard.nextLine();
      
      System.out.println("Enter a profession: ");
      profession = keyboard.nextLine();
      
      System.out.println("Enter an animal: ");
      animal = keyboard.nextLine();
      
      System.out.println("Enter a pet name: ");
      petName = keyboard.nextLine();

      System.out.printf("There once was a person named %s who lived in %s. At the age of %d, %s went to college at %s. %s graduated and went back to work as a %s. Then, %s adopted an %s named %s. They both lived happily ever after!", name, nameOfCity, age, name, nameOfCollege, name, profession, name, animal, petName);
   }
}<file_sep>#Write a program in python that displays your name, address, and telephone number
from textwrap import wrap


school = 'Rider Unviersity'
name = '<NAME>'
csc = 'CSC 110 Computer Science I'
assignment = 'Assignment Number 01 '

lines = '\n Rider University \n <NAME> \n CSC 110 Computer Science I \n Assignment Number 01'
test = 'asdlfkadf'
width = 30

print ('-' * width)

for line in wrap(lines, width):
    print('| {0:^{1}} |'.format(line, width))

print('-' * width)

#print('-' * 70)
#print('{:^24s}'.format(school + '\n' + csc + '\n' + assignment + '\n' + name))
print(lines)
<file_sep># <NAME>, redo, better code and understanding of test2
# declare 3 functions: main, instruction, and prime_funciton



def main():



    def instruction():
        print('This program asks the user for an integer and verifies whether it is prime or not')

    instruction();

    x = input('Enter y or Y to continue');

    while x == 'y' or x == 'Y':

        y = int(input('Enter an integer:'))

        def prime_function(x):
            r = 0;
            for i in range(2, x):
                # print(i)
                if x % i == 0 and r == 0:
                    # print('beepboop')
                    r = 1;
                    print(x, 'is not a prime number');

                elif x % i != 0 and r == 0:
                    r = 1;

                    print(x, 'is a prime number');

# It is only determining if the input is divisible by 2, not the following
# numbers in the for loop. This is not what a prime number is.

        prime_function(y)

        x = input('Enter y or Y to continue');
main();


#
# x = 0;
# for i in range(6):
#     print(i)
#     if i == i and x == 0:
#         print('toads');
#         x += 1;
<file_sep>public class test {

   public static void main(String[] args) {
      
      // int x = 0;

      // for (int count = 10; count <= 21; count++) {
      //    // System.out.println(count);
      //    System.out.println(x++);

      // }

      toadies();
   }

   public static void toadies() {

      int x = 10;

      switch (x) {
         case 10:
            x += 15;
            break;
         case 12:
            x -= 5;
         default:
            break;
      }

      System.out.println(x);

   }

}<file_sep># <NAME>, CSC 110, Prof Ali, 10/31/19
# Task 01
#


import matplotlib.pyplot as plt

def main():

    programmingLanguages = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
    popularity = ['22.2', '17.6', '8.8', '8', '7.7', '6.7']

    programmingLanguages.reverse()
    popularity.reverse()

    plt.bar(programmingLanguages, popularity)
    plt.show()

main();
<file_sep># <NAME>, CSC 110, 15 October 2019, Prof Ali
# Task 1
#

max_temp = 102.5

#Get the temp
temperature = float(input("Enter the substance's Celcius temperature:  "))

while temperature > max_temp:
    print('The temperature is too high.')
    print('Turn the thermostat down and wait')
    print('5 minutes. Then take the temperature')
    print('again and enter it.')
    temperature = float(input('Enter the new Celcius temperature: '))
    print('The temperature is acceptable.')
    print('Check it again in 15 minutes.')


######################################################
# Task 2

max = 5

total = 0.0

print('This program calculates the total of')
print(max, 'numbers you will enter.')

for counter in range(max):
    number = int(input('Enter a number: '))
    total += number

print('The total is', total)

######################################################
# Task 3

for x in range(0, 1001, 10):
    print(x)

# <NAME>, CSC 110, 15 October 2019, Prof Ali
#Task 1
#
<file_sep># 110
Comp Sci
<file_sep>#Create two variables
top_speed = 160
distance = 300
# Display the values referenced by the variables
print('The top speed is')
print(top_speed)

print('The distance traveled is')
print(distance)

############################################

val = 99
print 'the value of val is: ', val


############################################

name = '<NAME>'

print 'My name is: ', name


############################################
############################################
<file_sep>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

####

PA = pd.read_csv("./base/pre.csv")
date= []
time= []
B= []
C= []
D= []
E= []
F= []
G= []
H= []
I= []
J= []

for index, row in PA.iterrows():
   split=row['Team'].split()
   print('toads')<file_sep># <NAME> , CSC 110, 9/24/19
#
# Task 1
x = float(input('Number: '))

if x > 100:
    y = 20
    z = 40
    print(y,z)




# Task 2
a = 1

if a < 10:
    b = 20
else:
    b = 99



# Task 3

x = int(input('Enter your first number: '))
y = int(input('Enter your second number: '))

if y<=0:
    print('Division by zero is not possible. Please run the program again and enter a number other than zero.')
else:
    print('The quotient of', x, 'divided by', y, 'is: ', x/y)


##################### Extra

# x = float(245.334)
# print('The quotient of {} is '.format(10/3, '.2f'))
#
#
# print(format(20/3, '.3f'))



####

4:30 October 1. Science building meet professor


print('Room   Capacity   Test')
print('----   --------   ----')

n = 10
x = 1

while x<=n:
    sum = sum + x
    x = x + 1
print(sum)
<file_sep>import random

# The Coin class simulates a coin that can
# be flipped.

class Coin:

    # The __init__ method initializes the
    # sideup data attribute with 'Heads'.

    def __init__(self):
        self.sideup = 'Heads'

    # The toss method generates a random number
    # in the range of 0 through 1. If the number
    # is 0, then sideup is set to 'Heads'.
    # Otherwise, sideup is set to 'Tails'.

    def toss(self):
        if random.randint(0, 1) == 0:
            self.sideup = 'Heads'
        else:
            self.sideup = 'Tails'

    # The get_sideup method returns the value
    # referenced by sideup.

    def get_sideup(self):
        return self.sideup

# The main function.
def main():
    # Create an object from the Coin class.
    my_coin = Coin()


    # Display the side of the coin that is facing up.
    print('This side is up:', my_coin.get_sideup())

    # Toss the coin.
    print('I am tossing the coin...')
    my_coin.toss()

    # Display the side of the coin that is facing up.
    print('This side is up:', my_coin.get_sideup())

# Call the main function.
main()


# how to create exe file so you do not have to give someone your source code and instead just give someone your program.
# write a step-by-step of what you did to create an exe file and then email it to him.\
# pyinstaller is what ali used.
<file_sep>class Net():
    def __init__(self):

      # First 2D convolutional layer, taking in 1 input channel (image),
      # outputting 32 convolutional features, with a square kernel size of 3
      self.conv1 = 1
      # Second 2D convolutional layer, taking in the 32 input layers,
      # outputting 64 convolutional features, with a square kernel size of 3
      self.conv2 = 2

      # Designed to ensure that adjacent pixels are either all 0s or all active
      # with an input probability
      self.dropout1 = 3
      self.dropout2 = 4
      # First fully connected layer
      self.fc1 = 5
      # Second fully connected layer that outputs our 10 labels
      self.fc2 = 6

test = Net()
print(test.conv1)<file_sep>public class tClass {

    int x;
    int y;

    public tClass(int _x, int _y) {
        x = _x;
        y = _y;
    }



    public int getX() {
        return x;
    }

}
<file_sep># <NAME>, CSC 110, 15 October 2019, Prof Ali
#Task 1
#

product = float(input('Enter a number:'))
while product < 100:
    product *= 10

    # Will terminate print statement if the product is > 100.
    # if product > 100:
    #     break

    print('{:.3f}'.format(product))


######################################################
# Task 2

base_size = 8

for i in range(base_size):
    for c in range(i - 1):
        print('*', end='')
    print()

######################################################
# Task 3

n = int(input('Enter a number: '))
x = 0
for i in range(0, n + 1, 2):
    x +=i

print(x)




for hours in range(24):
    for min in range(60):
        for sec in range(60):
            print(hours, min, sec)
<file_sep># Test 1 Lab, <NAME>, CSC 110, Prof Ali, 10/8/19
#

hours = int(input('Enter hour: '))

if hours >= 1 and hours <= 11:
    print(hours, 'AM')

elif hours == 12:
    print(hours, 'PM')

elif hours >= 13 and hours <= 23:
    print(hours - 12, 'PM')

elif hours == 24:
    print(hours - 12, 'AM')

else:
    print('You have entered an invalid value')
<file_sep># CSC 410 Data Structure / Big Data<file_sep># <NAME>, CSC 110, Prof Ali, Dec 5 2019
# Problem A | Turing Machine
#

# Power of 2 ------ 2 4 8 16 32 64

def main():

    x = int(input('Enter an integer less than 1000: '))
    y = x * '0'
    z = 2

    def orig(z):

        if z < 1000:
            while z < 1000:
                for i in range(1000):
                    print(z**i)


    print(x, 'Accepted')


    for i in range(x):
        aa = (y[i] * (i + 1))

        if len(aa) == range(z**z):
            bb = 'Accepted'
        else:
            bb = 'Rejected'


        # print(aa, bb)


    # print(z**z)
    orig(2)
main();
<file_sep># # <NAME>, CSC 110, Prof Ali, 10/19/2019
# # Task 2
# #
#
# def main():
#     x = int(input('Enter a number in kilometers: '))
#     print('This formula converts kilometers to miles.')
#
#     def kilometerConveter(y):
#         y *= 0.6214
#         print(x, 'miles is', '{:.2f}'.format(y), 'kilometers.')
#
#
#     kilometerConveter(x);
#
# main()
#
#


def main():
    x = int(input('Enter a number in kilometers: '))
    print('This function / formula will convert to miles.')

    def kilometerConverter(y):
        y *= 0.6214
        print(x, 'miles is', '{:.2f}'.format(y), 'kilometers.')

    kilometerConverter(x);

main()




x = int(input('Enter a number in kilometers: '))

def main():
    print('This formula will convert miles to kilometers')
    kilometerConverter(x)

def kilometerConverter(y):
    y *= 0.6214
    print(x, 'miles is', '{:.2f}'.format(y), 'kilometers.')


main()
<file_sep>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_xlim3d(0, 3)
ax.set_ylim3d(0, 3)
ax.set_zlim3d(0, 3)

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

# ax.quiver(x, y ,z, x, y, z) first 3 param are origin definition, following 3 are vector definition


# ax.quiver(0, 0, 0, 1, 1, 1, length = 0.5, normalize = True)
# ax.quiver(0, 0, 0, 1, 2, 0, length=0.5)
# ax.quiver(0, 1, 0, 1, 2, 0)
# ax.quiver(0, 2, 0, 1, 2, 0)

ax.quiver(0, 0, 0, 1,-1,1)
ax.quiver(0, 0, 0, 0, 1, -1)
ax.quiver(0, 0, 0, -1, 0, 1)

plt.show()<file_sep># <NAME>, CSC 110, Prof Ali, 10/26/19
# Question 1
#

import random

def main():

    # MAC
    x = open('/Users/Ryan/Documents/GitHub/csc110/Assignments/random.txt', 'w')

    # WINDOWS
    # x = open('D:\Github\CSC110\Assignments/random.txt', 'w')

    y = int(input('How many random numbers do you want this file to hold? '))

    for z in range(y):
        i = str(random.randrange(1, 300))
        x.write(i + '\n')

    x.close()
main();

####################################################################################################
# Question 2

def main():

    # MAC
    x = open('/Users/Ryan/Documents/GitHub/csc110/Assignments/random.txt', 'r')
    h = open('/Users/Ryan/Documents/GitHub/csc110/Assignments/random.txt', 'r')

    # WINDOWS
    # x = open('D:\Github\CSC110\Assignments/random.txt', 'r')
    # h = open('D:\Github\CSC110\Assignments/random.txt', 'r')
    c = i = 0

    print(x.read())

    # Puts cursor back to beginning
    x.seek(0)

    for line in x:
        if line.strip():
            n = int(line)
            c += n
            i += 1
    print('The sum of these numbers is: ', c)
    print('The number of random numbers read from the file is: ', i)
    x.close()
main();
<file_sep>import matplotlib.pyplot as plt
import pandas as pd

from sklearn.cluster import KMeans
# from sklearn.preprocessing import MinMaxScaler

df = pd.read_csv("exoplanets_small.csv")

df.head(10)

# print(df)

plt.scatter(df.Tday, df.Distance)
plt.show()<file_sep># <NAME>, CSC 110, Prof Ali, November 12 2019
# Task 1
#

def main():

    x = input('Enter your first name: ')
    y = input('Enter your middle name: ')
    z = input('Enter your last name: ')

    print(x[0], y[0], z[0])

main();


def main():
    # Extra credit if all the text is lowercase
    x = input('Enter your name, first characters should be upper case:').split()

    # Comprehends only uppercase text
    # for i in x:
    #     print(i)
    #     if i.isupper():
    #         print(i+'.', end='');


    # Comprehends lower and uppercase text
    for word in x:
        y = word[0].upper()
        print(y + '.' , end = '')


    # List comprehension syntax, same code as above.
    # [print(word[0] + '.' , end = '') for word in x]
main();


######################################################################
# Task 2


def main():

    x = input('Enter single-digit numbers with no seperators:')
    # y = [int(i) for i in x]
    # print(sum(y))
    total = 0
    for i in x:

        total += int(i);
    print(total)

main();
<file_sep># <NAME>, CSC 110, Prof Ali, 11/14/19, Mod 8 Lab 2
# Task 01
#

def main():
    values = 'one$two$three$four'
    newValues = values.split('$')

    print(newValues);
main();

##############################################################################
# Task 02

import calendar as c

def main():

    # I doubt this is how he wanted, it.

    x = input('Enter the date in mm/dd/yyyy syntax: ')
    y = x.split('/')

    # print(y[0])
    print(c.month_name[int(y[0])], y[1], y[2])

main();



def main():

    x = input('Enter the date in mm/dd/yyyy syntax: ')
    y = x.split('/')

    sample_list = values.split('/')
    print(sample_list[1])
    if int(sample_list[1]) == 1:
        print('January', end = '')


main();
##############################################################################
# Task 03

def main():

    x = {'a':1, 'b':2, 'c':3}
    print(x)

main();

##############################################################################
# Task 04

def main():

    dct = {'Jim':1, 'Ryan':2, 'Jared':3, 'Leo':4}

    if 'Jim' in dct:
        del dct['Jim']
    print(dct)
main();







x = {'a':'1', 'b':'2', 'c':'3'}
print(x[1])

stuff = {1:'aaa', 2:'bbb', 3:'ccc'}
print(stuff[3])
<file_sep># <NAME>, CSC 110, Prof Ali, 10/22/19
# Task 01
#

def main():

    kilometers = int(input('Enter the distance in kilometers: '))
    print('This program converts miles to kilometers.')

    def miles(x):
        return x * 0.6214

    print(kilometers,' kilometers is equal to {:.2f} miles'.format(miles(kilometers)))

main();



####################################################################
# Task 02


def main():

    print('Enter 5 test scores')
    t1 = int(input('Test Score 1: '))
    t2 = int(input('Test Score 2: '))
    t3 = int(input('Test Score 3: '))
    t4 = int(input('Test Score 4: '))
    t5 = int(input('Test Score 5: '))


    def calc_average(t1, t2, t3, t4, t5):
        return (t1 + t2 + t3 + t4 +t5) / 5


    def determine_grade(testScore):
        if testScore <=100 and testScore >=90:
            return ('A')
        elif testScore <=89 and testScore >=80:
            return ('B')
        elif testScore <=79 and testScore >=70:
            return ('C')
        elif testScore <=69 and testScore >=60:
            return ('D')
        elif testScore <=59:
            return('F')



    print('Your test average is {:.2f}'.format(calc_average(t1, t2, t3, t4, t5)))
    print('Your test 1 letter grade is: ' , determine_grade(t1))
    print('Your test 2 letter grade is: ' , determine_grade(t2))
    print('Your test 3 letter grade is: ' , determine_grade(t3))
    print('Your test 4 letter grade is: ' , determine_grade(t4))
    print('Your test 5 letter grade is: ' , determine_grade(t5))

main();
<file_sep># <NAME>, CSC 110, 10/10/19, Prof Ali
#
# Assignment 1

x = 0

for x in range(1, 10, 2):
    y = "*" * x
    print('{:^10}'.format(y))
    x += 1;
    if x == 10:
        for x in range(7, 0 , -2):
            y = '*' * x
            print('{:^10}'.format(y))
            x -= - 1

##############################################
# Assignment 2

n = int(input('Give me a non negative integer to factorialize: '))
# n = 5
fac = 1
if n < 0 or isinstance(n, int) != True:
    print('Give me a non negative integer...')

for i in range(1,  n + 1):
        fac *= i

print(fac)

##############################################
# Assignment 3

n = int(input('Give me an integer: '))
# n = 5
ans = 0

for i in range(1, n + 1):
    # print(i)
    ans += (i / n)
    n -= 1
    # n = 1
    # ans += (i / n -1)

print('{0:.3f}'.format(ans))
<file_sep># <NAME> , CSC 110, 10/1/19
# Task 1

base_hours = 40
ot_multiplier = 1.5

hours = float(input('Enter the number of hours worked: '))
pay_rate = float(input('Enter the hourly pay rate: '))


if hours > base_hours:

    overtime_hours = hours - base_hours
    overtime_pay = overtime_hours * pay_rate * ot_multiplier
    gross_pay = base_hours * pay_rate + overtime_pay

else:

    gross_pay = hours * pay_rate

if gross_pay > 100:
    net_pay = gross_pay - 15

print('The gross pay is $', format(gross_pay, ',.2f'), sep='')
print('The net pay is $', format(net_pay,',.2f'))


# Task 2
base_hours = 40
ot_multiplier = 1.5

hours = float(input('Enter the number of hours worked: '))
pay_rate = float(input('Enter the hourly pay rate: '))


if hours > base_hours:

    overtime_hours = hours - base_hours
    overtime_pay = overtime_hours * pay_rate * ot_multiplier
    gross_pay = base_hours * pay_rate + overtime_pay

else:

    gross_pay = hours * pay_rate

medicareCost = gross_pay * .029
socialSecurityCost = gross_pay * .124

if gross_pay > 100:
    net_pay = ((gross_pay - medicareCost) - socialSecurityCost - 15)

print('The gross pay is $', format(gross_pay, ',.2f'), sep='')
print('The net pay is $', format(net_pay,',.2f'))


# Task 3

x = int(input('Give me an integer'))

if x % 2 == 0:
    print('Even number')

else:
    print('Odd Number')



####################################

elif x % 2 != 0:
    print('Odd number')

else:
    print('Whole number pls')

elif x != int:
    print('fake')
<file_sep># <NAME>, CSC 110, Prof Ali, Final, 12/11
# Lab
#
# Write a python program that reads the test.txt file’s contents, counts and
# displays the number of vowels and the number of consonants it contains.

def main():

    x = open('/Users/Ryan/Documents/GitHub/csc110/test.txt', 'r')
    vowelCount = consCount = 0;
    vowels = ['a', 'e', 'i', 'o', 'u']
    # vowels = 'a'

    y = x.read();
    # z = y.split();

    for i in y:
        if i in vowels:
            vowelCount += 1;
            print(i)
        elif i not in vowels:
            consCount += 1;
    print('There are', vowelCount, 'vowels.');
    print('There are', consCount, 'consonats.');

    # print(vowels)




main();
<file_sep>post = 'post.csv'
f = open(post, 'w+')
f.close()<file_sep>import java.util.Scanner;

/**
 * test2
 */
public class test2 {

   public static void main(String[] args) {
      // System.out.println("toaders");

      Scanner keyboard = new Scanner(System.in);
      System.out.println("Enter a name: ");

      String uName = keyboard.nextLine();
      System.out.println("Hello" + uName);
   }
}<file_sep># <NAME> | Comp Sci 101 | 9/17/19


#answer = float(input('Enter how many shares Ali purchased: '))
answer = float(input('Enter how many shares Ali purchased: '))
#answer = 1000


print('The amount of commission Ali paid to his broker: ${:5,.2f}'.format(answer * 30 * .025))
print('The net amount of money Ali paid for his stock including commission: ${:5,.2f}'.format((answer * 30) + (answer * 30 * .025)))
print('The amount of commission Ali paid his broker when he sold the stock: ${:5,.2f}'.format(answer * .025 * 45))
print('The net amount that Ali received by selling the stock including the cost of commission: ${:5,.2f}'.format(45 * answer - (answer * .025 * 45)))
print('Ali profit made: ${:5,.2f}'.format(45 * answer - (answer * .025 * 45) - ((answer * 30) + (answer * 30 * .025))))
<file_sep># <NAME>
# Hello professor

width = 70

str = '|'
str1 = 'Rider University'
str2 = 'CSC 110 Computer Science I'
str3 = 'Assignment Number 01'
str4 = 'Name: <NAME>'

print('-'*width)
print (str.ljust(0,), str1.center(66,), str.rjust(0))
print (str.ljust(0,), str2.center(66,), str.rjust(0))
print (str.ljust(0,), str3.center(66,), str.rjust(0))
print (str.ljust(0,), str4.center(66,), str.rjust(0))
print('-'*width)
<file_sep># <NAME>, CSC 110, Prof Ali, 11/1/19
# assignment07 task 02
#

def main():

    # WINDOWS
    x = open('D:\Github\CSC110\Assignments\lin_assignment07\lottery.txt', 'r')
    #MAC
    # x = open('/Users/Ryan/Documents/GitHub/csc110/Assignments/lin_assignment07/lottery.txt', 'r')

    newNumbers = [i.rstrip('\n') for i in x]

    # for i in x:
    #     z = i.rstrip('\n')
    #     newNumbers.append(z)

    print(newNumbers)
    # print(type(newNumbers))


    x.close();
main();
<file_sep># Variables to represent the base hours and
# the overtime multiplier.
base_hours = 40
ot_multiplier = 1.5

hours = float(input('Enter the number of hours worked: '))
pay_rate = float(input('Enter the hourly pay rate: '))


if hours > base_hours:

    overtime_hours = hours - base_hours
    overtime_pay = overtime_hours * pay_rate * ot_multiplier
    gross_pay = base_hours * pay_rate + overtime_pay

else:

    gross_pay = hours * pay_rate

medicareCost = gross_pay * .029
socialSecurityCost = gross_pay * .124

if gross_pay > 100:
    net_pay = ((gross_pay - medicareCost) - socialSecurityCost - 15)

print('The gross pay is $', format(gross_pay, ',.2f'), sep='')
print('The net pay is $', format(net_pay,',.2f'))
<file_sep>cis200

Professor Taylor
<file_sep>import numpy as np
import matplotlib.pyplot as plt
import sys

from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs

print(sys.path)<file_sep>#Orthogonal Matrix:
# QT == Q^-1
# QQT == I


from numpy import array
from numpy import linalg
# from scipy import linalg


U = array([
   [-0.2298477, 0.88346102, 0.40824829],
   [-0.52474482, 0.24078249, -0.81649658],
   [-0.81964194, -0.40189603, 0.40824829]
])

VT = array([
   [-0.61962948, -0.78489445],
   [-0.78489445,  0.61962948]
])

BB = array([
   [-0.2298477],
   [-0.52474482],
   [-0.81964194]
])


# Standard Orthogonal Matrix
C = array([
   [1/3, 2/3, -2/3],
   [-2/3, 2/3, 1/3],
   [2/3, 1/3, 2/3]
])

# Matrix that produces a diagonal but is not normalized, therefore is not orthogonal
D = array([
   [1, 2, -2],
   [-2, 2, 1],
   [2, 1, 2]
])

print(U.dot(U.transpose()))
print(VT.dot(VT.transpose()))
# print(linalg.inv(C))

<file_sep>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# PA = pd.read_csv("data.csv")
# df = pd.DataFrame([{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}])
df = pd.read_csv("data.csv")


date = []
B = []
C = []
D = []
E = []
F = []
G = []
H = []
I = []
J = []

for index, row in df.iterrows():
    print(row['ADC'])

# for index, row in PA.iterrows():
#    split = row['created_at'].split()

# print(split)<file_sep># <NAME> , 9/24/19, CSC 110
#

test1 = float(input('Enter the first test score: '))
test2 = float(input('Enter the second test score: '))
test3 = float(input('Enter the third test score: '))

sum = test1 + test2 + test3
avg = sum/3

print('The sum of the score is ', sum)
print('The average of the score is ', avg)


# Task 1

import turtle

turtle.hideturtle()
turtle.fillcolor('#00ff00')
turtle.begin_fill()
turtle.goto(150, 0)
turtle.goto(150, 200)
turtle.goto(-150, 200)
turtle.goto(-150, 0)
turtle.goto(0, 0)
turtle.end_fill()

turtle.penup()
turtle.hideturtle()
turtle.fillcolor('red')
turtle.begin_fill()
turtle.goto(0,20)
turtle.circle(75)
turtle.end_fill()

turtle.exitonclick()

# EXTRA CREDITTTT

# Download .csv file
# Install pandas module
# Copy a couple columns into another csv file
# 2 / 3 weeks
# this is extra credit
<file_sep>public class t {

    public static void main(String[] args) {

        tClass abc = new tClass(5, 6);

        System.out.println(abc.x);

        System.out.println(abc.getX() + "toads");

    }

}
<file_sep>#<NAME> | CIS 101 | 9/17/19

import turtle

t = turtle.Turtle()

t.hideturtle()
t.begin_fill()

t.forward(100)
t.right(90)
t.forward(100)
t.left(90)
t.forward(150)
t.right(90)
t.forward(100)
t.right(90)
t.forward(250)
t.right(90)
t.forward(200)
t.fillcolor('#4b99e0')
t.end_fill()

turtle.exitonclick()
<file_sep># <NAME>, CSC 110, Prof Ali, 10/31/19
# Task 1
#

def main():

    list = ['Galileo', 'Oliver', 'Ostwald', 'Descartes']

    # for i in list[:]:
    for i in list:
        print(i)

main();


################################################################################
# Task 02
#

def main():

    names = ['Ali', 'John', 'Doe', 'Jane']

    for i in names:
        if i == 'Ali':
            print('Hello Ali')
        else:
            print('no')
main();
<file_sep>public class BigLittle {

    public static void main(String[] args) {

        int little;
        int big;

        little = 2;
        big = 2000;

        System.out.println("The little number is: " + little);
        System.out.print("The big number is: " + big);
    }
}<file_sep># <NAME>, October 3, 2019, CSC 110, Prof Ali
#
import sys

roomNumber = int(input('Enter room number: '))
capacity = int(input('Enter capacity: '))
enrollment = int(input('Enter enrollment: '))
#
# roomNumber = 345
# capacity = 32
# enrollment = 23

if roomNumber < 0 or capacity < 0 or enrollment < 0:
    print('Error! Capacity cannot be a negative number.')
    sys.exit()

if enrollment > capacity:
    print('Error! Enrollment can not be greater than capacity')
    sys.exit()

emptySeats = capacity - enrollment

if enrollment == capacity:
    filled = 'Filled'
else:
    filled = 'Not filled'

print('{:^15} {:^15} {:^15} {:^15} {:^15}'.format('Room',    'Capacity',    'Enrollment',    'Empty Seats',    'Filled/Not filled'))
print('{:^15} {:^15} {:^15} {:^15} {:^15}'.format('----', '--------', '----------', '-----------', '-----------------'))
print('{:^15} {:^15} {:^15} {:^15} {:^15}'.format(roomNumber, capacity, enrollment, emptySeats, filled))
<file_sep># Read me

The base folder consists of all the files emailed to me from Professor Ali<file_sep># libraries
import numpy as np # used for handling numbers
import pandas as pd # used for handling the dataset

#Importing the Dataset:
# to import the dataset into a variable with
# Removing the first unnamed column

dataset = pd.read_csv('mpg.csv',index_col=0)

#print(dataset) #print all
#print(dataset.head()) #print the first 5 rows
#print(dataset.head(10))  # print the first n rows



# Total missing values for each feature
print(dataset.isnull().sum())

# Replace using median
median = dataset['cyl'].median()
dataset['cyl'].fillna(median, inplace=True) #fillna fills the NaN values with a given number with which you want to substitute
print(dataset.isnull().sum())# Check again any missing or not

# Now we are going to encode the categorical data into numerical data type.
print(dataset.dtypes)# See the datatypes

# encode categorical data
from sklearn.preprocessing import LabelEncoder
le=LabelEncoder()
dataset["manufacturer"]=le.fit_transform(dataset["manufacturer"])
dataset["model"]=le.fit_transform(dataset["model"])
dataset["trans"]=le.fit_transform(dataset["trans"])
dataset["drv"]=le.fit_transform(dataset["drv"])
dataset["fl"]=le.fit_transform(dataset["fl"])
dataset["class"]=le.fit_transform(dataset["class"])
print(dataset.dtypes)
'''
#Visualize the data with boxplot
import matplotlib.pyplot as plt

for column in dataset:
    plt.figure()
    dataset.boxplot([column])
    plt.show()

# Visualize all column in one histogram
fig, axes = plt.subplots(ncols=len(dataset.columns), figsize=(10,5))
for col, ax in zip(dataset, axes):
    dataset[col].value_counts().sort_index().plot.bar(ax=ax, title=col)
plt.tight_layout()
plt.show()
# Visualize all column in separate histogram
fig = plt.figure(figsize = (8,8))
ax = fig.gca()
dataset.hist(ax=ax)
plt.show()
'''
# Splitting the attributes into independent and dependent attributes
X = dataset.iloc[:, :-1].values # attributes to determine independent variable / Class
Y = dataset.iloc[:, -1].values # dependent variable / Class
#print(X)
#print(Y)

#Split data into training and testing dataset. test_size=0.2 means 80% trainig data 20% test data
#Random state ensures that the splits that you generate are reproducible. Scikit-learn uses random permutations to generate the splits.
#The random state that you provide is used as a seed to the random number generator.
from sklearn.model_selection import train_test_split # used for splitting training and testing data
# splitting the dataset into training set and test set
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)

#import your model from scikit-learn
from sklearn.ensemble import RandomForestClassifier
from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation

#Train Random Forest Model
rf_classifier = RandomForestClassifier(n_estimators=20, max_depth=4)
rf_model=rf_classifier.fit(X_train,Y_train)

#Predict Label
pred=rf_model.predict(X_test)

#Test Model
print("Accuracy:",metrics.accuracy_score(Y_test, pred))

from matplotlib import pyplot as plt
## The line / model
plt.scatter(Y_test, pred)
plt.xlabel("True Values")
plt.ylabel("Predictions")
plt.show()

from sklearn.model_selection import KFold
kf = KFold(n_splits=5,random_state=42,shuffle=True)
# Splitting the attributes into independent and dependent attributes
X = dataset.iloc[:, :-1].values # attributes to determine independent variable / Class
Y = dataset.iloc[:, -1].values # dependent variable / Class
accuracies = []
for train_index, test_index in kf.split(X):

    data_train   = X[train_index]
    target_train = Y[train_index]

    data_test    = X[test_index]
    target_test  = Y[test_index]

    # if needed, do preprocessing here

    clf = RandomForestClassifier(n_estimators=20, max_depth=4)
    clf.fit(data_train,target_train)

    preds = clf.predict(data_test)

    # accuracy for the current fold only
    accuracy = metrics.accuracy_score(target_test,preds)

    accuracies.append(accuracy)

# this is the average accuracy over all folds
average_accuracy = np.mean(accuracies)
print("Using Kfold validation, average accuracy:", average_accuracy)<file_sep># <NAME>, <NAME>, Nov 18, 2019, Assignment 08
# Task 01
#

def main():

    x = open('/Users/Ryan/Documents/GitHub/csc110/Assignments/lin_assignment08/test.txt', 'r')
    a = b = c = d = e = f = 0

    y = x.read()
    g = y.split()
    # print(g)

    for z in g:
        # print(z)
        if z[0].isupper():
            a += 1;
        elif z.islower():
            b += 1;

        # Can't use 'elif' here because prior conditions are already met for elements in the list such as '650-horsepower', which is lowercase
        if z[0].isdigit():
            c += 1;
            # print(z)


    d = len(g)

    print('There are', a ,'words in uppercase')
    print('There are', b ,'words in lowercase')
    print('There are', c ,'numbers')
    print('There are', d ,'spaces')

main();
#
# a = 0
# x = ['four', '650-horsepower', 'ships', 'at']
# for i in x:
#
#     if z.islower():
#         print('toads')
#
#     elif i[0].isdigit():
#         a += 1
#         print(i)
        # print(a)
    # print(i)

###########################################################################################
# Task 02
#

def main():

    roomNumber = {'CS101':'3004', 'CS102':'4501', 'CS103':'6755', 'NT110':'1244', 'CM241':'1411'}
    instructor = {'CS101':'Haynes', 'CS102':'Alvarodo', 'CS103':'Rich', 'NT110':'Burke', 'CM241':'Lee'}
    meetingTime = {'CS101':'8:00am', 'CS102':'9:00am', 'CS103':'10:00am', 'NT110':'11:00am', 'CM241':'1:00pm'}

    a = input('Enter a course number (key): ')

    def userInput(a):

        print('You are meeting in room', roomNumber[a], 'with instructor', instructor[a], 'at', meetingTime[a])

    userInput(a)
main();
<file_sep># <NAME>, CSC 110, Prof Ali, 11/1/19
# assignment 07
#

import random as r

def main():

    # WINDOWS
    x = open('D:\Github\CSC110\Assignments\lin_assignment07\lottery.txt', 'w')

    #MAC
    # x = open('/Users/Ryan/Documents/GitHub/csc110/Assignments/lin_assignment07/lottery.txt', 'w')
    number = []

    for i in range(0,6):
        randomNumber = r.randrange(0,10)
        number.append(randomNumber)
        # number[i] = randomNumber

    for item in number:
        # x.write('%s\n' % item)
        x.write('{0!s}\n'.format(item))

    print(number)

    x.close();
main();
<file_sep>
x = 1, 2, 3
print(x)
print(type(x))<file_sep># Singular Value Decomposition w/ SciPy
from numpy import array
# from scipy.linalg import svd
# from scipy.linalg import inv
from scipy.linalg import *

##

# A = array([
#    [1.1, 1.0, 0.9, 1.0],
#    [1.0, 1.1, 1.0, 0.9]])

A = array([
   [1, 2],
   [3, 4],
   [5, 6]])

B = array([
   [2, 3],
   [1, 5]
])
   
# print("input \n", A)

# print("column \n", A[:,3])
##

U, s, VT = svd(A, full_matrices= True)
print("U \n", U)
print("S \n", s)
print("VT \n", VT)<file_sep># CSC 220 Data Structure / Big Data

