Пример #1
0
 def testRemoveDaysAfter(self):
     day = Employee.myDateTime(6,6)
     day2 = Employee.myDateTime(3,3)
     middleDay = Employee.myDateTime(3,3)
     self.e.addReqDay(day)
     self.e.addReqDay(day2)
     self.assertTrue(len(self.e.getReqDays()) == 2)
     self.e.removeReqDaysBefore(middleDay)
     self.assertTrue(len(self.e.getReqDays()) == 1)
     self.assertEqual(self.e.getReqDays(),{day})
Пример #2
0
def main():
    # 1. add employee data
    e1 = Employee("sga59", "Susan Gilmore", "Accounts", 80000, 6)
    e2 = Employee("gai09", "Greg Anderson", "IT", 120000, 12)
    e2 = Employee("dje23", "Dave Jones", "Engineering", 100000, 10)
    e3 = Employee("lwf05", "Luke Williamson", "Finance", 125000, 15)
    e4 = Employee("wnf11", "William Norman", "Finance", 101000, 11)
    e5 = Employee("hse55", "Harvey Smith", "Engineering", 80000, 5)
    e6 = Employee("dmm33", "Debbie Myer", "Marketing", 120000, 15)

    # 3. print employee details
    print "%-8s %-18s %-15s %-10s %-10s" % ("ID", "NAME", "DEPARTMENT",
                                            "SALARY", "YRS OF SERVICE")
    Employee.getEmpDetails(e1)
    Employee.getEmpDetails(e2)
    Employee.getEmpDetails(e3)
    Employee.getEmpDetails(e4)
    Employee.getEmpDetails(e5)
    Employee.getEmpDetails(e6)
    print "\n"

    # 2. delete employee data
    #Employee.delEmpDetails( "sga59" )
    #print "EMPLOYEE 'sga59' HAS BEEN REMOVED FROM THE EMPLOYEE RECORD"

    # 5. print employee who worked > 10 yr
    #for yr in yrOfServ: #yrOfServ:
    #if Employee.emp_service_years >= 10:
    #print empID, empName, yrOfServ
    #else:
    #print "NO EMPLOYEE WORKED > 10yr"

    # 6. change department of employee1 (e1)
    e1.change_dept("Arts")
    print "EMPLOYEE 'Susan Gilmore' DEPARTMENT HAS BEEN CHANGED TO 'Arts' "
    print "%-8s %-18s %-15s %-10s %-10s" % ("ID", "NAME", "DEPARTMENT",
                                            "SALARY", "YRS OF SERVICE")
    e1.getEmpDetails()
Пример #3
0
from Employee import *
if __name__ == "__main__":
    emp_list = []
    while True:
        print("Press 1 for Employees.")
        print("Press 2 for Exiting.")

        enter = input("")
        if enter == "1":
            while enter == "1" or enter == "2":
                if enter == "1":
                    print("Press 1 for Add Employee.")
                    print("Press 2 for View Employee.")
                    print("Press 3 for Main Menu.")
                    enter = input("")
                    if enter == "1":
                        name = input("Name = ")
                        sal = int(input("Salary = "))
                        emp = Employee(name, sal)
                        emp_list.append(emp)
                    elif enter == "2":
                        for i in emp_list:
                            print(i.displayEmployee())
                    else:
                        break
                elif enter == "2":
                    break
        else:
            break
 def openEmployee():
     e.vp_start_gui()
Пример #5
0
2) Here each unique employee we will create, as a instance of 	this class.

3) We also have Class veriable. AND Instance variable. 

------
Object :--
------

1) Object is one of instances of the class. 

2) Which can perform the functionalities ,which are defined in the class.

------
self :--
------

1) self represents the instance of the class. 

2) By using the "self" keyword we can access the attributes and methods of the class in python.

------
__init__ :--
------

The __init__ function is called a constructor, or initializer, and is automatically called 
when you create a new instance of a class. Within that function, the newly created object 
is assigned to the parameter self.

Please check blog:-
https://stackoverflow.com/questions/8609153/why-do-we-use-init-in-python-classes#

------------------------
Creating an empty class:-
------------------------

class Employee:
	pass

NOTE:-	The pass statement is a null operation; nothing happens when it executes. 
		The pass is also useful in places where your code will eventually go, but has not been written yet.
		
		It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:

def f(arg): pass    # a function that does nothing (yet)

class C: pass       # a class with no methods (yet)
	
------------------------
Creating Instances of Employee class:-
------------------------

emp_1 = Employee()
emp_2 = Employee()

---> emp_1 and emp_2 are the instances of the class.


Let's Print:-

>>> print(emp_1)
<__main__.Employee instance at 0x7ff209221488>

>>> print(emp_2)
<__main__.Employee instance at 0x7ff2092214d0>


NOTE:-	Both will be employee object and they both will be unique.
		Both will be at different location in the memory.

------------------------
Using INSTANCE Variable:-
------------------------

class Employee:
	pass

#Creating Instances of Employee class:-
emp_1 = Employee()
emp_2 = Employee()

#INSTANCE VARIABLE

emp_1.first = 'rudra'
emp_1.last  = 'singh'
emp_1.email = '*****@*****.**'
emp_1.pay   = 10000

#INSTANCE VARIABLE

emp_2.first = 'seema'
emp_2.last  = 'singh'
emp_2.email = '*****@*****.**'
emp_2.pay   = 20000

print(emp_1.email)
print(emp_2.email)

------------
Using Class:-
------------

NOTE:- Class Variable are variable which are shared among Instances with in the class.
	   Class variable will be same for each variable.

class Employee:

	def __init__(self, first, last, pay): 
		self.fname  = first
		self.lname  = last
		self.pay 	= pay
		self.email  = first + '.' + last + '@gmail.com'

#Creating Instances of Employee class:-
emp_1 = Employee('rudra','singh',10000)
emp_2 = Employee('seema','singh',20000)

>>> print(emp_1.email)
[email protected]

>>> print(emp_2.email)
[email protected]

>>> print(emp_1.fname)
rudra
>>> print(emp_2.fname)
seema

# Other Way to print first and last name

print('{} {}'.format(emp_1.first, emp_2.last))

------------------------
NOTE:- Better to create a METHOD for FULL NAME as we are doing this only for a single employee.
------------------------

class Employee:
	
	def __init__(self, first, last, pay):
		self.fname	= first
		self.lname	= last
		self.pay	= pay
		self.email	= first + '.' + '@gmail.com'
		
##METHOD for FULL NAME
	def fullname(self):
		return '{} {}'.format(self.fname, self.lname)

#Instance

emp_1 = Employee('rudra','singh',10000)
emp_2 = Employee('seema','singh',20000)

print(emp_2.fullname())

------------------
Calling or Running these method using class name:-
------------------

print(Employee.fullname(emp_1));

#similer to calling it using Instance
#emp_2.fullname()
	
	
-------------Class Variable Examples------------

class Employee:
	
	def __init__(self, first, last, pay):
		self.fname	= first
		self.lname	= last
		self.pay	= pay
		self.email	= first + '.' + '@gmail.com'
		
#METHOD for FULL NAME
	def fullname(self):
		return '{} {}'.format(self.first, self.last)
		
#Method for Raise
	def apply_raise(self):
		self.pay	= int(self.pay * 1.04)
		
#Instance

emp_1 = Employee('rudra','singh',10000)
emp_2 = Employee('seema','singh',20000)

print(emp1.pay) --> Will give present pay

emp_1.apply_raise()
print(emp.pay)	--> Will print pay with raise.

------------

class Employee:

	raise_amount	=	1.04	#class Variable
	
	def __init__(self, first, last, pay):
		self.fname	= first
		self.lname	= last
		self.pay	= pay
		self.email	= first + '.' + '@gmail.com'
		
##METHOD for FULL NAME
	def fullname(self):
		return '{} {}'.format(self.first, self.last)
		
#Method for Raise
	def apply_raise(self):
		self.pay	= int(self.pay * Employee.raise_amount)	
		#We need to access class variable either using class--> Employee.raise_amount 
		#or using INSTANCE --> self.raise_amount
		

#Instance

emp_1 = Employee('rudra','singh',10000)
emp_2 = Employee('seema','singh',20000)

print(emp1.pay)

emp_1.apply_raise()		#will raise only for emp1
print(emp1.pay)

NOTE:- Why we are using class vaiable using instance!! -->

print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)

All will give you the value of raise  i.e. 1.04
		
NOTE:-
If we want to access an attribute using instance, it will check whether that instance contain attribute or not ! if not then it will check in the class from where it inharits , contains attrebute or not.

So as above instance emp_1 doesn't have attrebute but emp_1 inherits class Employee which contain the attrebute.

----------------------
Changing raise_amount:-
----------------------

Now If we want to change raise amount 

Using Class:-

Employee.raise_amount	=	1.05			#We also can do this by class method is examples given down the line

This will change raise_amount every where.

print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)

Result:-

1.05
1.05
1.05

------------------------------------
Let's change it only for instance:-
------------------------------------

emp_1.raise_amount	=	1.05


print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)

Result:-

1.04
1.05
1.04

---------------------------------------------
Regular Methods , CLASS METHODS and STATIC METHODS
---------------------------------------------


class Employee:

	raise_amount	=	1.04	#class Variable
	
	def __init__(self, first, last, pay):			#---- Regular Method
		self.fname	= first
		self.lname	= last
		self.pay	= pay
		self.email	= first + '.' + '@gmail.com'
		
##METHOD for FULL NAME 								#---- Regular Method
	def fullname(self):
		return '{} {}'.format(self.first, self.last)
		
#Method for Raise
	def apply_raise(self):							#---- Regular Method
		self.pay	= int(self.pay * Employee.raise_amount)	
		
		# We need to access class variable either using class
		# Employee.raise_amount or using INSTANCE --> self.raise_amount

#As below , in regular methods we use (self) but in class methods , we pass a variable i.e. (cls) in below example.
		
	@classmethod
	def set_raise_amt(cls, amount):
		cls.raise_amount = amount
		

#Instance

emp_1 = Employee('rudra','singh',10000)
emp_2 = Employee('seema','singh',20000)

print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)

#All will give you the value of raise  i.e. 

1.04
1.04
1.04

------

Now if we want to change it to 5 % then --> USE CLASS METHOD

Employee.set_raise_amt(1.05)

#Now All will give you the value of raise  i.e. 

1.05
1.05
1.05

NOTE :- Because set_raise_amt is a class method so it is changing all values. 
		Works same as Employee.raise_amount	=	1.05 works.
Пример #6
0
    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)

    @classmethod
    def set_raise_amt(cls, amount):
        cls.raise_amt = amount

Employee.set_raise_amt(1.05)

emp_str_1 = 'John-Doe-70000'		#Getting employees as string
emp_str_2 = 'Steve-Smith-30000'		#Getting employees as string
emp_str_3 = 'Jane-Doe-90000'		#Getting employees as string

first, last, pay = emp_str_1.split('-')		#Splitting string

new_emp_1 = Employee(first, last, pay)		#Creating employee using class based on above split string.

print(new_emp_1.email)				#Printing new_emp_1
print(new_emp_1.pay)				#Printing new_emp_1


Result:-
[email protected]
70000

-----------------------------------------------------------------------------------------
In above we need to parse every time , So better to create class for that as given below.

Meaning Using Class method as alternative Constructor.
-----------------------------------------------------------------------------------------
Пример #7
0
 def testJane(self):
     Jane=Employee("Jane", "DUB", "LHR","AMS", "ARN", "SIN")
     airports=Jane.visitList()
     bestRoute=route.permutatuions(airports)
     self.assertEqual(bestRoute,['DUB', 'LHR', 'AMS', 'ARN', 'SIN','ARN', 'DUB', 9947])
Пример #8
0
def create_regular_employee(name, wage=None):
    return Employee.RegularEmployee(name, wage)
Пример #9
0
                    "sign in \t press 4 to Exit \n"))
            return choice
        except ValueError:
            print("Invalid choice please try again")


if __name__ == '__main__':
    while True:
        user_choice = get_choice()
        if user_choice == 1:
            user_name = input("Enter your name Admin")
            user_id = input("Enter your ID Admin")
            user_pass = input("Enter your password Admin")
            admin = Admin.Admin(user_id, user_pass, user_name)
            admin.admin_register()
        elif user_choice == 2:
            user_id = input("Enter your ID Admin")
            user_pass = input("Enter your password")
            admin = Admin.Admin(user_id, user_pass)
            admin.admin_login()
            break
        elif user_choice == 3:
            user_id = input("Enter your ID ")
            user_pass = input("Enter your password")
            trainee = Employee.Employee(user_id, user_pass)
            trainee.employee_login()
        elif user_choice == 4:
            exit(1)
        else:
            print("Sorry you have entered wrong option! please Try Again.")
Пример #10
0
def main():
    print("\t***** Payroll System *****\n")
    print("*********************************************************")
    print("*\tMilitary time\t\t\t\t\t*")
    print("*\tThis is time for morning 8:00 - 17:00\t\t*")
    print("* \tThis is time for overtime 18:00 - 23:00\t\t*")
    print("*********************************************************\n")
    e = Employee() # instanciate
    e.logIn()
    e.generateDTRRecord1() # save in file.txt the personal info of user
    for day in e.days:
        print("Today is", day)
        e.checkDay()
        e.work()
        e.askUserWantOt()
        e.generateDTRRecord2(day) # save in file.txt the time in time out record
    e.generateDTRRecord3() # save in file.txt the total of all salary and it's expenses
    print("The program is done, Please open the file", e.user_username + '.txt to see your DTR record')
    print("Thanks for using this program :)")
Пример #11
0
 def testRequestedDays(self):
     day = Employee.myDateTime(1,1)
     self.e.addReqDay(day)
     self.assertEqual(self.e.getReqDays(),{day})
Пример #12
0
#from employee3 import *


# Function definition is here
def printme( st ):
    "This prints a passed string into this function"
    print st;
    return;
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
print "-------------------------------"


"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)

"This would create first object of Employee class"
emp3 = Employee2("Per", 1968)
"This would create second object of Employee class"
emp4 = Employee2("Elsabeth Rodenvall", 1969)

"This would create first object of Employee class"
#emp5 = employee4("Filip", 1998)
"This would create second object of Employee class"
#emp6 = employee4("Jona", 1999)

emp1.displayCount()
emp2.displayEmployee()
Пример #13
0
 def testAlice(self):
     Alice=Employee("Alice", "DUB", "JFK","AAL", "CDG", "SYD")
     airports=Alice.visitList()
     bestRoute=route.permutatuions(airports)
     self.assertEqual(bestRoute,['DUB', 'CDG', 'AAL', 'SYD', 'JFK', 'DUB', 20431])
Пример #14
0
 def testTom(self):
     Tom=Employee("Tom", "LHR", "AMS","SFO", "SIN", "DUB")
     airports=Tom.visitList()
     bestRoute=route.permutatuions(airports)
     self.assertEqual(bestRoute,['LHR', 'AMS', 'SIN', 'SFO', 'DUB', 'LHR', 28524])
Пример #15
0
__author__ = 'Tramel Jones'

import Employee
e = Employee.Employee("Steve Jobs", 700051364)
f = Employee.Employee("Mark Jacobs", 2334512)
g = Employee.Employee("Carl", 14982)

employees = [e, f, g]
print(employees.__str__())
for emp in employees:
    print(emp.__str__())
Пример #16
0
from Employee import TemporarySecretary

print(TemporarySecretary.__mro__)  # MRO(Method Resolution Order)
import hr
import Employee
import Productivity

Manager = Employee.Manager(1, 'Mary Poppins', 1000)
Secretary = Employee.Secretary(2, 'John Scoe', 1000)
SalesPerson = Employee.SalesPerson(3, 'Adil ', 2000, 250)
FactoryWorker = Employee.FactoryWorker(4, 'Adis', 40, 15)
Temporary_Secretary = Employee.TemporarySecretary(5, 'Adarsh', 40, 9)
employees = ([
    Manager, Secretary, SalesPerson, FactoryWorker, Temporary_Secretary
])
Productivity_System = Productivity.ProductivitySystem()
Productivity_System.track(employees, 40)
payroll_system = hr.PayrollSystem()
payroll_system.calculate_payroll(employees)
Пример #17
0
rows = cur.fetchall()

for row in rows:
    object_row = Operating_Cost.Operating_Cost(row[0], row[1], row[2], row[3],
                                               row[4])
    Op_Costs_list.append(object_row)

for item in Op_Costs_list:
    total_opCost += item.get_Operating_Costs()

cur.execute("SELECT * FROM Employees")

rows = cur.fetchall()

for row in rows:
    object_row = Employee.Employee(row[0], row[1], row[2], row[3], row[4])
employees_list.append(object_row)

for item in employees_list:
    total_salaries += item.getSalary()
cur.execute("SELECT * FROM Supplies")
rows = cur.fetchall()

for row in rows:
    object_row = Supply.Supply(row[0], row[1])
supplies_list.append(object_row)

total_expenses = total_SupCost + total_salaries + total_opCost


def MonthlyWindow():
#!/usr/bin/python

#!Creating Classes and Objects

class Employee:

    def __init__(self, name, department, position, is_on_leave):
        self.name = name
        self.department = department
        self.position = position
        self.is_on_leave = is_on_leave

#!Creating an object this data should be on a different file

from "python file" import Employee

employee1 = Employee("Nick", "Engineering", "Senior_Engineer", False)
employee2 = Employee("Ivy", "Human Resource", "Customer Service", True)


print(employee1)
print(employee2)


#!Go ahead and test it out!!!
Пример #19
0
					if (fill(Schedule, Employees, day, shift+1, debug)):
						return True
					else:
						Schedule.clearshift(employee, day, shift)
						#remove employee from shift, next employee
						continue
			else:
				continue
		return False


#tests and what not

sched = s.Schedule()

time = s.Time(20, 17, 20)
temp1 = parse("Text Sample")
emps = []
for i in range(len(temp1)):
		emps.append(e.Employee(temp1[i]))
		


fill(sched, emps, 0, 0, "--")
print sched
for e in emps:
	print e.info()



Пример #20
0
 def setUp(self):
     print("SetUp\n")
     self.emp_1 = Employee('monika', 'dhiman', 50000)
     self.emp_2 = Employee('nitish', 'goswami', 60000)
Пример #21
0
'''
Created on Jul 19, 2017

@author: iaktas
'''

import Employee
import Department
from __builtin__ import int, str
from datetime import datetime

#Create Employees
employeeIrem = Employee.Employee("Irem", "Aktas", "Software Engineer",
                                 "Istanbul", "Real Time Charging & Billing",
                                 "250")
employeeKutyar = Employee.Employee("Kutyar", "Koctas", "Sr Test Engineer",
                                   "Istanbul", "Real Time Charging & Billing",
                                   "350")
employeeDavid = Employee.Employee("David", "Daryl", "Technical Architect",
                                  "Istanbul", "Real Time Charging & Billing",
                                  "450")
employeeAbdullah = Employee.Employee("Abdullah", "Serin", "Solution Architect",
                                     "Istanbul",
                                     "Real Time Charging & Billing", "450")
employeeBulent = Employee.Employee("Bulent", "Tatli", "Project Manager",
                                   "Istanbul", "Real Time Charging & Billing",
                                   "500")
employeeRaphael = Employee.Employee("Raphael", "Chu", "Sales Director",
                                    "Canada", "Sales", "650")
employeeMelahat = Employee.Employee("Melahat", "Garden", "Sales Manager",
                                    "Canada", "Sales", "600")
Пример #22
0
#Program to demonstrate how to use MongoDB with Python

import Employee
import Emp_MongoDB

while True:
	ch=int(input("\n1->New Employee  2->Delete Employee  3->Update Employee  4->Search Employee  5->Display Employees  6->Exit\n"))
	if ch==1:
		e=Employee.Employee()
		e.readEmployee()
		Emp_MongoDB.insertEmployee(e)

	elif ch==2:
		eno=int(input("Enter Empno to delete:"))
		Emp_MongoDB.deleteEmployee(eno)

	elif ch==3:
		eno=int(input("Enter EmpNo to Update:"))
		Emp_MongoDB.updateEmployee(eno)

	elif ch==4:
		eno=int(input("Enter Empno to search:"))
		Emp_MongoDB.searchEmployee(eno)

	elif ch==5:
		Emp_MongoDB.displayEmployees()

	elif ch==6:
		break
Пример #23
0
Creating Instances of Employee class:-
------------------------

emp_1 = Employee()
emp_2 = Employee()
Пример #24
0
from Employee import *
if __name__ == "__main__":
    print "Hello..."
    "This would create first object of Employee class"
    emp1 = Employee("Zara", 2000)
    "This would create second object of Employee class"
    emp2 = Employee("Manni", 5000)

    emp1.displayEmployee()
    emp2.displayEmployee()
    print "Total Employee %d" % Employee.empCount

    #Note:
    #You can add, remove, or modify attributes of classes and objects at any time
    #Very different from Java.
    #Why do we need this feature? If we add attributes to an object from here and there, will it not be a problem to
    #manage it?

    emp1.age = 7  # Add an 'age' attribute.
    emp1.age = 8  # Modify 'age' attribute.
    #del emp1.age  # Delete 'age' attribute.

    print "hasattr(emp1, 'age') : ", hasattr(
        emp1, 'age')  # Returns true if 'age' attribute exists
    getattr(emp1, 'age')  # Returns value of 'age' attribute
    setattr(emp1, 'age', 8)  # Set attribute 'age' at 8
    delattr(emp1, 'age')  # Delete attribute 'age'

    #Built-In Class Attributes

    print "Employee.__doc__:", Employee.__doc__  #Class documentation string or none, if undefined.
Пример #25
0
import GSCashierRegister
import Employee
import ReceiptManagement
import UtilityFunctions

loopCheck = True
print("Costco Employee Login Screen")
while loopCheck == True:
    x = Employee.verifyCredentials()
    print(x)
    if x == True:
        check = True
        while check == True:
            UtilityFunctions.cls()
            print("Costco Options")
            print("1.Cash Register")
            print("2.Receipts")
            print("3.New Employee")
            print("0.Quit")
            choice = int(input("Enter option: "))
            if choice == 1:
                GSCashierRegister.main()
            if choice == 2:
                ReceiptManagement.main()
            if choice == 3:
                Employee.createUser()
            if choice == 0:
                loopcheck = False
                exit()
    else:
        print("Incorrect Credentials. 1 to Retry or 0 to quit")
Пример #26
0
import Employee as e
import classtest as a
import SQLDB

emp = e.Employee("Shah", 200)

##Polymorphism Example.


def makeSound(animalType):
    animalType.sound()


def mytesting():
    emp.displayEmployee()
    emp2 = e.Employee("Imran", 200)
    emp2.displayEmployee()
    print("Employee %d" % emp.empCount)
    try:

        print("Polymorphism Example")
        bearObj = a.Bear()
        dogObj = a.Dog()
        makeSound(bearObj)
        makeSound(dogObj)

        print("Inheritance Example")

        brian = a.User("Brian")
        brian.printName()
Пример #27
0
import Employee


def inputDate():
    surname = input("\nEnter employee\'s surname\n-->")
    yearBirth = int(input("Enter employee\'s year birth\n-->"))
    monthBirth = int(input("Enter employee\'s month birth\n-->"))
    dayBirth = int(input("Enter employee\'s day birth\n-->"))
    return surname, yearBirth, monthBirth, dayBirth


engineProgramLoop = True
while engineProgramLoop == True:
    Employee.Employee().meetUser()

    size = int(input("Enter how many employees, please.\n--> "))
    employeesAgeList = list()
    employeesAgeTo50List = list()

    userChoose = int(
        input(
            "\nIf you want get age employees enter  1\n"
            "If you find days when their turns 50 years or turned 50 years enter 2\n"
            "If you want get age employees and find days when their turns 50 years or turned 50 years enter 3\n--> "
        ))

    i = 0
    if (userChoose == 1):
        while i < size:
            surname, yearBirth, monthBirth, dayBirth = inputDate()
            employee_n = Employee.Employee(surname, yearBirth, monthBirth,
Пример #28
0
def mytesting():
    emp.displayEmployee()
    emp2 = e.Employee("Imran", 200)
    emp2.displayEmployee()
    print("Employee %d" % emp.empCount)
    try:

        print("Polymorphism Example")
        bearObj = a.Bear()
        dogObj = a.Dog()
        makeSound(bearObj)
        makeSound(dogObj)

        print("Inheritance Example")

        brian = a.User("Brian")
        brian.printName()

        diana = a.programmer("Diana")
        diana.printName()
        diana.doPython()

        print("Encapsulation")

        car = a.Car()
        car.drive()
        car.setspeed(300)
        car.drive()

        ##Functional Overloading
        car.setspeed(100, "Toyota")
        car.drive()

        ##Reading Text File
        filename = open("mytextfile.txt", "r")
        handle = filename.readlines()

        wordcount = 0
        for line in handle:
            print(line)
            words = line.split(" ")
            for word in words:
                wordcount += 1

        print(wordcount)

        ##CSV File TEST

        csvfile = a.Workwithcvs()
        csvfile.openfile("Student.csv")
        csvfile.AddHeaderRecord()
        csvfile.AddRecord("Al", "7th", "A+")
        csvfile.AddRecord("Aayan", "5th", "A")
        csvfile.AddRecord("Brian", "MS", "B")
        csvfile.AddRecord("Shah", "MS", "A")

        csvfile.DisplayRecord()

        ##DAtabase Example
        DB = SQLDB.SQLDB(
            "Driver={SQL Server}; server=LENOVO-PC\TESTSQLEXPRESS;database=schoolms;uid=sa;pwd=macrosoft"
        )
        DB.DisplayRecord()

        print("Employee.__doc__:", e.__doc__)
        print("Employee.__name__:", e.__name__)

    except Exception as er:
        print(er.args)
    finally:
        print("Code executed successfully!")
Пример #29
0
import client
import Employee
import sales

client.main()
Employee.main()
sales.main()
Пример #30
0
def Add():
    IDin = Validate("Enter Employee ID: ")
    pay = ValidateN("Enter hourly rate: ",lower=6.00)
    employee = Employee(ID=IDin, wage=pay)
    eList.append(employee)
Пример #31
0
from Employee import*
from Manager import*

emp= Employee("Julia", 200000)

print("Employee %s pay %.2f"% (emp.getFormattedName() ,emp.calculatePay()))
emp= Employee("Anna", 200000, exempt=2)

print("Employee %s pay %.2f"% (emp.getFormattedName() ,emp.calculatePay()))
man=Manager("Hhhm", 10000000, 10000, "BeastMaster")
print("Manager %s pay %.2f"% (man.getFormattedName() ,man.calculatePay()))

Пример #32
0
# -*- coding: utf-8 -*-
import Employee as emp
import EvalShift as eva
"""
Define Employee
"""
e0 = emp.Employee(1, "abe", 3, False, ['mon_a', 'tue_b'])
e1 = emp.Employee(1, "chiba", 4, True, ['sat_b', 'sun_a'])
e2 = emp.Employee(2, "takahashi", 3, False,
                  ['mon_a', 'mon_b', 'tue_a', 'sun_a', 'sun_b'])
e3 = emp.Employee(3, "suzuki", 4, True, ['wed_a', 'wed_b', 'sat_a', 'sat_b'])
e4 = emp.Employee(4, "hayashi", 4, True, ['tue_b', 'thu_a', 'thu_b'])
e5 = emp.Employee(5, "ota", 3, False, ['thu_a', 'thu_b', 'fri_a', 'fri_b'])
e6 = emp.Employee(6, "kato", 3, False, ['wed_a', 'wed_b'])
e7 = emp.Employee(7, "pika", 3, False, [])
e8 = emp.Employee(8, "komori", 3, False, ['mon_a', 'mon_b', 'sun_b'])
e9 = emp.Employee(9, "kobayashi", 4, True,
                  ['tue_b', 'thu_a', 'thu_b', 'fri_a', 'sun_b'])
e10 = emp.Employee(10, "tanaka", 3, False,
                   ['fri_a', 'fri_b', 'sat_a', 'sun_a'])

EMPLOYEES = [e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10]
EMPLOYEE_NUM = len(EMPLOYEES)
DAY_VARIATION_NUM = 2
WEEK_OF_DAY = 7
SHIFT_ALL_NUM = WEEK_OF_DAY * DAY_VARIATION_NUM  # 7 days * 2(a or b)
INDIVIDUAL_NUM = WEEK_OF_DAY * DAY_VARIATION_NUM * EMPLOYEE_NUM
PROBABIRITY = 0.8  # 休暇希望日の要求達成率

NUM = 500  # 個体数
CROSS_PROBABIRTY = 0.9  # 交差確率
Пример #33
0
 def __init__(self):
     self.employees_info = Employee().get_all_db_data()
     self.positions_info = Position().get_all_db_data()
     self.tables_info = Table().get_all_db_data()
Пример #34
0
def main():
    print("\t***** Payroll System *****\n")
    print("*********************************************************")
    print("*\tMilitary time\t\t\t\t\t*")
    print("*\tThis is time for morning 8:00 - 17:00\t\t*")
    print("* \tThis is time for overtime 18:00 - 23:00\t\t*")
    print("*********************************************************\n")
    e = Employee()  # instanciate
    e.logIn()
    e.generateDTRRecord1()  # save in file.txt the personal info of user
    for day in e.days:
        print("Today is", day)
        e.checkDay()
        e.work()
        e.askUserWantOt()
        e.generateDTRRecord2(
            day)  # save in file.txt the time in time out record
    e.generateDTRRecord3(
    )  # save in file.txt the total of all salary and it's expenses
    print("The program is done, Please open the file",
          e.user_username + '.txt to see your DTR record')
    print("Thanks for using this program :)")
Пример #35
0
def create_manager(name):
    return Employee.Manager(name)
Пример #36
0
    async def for_select(self):
        users = await User.select().all()
        assert isinstance(users, db.FetchResult)
        assert users.count == 15
        assert isinstance(users[1], User)
        assert users[0].id == 1
        assert users[0].name == 'at7h'
        assert users[1].id == 2
        assert users[2].id == 4
        assert users[2].name == 'keyoxu'
        assert users[11].name == 'user5'
        assert repr(users[10]) == '<User object at 12>'
        assert str(users[10]) == '<User object at 12>'
        assert users[14].name == 'user8forset'

        users = await User.select(User.id, User.name).where(User.id > 10).all()
        assert users.count == 6
        assert isinstance(users[0], User)
        assert users[1].id == 12
        assert users[1].name == 'user4forsave'
        assert users[1].lastlogin is None
        assert users[2].password is None
        assert users[3].id == 14
        assert users[3].name == 'user6'

        users = await User.select(User.id.as_('uid'),
                                  User.name.as_('username')).where(User.id < 3
                                                                   ).all()
        assert users.count == 2
        assert isinstance(users[0], User)
        assert users[0].id == 1
        assert users[0].name == 'at7h'
        users = await User.select(User.id.as_('uid'),
                                  User.name.as_('username')).where(User.id < 3
                                                                   ).all(False)
        assert users.count == 2
        assert isinstance(users[0], util.adict)
        assert users[0].id == 1
        assert users[0].name == 'at7h'

        users = await User.select().all()
        assert isinstance(users, db.FetchResult)
        assert users.count == 15
        assert users[-1].id == 16
        assert users[-2].name == 'user7'

        users = await User.select().paginate(1, 100, wrap=False)
        assert isinstance(users, db.FetchResult)
        assert users.count == 15
        assert isinstance(users[-1], util.adict)
        assert users[6].id == 8
        assert users[9].age == 3
        users_ = await User.select().paginate(1, 100, wrap=False)
        assert users == users_

        try:
            await User.select().order_by(User.id.desc()).rows(-10)
            assert False, "Should raise ValueError"
        except ValueError:
            pass
        try:
            await User.select().order_by(User.id.desc()).paginate(-1)
            assert False, "Should raise ValueError"
        except ValueError:
            pass
        try:
            await User.select().order_by(User.id.desc()).paginate(1, -1)
            assert False, "Should raise ValueError"
        except ValueError:
            pass

        user = await User.select().order_by(User.id.desc()).first()
        assert isinstance(user, User)
        assert user.id == 16
        assert user.name == 'user8forset'
        user = await (User.select().order_by(User.id.desc()).first(False))
        assert isinstance(user, util.adict)
        assert user.id == 16
        assert user.name == 'user8forset'
        users = await (User.select().order_by(
            User.id.desc()).limit(1).offset(4).all(False))
        user = users[0]
        assert isinstance(user, util.adict)
        assert user.id == 12
        assert user.name == 'user4forsave'
        assert user.age == 4
        users = await (User.select().where(User.id.between(100, 200)).all())
        assert isinstance(users, db.FetchResult)
        assert users.count == 0
        assert users == []
        users = await (User.select().where(User.id.between(100, 200)).rows(1))
        assert isinstance(users, db.FetchResult)
        assert users.count == 0
        assert users == []
        users = await (User.select().where(User.id.between(100, 200)).order_by(
            User.id.desc()).paginate(1))
        assert isinstance(users, db.FetchResult)
        assert users.count == 0
        assert users == []
        users = await (User.select().where(User.id.between(100, 200)).order_by(
            User.create_at.desc()).first())
        assert users is None
        users = await (User.select().where(User.id.between(100, 200)).get())
        assert users is None

        user = await (User.select().order_by(User.age.desc()).get())
        assert isinstance(user, User)
        assert user.age == 90
        assert user.id == 16
        assert user.name == 'user8forset'

        users = await User.select().where(
            User.lastlogin < deltanow(1), User.age < 25,
            User.name != 'at7h').order_by(User.age).rows(10)
        assert users.count == 5
        assert users[1].name == 'user2'
        assert users[4].name == 'mejor'

        users = await User.select().where((User.password == 'xxxx') | (
            User.name.startswith('at'))).all()
        assert users.count == 2
        assert users[0].id == 1
        assert users[0].gender == 0
        assert users[0].name == 'at7h'
        assert users[1].name == 'mejor'
        users = await User.select().where(
            util.or_(User.password == 'xxxx',
                     User.name.startswith('at'))).rows(10, 0)
        assert users.count == 2
        assert users[0].id == 1
        assert users[0].gender == 0
        assert users[0].name == 'at7h'
        assert users[1].name == 'mejor'

        users = await User.select().paginate(1, 5)
        assert users.count == 5
        assert users[-1].id == 6
        users = await User.select().paginate(2, 5)
        assert users.count == 5
        assert users[-1].id == 11

        users = await User.select(User.gender,
                                  t.F.count(t.SQL('1')).as_('num')).group_by(
                                      User.gender).all(False)
        assert users.count == 3
        assert isinstance(users[0], util.adict)
        for user in users:
            if user.gender is None:
                assert user.num == 10
            elif user.gender == 0:
                assert user.num == 2
            elif user.gender == 1:
                assert user.num == 3

        users = await User.select(User.gender,
                                  t.F.count(t.SQL('1')).as_('num')).group_by(
                                      User.gender).all()
        assert users.count == 3
        assert isinstance(users[0], util.adict)

        users = await User.select(User.age,
                                  t.F.count(t.SQL('*')).as_('num')).group_by(
                                      User.age).having(User.age >= 10).all()
        assert users.count == 5
        for user in users:
            if user.age in (18, 25, 28, 90):
                assert user.num == 1
            elif user.age == 45:
                assert user.num == 2

        users = await User.select().order_by(User.name
                                             ).limit(10).offset(7).all()
        assert users.count == 8
        assert isinstance(users[0], User)
        assert users[0].id == 9
        assert users[0].name == 'user1'

        user = await User.select().where(User.name == 'xxxx').exist()
        assert user is False
        user = await User.select().where(User.name == 'at7h').exist()
        assert user is True
        user = await User.select().where(User.age > 10).exist()
        assert user is True
        user = await User.select().where(User.age > 80).exist()
        assert user is True
        user = await User.select().where(User.age > 90).exist()
        assert user is False
        user = await User.select().where(
            User.id.in_(People.select(People.id).where(People.id > 1))).all()
        assert user.count == 0
        user = await User.select().where(
            User.id.in_(
                Employee.select(Employee.id).where(
                    Employee.name.nin_(
                        People.select(People.name).where(People.id > 1))))
        ).all()
        assert user.count == 1

        user_count = await User.select().count()
        assert user_count == 15
        ret = await User.select().join(Employee).all()
        assert ret.count == 15

        ret = await User.select(User.id, Employee.id).join(
            Employee, on=(User.name == Employee.name)).all()
        assert ret.count == 1
        assert ret[0]['id'] == 1
        assert ret[0]['t2.id'] == 1

        assert (await Employee(name='mejor').save()) == 2

        ret = await User.select(User.id, Employee.id).join(
            Employee, on=(User.name == Employee.name)).all()
        assert ret.count == 2
        assert ret[1]['id'] == 2
        assert ret[1]['t2.id'] == 2

        ret = await User.select(User.id, Employee.id).join(
            Employee, JOINTYPE.LEFT, on=(User.name == Employee.name)).all()
        assert ret.count == 15

        ret = await User.select(User.id, User.name, Employee.id).join(
            Employee, JOINTYPE.RIGHT, on=(User.name == Employee.name)).all()
        assert ret.count == 2
        assert ret[0].name == 'at7h'
        assert ret[1].name == 'mejor'

        try:
            await User.select().group_by()
            assert False, "Should raise ValueError"
        except ValueError:
            pass
        try:
            await User.select().group_by(1)
            assert False, "Should raise TypeError"
        except TypeError:
            pass
        try:
            await User.select().order_by()
            assert False, "Should raise ValueError"
        except ValueError:
            pass
        try:
            await User.select().order_by(1)
            assert False, "Should raise TypeError"
        except TypeError:
            pass
        try:
            await User.select().offset(1)
            assert False, "Should raise err.ProgrammingError"
        except err.ProgrammingError:
            pass

        s = User.select(User.name).where(User.name == 'at7h')
        q = _builder.Query(
            'SELECT `t1`.`name` FROM `helo`.`user_` AS `t1` '
            'WHERE (`t1`.`name` = %s);',
            params=['at7h'])
        assert str(s) == str(q)
        assert repr(s) == repr(q)

        # test funcs and scalar
        user_count = await User.select().count()
        assert user_count == 15

        user_count = await User.select().where(User.age > 25).count()
        assert user_count == 4

        user_count = await User.select().where(User.id.in_(list(range(10)))
                                               ).count()
        assert user_count == 8

        users = await User.select(User.age).all()
        sum_age = 0
        for u in users:
            if u.age is not None:
                sum_age += u.age
        assert sum_age == 261

        age_sum = await User.select(t.F.sum(User.age)).scalar()
        assert age_sum == 261

        user_count = await User.select(t.F.count(User.age).as_('age_count')
                                       ).where(User.age > 25).get()
        assert user_count == {'age_count': 4}

        user_count = await User.select(t.F.count(User.age)
                                       ).where(User.gender == 0).scalar()
        assert user_count == 2

        user_count = await User.select(t.F.max(User.age)).where(User.age > 25
                                                                ).scalar()
        assert user_count == 90

        age_max = await User.select(t.F.sum(User.age)).where(User.age > 25
                                                             ).scalar()
        assert age_max == 208
Пример #37
0
def create_contract_employee(name, rate=46):
    return Employee.ContractEmployee(name, rate)
Пример #38
0
    async def for_save_and_remove(self):
        user = User(name='at7h', gender=0, age=25)
        uid = await user.save()
        assert uid == 1
        assert user.id == 1
        assert user.password is None
        assert user.lastlogin is None

        user = User(name='mejor',
                    gender=1,
                    age=22,
                    password='******',
                    nickname='huhu',
                    lastlogin=datetime.datetime.now())
        uid = await user.save()
        assert uid == 2
        assert user.id == 2
        assert user.age == 22
        assert user.nickname == 'huhu'
        assert user.password == 'xxxx'
        assert isinstance(user.lastlogin, datetime.datetime)

        user.age = 18
        user.gender = 0
        uid = await user.save()
        assert uid == 2
        user = await User.get(2)
        assert user.id == 2
        assert user.nickname == 'huhu'
        assert user.password == 'xxxx'
        assert user.age == 18
        assert user.gender == 0

        try:
            user = User(id=3,
                        name='mejor',
                        gender=1,
                        age=22,
                        password='******',
                        nickname='huhu',
                        lastlogin=datetime.datetime.now())
            assert False, "Should raise err.NotAllowedError"
        except err.NotAllowedError:
            pass

        user = User(name='keyoxu',
                    gender=1,
                    age=28,
                    password='******',
                    nickname='jiajia',
                    lastlogin=datetime.datetime.now())
        uid = await user.save()
        assert uid == 3
        ret = await user.remove()
        assert ret == 1
        user = User(name='n')
        try:
            await user.remove()
            assert False, "Should raise RuntimeError"
        except RuntimeError:
            pass

        employee = Employee(name='at7h', email='*****@*****.**')
        assert (await employee.save()) == 1
        try:
            await Employee(email='[email protected]').save()
            assert False, "Should raise ValueError"
        except ValueError:
            pass
Пример #39
0
Файл: L3.py Проект: Hellocxc/L3
import Employee

countent = help(Employee)

print countent
countent1 = dir(Employee.__package__)
print countent1

emp1 = Employee("Zara", 2000)
emp2 = Employee("Manni", 5000)

emp1.displayEmployee()
Пример #40
0
 def testBob(self):
     Bob=Employee("Bob", "DUB", "LHR","AMS", "AAL", "CDG")
     airports=Bob.visitList()
     bestRoute=route.permutatuions(airports)
     self.assertEqual(bestRoute,['DUB', 'LHR', 'CDG', 'AMS', 'AAL', 'DUB', 2106])