index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
62,350 | theduderog/Superlance | refs/heads/master | /superlance/process_state_email_monitor.py | #!/usr/bin/env python -u
##############################################################################
#
# Copyright (c) 2007 Agendaless Consulting and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the BSD-like license at
# http://www.repoze.org/LICENSE.txt. A copy of the license should accompany
# this distribution. THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL
# EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND
# FITNESS FOR A PARTICULAR PURPOSE
#
##############################################################################
import os
import sys
import smtplib
import copy
from email.mime.text import MIMEText
from superlance.process_state_monitor import ProcessStateMonitor
doc = """\
Base class for common functionality when monitoring process state changes
and sending email notification
"""
class ProcessStateEmailMonitor(ProcessStateMonitor):
@classmethod
def createFromCmdLine(cls):
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-i", "--interval", dest="interval", type="int",
help="batch interval in minutes (defaults to 1 minute)")
parser.add_option("-t", "--toEmail", dest="toEmail",
help="destination email address")
parser.add_option("-f", "--fromEmail", dest="fromEmail",
help="source email address")
parser.add_option("-s", "--subject", dest="subject",
help="email subject")
(options, args) = parser.parse_args()
if not options.toEmail:
parser.print_help()
sys.exit(1)
if not options.fromEmail:
parser.print_help()
sys.exit(1)
if not 'SUPERVISOR_SERVER_URL' in os.environ:
sys.stderr.write('Must run as a supervisor event listener\n')
sys.exit(1)
return cls(**options.__dict__)
def __init__(self, **kwargs):
ProcessStateMonitor.__init__(self, **kwargs)
self.fromEmail = kwargs['fromEmail']
self.toEmail = kwargs['toEmail']
self.subject = kwargs.get('subject', 'Alert from supervisord')
self.digestLen = 20
def sendBatchNotification(self):
email = self.getBatchEmail()
if email:
self.sendEmail(email)
self.logEmail(email)
def logEmail(self, email):
email4Log = copy.copy(email)
if len(email4Log['body']) > self.digestLen:
email4Log['body'] = '%s...' % email4Log['body'][:self.digestLen]
self.writeToStderr("Sending notification email:\nTo: %(to)s\n\
From: %(from)s\nSubject: %(subject)s\nBody:\n%(body)s\n" % email4Log)
def getBatchEmail(self):
if len(self.batchMsgs):
return {
'to': self.toEmail,
'from': self.fromEmail,
'subject': self.subject,
'body': '\n'.join(self.getBatchMsgs()),
}
return None
def sendEmail(self, email):
msg = MIMEText(email['body'])
msg['Subject'] = email['subject']
msg['From'] = email['from']
msg['To'] = email['to']
s = smtplib.SMTP('localhost')
s.sendmail(email['from'], [email['to']], msg.as_string())
s.quit()
| {"/superlance/process_state_email_monitor.py": ["/superlance/process_state_monitor.py"], "/superlance/tests/process_state_email_monitor_test.py": ["/superlance/process_state_email_monitor.py"], "/superlance/tests/process_state_monitor_test.py": ["/superlance/process_state_monitor.py"]} |
62,351 | theduderog/Superlance | refs/heads/master | /superlance/tests/fatalmailbatch_test.py | import unittest
import mock
import time
from StringIO import StringIO
class FatalMailBatchTests(unittest.TestCase):
fromEmail = 'testFrom@blah.com'
toEmail = 'testTo@blah.com'
subject = 'Test Alert'
now = 1279677400.1
unexpectedErrorMsg = '2010-07-20 18:56:40,099 -- Process bar:foo \
failed to start too many times'
def _getTargetClass(self):
from superlance.fatalmailbatch import FatalMailBatch
return FatalMailBatch
def _makeOneMocked(self, **kwargs):
kwargs['stdin'] = StringIO()
kwargs['stdout'] = StringIO()
kwargs['stderr'] = StringIO()
kwargs['fromEmail'] = kwargs.get('fromEmail', self.fromEmail)
kwargs['toEmail'] = kwargs.get('toEmail', self.toEmail)
kwargs['subject'] = kwargs.get('subject', self.subject)
kwargs['now'] = self.now
obj = self._getTargetClass()(**kwargs)
obj.sendEmail = mock.Mock()
return obj
def getProcessFatalEvent(self, pname, gname):
headers = {
'ver': '3.0', 'poolserial': '7', 'len': '71',
'server': 'supervisor', 'eventname': 'PROCESS_STATE_FATAL',
'serial': '7', 'pool': 'checkmailbatch',
}
payload = 'processname:%s groupname:%s from_state:BACKOFF' \
% (pname, gname)
return (headers, payload)
def test_getProcessStateChangeMsg(self):
crash = self._makeOneMocked()
hdrs, payload = self.getProcessFatalEvent('foo', 'bar')
msg = crash.getProcessStateChangeMsg(hdrs, payload)
self.assertEquals(self.unexpectedErrorMsg, msg)
if __name__ == '__main__':
unittest.main() | {"/superlance/process_state_email_monitor.py": ["/superlance/process_state_monitor.py"], "/superlance/tests/process_state_email_monitor_test.py": ["/superlance/process_state_email_monitor.py"], "/superlance/tests/process_state_monitor_test.py": ["/superlance/process_state_monitor.py"]} |
62,352 | theduderog/Superlance | refs/heads/master | /superlance/process_state_monitor.py | #!/usr/bin/env python -u
##############################################################################
#
# Copyright (c) 2007 Agendaless Consulting and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the BSD-like license at
# http://www.repoze.org/LICENSE.txt. A copy of the license should accompany
# this distribution. THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL
# EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND
# FITNESS FOR A PARTICULAR PURPOSE
#
##############################################################################
doc = """\
Base class for common functionality when monitoring process state changes
"""
import os
import sys
from supervisor import childutils
class ProcessStateMonitor:
# In child class, define a list of events to monitor
processStateEvents = []
def __init__(self, **kwargs):
self.interval = kwargs.get('interval', 1)
self.debug = kwargs.get('debug', False)
self.stdin = kwargs.get('stdin', sys.stdin)
self.stdout = kwargs.get('stdout', sys.stdout)
self.stderr = kwargs.get('stderr', sys.stderr)
self.batchMsgs = []
self.batchMins = 0
def run(self):
while 1:
hdrs, payload = childutils.listener.wait(self.stdin, self.stdout)
self.handleEvent(hdrs, payload)
childutils.listener.ok(self.stdout)
def handleEvent(self, headers, payload):
if headers['eventname'] in self.processStateEvents:
self.handleProcessStateChangeEvent(headers, payload)
elif headers['eventname'] == 'TICK_60':
self.handleTick60Event(headers, payload)
def handleProcessStateChangeEvent(self, headers, payload):
msg = self.getProcessStateChangeMsg(headers, payload)
if msg:
self.writeToStderr('%s\n' % msg)
self.batchMsgs.append(msg)
"""
Override this method in child classes to customize messaging
"""
def getProcessStateChangeMsg(self, headers, payload):
return None
def handleTick60Event(self, headers, payload):
self.batchMins += 1
if self.batchMins >= self.interval:
self.sendBatchNotification()
self.clearBatch()
"""
Override this method in child classes to send notification
"""
def sendBatchNotification(self):
pass
def getBatchMinutes(self):
return self.batchMins
def getBatchMsgs(self):
return self.batchMsgs
def clearBatch(self):
self.batchMins = 0;
self.batchMsgs = [];
def writeToStderr(self, msg):
self.stderr.write(msg)
self.stderr.flush() | {"/superlance/process_state_email_monitor.py": ["/superlance/process_state_monitor.py"], "/superlance/tests/process_state_email_monitor_test.py": ["/superlance/process_state_email_monitor.py"], "/superlance/tests/process_state_monitor_test.py": ["/superlance/process_state_monitor.py"]} |
62,353 | theduderog/Superlance | refs/heads/master | /superlance/tests/process_state_email_monitor_test.py | import unittest
import mock
import time
from StringIO import StringIO
class ProcessStateEmailMonitorTests(unittest.TestCase):
fromEmail = 'testFrom@blah.com'
toEmail = 'testTo@blah.com'
subject = 'Test Alert'
def _getTargetClass(self):
from superlance.process_state_email_monitor \
import ProcessStateEmailMonitor
return ProcessStateEmailMonitor
def _makeOneMocked(self, **kwargs):
kwargs['stdin'] = StringIO()
kwargs['stdout'] = StringIO()
kwargs['stderr'] = StringIO()
kwargs['fromEmail'] = kwargs.get('fromEmail', self.fromEmail)
kwargs['toEmail'] = kwargs.get('toEmail', self.toEmail)
kwargs['subject'] = kwargs.get('subject', self.subject)
obj = self._getTargetClass()(**kwargs)
obj.sendEmail = mock.Mock()
return obj
def test_sendBatchNotification(self):
testMsgs = ['msg1', 'msg2']
monitor = self._makeOneMocked()
monitor.batchMsgs = testMsgs
monitor.sendBatchNotification()
#Test that email was sent
self.assertEquals(1, monitor.sendEmail.call_count)
emailCallArgs = monitor.sendEmail.call_args[0]
self.assertEquals(1, len(emailCallArgs))
expected = {
'body': 'msg1\nmsg2',
'to': 'testTo@blah.com',
'from': 'testFrom@blah.com',
'subject': 'Test Alert',
}
self.assertEquals(expected, emailCallArgs[0])
#Test that email was logged
self.assertEquals("""Sending notification email:
To: testTo@blah.com
From: testFrom@blah.com
Subject: Test Alert
Body:
msg1
msg2
""", monitor.stderr.getvalue())
def test_logEmail_with_body_digest(self):
monitor = self._makeOneMocked()
email = {
'to': 'you@fubar.com',
'from': 'me@fubar.com',
'subject': 'yo yo',
'body': 'a' * 30,
}
monitor.logEmail(email)
self.assertEquals("""Sending notification email:
To: you@fubar.com
From: me@fubar.com
Subject: yo yo
Body:
aaaaaaaaaaaaaaaaaaaa...
""", monitor.stderr.getvalue())
self.assertEquals('a' * 30, email['body'])
def test_logEmail_without_body_digest(self):
monitor = self._makeOneMocked()
email = {
'to': 'you@fubar.com',
'from': 'me@fubar.com',
'subject': 'yo yo',
'body': 'a' * 20,
}
monitor.logEmail(email)
self.assertEquals("""Sending notification email:
To: you@fubar.com
From: me@fubar.com
Subject: yo yo
Body:
aaaaaaaaaaaaaaaaaaaa
""", monitor.stderr.getvalue())
if __name__ == '__main__':
unittest.main() | {"/superlance/process_state_email_monitor.py": ["/superlance/process_state_monitor.py"], "/superlance/tests/process_state_email_monitor_test.py": ["/superlance/process_state_email_monitor.py"], "/superlance/tests/process_state_monitor_test.py": ["/superlance/process_state_monitor.py"]} |
62,354 | theduderog/Superlance | refs/heads/master | /superlance/tests/process_state_monitor_test.py | import unittest
import mock
import time
from StringIO import StringIO
from superlance.process_state_monitor import ProcessStateMonitor
class TestProcessStateMonitor(ProcessStateMonitor):
processStateEvents = ['PROCESS_STATE_EXITED']
def getProcessStateChangeMsg(self, headers, payload):
return repr(payload)
class ProcessStateMonitorTests(unittest.TestCase):
def _getTargetClass(self):
return TestProcessStateMonitor
def _makeOneMocked(self, **kwargs):
kwargs['stdin'] = StringIO()
kwargs['stdout'] = StringIO()
kwargs['stderr'] = StringIO()
obj = self._getTargetClass()(**kwargs)
obj.sendBatchNotification = mock.Mock()
return obj
def getProcessExitedEvent(self, pname, gname, expected,
eventname='PROCESS_STATE_EXITED'):
headers = {
'ver': '3.0', 'poolserial': '7', 'len': '71',
'server': 'supervisor', 'eventname': eventname,
'serial': '7', 'pool': 'checkmailbatch',
}
payload = 'processname:%s groupname:%s from_state:RUNNING expected:%d \
pid:58597' % (pname, gname, expected)
return (headers, payload)
def getTick60Event(self):
headers = {
'ver': '3.0', 'poolserial': '5', 'len': '15',
'server': 'supervisor', 'eventname': 'TICK_60',
'serial': '5', 'pool': 'checkmailbatch',
}
payload = 'when:1279665240'
return (headers, payload)
def test_handleEvent_exit(self):
monitor = self._makeOneMocked()
hdrs, payload = self.getProcessExitedEvent('foo', 'bar', 0)
monitor.handleEvent(hdrs, payload)
unexpectedErrorMsg = repr(payload)
self.assertEquals([unexpectedErrorMsg], monitor.getBatchMsgs())
self.assertEquals('%s\n' % unexpectedErrorMsg, monitor.stderr.getvalue())
def test_handleEvent_non_exit(self):
monitor = self._makeOneMocked()
hdrs, payload = self.getProcessExitedEvent('foo', 'bar', 0,
eventname='PROCESS_STATE_FATAL')
monitor.handleEvent(hdrs, payload)
self.assertEquals([], monitor.getBatchMsgs())
self.assertEquals('', monitor.stderr.getvalue())
def test_handleEvent_tick_interval_expired(self):
monitor = self._makeOneMocked()
#Put msgs in batch
hdrs, payload = self.getProcessExitedEvent('foo', 'bar', 0)
monitor.handleEvent(hdrs, payload)
hdrs, payload = self.getProcessExitedEvent('bark', 'dog', 0)
monitor.handleEvent(hdrs, payload)
self.assertEquals(2, len(monitor.getBatchMsgs()))
#Time expired
hdrs, payload = self.getTick60Event()
monitor.handleEvent(hdrs, payload)
#Test that batch messages are now gone
self.assertEquals([], monitor.getBatchMsgs())
#Test that email was sent
self.assertEquals(1, monitor.sendBatchNotification.call_count)
def test_handleEvent_tick_interval_not_expired(self):
monitor = self._makeOneMocked(interval=3)
hdrs, payload = self.getTick60Event()
monitor.handleEvent(hdrs, payload)
self.assertEquals(1, monitor.getBatchMinutes())
monitor.handleEvent(hdrs, payload)
self.assertEquals(2, monitor.getBatchMinutes())
if __name__ == '__main__':
unittest.main() | {"/superlance/process_state_email_monitor.py": ["/superlance/process_state_monitor.py"], "/superlance/tests/process_state_email_monitor_test.py": ["/superlance/process_state_email_monitor.py"], "/superlance/tests/process_state_monitor_test.py": ["/superlance/process_state_monitor.py"]} |
62,362 | ravioli0509/agent_officer_UI | refs/heads/master | /agent.py | import time, sqlite3, datetime, re, getpass
def register_birth(user,conn):
# The agent should be able to register a birth by providing the first name, the last name, the gender, the birth date,
# the birth place of the newborn, as well as the first and last names of the parents.
# The registration date is set to the day of registration (today's date) and the registration place is set to the city of the user.
# The system should automatically assign a unique registration number to the birth record.
# The address and the phone of the newborn are set to those of the mother.
# If any of the parents is not in the database, the system should get information about the parent including first name, last name,
# birth date, birth place, address and phone. For each parent, any column other than the first name and last name can be null if it is not provided.
c = conn.cursor()
# Get inputs from user
while True:
fname = input("First name: ")
# cancel command aborts operation and returns to main menu
if fname.lower() == "cancel":
return
# Checks to see if input is not only whitespace or no input
elif not fname.isspace() and fname != '':
break
# Loops until valid input is obtained
print("Please enter a first name.")
while True:
lname = input("Last name: ")
if lname.lower() == "cancel":
return
elif not lname.isspace() and lname !='':
break
print("Please enter a last name")
# Check to see if person already exists in database
c.execute('''SELECT * FROM persons WHERE fname=:fname COLLATE NOCASE AND lname=:lname COLLATE NOCASE''',{'fname':fname,'lname':lname})
if c.fetchone() != None:
print("Person already exists, can not register birth for this person")
return
while True:
gender = input("Gender (M/F): ")
if gender.lower() == "cancel":
return
elif gender.lower() =="f" or gender.lower() == "m":
break
print("Invalid Gender")
# Checks to see if date is valid
validdate = False
while validdate == False:
bdate = input("Birth date (YYYY-MM-DD): ")
if bdate.lower() == "cancel":
return
else:
validdate = True
try:
# Splits input into year month and day
year,month,day = bdate.split("-")
# Checks to see values are valid (ie. month isn't greater than 12 or day isn't greater than 31)
datetime.datetime(int(year),int(month),int(day))
except ValueError:
# If input is not valid, cycle through loop until input is valid
validdate = False
print("Invalid date")
while True:
blocation = input("Birth Location: ")
if blocation.lower() == "cancel":
return
elif not blocation.isspace() and blocation !='':
break
print("Please enter the location where the person was born")
while True:
f_fname = input("Father's first name: ")
if f_fname.lower() == "cancel":
return
elif not f_fname.isspace() and f_fname !='':
break
print("Please enter the father's first name")
while True:
f_lname = input("Father's last name: ")
if f_lname.lower() == "cancel":
return
elif not f_lname.isspace() and f_lname!='':
break
print("Please enter the father's last name")
while True:
m_fname = input("Mother's first name: ")
if m_fname.lower() == "cancel":
return
elif not m_fname.isspace() and m_fname!='':
break
print("Please enter the mother's first name")
while True:
m_lname = input("Mother's last name: ")
if m_lname.lower() == "cancel":
return
elif not m_lname.isspace() and m_lname!='':
break
print("Please enter the mother's last name")
# Check to see if father input is in database
c.execute('''SELECT * FROM persons WHERE (fname = :f_fname COLLATE NOCASE AND lname = :f_lname COLLATE NOCASE) ''',{'f_fname':f_fname,'f_lname':f_lname})
father = c.fetchone()
# Get details of father if not in database
if father == None:
print("Father has no entry in database, Please input details")
if addPerson(conn, f_fname,f_lname) == None:
return
# Get father's details
c.execute('''SELECT * FROM persons WHERE (fname = :f_fname COLLATE NOCASE AND lname = :f_lname COLLATE NOCASE)''',{'f_fname':f_fname,'f_lname':f_lname})
father = c.fetchone()
# Check to see if mother input is in database
c.execute('''SELECT * FROM persons WHERE (fname = :m_fname COLLATE NOCASE AND lname = :m_lname COLLATE NOCASE)''',{'m_fname':m_fname,'m_lname':m_lname})
mother = c.fetchone()
# Get details of mother if not in database
if mother == None:
print("Mother has no entry in database, Please input details")
if addPerson(conn,m_fname,m_lname) == None:
return
# Get mother's details
c.execute('''SELECT * FROM persons WHERE (fname = :m_fname COLLATE NOCASE AND lname = :m_lname COLLATE NOCASE)''',{'m_fname':m_fname,'m_lname':m_lname})
mother = c.fetchone()
# Assign unique registration number
c.execute('''SELECT MAX(regno) FROM births''')
regno = c.fetchone()
if regno[0] == None:
regno = 1
else:
regno = int(regno[0])+1
date = datetime.datetime.now().strftime("%Y-%m-%d")
# Create new person
c.execute('''INSERT INTO persons VALUES (:fname,:lname,:bdate,:blocation,:address,:phone)''',{'fname':fname,'lname':lname,'bdate':bdate,'blocation':blocation,'address':mother[4],'phone':mother[5]})
conn.commit()
# Create new birth registration
c.execute('''INSERT INTO births VALUES (:regno,:fname,:lname,:regdate,:regplace,:gender,:f_fname,:f_lname,:m_fname,:m_lname)''',{'regno':regno,'fname':fname,'lname':lname,'regdate':date,'regplace':user[5],'gender':gender,'f_fname':f_fname,'f_lname':f_lname,'m_fname':m_fname,'m_lname':m_lname})
conn.commit()
input("Birth registration successfully added (Press Enter to Proceed)")
def register_marriage(user,conn):
# The user should be able to provide the names of the partners and the system should assign the registration date and place and a unique registration number as discussed in registering a birth.
# If any of the partners is not found in the database, the system should get information about the partner including first name, last name, birth date, birth place, address and phone.
# For each partner, any column other than the first name and last name can be null if it is not provided.
c = conn.cursor()
# Get both partners' first and last names
while True:
p1_fname = input("Enter partner 1's first name: ")
if p1_fname.lower() == "cancel":
return
elif not p1_fname.isspace() and p1_fname != '':
break
print("Please enter the first name of partner 1.")
while True:
p1_lname = input("Enter partner 1's last name: ")
if p1_lname.lower() == "cancel":
return
elif not p1_lname.isspace() and p1_lname!= '':
break
print("Please enter the last name of partner 1.")
while True:
p2_fname = input("Enter partner 2's first name: ")
if p2_fname.lower() == "cancel":
return
elif not p2_fname.isspace() and p2_fname!= '':
break
print("Please enter the first name of partner 2.")
while True:
p2_lname = input("Enter partner 2's last name: ")
if p2_lname.lower() == "cancel":
return
elif not p2_lname.isspace() and p2_lname!= '':
break
print("Please enter the last name of partner 2.")
# Check to see if partner 1 is in database
c.execute('''SELECT * FROM persons WHERE (fname = :p1_fname COLLATE NOCASE AND lname = :p1_lname COLLATE NOCASE) ''', {'p1_fname':p1_fname,'p1_lname':p1_lname})
p1 = c.fetchone()
# Get details of partner 1 if not in database
if p1 == None:
print("Partner 1 has no entry in database, please input details")
if addPerson(conn,p1_fname,p1_lname) == None:
return
c.execute('''SELECT * FROM persons WHERE (fname = :p1_fname COLLATE NOCASE AND lname = :p1_lname COLLATE NOCASE) ''', {'p1_fname':p1_fname,'p1_lname':p1_lname})
p1 = c.fetchone()
# Check to see if partner 2 is in database
c.execute('''SELECT * FROM persons WHERE (fname = :p2_fname COLLATE NOCASE AND lname = :p2_lname COLLATE NOCASE) ''', {'p2_fname':p2_fname,'p2_lname':p2_lname})
p2 = c.fetchone()
# get details of partner 2 if not in databse
if p2 == None:
print("Partner 2 has no entry in database, please input details")
if addPerson(conn,p2_fname,p2_lname) == None:
return
c.execute('''SELECT * FROM persons WHERE (fname = :p2_fname COLLATE NOCASE AND lname = :p2_lname COLLATE NOCASE) ''', {'p2_fname':p2_fname,'p2_lname':p2_lname})
p2 = c.fetchone()
# Create unique registration number
c.execute('''SELECT MAX(regno) FROM marriages''')
regno = c.fetchone()
if regno[0] == None:
regno = 1
else:
regno = int(regno[0])+1
regdate = datetime.datetime.now().strftime("%Y-%m-%d")
# Insert marriage registration
c.execute('''INSERT INTO marriages VALUES (:regno,:regdate,:regplace,:p1_fname,:p1_lname,:p2_fname,:p2_lname)''', {'regno':regno,'regdate':regdate,'regplace':user[5],'p1_fname':p1_fname,'p1_lname':p1_lname,'p2_fname':p2_fname,'p2_lname':p2_lname})
conn.commit()
input("Marriage Registration successfully added (Press Enter to Proceed)")
def renew_vehicle_registration(conn):
# The user should be able to provide an existing registration number and renew the registration.
# The system should set the new expiry date to one year from today's date if the current registration either has expired or expires today.
# Otherwise, the system should set the new expiry to one year after the current expiry date.
c = conn.cursor()
while True:
# Get registration number from user
regno = input("Registration Number: ")
# Check to see if regno is a number
if regno.isdigit():
c.execute('''SELECT * FROM registrations WHERE regno =:regno''',{'regno':regno})
registry = c.fetchone()
if not registry == None:
exdate = registry[2]
year,month,day = exdate.split("-")
expdate = datetime.datetime(int(year),int(month),int(day))
if expdate < datetime.datetime.now():
expdate = datetime.datetime.now()
exdate = datetime.datetime(expdate.year+1,expdate.month,expdate.day).strftime("%Y-%m-%d")
c.execute('''UPDATE registrations SET expiry=:expiry WHERE regno = :regno''',{'expiry':exdate,'regno':regno})
conn.commit()
input("Registration successfully updated (Press Enter to Proceed)")
break
elif regno.lower() == "cancel":
break
print("Invalid registration number")
def process_bill(conn):
# The user should be able to record a bill of sale by providing the vin of a car, the name of the current owner, the name of the new owner, and a plate number for the new registration.
# If the name of the current owner (that is provided) does not match the name of the most recent owner of the car in the system, the transfer cannot be made.
# When the transfer can be made, the expiry date of the current registration is set to today's date and a new registration under the new owner's name is recorded with the registration date and the expiry date set by the system to today's date and a year after today's date respectively.
# Also a unique registration number should be assigned by the system to the new registration.
# The vin will be copied from the current registration to the new one.
c = conn.cursor()
# Get Vechicle identification number
while True:
vin = input("Vechicle Identification Number (VIN): ")
if vin.lower() == "cancel":
return
elif vin.isdigit():
c.execute("SELECT * FROM registrations WHERE vin =:vin ORDER BY regdate",{'vin':vin})
cur_reg = c.fetchone()
if cur_reg == None:
print("Invalid VIN")
else:
break
# Get current owner's first name and last name
while True:
while True:
cur_fname = input("Current owner's first name: ")
if cur_fname.lower() == "cancel":
return
elif not cur_fname.isspace() and cur_fname != '':
break
while True:
cur_lname = input("Current owner's last name: ")
if cur_lname.lower() == "cancel":
return
elif not cur_lname.isspace() and cur_lname != '':
break
# Check to see if input is correct
if cur_fname.lower() == cur_reg[5].lower() and cur_lname.lower() == cur_reg[6].lower():
break
print("Name entered does not correspond to current owner's name")
print("Please enter current owner's name")
# Get new owner's first name and last name
while True:
while True:
new_fname = input("New owner's first name: ")
if new_fname.lower() == "cancel":
return
elif not new_fname.isspace() and new_fname != '':
break
print("Please enter the new owner's first name")
while True:
new_lname = input("New owner's last name: ")
if new_lname.lower() == "cancel":
return
elif not new_lname.isspace() and new_lname != '':
break
print("Please enter the new owner's last name")
# Check to see if person exists in the database
c.execute('''SELECT * FROM persons WHERE fname=:fname AND lname=:lname''',{'fname':new_fname,'lname':new_lname})
if c.fetchone() == None:
print("Person to transfer ownership to does not exist")
else:
break
while True:
lic_plate = input("New Licence Plate Number: ")
if lic_plate.lower() == 'cancel':
return
elif not lic_plate.isspace() and lic_plate != '':
break
# Get current date
today = datetime.datetime.now().strftime("%Y-%m-%d")
# Get date one year from now
nextyear = datetime.datetime(datetime.datetime.now().year+1,datetime.datetime.now().month,datetime.datetime.now().day)
# Create unique registration number
c.execute('''SELECT MAX(regno) FROM registrations''')
regno = c.fetchone()
if regno[0] == None:
regno = 1
else:
regno = int(regno[0])+1
# Change expiry of old owner to today's date
c.execute('''UPDATE registrations SET expiry=:expiry WHERE regno=:regno''',{'expiry':today,'regno':cur_reg[0]})
conn.commit()
# Create new registration for new owner
c.execute('''INSERT INTO registrations VALUES (:regno,:regdate,:expiry,:plate,:vin,:fname,:lname)''',{'regno':regno,'regdate':today,'expiry':nextyear,'plate':lic_plate,'vin':vin,'fname':new_fname,'lname':new_lname})
conn.commit()
input("Ownership successfully transferred (Press Enter to Proceed)")
def process_payment(conn):
# The user should be able to record a payment by entering a valid ticket number and an amount.
# The payment date is automatically set to the day of the payment (today's date).
# A ticket can be paid in multiple payments but the sum of those payments cannot exceed the fine amount of the ticket.
c = conn.cursor()
validation = True
while True:
# Get tno from user
tno = input("Please enter the ticket number (tno): ")
if tno.lower() == 'cancel':
return
# Check to see if tno is a number
elif tno.isdigit():
# Check to see if tno has a corresponding ticket
c.execute('''SELECT *, fine FROM tickets WHERE tno=:tno''', {'tno':tno})
ticket = c.fetchone()
# No ticket associated with given ticket number
if ticket == None:
print("Invalid ticket number, please enter a valid ticket number.")
else:
validation = False
while validation == False:
# Get fine amount of ticket
c.execute('''SELECT fine FROM tickets WHERE tno=:tno''', {'tno':tno})
info = c.fetchone()
amount = int(info[0])
# Get current amount payed for
c.execute('''SELECT SUM(amount) FROM payments WHERE tno=:tno''', {'tno':tno})
info_1 = c.fetchone()[0]
if info_1 == None:
sum_amount = 0
else:
sum_amount = int(info_1)
# If ticket already paid for
if (amount-sum_amount) <= 0:
input("This ticket has already been paid for. (Press Enter to Continue)")
return
# Check if payment has been made today (since unique key: tno + ddate)
c.execute('''SELECT * FROM payments WHERE tno=:tno AND pdate = date('now','localtime')''', {'tno':tno})
check = c.fetchone()
if check != None:
input("You have already processed your payment today for tno: "+ str(tno) +" (Press Enter to Continue)")
return
# Get how much user wants to pay
while True:
print("You still owe $"+ str(amount-sum_amount) + ".")
payment = input("Please enter the payment ($): ")
if payment.lower() == 'cancel':
return
elif payment.isdigit():
if ((amount - sum_amount - int(payment)) < 0):
print("Payment is over the amount you owe.")
else:
validation = True
break
update_date = datetime.datetime.now().strftime("%Y-%m-%d")
break
# Add payment to payments table
c.execute('''INSERT INTO payments VALUES (:tno,:pdate,:amount)''',{'tno':tno,'pdate':update_date,'amount':payment})
conn.commit()
input("Payment successfully processed (Press Enter to Proceed)")
def get_driver_abstract(conn):
# The user should be able to enter a first name and a last name and get a driver abstract,
# which includes the number of tickets, the number of demerit notices, the total number of demerit points received both within the past two years and within the lifetime.
# The user should be given the option to see the tickets ordered from the latest to the oldest.
# For each ticket, you will report the ticket number, the violation date, the violation description, the fine, the registration number and the make and model of the car for which the ticket is issued.
# If there are more than 5 tickets, at most 5 tickets will be shown at a time, and the user can select to see more.
c = conn.cursor()
# Get first name and last name of person to get information about
while True:
fname = input("First name: ")
if fname.lower() == "cancel":
return
elif not fname.isspace() and fname != '':
break
while True:
lname = input("Last name: ")
if lname.lower() == "cancel":
return
elif not fname.isspace() and fname != '':
break
# Get number of tickets in person's lifetime
c.execute('''SELECT count(tno) FROM registrations LEFT JOIN tickets ON registrations.regno = tickets.regno WHERE fname=:fname COLLATE NOCASE and lname=:lname COLLATE NOCASE GROUP BY fname,lname''',{'fname':fname,'lname':lname})
numTickets = c.fetchone()
if numTickets == None:
numTickets = 0
else:
numTickets = numTickets[0]
# Get number of tickets in last two years
c.execute('''SELECT count(tno) FROM registrations LEFT JOIN tickets ON registrations.regno = tickets.regno WHERE fname=:fname COLLATE NOCASE and lname=:lname COLLATE NOCASE AND vdate>datetime('now','-2 years') GROUP BY fname,lname''',{'fname':fname,'lname':lname})
rec_numTickets = c.fetchone()
if rec_numTickets == None:
rec_numTickets = 0
else:
rec_numTickets = rec_numTickets[0]
# Get number of demerit notices in person's lifetime
c.execute('''SELECT count(points) FROM demeritNotices WHERE fname=:fname COLLATE NOCASE and lname=:lname COLLATE NOCASE GROUP BY fname,lname''',{'fname':fname,'lname':lname})
numDemerits = c.fetchone()
if numDemerits == None:
numDemerits = 0
else:
numDemerits = numDemerits[0]
# Get number of demerit notices in last two years
c.execute('''SELECT count(points) FROM demeritNotices WHERE fname=:fname COLLATE NOCASE and lname=:lname COLLATE NOCASE AND ddate>datetime('now','-2 years') GROUP BY fname,lname''',{'fname':fname,'lname':lname})
rec_numDemerits = c.fetchone()
if rec_numDemerits == None:
rec_numDemerits = 0
else:
rec_numDemerits = rec_numDemerits[0]
# Get number of demerit points in last two years
c.execute('''SELECT sum(points) FROM demeritNotices WHERE fname=:fname COLLATE NOCASE and lname=:lname COLLATE NOCASE AND ddate>datetime('now','-2 years') GROUP BY fname,lname''',{'fname':fname,'lname':lname})
recentDemeritPoints = c.fetchone()
if recentDemeritPoints == None:
recentDemeritPoints = 0
else:
recentDemeritPoints = recentDemeritPoints[0]
# Get number of demerit points in person's lifetime
c.execute('''SELECT sum(points) FROM demeritNotices WHERE fname=:fname COLLATE NOCASE and lname=:lname COLLATE NOCASE GROUP BY fname,lname''',{'fname':fname,'lname':lname})
totalDemeritPoints = c.fetchone()
if totalDemeritPoints == None:
totalDemeritPoints = 0
else:
totalDemeritPoints = totalDemeritPoints[0]
print("Number of tickets in the last two years:",rec_numTickets)
print("Number of tickets within entire lifetime:",numTickets)
print("Number of demerit notices in the last two years:",rec_numDemerits)
print("Number of demerit notices within entire lifetime:",numDemerits)
print("Number of demerit points in the last two years:",recentDemeritPoints)
print("Number of demerit points within entire lifetime:",totalDemeritPoints)
if int(numTickets)>0:
while True:
# Ask user if ticket details should be printed
getTickets = input("Get tickets? (y/n): ")
if getTickets.lower() == 'y':
c.execute('''SELECT * FROM registrations LEFT JOIN tickets ON registrations.regno = tickets.regno INNER JOIN vehicles ON registrations.vin = vehicles.vin WHERE fname=:fname COLLATE NOCASE and lname=:lname COLLATE NOCASE AND tno IS NOT NULL ORDER BY vdate DESC''',{'fname':fname,'lname':lname})
tickets = c.fetchall()
print("TNO | Ticket date | Description | Fine Amount | Regno | Vehicle")
for i in range(len(tickets)):
print(tickets[i][7],'|',tickets[i][11],'|',tickets[i][10],'|',tickets[i][9],'|',tickets[i][8],'|',tickets[i][13],'|',tickets[i][14])
# Everytime 5 tickets have been printed, ask if more should be printed
if (i+1)%5==0:
while True:
getTickets = input('Continue getting tickets? (y/n): ')
if getTickets.lower() == 'y':
break
elif getTickets.lower() == 'n':
return
break
elif getTickets.lower() == 'n':
break
input("(Press Enter to Proceed)")
def addPerson(conn,fname,lname):
# get first name and last name inputs from previous functions
c = conn.cursor()
print("First Name: "+fname)
print("Last Name: "+lname)
validdate = False
while not validdate:
bdate = input("Birth date (YYYY-MM-DD): ")
if bdate.lower() == "cancel":
return
elif bdate.isspace() or bdate=='':
bdate = None
break
else:
validdate = True
try:
year,month,day = bdate.split("-")
datetime.datetime(int(year),int(month),int(day))
except ValueError:
validdate = False
print("Invalid date")
blocation = input("Birth Location: ")
if blocation.lower() == "cancel":
return
elif blocation.isspace() or blocation =='':
blocation = None
address = input("Current Address: ")
if address.lower() == "cancel":
return
elif address.isspace() or address == '':
address = None
phone = input("Current Phone Number: ")
if phone.lower() == "cancel":
return
elif phone.isspace() or phone == '':
phone = None
c.execute('''INSERT INTO persons VALUES (:fname,:lname,:bdate,:bplace,:address,:phone)''',{'fname':fname,'lname':lname,'bdate':bdate,'bplace':blocation,'address':address,'phone':phone})
conn.commit()
return 1 | {"/project.py": ["/agent.py", "/traffic_officer.py"]} |
62,363 | ravioli0509/agent_officer_UI | refs/heads/master | /project.py | import time, sqlite3, datetime, re, getpass,os, sys
import agent, traffic_officer
def login(c,uid,pwd):
c.execute('''SELECT * FROM users WHERE uid = :username;''',{'username':uid})
user = c.fetchone()
if user == None:
return None
elif pwd == user[1]:
return user
else:
return None
def agent_menu(user,conn):
action = None
while action != 8 or action.lower()=="exit":
os.system('clear')
print("Agent Menu:")
print("1. Register a birth")
print("2. Register a marriage")
print("3. Renew a vehicle registration")
print("4. Process a bill of sale")
print("5. Process a payment")
print("6. Get a driver abstract")
print("7. Logout")
print("8. Exit")
action = input("Enter the number to which the action corresponds to: ")
if action == '1':
os.system('clear')
agent.register_birth(user,conn)
elif action == '2':
os.system('clear')
agent.register_marriage(user,conn)
elif action == "3":
os.system('clear')
agent.renew_vehicle_registration(conn)
elif action == "4":
os.system('clear')
agent.process_bill(conn)
elif action == '5':
os.system('clear')
agent.process_payment(conn)
elif action == '6':
os.system('clear')
agent.get_driver_abstract(conn)
elif action == '7' or action.lower()=="logout":
os.system('clear')
return
elif action == '8' or action.lower()=="exit":
os.system('clear')
sys.exit()
else:
os.system('clear')
print ("Invalid Action.")
def traffic_officer_menu(user,conn):
action = None
while action != 4 or action.lower()=="exit":
os.system('clear')
print("Traffic Officer Menu:")
print("1. Issue a ticket")
print("2. Find a car owner")
print("3. Logout")
print("4. Exit")
action = input("Enter the number to which the action corresponds to: ")
if action == '1':
os.system('clear')
traffic_officer.issue_ticket(conn)
elif action == '2':
os.system('clear')
traffic_officer.find_car_owner(conn)
elif action == '3' or action.lower()=="logout":
os.system('clear')
return
elif action == '4' or action.lower()=="exit":
os.system('clear')
sys.exit()
else:
os.system('clear')
print("Invalid Action.")
def main():
if len(sys.argv)>2 or len(sys.argv)<2:
print("Invalid number of arguments")
return
conn = sqlite3.connect(sys.argv[1],timeout=30)
c = conn.cursor()
while True:
os.system('clear')
user = None
while user == None:
uid = input("UID: ")
pwd = getpass.getpass("PWD: ")
user = login(c,uid,pwd)
if user == None:
os.system('clear')
print("Invalid user ID or password")
if user[2] == 'a':
agent_menu(user,conn)
elif user[2] == 'o':
traffic_officer_menu(user,conn)
main() | {"/project.py": ["/agent.py", "/traffic_officer.py"]} |
62,364 | ravioli0509/agent_officer_UI | refs/heads/master | /traffic_officer.py | import time, sqlite3, datetime, re, getpass
def issue_ticket(conn):
# The user should be able to provide a registration number and see the person name that is listed in the registration and the make, model, year and color of the car registered.
# Then the user should be able to proceed and ticket the registration by providing a violation date, a violation text and a fine amount.
# A unique ticket number should be assigned automatically and the ticket should be recorded.
# The violation date should be set to today's date if it is not provided.
c = conn.cursor()
while True:
regno = input("Enter Registration Number: ")
if regno.lower() == 'cancel':
return
elif regno.isdigit():
c.execute('''SELECT fname, lname FROM registrations WHERE regno =:regno''',{'regno':regno})
names = c.fetchone()
if names == None:
print("Error, the registration doesn't exist on the database. Try again")
else:
print("First Name: ", names[0])
print("Last Name: ", names[1])
c.execute(''' SELECT make, model, year, color FROM registrations LEFT JOIN vehicles ON registrations.vin = vehicles.vin WHERE regno =:regno''', {'regno':regno})
car = c.fetchone()
print("Vehicle details: ")
print("Make: ", car[0])
print("Model: ", car[1])
print("Year: ", car[2])
print("Color: ", car[3])
v_text = input("Enter the violation text: ")
if v_text.isspace() or v_text == '':
v_text = None
fine = input("Enter the fine amount ($): ")
while True:
check_date = input("Is the violation date today? (Y/N)")
if check_date.lower() == 'y':
v_date = datetime.datetime.now().strftime("%Y-%m-%d")
break
elif check_date.lower() == 'n':
validdate = False
while validdate == False:
v_date = input("Enter the violation date (YYYY-MM-DD): ")
validdate = True
try:
year,month,day = v_date.split("-")
datetime.datetime(int(year),int(month),int(day))
except ValueError:
validdate = False
print("Invalid date")
break
elif check_date.lower() != 'y' or 'n':
print("Please choose an option")
c.execute('''SELECT MAX(tno) FROM tickets''')
tno = c.fetchone()
if tno[0] == None:
tno = 1
else:
tno = int(tno[0])+1
break
else:
print("Invalid Registration Number")
c.execute('''INSERT INTO tickets VALUES (:tno,:regno,:fine,:violation,:vdate)''', {'tno':tno,'regno':regno,'fine':fine,'violation':v_text,'vdate':v_date})
conn.commit()
input("Ticket Successfully Issued (Press Enter to Continue)")
def find_car_owner(conn):
# The user should be able to look for the owner of a car by providing one or more of make, model, year, color, and plate.
# The system should find and return all matches.
# If there are more than 4 matches, you will show only the make, model, year, color, and the plate of the matching cars and let the user select one.
# When there are less than 4 matches or when a car is selected from a list shown earlier, for each match, the make, model, year, color, and the plate of the matching car will be shown
# as well as the latest registration date, the expiry date, and the name of the person listed in the latest registration record.
c = conn.cursor()
while True:
make = input('make: ')
if make.lower() == "cancel":
return
model = input('model: ')
if model.lower() == "cancel":
return
while True:
year = input('year: ')
if year.lower() == "cancel":
return
elif year.isdigit() or year.isspace() or year =='':
break
else:
print("Invalid Year")
color = input('color: ')
if color.lower() == "cancel":
return
plate = input('plate: ')
if plate.lower() == "cancel":
return
given_params = []
params = {}
if not make.isspace() and make != '':
given_params.append('make=:make COLLATE NOCASE')
params['make']=make
if not model.isspace() and model != '':
given_params.append("model=:model COLLATE NOCASE")
params['model']=model
if not year.isspace() and year != '':
given_params.append('year=:year')
params['year']=year
if not color.isspace() and color != '':
given_params.append("color=:color COLLATE NOCASE")
params['color']=color
if not plate.isspace() and plate != '':
given_params.append("plate=:plate COLLATE NOCASE")
params['plate']=plate
if given_params:
break
else:
print("Please provide at least one detail.")
c.execute('''SELECT * FROM vehicles WHERE ''' + ' AND '.join(given_params), params)
searchcar = c.fetchall()
index = 1
# 4 or more matches
if len(searchcar) >= 4:
for car in searchcar:
c.execute('''SELECT * FROM registrations WHERE vin=:vin''', {'vin':car[0]})
carreg = c.fetchone()
# make, model, year, color, and the plate
print(str(index) + ": " + car[1] + ", " + car[2] + ", " + str(car[3]) + ", " + car[4] + ", " + carreg[3])
index += 1
while True:
selectcarnum = input ("Select one or type 'cancel' to return: ")
if selectcarnum.lower() == 'cancel':
return
elif selectcarnum.isdigit() and int(selectcarnum)>=0 and int(selectcarnum)<=index:
selectcarnum = int(selectcarnum)-1
c.execute('''SELECT * FROM registrations WHERE vin=:vin ORDER BY regdate DESC''', {'vin':searchcar[selectcarnum][0]})
selectedcarreg = c.fetchone()
# make, model, year, color, and the plate
print("Selected: " + str(searchcar[selectcarnum][1]) + ", " + str(searchcar[selectcarnum][2]) + ", " + str(searchcar[selectcarnum][3]) + ", " + str(selectedcarreg[3]))
# latest registration date, the expiry date, and the name of the person listed in the latest registration record.
print("reg date: " + str(selectedcarreg[1]))
print("expiry date: " + str(selectedcarreg[2]))
print("owner: " + str(selectedcarreg[5]) + " " + str(selectedcarreg[6]))
else:
print('Invalid Option')
# less than four matches
else:
for car in searchcar:
c.execute('''SELECT * FROM registrations WHERE vin=:vin ORDER BY regdate DESC''', {'vin':car[0]})
carreg = c.fetchone()
print(str(index) + ": " + car[1] + ", " + car[2] + ", " + str(car[3]) + ", " + car[4] + ", " + carreg[3])
print("reg date: " + carreg[1])
print("expiry date: " + carreg[2])
print("owner: " + carreg[5] + " " + carreg[6])
print('')
index += 1
input("(Press Enter to Proceed)") | {"/project.py": ["/agent.py", "/traffic_officer.py"]} |
62,388 | escramer/freecellv2 | refs/heads/master | /search.py | """Depth first search, breadth first search, and A*
See https://en.wikipedia.org/wiki/A*_search_algorithm
"""
from collections import deque
from heapq import heappush, heappop
import logging
from time import time
_INFINITY = float('inf')
class _OpenSet(object):
"""An object for pushing on states and popping them off."""
def push(self, state, cost):
"""Put this state in this open set if possible.
This will return whether or not the state can be pushed.
:param cost: the cost to go from the parent state to this state
:type cost: integer
"""
raise NotImplementedError
def pop(self):
"""Remove and return a state. Raise an IndexError if the set is empty."""
raise NotImplementedError
def empty(self):
"""Return whether or not this open set is empty."""
raise NotImplementedError
def __len__(self):
"""Return the length of this open set."""
raise NotImplementedError
class _Stack(_OpenSet):
"""A stack"""
def __init__(self):
"""Initialize."""
self._stack = []
def push(self, state, _):
"""Put the state in this stack."""
self._stack.append(state)
return True
def pop(self):
"""Remove and return a state. Raise an IndexError if the stack is empty."""
self._stack.pop()
def empty(self):
"""Return whether or not this stack is empty."""
return len(self._stack) == 0
def __len__(self):
"""Return the length."""
return len(self._stack)
class _Queue(_OpenSet):
"""A queue"""
def __init__(self):
"""Initialize."""
self._queue = deque()
def push(self, state, _):
"""Put this state in this queue."""
self._queue.append(state)
return True
def pop(self):
"""Remove and return a state. Raise an IndexError if the stack is empty."""
self._queue.popleft()
def empty(self):
"""Return whether or not this queue is empty."""
return len(self._queue) == 0
def __len__(self):
"""Return the length."""
return len(self._queue)
class _PriorityQueue(_OpenSet):
"""A priority queue that uses F score"""
def __init__(self, heuristic):
"""Initialize.
:param heuristic: the heuristic function that maps a state to an integer
:type heuristic: function
"""
self._heuristic = heuristic
self._heap = []
self._g_score = {}
self._last_g_score = None # g score of the last state returned from pop
def push(self, state, cost):
"""Put this state in this priority queue. Return whether or not it can push.
:param cost: the cost to go from the parent state to this state
:type cost: integer
Its parent is assumed to be the last state returned from pop.
"""
if self._last_g_score is None:
g_score = 0
else:
g_score = self._last_g_score + cost
if g_score >= self._g_score.get(state, _INFINITY):
return False
self._g_score[state] = g_score
heappush(self._heap, (g_score + self._heuristic(state), state))
return True
def pop(self):
"""Remove and return a state."""
rtn = heappop(self._heap)[1]
self._last_g_score = self._g_score[rtn]
return rtn
def empty(self):
"""Return whether or not the priority queue is empty."""
return len(self._heap) == 0
def __len__(self):
"""Return the length."""
return len(self._heap)
class Problem(object):
"""Represents a problem.
Subclass this with your own problem.
"""
def initial_state(self):
"""Return the initial state."""
raise NotImplementedError
def is_goal(self, state):
"""Return whether or not this state is the goal state."""
raise NotImplementedError
def neighbors(self, state):
"""Return a list of (state, cost) tuples that can be reached from this state."""
raise NotImplementedError
def move_description(self, from_state, to_state):
"""Return a string describing the transition between the two states.
e.g. 'Move 3H home'.
"""
raise NotImplementedError
class NoSolutionError(Exception):
"""Represents no solution."""
pass
def _reconstruct_path(current, came_from, problem):
"""Return a list of moves.
:param current: the final state
:type current: a state
:param came_from: maps a state to its parent
:type came_from: dict
:param problem: a problem
:type problem: Problem
"""
rtn = []
while current in came_from:
parent = came_from[current]
rtn.append(problem.move_description(parent, current))
current = parent
return reversed(rtn)
def _search(problem, open_set):
"""Return a list of moves from the start node to the end node.
:param problem: The problem
:type problem: Problem
:param open_set: The empty open set
:type open_set: _OpenSet
This may raise a NoSolutionError.
"""
logging.info('Starting search')
closed = set()
came_from = {}
open_set.push(problem.initial_state(), 0)
last_time = int(time())
while not open_set.empty():
new_time = int(time())
if new_time >= last_time + 10:
logging.info('Open set size: %s' % len(open_set))
last_time = new_time
current = open_set.pop()
if problem.is_goal(current):
logging.info('Found solution')
return _reconstruct_path(current, came_from, problem)
closed.add(current)
for neighbor, cost in problem.neighbors(current):
if neighbor in closed:
continue
if open_set.push(neighbor, cost):
came_from[neighbor] = current
raise NoSolutionError
def astar(problem, heuristic):
"""Return a list of moves from the start node to the end node using A*.
:param problem: The problem
:type problem: Problem
:param heuristic: the heuristic that takes in a state and returns an integer
:type heuristic: function
This may raise a NoSolutionError.
"""
return _search(problem, _PriorityQueue(heuristic))
def dfs(problem):
"""Return a list of moves from the start node to the end node using depth first search.
:param problem: The problem
:type problem: Problem
This may raise a NoSolutionError.
"""
return _search(problem, _Stack())
def bfs(problem):
"""Return a list of moves from the start node to the end node using breadth first search.
:param problem: The problem
:type problem: Problem
This may raise a NoSolutionError.
"""
return _search(problem, _Queue()) | {"/test_freecell.py": ["/freecell.py"]} |
62,389 | escramer/freecellv2 | refs/heads/master | /test_freecell.py | import pytest
from freecell import Card, FreeCellProblem
def test_card():
"""Test the Card class."""
card = Card(1, 2)
assert card.rank_str == 'A'
assert card.rank_int == 1
assert card.suit_str == 'C'
assert card.suit_int == 2
assert str(card) == 'AC'
assert not card.is_red
assert card.type == (1, False)
assert card.next_type is None
assert card.tup == (1, 2)
card = Card(5, 1)
assert card.next_type == (4, False)
class TestFreeCellProblem:
prob = FreeCellProblem('init_state.csv')
@staticmethod
def _equal_no_order(lst1, lst2):
"""Return whether or not these lists are equal without regards to order."""
return isinstance(lst1, list) and isinstance(lst2, list) and set(lst1) == set(lst2)
def test_init(self):
"""Test the __init__ method."""
assert self.prob.initial_state() == (0, 0, 0, 0, frozenset([]), frozenset(['5S7D5DJHQC4H', '2H9SJS6HKSTCTS', 'KC5H2DAC8HQD9D', '2SAH2CQS4C7S', '4S8D3HTDTH8C3S', 'JC5CKHQH9H6C7H', 'ADKD8S6D6SAS', '3D4D3C7C9CJD']))
with pytest.raises(ValueError):
FreeCellProblem('bad_state.csv')
def test_is_red(self):
assert self.prob._is_red('H')
assert self.prob._is_red(0)
def test_card_tup(self):
assert self.prob._card_tup('3C') == (3, 2)
def test_card_str(self):
assert self.prob._card_str((3, 2)) == '3C'
def test_is_goal(self):
state = (13, 13, 13, 13, frozenset(), frozenset())
assert self.prob.is_goal(state)
state = (13, 13, 13, 12, frozenset(), frozenset())
assert not self.prob.is_goal(state)
def test_meeets_need(self):
assert self.prob._meets_need((3, 2), (3, False))
assert not self.prob._meets_need((3, 2), (4, False))
def test_remove_card_from_col(self):
tab = frozenset(['3H6C', '4DKD'])
assert self.prob._remove_card_from_col(tab, '4DKD') == {'3H6C', '4D'}
tab = frozenset(['3H6C', '4D'])
assert self.prob._remove_card_from_col(tab, '4D') == {'3H6C'}
def test_add_card_to_col(self):
tab = frozenset(['3H6C', '4DKD'])
assert self.prob._add_card_to_col(tab, '3H6C', '8S') == {'3H6C8S', '4DKD'}
def test_add_card_to_new_col(self):
tab = frozenset(['3H6C'])
assert self.prob._add_card_to_new_col(tab, '8S') == {'3H6C', '8S'}
def test_add_card_to_free(self):
assert self.prob._add_card_to_free(frozenset(['8S']), '3D') == frozenset(['8S', '3D'])
def test_remove_card_from_free(self):
assert self.prob._remove_card_from_free(frozenset(['8S', '3D']), '3D') == frozenset(['8S'])
def test_to_home(self):
needed_home = {(3, 2)}
state = (13, 13, 2, 13, frozenset(), frozenset())
assert self.prob._to_home(state, needed_home, (3, 2)) == (13, 13, 3, 13)
assert self.prob._to_home(state, needed_home, (4, 2)) is None
def test_remove_from_home(self):
state = (4, 8, 9, 0, frozenset(), frozenset())
assert self.prob._remove_from_home(state, (8, 1)) == (4, 7, 9, 0)
def test_to_tab(self):
tab = frozenset(['3H6C', '6S', 'TD'])
needed_tab = {
(5, True): ['3H6C', '6S'],
(9, False): ['TD']
}
result = self.prob._to_tab(tab, needed_tab, (5, 1))
assert isinstance(result, list) and set(result) == {
frozenset(['3H6C5H', '6S', 'TD']),
frozenset(['3H6C', '6S5H', 'TD']),
frozenset(['3H6C', '6S', 'TD', '5H'])
}
tab = frozenset(['3H', 'AC', '7C', 'JD', '9S', '9D', 'KH', '7S'])
needed_tab = {
(2, False): ['3H'],
(6, True): ['7C', '7S'],
(10, False): ['JD'],
(8, True): ['9S'],
(8, False): ['9D'],
(12, False): ['KH']
}
assert self.prob._to_tab(tab, needed_tab, (2, 0)) == []
def test_card_type(self):
assert self.prob._card_type((5, 2)) == (5, False)
def test_within_tab(self):
tab = frozenset(['3H6C', '6S'])
av_tab = self.prob._av_tab(tab)
needed_tab = self.prob._needed_tab(av_tab)
assert self.prob._within_tab(tab, needed_tab, av_tab) == [frozenset(['3H', '6S', '6C'])]
tab = frozenset(['AC', 'AS', 'AD', 'AH', '3C', '3S', '3D', '3H'])
av_tab = self.prob._av_tab(tab)
needed_tab = self.prob._needed_tab(av_tab)
assert self.prob._within_tab(tab, needed_tab, av_tab) == []
tab = frozenset(['AC', 'AS', 'AD', 'AH', '3H6C', '7H', 'KD8C', 'JDTD'])
av_tab = self.prob._av_tab(tab)
needed_tab = self.prob._needed_tab(av_tab)
result = self.prob._within_tab(tab, needed_tab, av_tab)
assert isinstance(result, list) and set(result) == {
frozenset(['AC', 'AS', 'AD', 'AH', '3H', '7H6C', 'KD8C', 'JDTD']),
frozenset(['AC', 'AS', 'AD', 'AH', '3H6C', 'KD8C7H', 'JDTD'])
}
def test_new_state(self):
state = (3, 8, 10, 0, frozenset(['3H']), frozenset(['6C8C', '9S3C']))
assert self.prob._new_state(state) == state
assert self.prob._new_state(state, free=frozenset()) == \
(3, 8, 10, 0, frozenset(), frozenset(['6C8C', '9S3C']))
def test_av_home(self):
state = (3, 8, 10, 0, frozenset(), frozenset())
assert self.prob._av_home(state) == {(3, 0), (8, 1), (10, 2)}
def test_needed_home(self):
state = (3, 8, 13, 0, frozenset(), frozenset())
assert self.prob._needed_home(state) == {(4, 0), (9, 1), (1, 3)}
def test_av_tab(self):
tab = frozenset(['3H6C', '6S'])
assert self.prob._av_tab(tab) == {(6, 2): '3H6C', (6, 3): '6S'}
def test_needed_tab(self):
av_tab = {(1, 1): '4HAH', (9, 2): '4D9C', (13, 0): 'KD', (13, 1): 'KH'}
result = self.prob._needed_tab(av_tab)
assert isinstance(result, dict)
assert set(result) == {(8, True), (12, False)}
assert result[(8, True)] == ['4D9C']
assert self._equal_no_order(result[(12, False)], ['KD', 'KH'])
| {"/test_freecell.py": ["/freecell.py"]} |
62,390 | escramer/freecellv2 | refs/heads/master | /freecell.py | #! /usr/bin/env python
"""A Freecell solver"""
import argparse
import csv
import logging
from search import Problem, astar, dfs
_MAX_RANK = 13
_MAX_COLS = 8
_MAX_FREE_CELLS = 4
_DECK_SIZE = 52
_SUIT_LST = ('D', 'H', 'C', 'S')
_RANK_LST = (None, 'A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K')
class Card(object):
"""Represents a card."""
_rank_map = {rank_str: rank_int for rank_int, rank_str in enumerate(_RANK_LST) if rank_str is not None}
def __init__(self, rank, suit):
"""Initialize.
:param rank: the rank
:type rank: int
:param suit: the suit
:type suit: int
"""
self.rank_str = _RANK_LST[rank]
self.rank_int = rank
self.suit_str = _SUIT_LST[suit]
self.suit_int = suit
self._str = '%s%s' % (self.rank_str, self.suit_str)
self.is_red = is_red(self.suit_str)
self.type = (rank, self.is_red)
self.next_type = (rank - 1, not self.is_red) if rank > 1 else None # Next card type in tableau
self.tup = (rank, suit)
def __str__(self):
return self._str
@classmethod
def get_rank_int(cls, rank_str):
"""Return the integer rank for this rank string.
:param rank_str: a rank
:type rank_str: string
"""
return cls._rank_map[rank_str]
def is_red(suit):
"""Return whether or not this suit is red.
:param suit: a suit
:type suit: string or int
"""
if isinstance(suit, str):
return suit in ('D', 'H')
else:
return _SUIT_LST[suit] in ('D', 'H')
class FreeCellProblem(Problem):
"""A FreeCell problem
Description of a state:
Each card is 2-character string.
Each column is a string containing the concatenated cards. The last two
characters are the playable card.
The state is a tuple:
0: Rank of card on home cell for suit 0
1: Rank of card on home cell for suit 1
2: Rank of card on home cell for suit 2
3: Rank of card on home cell for suit 3
4: Set of free cells
5: Set of columns (tableau)
"""
def __init__(self, filename):
"""Initialize from this board layout.
:param filename: the name of the csv file
:type filename: string
"""
self._cards = self._deck() # Use this to get precomputed Card objects.
# Get each card's next card in rank
self._next_in_rank = {}
for card in self._cards.itervalues():
if card.rank_int != _MAX_RANK:
new_rank = card.rank_int + 1
suit = card.suit_int
self._next_in_rank[card] = self._cards[(new_rank, suit)]
# Suit color
self._is_red = [is_red(suit) for suit in _SUIT_LST]
self._opp_color = [] # self._opp_color[i] is the set of suits opposite in color from i
self._sibling_suit = [] # self._sibling_suit[i] is the other suit of the same color as i
for suit in xrange(4):
is_red_ = self._is_red[suit]
opp_colors = set()
for other_suit in xrange(4):
if self._is_red[other_suit] != is_red_:
opp_colors.add(other_suit)
elif other_suit != suit:
self._sibling_suit.append(other_suit)
self._opp_color.append(opp_colors)
deck = set(str(card) for card in self._cards.itervalues())
tableau = set()
with open(filename) as file_obj:
for row in csv.reader(file_obj):
# Ignore commented rows
if not row or not row[0] or row[0].isspace() or row[0][0] == '#':
continue
column = ''
for card in row:
card = card.upper()
deck.remove(card)
column += card
tableau.add(column)
if len(deck) > 0:
raise ValueError('Missing cards: %s' % deck)
self._init_state = (0, 0, 0, 0, frozenset(), frozenset(tableau))
@staticmethod
def _deck():
"""Return a deck of cards.
More specifically, return a dictionary mapping a string (such as '3H')
and its corresponding (rank, suit) tuple (for '3H', this is (3, 1))
to its Card.
"""
rtn = {}
for suit_ndx in xrange(4):
for rank_ndx in xrange(1, _MAX_RANK+1):
card = Card(rank_ndx, suit_ndx)
rtn[str(card)] = card
rtn[card.tup] = card
return rtn
def initial_state(self):
"""Return the initial state."""
return self._init_state
def is_goal(self, state):
"""Return whether or not this is the goal."""
for suit in xrange(4):
if state[suit] != _MAX_RANK:
return False
return True
@staticmethod
def _remove_card_from_col(tableau, col):
"""Remove a card from the column.
:param tableau: the set of columns
:type tableau: frozenset or set
:param col: the column
:type col: string
This returns the modified tableau.
i.e.
If tableau is a frozenset, this will return a new set.
If tableau is a set, this will return it.
"""
if isinstance(tableau, frozenset):
tableau = set(tableau)
tableau.remove(col)
col = col[:-2]
if col:
tableau.add(col)
return tableau
@staticmethod
def _add_card_to_col(tableau, col, card):
"""Add a card to a column.
:param tableau: the set of columns
:type tableau: set or frozenset
:param col: a column
:type col: string
:param card: a card
:type card: Card
This returns the modified tableau.
i.e.
If tableau is a frozenset, this will return a new set.
If tableau is a set, this will return it.
"""
if isinstance(tableau, frozenset):
tableau = set(tableau)
tableau.remove(col)
col += str(card)
tableau.add(col)
return tableau
@staticmethod
def _add_card_to_new_col(tableau, card):
"""Put this card in a new column.
:param tableau: the set of columns
:type tableau: frozenset or set
:param card: a card
:type card: Card
This returns the modified tableau.
i.e.
If tableau is a frozenset, this will return a new set.
If tableau is a set, this will return it.
"""
if isinstance(tableau, frozenset):
tableau = set(tableau)
tableau.add(str(card))
return tableau
@staticmethod
def _add_card_to_free(freecells, card):
"""Add this card to a free cell.
:param freecells: the free cells (set of strings)
:type freecells: frozenset
:param card: a card
:type card: Card
This returns freecells as a new frozenset.
"""
freecells = set(freecells)
freecells.add(str(card))
return frozenset(freecells)
@staticmethod
def _remove_card_from_free(freecells, card):
"""Remove this card from the free cells.
:param freecells: the free cells (set of strings)
:type freecells: frozenset
:param card: a card
:type card: Card
This returns freecells as a new frozenset.
"""
freecells = set(freecells)
freecells.remove(str(card))
return frozenset(freecells)
@staticmethod
def _to_home(state, needed_home, card):
"""Return a tuple of the 4 home cells as a result of adding this card to home.
If the card cannot be added, return None.
:param needed_home: a set of Cards needed
:type needed_home: set
:param card: a card
:type card: Card
"""
if card in needed_home:
rtn = list(state[:4])
rtn[card.suit_int] = card.rank_int
return tuple(rtn)
else:
return None
@staticmethod
def _remove_from_home(state, card):
"""Return a tuple of the 4 home cells as a result of removing this card.
:param card: a card
:type card: Card
"""
home = list(state[:4])
home[card.suit_int] -= 1
return tuple(home)
def _to_tab(self, tab, needed_tab, card):
"""Return a list of tableaus resulting from putting this card in the tableau
from outside the tableau.
:param tab: a tableau
:type tab: frozenset
:param needed_tab: maps a (rank, is_red) tuple (card that's needed) to a list of columns
:type needed_tab: dict
:param card: a card
:type card: Card
The new tableaus will be frozensets.
"""
rtn = []
if len(tab) < _MAX_COLS:
rtn.append(frozenset(self._add_card_to_new_col(tab, card)))
for col in needed_tab.get(card.type, []):
rtn.append(frozenset(self._add_card_to_col(tab, col, card)))
return rtn
def _within_tab(self, tab, needed_tab, av_tab):
"""Return a list of tableaus resulting from moving a card within the tableau.
:param tab: a tableau
:type tab: frozenset
:param needed_tab: maps a (rank, is_red) tuple (card that's needed) to a list of columns
:type needed_tab: dict
:param av_tab: maps a Card to its column
:type av_tab: dict
The new tableaus will be frozensets.
"""
rtn = []
for av_card, from_col in av_tab.iteritems():
if len(from_col) > 2 and len(tab) < _MAX_COLS:
new_tab = self._remove_card_from_col(tab, from_col)
new_tab = self._add_card_to_new_col(new_tab, av_card)
rtn.append(frozenset(new_tab))
for to_col in needed_tab.get(av_card.type, []):
new_tab = self._remove_card_from_col(tab, from_col)
new_tab = self._add_card_to_col(new_tab, to_col, av_card)
rtn.append(frozenset(new_tab))
return rtn
@staticmethod
def _new_state(state, home=None, free=None, tab=None):
"""Return a new state with some modifications.
If any of the options are not None, they will appear in the new state. Otherwise,
whatever's in "state" will appear in the new state.
:param home: the home cells
:type home: tuple
:param free: the free cells
:type free: frozenset
:param tab: the tableau
:type tab: frozenset
"""
if home is None:
home = state[:4]
if free is None:
free = state[4]
if tab is None:
tab = state[5]
return home + (free, tab)
def _av_home(self, state):
"""Return the set of available home cells."""
rtn = set()
for suit_ndx in xrange(4):
rank = state[suit_ndx]
if rank > 0:
rtn.add(self._cards[(rank, suit_ndx)])
return rtn
def _needed_home(self, state):
"""Return the set of needed cards to go home."""
rtn = set()
for suit in xrange(4):
rank = state[suit]
if rank < _MAX_RANK:
rtn.add(self._cards[(rank+1, suit)])
return rtn
def _av_tab(self, tab):
"""Return the available cards in the tableau.
:param tab: the tableau
:type tab: frozenset
More specifically, this returns a dictionary mapping a Card to its column.
"""
return {self._cards[col[-2:]]: col for col in tab}
@staticmethod
def _needed_tab(av_tab):
"""Return the cards that are needed in the tableau.
:param av_tab: the available cards in the tableau (from self._av_tab)
:type av_tab: dict
More specifically, return a dictionary mapping a (rank, is_red) tuple to a list of columns.
"""
rtn = {}
for card, col in av_tab.iteritems():
if card.rank_int > 1:
needed = card.next_type
if needed in rtn:
rtn[needed].append(col)
else:
rtn[needed] = [col]
return rtn
def _automatic_cards(self, state, cards):
"""Return a new set of cards that can be moved home automatically.
:param state: a tuple or list where the first four elements are the ranks of the home cells
:type state: tuple or list
:param cards: Cards to test
:type cards: set
A card can be automatically moved to its home cell if one of the following is true:
- the card is an Ace
- the card is a 2 and the Ace of the same suit is home
- the card is a 3, the 2's of opposite color are home, and the 2 of the
same suit is home
- the card is 4 or higher, the card of one less rank and same suit is home,
and all cards that could be attached to the card in a column are home
(e.g. for 6H, we need 5H, 5S, 5C, and 4D to be home)
Idea taken from http://www.idiotsdelight.net/freecell-help.html
Assume these cards can be moved home.
"""
rtn = set()
for card in cards:
rank = card.rank_int
if rank <= 2:
rtn.add(card)
else:
prev_rank = rank - 1 # Could be precomputed
opp_suits_home = True
suit = card.suit_int
for opp_color_suit in self._opp_color[suit]:
if state[opp_color_suit] < prev_rank:
opp_suits_home = False
break
if opp_suits_home and (rank == 3 or state[self._sibling_suit[suit]] >= rank - 2):
# rank-2 could be precomputed
rtn.add(card)
return rtn
def _move_home(self, card, needed_home, home):
"""Move this card home.
:param card: a card
:type card: Card
:param needed_home: Cards needed home
:type needed_home: set
:param home: the home cells
:type home: list
Assume the card can be moved home.
"""
home[card.suit_int] += 1
needed_home.remove(card)
if card.rank_int < _MAX_RANK:
needed_home.add(self._next_in_rank[card])
def _auto_neighbor(self, state, needed_home, free, av_tab):
"""Return the automatic neighbor and its cost.
:param needed_home: Cards needed home
:type needed_home: set
:param free: free cell Cards
:type free: set
:param av_tab: maps a Card to its column
:type av_tab: dict
For this, keep moving cards to their home cells. If none can be moved,
return None.
A card can be automatically moved to its home cell if one of the following is true:
- the card is an Ace
- the card is a 2 and the Ace of the same suit is home
- the card is a 3, the 2's of opposite color are home, and the 2 of the
same suit is home
- the card is 4 or higher, the card of one less rank and same suit is home,
and all cards that could be attached to the card in a column are home
(e.g. for 6H, we need 5H, 5S, 5C, and 4D to be home)
Idea taken from http://www.idiotsdelight.net/freecell-help.html
This may modify needed_home, free, and av_tab if there are moves.
"""
cost = 0
home = list(state[:4])
tab = state[5]
while True:
delta_cost = 0
# From free
for card in self._automatic_cards(home, free & needed_home):
free.remove(card)
self._move_home(card, needed_home, home)
delta_cost += 1
# From tab
for card in self._automatic_cards(home, set(av_tab) & needed_home):
self._move_home(card, needed_home, home)
col = av_tab[card]
del av_tab[card]
tab = self._remove_card_from_col(tab, col)
if len(col) > 2:
av_tab[self._cards[col[-4:-2]]] = col[:-2]
delta_cost += 1
if delta_cost == 0:
if cost == 0:
return None
return self._new_state(
state, home=tuple(home), free=frozenset(str(card) for card in free),
tab=frozenset(tab)
), cost
cost += delta_cost
def neighbors(self, state):
"""Return a list of states that can be reached from this state."""
# Automatic move
needed_home = self._needed_home(state)
free = {self._cards[card] for card in state[4]}
av_tab = self._av_tab(state[5])
auto_neighbor = self._auto_neighbor(state, needed_home, free, av_tab)
if auto_neighbor is not None:
return [auto_neighbor]
av_home = self._av_home(state)
needed_tab = self._needed_tab(av_tab)
rtn = [] # List of states only
### From free
for card in free:
new_free = None
# To tab
new_tabs = self._to_tab(state[5], needed_tab, card)
if new_tabs:
new_free = self._remove_card_from_free(state[4], card)
for new_tab in new_tabs:
rtn.append(self._new_state(state, free=new_free, tab=new_tab))
# To home
new_home = self._to_home(state, needed_home, card)
if new_home is not None:
if new_free is None:
new_free = self._remove_card_from_free(state[4], card)
rtn.append(self._new_state(state, home=new_home, free=new_free))
### From tab
# To tab
for new_tab in self._within_tab(state[5], needed_tab, av_tab):
rtn.append(self._new_state(state, tab=new_tab))
# To free
if len(state[4]) < _MAX_FREE_CELLS:
for card, col in av_tab.iteritems():
new_free = self._add_card_to_free(state[4], card)
new_tab = frozenset(self._remove_card_from_col(state[5], col))
rtn.append(self._new_state(state, free=new_free, tab=new_tab))
# To home
for card, col in av_tab.iteritems():
new_home = self._to_home(state, needed_home, card)
if new_home is not None:
new_tab = frozenset(self._remove_card_from_col(state[5], col))
rtn.append(self._new_state(state, home=new_home, tab=new_tab))
### From home
for card in av_home:
new_home = None
# To free
if len(state[4]) < _MAX_FREE_CELLS:
new_free = self._add_card_to_free(state[4], card)
new_home = self._remove_from_home(state, card)
rtn.append(self._new_state(state, home=new_home, free=new_free))
# To tab
for new_tab in self._to_tab(state[5], needed_tab, card):
new_home = self._remove_from_home(state, card) if new_home is None else new_home
rtn.append(self._new_state(state, home=new_home, tab=new_tab))
return [(new_state, 1) for new_state in rtn] # Place holder for now
def move_description(self, from_state, to_state):
"""Return a string describing the transition between the two states.
e.g. 'Move 3H home'.
"""
## Check free cells
added_free_cells = to_state[4] - from_state[4]
if added_free_cells:
for card in added_free_cells:
return 'Move %s to a free cell.' % card
## Check home cells
to_home_cards = []
for suit_int in xrange(4):
for rank_int in xrange(from_state[suit_int]+1, to_state[suit_int]+1):
to_home_cards.append(str(self._cards[(rank_int, suit_int)]))
if to_home_cards:
if len(to_home_cards) == 1:
return 'Move %s to its home cell.' % to_home_cards[0]
elif len(to_home_cards) == 2:
return 'Move %s and %s to their home cells.' % tuple(to_home_cards)
else:
return 'Move %s, and %s to their home cells.' % (', '.join(to_home_cards[:-1]), to_home_cards[-1])
## Check tableau
to_tab = to_state[5]
from_tab = from_state[5]
# Check for a card added to an existing column
for to_col in to_tab:
if to_col[:-2] in from_tab:
return 'Move %s on top of %s.' % (to_col[-2:], to_col[-4:-2])
# Check for a card added to a new column
for to_col in to_tab:
if len(to_col) == 2 and to_col not in from_tab:
return 'Move %s to a new column.' % to_col
raise ValueError('Unable to find the right move')
def display(self, state):
"""Display this state in a nice way."""
# First row
gap = 4 # Number of spaces between free and home cells
row = '|'
for card in sorted(state[4]):
row += card + '|'
for _ in range(4 - len(state[4])):
row += ' |'
row += ' ' * gap + '|'
for ndx in xrange(4):
home_rank = state[ndx]
if home_rank == 0:
row += ' '
else:
row += str(self._cards[(home_rank, ndx)])
row += '|'
print row
# Second row
print '+--+--+--+--+' + '-' * gap + '+--+--+--+--+'
# Tableau
max_len = max(len(col) for col in state[5]) / 2
for ndx in xrange(max_len):
row = ''
for col in sorted(state[5]):
if ndx * 2 < len(col):
card = col[ndx*2:ndx*2+2]
else:
card = ' '
row += card + ' '
print row
def heuristic(state):
"""Return the heuristic."""
# Imagine you have an infinite number of free cells.
#
# The idea is this:
# For a card c in the tableau, it must go to a free cell if there is a card with
# the same suit deeper in the column with a lower rank.
rtn = len(state[4])
for col in state[5]:
min_cards = {suit: _MAX_RANK for suit in ['S', 'C', 'D', 'H']}
for ndx in xrange(0, len(col), 2):
rank = Card.get_rank_int(col[ndx])
suit = col[ndx+1]
if min_cards[suit] < rank:
rtn += 2
else:
rtn += 1
min_cards[suit] = rank
return rtn
def main():
"""A Freecell solver"""
parser = argparse.ArgumentParser(description=__doc__)
help_text = """\
CSV file for a layout of a freecell game. Each row represents a Tableau column. \
Each card is 2 characters long (e.g. "3H"). You represent 10 with "T" or "t". All \
letters may be upper or lower case. For order, the card at the end of the row \
is the top of the column and can be moved. Example (you'll have more cards than this):
3h,as,4S,KD
TD,JC,2H
"""
parser.add_argument('filename', help=help_text)
args = parser.parse_args()
logging.basicConfig(level=logging.INFO, format='%(asctime)s: %(message)s')
logging.info('Starting')
problem = FreeCellProblem(args.filename)
for move in astar(problem, heuristic):
print move
if __name__ == '__main__':
main() | {"/test_freecell.py": ["/freecell.py"]} |
62,391 | dafatskin/CCA-Allocation | refs/heads/master | /mod_allocation.py | ###################
#Allocation module#
###################
import mod_data as modD
import random
def p2_assignDSA(DSA, final_dic, CCA_dic):
"""
Assigns all DSA students their CCA
Returns the final dictionaries
"""
for name, CCA in DSA.dic.items(): #DSA is a class object
final_dic[name] = {"CCA":CCA, "rank":0, "score":9001} #Allocation line
CCA_dic = {} #clear - CCA_dic is based on most updated final_dic
for name, CCA in final_dic.items(): #reverse
try:
dic = CCA_dic[CCA["CCA"]]
dic[name] = {"rank":CCA["rank"],"score":CCA["score"]}
CCA_dic[CCA["CCA"]] = dic
except KeyError:
CCA_dic[CCA["CCA"]] = {name:{"rank":CCA["rank"],"score":CCA["score"]}}
print("p2_assignDSA complete")
return final_dic, CCA_dic
def p2_assignUnderQuota(quota, pysmo, CCA_ranking, MEP, LOC, rank, final_dic, CCA_dic, config_vars):
"""
Assigns students to CCAs where the quota exceeds the applicants
Returns the final dictionaries
"""
CCAs_left = [] #this for the CCAs in p2_assignByScore
CCA_LOC = {} #reverse LOC
for name, CCA in LOC.dic[rank].items():
try:
lst = CCA_LOC[CCA]
lst.append(name)
CCA_LOC[CCA] = lst
except KeyError:
CCA_LOC[CCA] = [name]
for category, dic in quota.dic.items():
for CCA, quota2 in dic.items():
scorelist = p2_calculate_score(CCA, modD.data_to_nameCat(LOC, quota, rank, CCA), pysmo, CCA_ranking, MEP, config_vars)
lst = []
for key, value in scorelist.items():
lst.append(key)
try: #get number of first_choice
first_for_CCA = len(CCA_LOC[CCA])
except KeyError:
first_for_CCA = 0
try: #get number of assigned students
alras = len(CCA_dic[CCA])
except KeyError:
alras = 0
if first_for_CCA + alras <= quota2: #add, if less than quota:
try:
for name in CCA_LOC[CCA]:
var = {"CCA":CCA, "rank":rank, "score":scorelist[name]}
if name in final_dic:
pass
else:
final_dic[name] = var #Allocation line
except KeyError:
pass #lol no one wanted to join
else:
CCAs_left.append(CCA)
CCA_dic = {} #clear - CCA_dic is based on most updated final_dic
for name, CCA in final_dic.items(): #reverse
try:
dic = CCA_dic[CCA["CCA"]]
dic[name] = {"rank":CCA["rank"],"score":CCA["score"]}
CCA_dic[CCA["CCA"]] = dic
except KeyError:
CCA_dic[CCA["CCA"]] = {name:{"rank":CCA["rank"],"score":CCA["score"]}}
return final_dic, CCA_dic, CCAs_left
def p2_calculate_score(CCA, name_cat, psymo, CCA_ranking, MEP, config_vars):
"""
Calculates the score of applicants, to evaluate who should join
Returns the final dictionaries
"""
score=0
score_dict={}
for name, cat in name_cat.items(): #for each name and cateogory
if cat=="PERFORMING ARTS": #if its a performing arts cca
score=0
try:
for placeholder, rank in CCA_ranking[CCA][name]:
score=score+20/int(rank)
except:
pass
if name in MEP.dic:
score = 9001
score_dict[name]=str(score)
elif cat=="SPORTS": #if its a sports cca
score=0
scoring_details = config_vars["scoring details"][CCA]
if scoring_details["rankscoring"] == "on":
try:
for placeholder, rank in CCA_ranking[CCA][name].items(): #add rank to score
score=score+20/int(rank)
except KeyError:
pass
else:
pass
lst = ["Height", "Weight", "30m", "IPU", "SBJ", "1km"] #hardcoded psychomotor test variables. Change if required.
for i in lst:
var = psymo.dic[name][i]
if var == None:
var = 0
else:
pass
if var>=float(scoring_details[i]["criteria"]):
score+=float(scoring_details[i]["other"])
else:
score+=float(scoring_details[i]["default"])
score_dict[name]=str(score)
else:
score_dict[name]=str(score)
return score_dict
def p2_allocateByScore(CCA, nameCat, quota, rank, scorelist, final_dic, CCA_dic):
"""
Allocates students to cca where applicants exceed quota
Returns the final dictionaries
"""
cat = ""
for key, value in nameCat.items(): #theoretically it will all be the same anyway
cat = value
quota_int = quota.dic[cat][CCA]
in_order = []
for name, score in scorelist.items(): #names in order of score
if in_order == []:
in_order.append(name)
else:
added = False
for name2 in in_order:
if added == False:
if scorelist[name2] < score:
in_order.insert(in_order.index(name2), name)
added = True
else:
pass
else:
pass
try: #get number of assigned students
alras = len(CCA_dic[CCA])
except KeyError:
alras = 0
pos_left = quota_int - alras
to_add = in_order[0:pos_left]
for name in to_add:
if name in final_dic:
pass
else:
final_dic[name] = {"CCA":CCA, "rank":rank, "score":scorelist[name]} #Allocation line
CCA_dic = {} #clear - CCA_dic is based on most updated final_dic
for name, CCA in final_dic.items(): #reverse
try:
dic = CCA_dic[CCA["CCA"]]
dic[name] = {"rank":CCA["rank"],"score":CCA["score"]}
CCA_dic[CCA["CCA"]] = dic
except KeyError:
CCA_dic[CCA["CCA"]] = {name:{"rank":CCA["rank"],"score":CCA["score"]}}
return final_dic, CCA_dic
def p2_assignMerit(merit_choices):
"""
Assigns all merit ccas to students
Returns merit cca final dictionaries
"""
merit_CCA_dic = {} #clear - merit_CCA_dic is based on most updated final_dic
for name, CCA in merit_choices.dic.items(): #reverse
try:
lst = merit_CCA_dic[CCA]
lst.append(name)
merit_CCA_dic[CCA] = lst
except KeyError:
merit_CCA_dic[CCA] = [name]
del merit_CCA_dic[None]
return merit_choices, merit_CCA_dic
def p3_allocateRemainder(quota, master_dic, CCA_dic, final_dic):
"""
Allocates those students who did not get allocated, or did not submit allocation form
"""
unassigned = []
for name, data in master_dic["classlist"][0].items():
if name in final_dic: #alr assigned
pass
else:
unassigned.append(name)
del unassigned[0]
notfilled = [1]
allassigned = False
while notfilled != [] and allassigned != True:
notfilled = []
for category, dic in quota.dic.items():
for cca, quota2 in dic.items():
try:
if len(CCA_dic[cca]) < quota2:
notfilled.append(cca)
else:
pass
except KeyError:
notfilled.append(cca)
for cca in notfilled:
if unassigned != []:
index = random.randint(0, len(unassigned)-1)
final_dic[unassigned[index]] = {"CCA":cca, "rank":10, "score":0}
del unassigned[index]
else:
allassigned = True
CCA_dic = {} #clear - CCA_dic is based on most updated final_dic
for name, CCA in final_dic.items(): #reverse
try:
dic = CCA_dic[CCA["CCA"]]
dic[name] = {"rank":CCA["rank"],"score":CCA["score"]}
CCA_dic[CCA["CCA"]] = dic
except KeyError:
CCA_dic[CCA["CCA"]] = {name:{"rank":CCA["rank"],"score":CCA["score"]}}
return final_dic, CCA_dic
def p4_reassignment(LOC, quota, psymo, CCA_ranking, MEP, final_dic, CCA_dic, config_vars):
"""
Reassigns students, based on certain criteria, to increase higher choices
Returns final dictionaries
Note to editors and readers: this may look daunting and weird. I've commented some stuff to help
But I myself, having added on many times, can't read it very well as well.
A tip would be to look at different parts of the code, do some print tests.
"""
swap_was_made = True #we will repeat until all possible swaps have been made!!!
while swap_was_made == True:
swap_was_made = False
URC = config_vars["reassignment variables"]["under rank criteria"] #different criteria values
RDC = config_vars["reassignment variables"]["rank diff criteria"]
SWC = config_vars["reassignment variables"]["switch rank criteria"]
SDC = config_vars["reassignment variables"]["score diff criteria"]
student_lst = []
for name, data in final_dic.items():
student_lst.append(name)
choicedic = {}
for rank, data in LOC.dic.items():
for name, CCA in data.items():
try:
choicedic[name][rank] = CCA
except KeyError:
choicedic[name] = {rank:CCA}
for name in student_lst:
rank_current = final_dic[name]["rank"] #rank of current CCA
score_current = final_dic[name]["score"] #score of current CCA
try:
ranks_new = choicedic[name]
except:
ranks_new = {} #will become ranks of previously chosen
if rank_current == "0" or rank_current == "LO1":
ranks_new = {}
else:
end_con = False
try:
del ranks_new["LO1"]
except KeyError:
pass
for rank in ["LO2", "LO3", "LO4", "LO5", "LO6", "LO7", "LO8", "LO9"]: #for each rank
if rank_current == rank:
end_con = True
try:
del ranks_new[rank]
except KeyError:
pass
else:
if end_con == False:
try:
del ranks_new[rank]
except KeyError:
pass
else:
pass
swapped = False
another_scoredic = {}
for rank, CCA in ranks_new.items():
nameCat = {}
nameCat[name] = modD.data_to_nameCat(LOC, quota, rank, CCA)[name]
score_new = p2_calculate_score(CCA, nameCat, psymo, CCA_ranking, MEP, config_vars)[name] #score of new CCA
try:
for alras_name, data in CCA_dic[CCA].items():
student_rank = final_dic[alras_name]["rank"] #exchange student's current rank
student_score = final_dic[alras_name]["score"] #exchange student's current score
try:
choices = choicedic[alras_name]
except KeyError:
choices = {}
student_new_rank, student_new_score = "LO0", 0
for choice, cca in choices.items():
if cca == final_dic[name]["CCA"]:
student_new_rank = choice #exchange student's new rank
namecat = {}
namecat[name] = modD.data_to_nameCat(LOC, quota, rank, CCA)[name]
student_new_score = p2_calculate_score(CCA, namecat, psymo, CCA_ranking, MEP, config_vars)[name] #exchange student's new score
else:
pass
URC_con = None #URC condition
if int(URC[-1]) <= int(rank_current[-1]):
URC_con = True
else:
URC_con = False
RDC_con = None #RDC condition
if student_new_rank == "LO0":
if int(RDC) <= int(rank_current[-1]) - 10:
RDC_con = True
else:
RDC_con = False
else:
if int(RDC) <= int(rank_current[-1]) - int(student_new_rank[-1]):
RDC_con = True
else:
RDC_con = False
SWC_con = None #SWC condition
var = 0
if student_new_rank != "LO0":
try:
if int(SWC) <= (int(rank_current[-1]) + int(student_rank[-1])) - (int(student_new_rank[-1]) + int(rank[-1])):
var = (int(rank_current[-1]) + int(student_rank[-1])) - (int(student_new_rank[-1]) + int(rank[-1]))
SWC_con = True
else:
SWC_con = False
except TypeError:
if int(SWC) <= (int(rank_current[-1]) + student_rank) - (int(student_new_rank[-1]) + int(rank[-1])):
var = (int(rank_current[-1]) + student_rank) - (int(student_new_rank[-1]) + int(rank[-1]))
SWC_con = True
else:
SWC_con = False
else:
try:
if int(SWC) <= (int(rank_current[-1]) + int(student_rank[-1])) - (10 + int(rank[-1])):
var = (int(rank_current[-1]) + int(student_rank[-1])) - (10 + int(rank[-1]))
SWC_con = True
else:
SWC_con = False
except TypeError:
if int(SWC) <= (int(rank_current[-1]) + student_rank) - (10 + int(rank[-1])):
var = (int(rank_current[-1]) + student_rank) - (10 + int(rank[-1]))
SWC_con = True
else:
SWC_con = False
SDC_con = None #SDC condition
if int(SDC) >= float(student_score) - float(score_new):
SDC_con = True
else:
SDC_con = False
if URC_con == True and RDC_con == True and SWC_con == True and SDC_con == True: #if all conditions are GO
dic = {"alras_name":alras_name, "alras_CCA":final_dic[name]["CCA"], "alras_rank":student_new_rank, "alras_score":student_new_score}
dic["name_CCA"], dic["name_rank"], dic["name_score"] = CCA, rank, score_new
dic["score"] = var
try:
if dic["score"] >= another_scoredic["key"]["score"]:
another_scoredic["key"] = dic
else:
pass
except KeyError:
another_scoredic["key"] = dic
else:
pass
except KeyError as e:
pass
try: #Reassign!
asd = another_scoredic["key"]
final_dic[asd["alras_name"]] = {"CCA":asd["alras_CCA"], "rank":asd["alras_rank"], "score":asd["alras_score"]}
final_dic[name] = {"CCA":asd["name_CCA"], "rank":asd["name_rank"], "score":asd["name_score"]}
swap_was_made = True
except:
pass
CCA_dic = {} #clear - CCA_dic is based on most updated final_dic
for name, CCA in final_dic.items(): #reverse
try:
dic = CCA_dic[CCA["CCA"]]
dic[name] = {"rank":CCA["rank"],"score":CCA["score"]}
CCA_dic[CCA["CCA"]] = dic
except KeyError:
CCA_dic[CCA["CCA"]] = {name:{"rank":CCA["rank"],"score":CCA["score"]}}
return final_dic, CCA_dic
| {"/mod_allocation.py": ["/mod_data.py"], "/start.py": ["/mod_data.py", "/mod_allocation.py", "/mod_presentation.py", "/class_data.py"]} |
62,392 | dafatskin/CCA-Allocation | refs/heads/master | /start.py | #############
#Main script#
#############
#CCA Allocation v1.0#
import timeit
import os
import mod_data as modD
import mod_allocation as modA
import mod_presentation as modP
from class_data import *
#variables#
config_file = "Config file.txt"
def main(config_file):
"""
"""
final_dic, CCA_dic = {}, {}
#Phase 1 Data#
config_vars = modD.configure_variables(config_file) #config_vars
file = config_vars["file names"]["unallocated"] #get name of xlsx file
master_list = modD.extract_data(file, config_vars) #extract data
print("Extracting individual sheets...")
LOC = sheetdata("list_of_choices", modD.data_to_LOC(master_list)) #all indiv sheets
merit = sheetdata("list_of_merits", modD.data_to_merit(master_list))
MEP = sheetdata("MEP_students", modD.data_to_MEP(master_list))
DSA = sheetdata("DSA_students", modD.data_to_DSA(master_list))
quota = sheetdata("CCA_quota", modD.data_to_quota(master_list))
psymo = sheetdata("psychomotor", modD.data_to_psychomotor(master_list))
list_of_CCA = [] #get a list of CCAs
for key, value in config_vars["data formats"].items():
list_of_CCA.append(key)
del list_of_CCA[0:6]
CCA_ranking = {} #dic of all CCAs
for cca in list_of_CCA:
CCA_ranking[cca] = modD.data_to_CCA(master_list, cca)
print("Phase 1: Data extraction, complete\n")
#Phase 2 Allocation#
print("Assigning by score...")
final_dic, CCA_dic = modA.p2_assignDSA(DSA, final_dic, CCA_dic)
for rank in ["LO1", "LO2", "LO3", "LO4", "LO5", "LO6", "LO7", "LO8", "LO9"]:
final_dic, CCA_dic, CCAs_left = modA.p2_assignUnderQuota(quota, psymo, CCA_ranking, MEP, LOC, rank, final_dic, CCA_dic, config_vars) #assign under quota
for CCA in CCAs_left:
nameCat = modD.data_to_nameCat(LOC, quota, rank, CCA)
scorelist = modA.p2_calculate_score(CCA, nameCat, psymo, CCA_ranking, MEP, config_vars)
final_dic, CCA_dic = modA.p2_allocateByScore(CCA, nameCat, quota, rank, scorelist, final_dic, CCA_dic)
merit_dic, merit_CCA_dic = modA.p2_assignMerit(merit)
print("Phase 2: Allocation by score, complete\n")
#Phase 3 Allocation#
print("Assigning remainder...")
final_dic, CCA_dic = modA.p3_allocateRemainder(quota, master_list, CCA_dic, final_dic)
for rank in [0, "LO1", "LO2", "LO3", "LO4", "LO5", "LO6", "LO7", "LO8", "LO9", 10]:
count = 0 #test for rank count
for name, data in final_dic.items():
if data["rank"] == rank:
count = count + 1
else:
pass
print(rank, count)
print("Phase 3: Allocation of remainder, complete\n")
#Phase 4 Allocation#
print("Reassigning...")
final_dic, CCA_dic = modA.p4_reassignment(LOC, quota, psymo, CCA_ranking, MEP, final_dic, CCA_dic, config_vars)
for rank in [0, "LO1", "LO2", "LO3", "LO4", "LO5", "LO6", "LO7", "LO8", "LO9", 10]:
count = 0 #test for rank count
for name, data in final_dic.items():
if data["rank"] == rank:
count = count + 1
else:
pass
print(rank, count)
print("Phase 4: Reassignment, complete\n")
#Phase 5 Allocation#
print("Writing report...")
#modP.final_report(CCA_dic)
modP.p5_allocated(final_dic, CCA_dic, CCA_ranking, config_vars)
os.makedirs("CCA excel sheets")
os.makedirs("Class excel sheets")
nameClass = modD.data_to_nameClass(master_list)
for CCA, data in CCA_dic.items():
modP.p5_CCAxlsx(final_dic, CCA_dic, merit_CCA_dic, CCA, nameClass, config_vars)
for CCA, name in merit_CCA_dic.items():
modP.p5_meritCCAxlsx(merit_dic, merit_CCA_dic, CCA, nameClass, config_vars)
className = {}
for name, Class in nameClass.items():
try:
lst = className[Class]
lst.append(name)
className[Class] = lst
except:
className[Class] = [name]
for Class, names in className.items():
modP.p5_classxlsx(final_dic, CCA_dic, merit_dic, Class, className, config_vars)
modP.final_report(final_dic,list_of_CCA)
print("Phase 5: Presentation, complete\n")
print("All complete")
| {"/mod_allocation.py": ["/mod_data.py"], "/start.py": ["/mod_data.py", "/mod_allocation.py", "/mod_presentation.py", "/class_data.py"]} |
62,393 | dafatskin/CCA-Allocation | refs/heads/master | /class_data.py | ############
#Data class#
############
class sheetdata:
def __init__(self, sheetname, dic):
self.sheetname = sheetname
self.dic = dic
| {"/mod_allocation.py": ["/mod_data.py"], "/start.py": ["/mod_data.py", "/mod_allocation.py", "/mod_presentation.py", "/class_data.py"]} |
62,394 | dafatskin/CCA-Allocation | refs/heads/master | /mod_data.py | #############
#data module#
#############
import openpyxl
import timeit
def configure_variables(config_file):
"""
Returns all the variables stored in the config file
{data type:{data}}
"""
print("configuring variables...")
dic = {} #will return to config_vars
try: #test (and open) file
fp = open(config_file, "r")
except IOError:
print(e)
print("The config file has been moved or renamed.")
print("Please return it back to this directory or rename it to 'Config file'.")
data = fp.readlines()
fp.close()
section = "None" #different section = different data format
to_add = {}
for line in data: #each line
if line[:2] == "--" and line[8:].strip("\n") != section: #new section?
section = line[8:].strip("\n")
to_add = {}
elif line[:2] == "--" and line[8:].strip("\n") == section: #end of section?
dic[section[:-2]] = to_add
section = "None"
to_add = {}
else:
if section == "data formats--": #section specifying data form
elements = line.strip("\n").split(":")
elements.append(elements[1].split(","))
del elements[1]
areas = []
for i in range(len(elements[1])): #for each container
var = elements[1][i].split("-")
areas.append({"slice_coords":[var[0], var[1]], "ID_header":var[2]})
elements.append(areas)
del elements[1]
to_add[elements[0]] = elements[1]
elif section == "file names--": #section specifying file names
elements = line.strip("\n").split(":")
to_add[elements[0]] = elements[1]
elif section == "scoring details--": #section specifying scoring details
elements = line.strip("\n").split(":")
elements.append(elements[1].split(","))
del elements[1]
details = {}
for i in range(len(elements[1])): #for each detail
if elements[1][i] == "on" or elements[1][i] == "off":
details["rankscoring"] = elements[1][i]
else:
var = elements[1][i].split("-")
lst = ["Height", "Weight", "30m", "IPU", "SBJ", "1km"]
details[lst[i]] = {"default":var[0], "other":var[1], "criteria":var[2]}
elements.append(details)
del elements[1]
to_add[elements[0]] = elements[1]
elif section == "reassignment variables--":
elements = line.strip("\n").split(":")
to_add[elements[0]] = elements[1]
elif section == "None":
pass
else:
print("Error occured on line 50: section '{}' not found".format(section))
return dic
def extract_data(file, config_vars):
"""
Reads all data from the file specified in config file, and writes the data to a nested dictionary
{sheet:{ID:{data}}
Returns this dictionary
"""
print("extracting data...")
dic = {} #will return to master_list
try: #test (and open) file
fp = open(file, "r")
except IOError as e:
print(e)
print("File: '{}' not found. Please check the config file.".format(file))
wb = openpyxl.load_workbook(file) #open workbook
sheet_names = wb.sheetnames #get names of all sheets
for name in sheet_names: #for every sheet in the workbook
sheet = wb[name] #define the worksheet
sheet_list = []
areas = config_vars["data formats"][name]
sheet_list = extract_sheet(file, name, areas) #see extract_sheet
dic[name] = sheet_list #define sheet as a list of data containers
fp.close()
return dic
def extract_sheet(file, sheetname, areas):
"""
Extracts an individual sheet, used in extract_data
"""
lst = [] #will return to sheet_data
try: #test (and open) file
fp = open(file, "r")
except IOError as e:
print(e)
print("File: '{}' not found. Please check the config file.".format(file))
wb = openpyxl.load_workbook(file) #open workbook
try: #test (and open) spreadsheet
ws = wb[sheetname]
except KeyError as e:
print(e)
print("Sheet: '{}' not found. Please check the config file.".format(sheetname))
for i in areas: #for each area
area = ws[i["slice_coords"][0]:i["slice_coords"][1]]
area_dic = {}
ID_value = ""
for row in area: #for each row in area
row_dic = {}
for cell in row: #for each cell in row
col_letter = cell.column #this be column of cell
header = ws[col_letter + i["slice_coords"][0][1:]].value #this be header value of cell
if header == i["ID_header"]: #if its the ID column
ID_value = cell.value #get the ID value
else:
row_dic[header] = cell.value #define column of ID as value
area_dic[ID_value] = row_dic #define ID of area as column
lst.append(area_dic) #add to list of areas
fp.close()
return lst
def data_to_LOS(dic):
"""
Returns a list of all students in directory
[name]
"""
final_lst = []
dic_classlist = dic["classlist"][0] #relevant sheet
for key, value in classlist.items(): #name:data
final_lst.append(key)
del final_lst[0]
return final_lst
def data_to_LOC(dic):
"""
Returns a dictionary of core cca choices of each student
{rank of choice:{student:cca}}
"""
final_dic = {} #will return to list_of_firsts
dic_choices = dic["choices"][0] #the relevant sheet
pdic = {"LO1":"CORE1", "LO2":"CORE2", "LO3":"CORE3", "LO4":"CORE4", "LO5":"CORE5", "LO6":"CORE6", "LO7":"CORE7", "LO8":"CORE8", "LO9":"CORE9"}
qdic = {}
for key, value in pdic.items(): #for each rank:name of rank
for NRIC, choices in dic_choices.items(): #for each student:choices
choice = ""
if choices[value] == "01SCOUT": #these 2 values have changes later on. Standardising
choice = "O1"
elif choices[value] == "02SCOUT":
choice = "O2"
else:
choice = choices[value]
qdic[NRIC] = choice
final_dic[key] = qdic
qdic = {}
return final_dic
def data_to_merit(dic):
"""
Returns a dictionary of merit cca choices of each student
{student:merit cca}
"""
final_dic = {}
dic_choices = dic["choices"][0] #relevant sheet
for NRIC, choices in dic_choices.items():
final_dic[NRIC] = choices["MERIT1"] #just take first choice; no limit for merit CCAs
del final_dic["NRIC"]
return final_dic
def data_to_MEP(dic):
"""
Returns a list of MEP students
[name]
"""
final_lst = []
dic_MEP = dic["MEP"][0] #relevant sheet
for key, value in dic_MEP.items():
final_lst.append(key) #just append the name
del final_lst[0]
return final_lst
def data_to_DSA(dic):
"""
Returns a dictionary of DSA students
{name:CCA}
"""
final_dic = {} #will return to DSA_students
dic_DSA = dic["DSA"][0] #the relevant sheet
for key, value in dic_DSA.items():
final_dic[key] = value["Sports"]
del final_dic["Name"]
return final_dic
def data_to_quota(dic):
"""
Returns a dictionary of quota of each CCA
{CCA type:{CCA:quota}}
"""
final_dic = {} #will return to CCA_quota
dic_quota = dic["ccaquota"] #the relevant sheet
for dic in dic_quota: #SPORTS, UNIFORMED GROUPS, etc.
groupname = ""
groupdic = {}
for key, value in dic.items(): #SPORTS: {}
if value[None] == None:
final_dic[groupname] = groupdic
groupname = key
groupdic = {}
else:
groupdic[key] = value["QUOTA"]
final_dic[groupname] = groupdic
del final_dic[""]
return final_dic
def data_to_psychomotor(dic):
"""
Returns a dictionary of psychomotor details of each student
{name:{details}}
"""
final_dic = {} #will return to psychomotor
dic_psymo = dic["psychomotor"][0] #the relevant sheet
for key, value in dic_psymo.items():
del value["AGE"]
final_dic[key] = value
del final_dic["Name"]
return final_dic
def data_to_CCA(dic, CCA):
"""
Returns a dictionary of ranking details of each CCA
{name:{placeholder:rank}
"""
final_dic = {}
dic_CCA = dic[CCA][0] #the cca sheet
for key, value in dic_CCA.items():
try: #delete all the useless info
del value["Class"]
except KeyError:
del value["CLASS"]
try:
del value["Category"]
except:
pass
final_dic[key] = value
try:
del final_dic["Name"]
except KeyError:
pass
return final_dic
def data_to_nameCat(LOC, quota, rank, CCA):
"""
Returns a dictionary of the category of a CCA
"""
final_dic = {}
dic_quota = quota.dic #dictionary
cat = ""
for category, dic_CCAs in dic_quota.items(): #for each category
for cca, quota in dic_CCAs.items(): #for each cca
if cca == CCA:
cat = category #variable = category of cca
else:
pass
CCA_LOC = {} #reverse LOC
for name, cca in LOC.dic[rank].items():
try:
lst = CCA_LOC[cca]
lst.append(name)
CCA_LOC[cca] = lst
except KeyError:
CCA_LOC[cca] = [name]
try:
for name in CCA_LOC[CCA]:
final_dic[name] = cat #name:category
except KeyError:
pass
try:
del final_dic["Name"]
except KeyError:
pass
return final_dic
def data_to_nameClass(master_list):
"""
Returns a dictionary of students' classes
{name:class}
"""
final_dic = {}
dic_classlist = master_list["classlist"][0] #relevant sheet
for name, data in dic_classlist.items():
final_dic[name] = data["CLASS"]
del final_dic["NAME"]
return final_dic
| {"/mod_allocation.py": ["/mod_data.py"], "/start.py": ["/mod_data.py", "/mod_allocation.py", "/mod_presentation.py", "/class_data.py"]} |
62,395 | dafatskin/CCA-Allocation | refs/heads/master | /mod_presentation.py | #####################
#Presentation module#
#####################
import openpyxl
from docx import Document
from docx.shared import Inches
import datetime
import matplotlib.pyplot as plt
import numpy as np
def autolabel(rects, xpos='center'):
"""
Attach a text label above each bar in *rects*, displaying its height.
*xpos* indicates which side to place the text w.r.t. the center of
the bar. It can be one of the following {'center', 'right', 'left'}.
"""
xpos = xpos.lower() # normalize the case of the parameter
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
offset = {'center': 0.5, 'right': 0.57, 'left': 0.43} # x_txt = x + w*off
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()*offset[xpos], 1.01*height,
'{}'.format(height), ha=ha[xpos], va='bottom')
def plotchoicegraph(final_dic):
#Variables#
choice_no={1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,0:0}#Rank:Number of rank
choices=[]
fig=plt.figure()
#SetUp
for name in final_dic:
for CCA, choice, score in name:
choice_no[choice]+=1
for choicetype, choice in choice_no:
choices.append(int(choice))
ind = np.arange(len(choices)) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/2, choices, width,
color='SkyBlue')
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Number of choices')
ax.set_title('Number of choices allocated')
ax.set_xticks(ind)
ax.set_xticklabels(('C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C0'))
autolabel(rects1, "left")
return fig
def plotallocationgraph(final_dic,list_of_CCA):
#Variables#
CCA_no={}
fig=plt.figure()
#SetUp
for cca in list_of_CCA:
CCA_no[cca]=0
for name in final_dic:
for CCA, choice, score in final_dic:
if CCA==CCA_no[cca]:
CCA_no[cca]+=1
for ccatype, cca in CCA_no:
list.append(int(cca))
ind = np.arange(len(CCA_no)) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/2, choices, width,
color='SkyBlue')
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Number of choices')
ax.set_title('Number of choices allocated')
ax.set_xticks(ind)
ax.set_xticklabels(list_of_CCA)
autolabel(rects1, "left")
return fig
##def plotsuggestiongraph(final_dic)
def final_report(final_dic,list_of_CCA):
now=datetime.datetime.now()
document = Document()
document.add_heading('Report for CCA Allocation for ' + str(now.year), 0)
p = document.add_paragraph('This is the final report for the Year One CCA allocation program, detailing ')
p.add_run('the final product of the code and some graphical presentations of the final allocations')
document.add_heading('Content Page', level=1)
document.add_paragraph(
'Number of people allocated to their choice', style='List Bullet'
)
document.add_paragraph(
'Number of people allocated to each CCA', style='List Bullet'
)
document.add_paragraph(
'Suggestions for future changes', style='List Bullet'
)
document.add_page_break()
document.add_heading('Number of people allocated to their choice', level=1)
#document.add_picture(plotchoicegraph(final_dic))
document.add_page_break()
document.add_heading('Number of people allocated to each CCA', level=1)
#document.add_picture(plotallocationgraph(final_dic))
document.add_page_break()
document.add_heading('Suggestions for future changes', level=1)
#document.add_picture(plotsuggestiongraph)
document.save('final_report.docx')
def p5_CCAxlsx(final_dic, CCA_dic, merit_CCA_dic, CCA, nameClass, config_vars):
"""
"""
wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = CCA
sheet.column_dimensions["A"].width = 24
headerfont = openpyxl.styles.Font(size=12, bold=True) #headers
pdic = {"A1":"NRIC","B1":"Class","C1":"Rank"}
for cell, header in pdic.items():
sheet[cell].font = headerfont
sheet[cell] = header
datafont = openpyxl.styles.Font(size=11) #data
row = "1"
for name, data in CCA_dic[CCA].items():
row = str(int(row) + 1)
sheet["A"+row].font = datafont
sheet["A"+row] = name
sheet["B"+row].font = datafont
sheet["B"+row] = nameClass[name]
sheet["C"+row].font = datafont
if data["rank"] == 0:
sheet["C"+row] = "DSA"
elif data["rank"] == 10:
sheet["C"+row] = ""
else:
sheet["C"+row] = data["rank"][-1]
directory = os.path.abspath("mod_presentation.py")[0:-19]
savepath = directory + "CCA excel sheets\\" + CCA + " excel sheet.xlsx"
wb.save(savepath)
def p5_meritCCAxlsx(merit_dic, merit_CCA_dic, CCA, nameClass, config_vars):
"""
"""
wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = CCA
sheet.column_dimensions["A"].width = 24
headerfont = openpyxl.styles.Font(size=12, bold=True) #headers
pdic = {"A1":"NRIC","B1":"Class"}
for cell, header in pdic.items():
sheet[cell].font = headerfont
sheet[cell] = header
datafont = openpyxl.styles.Font(size=11) #data
row = "1"
for name in merit_CCA_dic[CCA]:
row = str(int(row) + 1)
sheet["A"+row].font = datafont
sheet["A"+row] = name
sheet["B"+row].font = datafont
sheet["B"+row] = nameClass[name]
directory = os.path.abspath("mod_presentation.py")[0:-19]
savepath = directory + "CCA excel sheets\\" + CCA + " excel sheet.xlsx"
wb.save(savepath)
def p5_classxlsx(final_dic, CCA_dic, merit_dic, Class, className, config_vars):
"""
"""
wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = Class
sheet.column_dimensions["A"].width = 24
sheet.column_dimensions["B"].width = 17
headerfont = openpyxl.styles.Font(size=12, bold=True) #headers
pdic = {"A1":"NRIC","B1":"ALLOCATED CCA", "C1":"MERIT CCA"}
for cell, header in pdic.items():
sheet[cell].font = headerfont
sheet[cell] = header
datafont = openpyxl.styles.Font(size=11) #data
row = "1"
for name in className[Class]:
data = final_dic[name]
row = str(int(row) + 1)
sheet["A"+row].font = datafont
sheet["A"+row] = name
sheet["B"+row].font = datafont
sheet["B"+row] = final_dic[name]["CCA"]
sheet["C"+row].font = datafont
try:
if merit_dic.dic[name] != None:
sheet["C"+row] = merit_dic.dic[name]
else:
sheet["C"+row] = ""
except KeyError:
pass
directory = os.path.abspath("mod_presentation.py")[0:-19]
savepath = directory + "Class excel sheets\\" + Class + " excel sheet.xlsx"
wb.save(savepath)
def p5_allocated(final_dic, CCA_dic, CCA_ranking, config_vars):
"""
"""
wb = openpyxl.load_workbook("unallocated.xlsx")
wb.create_sheet(index=0, title="classlist_new")
sheet = wb["classlist_new"]
for row in wb["classlist"][config_vars["data formats"]["classlist"][0]["slice_coords"][0]:config_vars["data formats"]["classlist"][0]["slice_coords"][1]]:
for cell in row:
if cell.row == 1:
sheet[cell.coordinate] = cell.value
else:
name = sheet["C" + str(cell.row)].value
if sheet[cell.column][0].value == "ALLOCATED CCA":
sheet[cell.coordinate] = final_dic[name]["CCA"]
elif sheet[cell.column][0].value == "CHOICE #":
sheet[cell.coordinate] = final_dic[name]["rank"]
elif sheet[cell.column][0].value == "CCA RANK":
try:
if name in CCA_ranking[final_dic[name]["CCA"]]:
try:
sheet[cell.coordinate] = CCA_ranking[final_dic[name]["CCA"]][name]["rank"]
except KeyError:
sheet[cell.coordinate] = CCA_ranking[final_dic[name]["CCA"]][name]["RANK"]
else:
pass
except KeyError:
pass
else:
sheet[cell.coordinate] = cell.value
del wb["classlist"]
sheet.title = "classlist"
wb.save("allocated1.xlsx")
| {"/mod_allocation.py": ["/mod_data.py"], "/start.py": ["/mod_data.py", "/mod_allocation.py", "/mod_presentation.py", "/class_data.py"]} |
62,407 | itisianlee/pyaccepted | refs/heads/master | /algorithm/sorting/bubble.py | import ipt
from algorithm.datastruct import ListNode, createlink, traverse
def bubblesort_a(arr):
l = len(arr)
i = 0
while i < l-1:
j = 0
flag = True
while j < l-1-i:
if arr[j] > arr[j+1]:
flag = False
arr[j], arr[j+1] = arr[j+1], arr[j]
j += 1
if flag:
break
i += 1
def bubblesort_l(head):
if head is None or head.next is None:
return head
pend = None
while pend is not head.next:
p = head
flag = False
while p.next is not pend:
if p.val > p.next.val:
p.val, p.next.val = p.next.val, p.val
flag = True
p = p.next
if flag:
break
pend = p
return head
if __name__ == '__main__':
arr = [3, 1, 5, 10, 2, 8, 6]
# bubblesort_a(arr)
# print(arr)
head = createlink(arr)
head = bubblesort_l(head)
traverse(head) | {"/algorithm/sorting/bubble.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/datastruct/__init__.py": ["/algorithm/datastruct/listnode.py", "/algorithm/datastruct/tree.py"], "/algorithm/sorting/merge.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/quick.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/traverse/binary_tree_traverse.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/insertion.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/selection.py": ["/algorithm/datastruct/__init__.py"]} |
62,408 | itisianlee/pyaccepted | refs/heads/master | /algorithm/datastruct/__init__.py | from .listnode import ListNode, createlink, traverse
from .tree import TreeNode, Tree
| {"/algorithm/sorting/bubble.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/datastruct/__init__.py": ["/algorithm/datastruct/listnode.py", "/algorithm/datastruct/tree.py"], "/algorithm/sorting/merge.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/quick.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/traverse/binary_tree_traverse.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/insertion.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/selection.py": ["/algorithm/datastruct/__init__.py"]} |
62,409 | itisianlee/pyaccepted | refs/heads/master | /algorithm/sorting/merge.py | import ipt
from algorithm.datastruct import ListNode, createlink, traverse
def mergesort_a(arr):
l = len(arr)
def merge(arr, left, mid, right):
i = left
j = mid + 1
tmp = []
while i <= mid and j <= right:
if arr[i] < arr[j]:
tmp.append(arr[i])
i += 1
else:
tmp.append(arr[j])
j += 1
while i <= mid:
tmp.append(arr[i])
i += 1
while j <= right:
tmp.append(arr[j])
j += 1
for x in tmp:
arr[left] = x
left += 1
def sort(arr, left, right):
if left < right:
mid = (left + right) // 2
sort(arr, left, mid)
sort(arr, mid+1, right)
merge(arr, left, mid, right)
sort(arr, 0, l-1)
def merge(h1, h2):
if h1 is None:
return h2
if h2 is None:
return h1
if h1.val < h2.val:
head = h1
h1 = h1.next
else:
head = h2
h2 = h2.next
p = head
while h1 and h2:
if h1.val < h2.val:
p.next = h1
h1 = h1.next
else:
p.next = h2
h2 = h2.next
p = p.next
p.next = h1 if h1 else h2
return head
def mergesort_l(head):
if head is None or head.next is None:
return head
fast = head
slow = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
fast = slow.next
slow.next = None
head = mergesort_l(head)
fast = mergesort_l(fast)
return merge(head, fast)
if __name__ == '__main__':
arr = [3, 1, 5, 10, 2, 8, 6]
# mergesort_a(arr)
# print(arr)
head = createlink(arr)
head = mergesort_l(head)
traverse(head)
| {"/algorithm/sorting/bubble.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/datastruct/__init__.py": ["/algorithm/datastruct/listnode.py", "/algorithm/datastruct/tree.py"], "/algorithm/sorting/merge.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/quick.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/traverse/binary_tree_traverse.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/insertion.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/selection.py": ["/algorithm/datastruct/__init__.py"]} |
62,410 | itisianlee/pyaccepted | refs/heads/master | /algorithm/sorting/quick.py | import ipt
from algorithm.datastruct import ListNode, createlink, traverse
def quicksort_a(arr):
l = len(arr)
def quicksort(arr, left, right):
if left <= right:
idx = partition(arr, left, right)
quicksort(arr, left, idx-1)
quicksort(arr, idx+1, right)
def partition(arr, left, right):
pivot = left
idx = pivot + 1
for i in range(idx, right+1):
if arr[i] < arr[pivot]:
arr[i], arr[idx] = arr[idx], arr[i]
idx += 1
arr[idx-1], arr[left] = arr[left], arr[idx-1]
return idx-1
quicksort(arr, 0, l-1)
def quicksort_l_switch_val(head):
if head is None or head.next is None:
return head
def partition(left, right):
pivot = left.val
p = left.next
q = left
while p is not right:
if p.val < pivot:
p.val, q.next.val = q.next.val, p.val
q = q.next
p = p.next
left.val, q.val = q.val, left.val
return q
def sort(head, tail):
if head is not tail and head.next is not tail:
q = partition(head, tail)
sort(head, q)
sort(q.next, tail)
sort(head, None)
return head
def quicksort_l_switch_node(head):
if head is None or head.next is None:
return head
def partition(pre, left, right):
pivot = left.val
h1 = ListNode(0)
h2 = ListNode(0)
big = h1
sma = h2
p = left.next
while p is not right:
if p.val < pivot:
sma.next = p
sma = p
else:
big.next = p
big = p
p = p.next
big.next = right
sma.next = left
left.next = h1.next
pre.next = h2.next
return left
def sort(pre, head, tail):
if head is not tail and head.next is not tail:
q = partition(pre, head, tail)
sort(pre, pre.next, q)
sort(q, q.next, tail)
headpre = ListNode(0)
headpre.next = head
sort(headpre, head, None)
return headpre.next
if __name__ == '__main__':
# arr = [3, 1, 5, 10, 2, 8, 6]
arr = [3, 2, 1]
# quicksort_a(arr)
# print(arr)
head = createlink(arr)
# quicksort_l_switch_val(head)
head = quicksort_l_switch_node(head)
traverse(head)
| {"/algorithm/sorting/bubble.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/datastruct/__init__.py": ["/algorithm/datastruct/listnode.py", "/algorithm/datastruct/tree.py"], "/algorithm/sorting/merge.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/quick.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/traverse/binary_tree_traverse.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/insertion.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/selection.py": ["/algorithm/datastruct/__init__.py"]} |
62,411 | itisianlee/pyaccepted | refs/heads/master | /leetcode/top100/t2/t2.py | def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
carry = 0
p = l1
q = l2
r = ListNode()
r.next = p
while p and q:
cur = p.val + q.val + carry
carry = cur // 10
cur %= 10
p.val = cur
p = p.next
q = q.next
r = r.next
while p:
cur = p.val + carry
carry = cur // 10
cur %= 10
p.val = cur
p = p.next
r = r.next
while q:
cur = q.val + carry
carry = cur // 10
cur %= 10
q.val = cur
r.next = q
q = q.next
r = r.next
if carry:
r.next = ListNode(carry)
return l1 | {"/algorithm/sorting/bubble.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/datastruct/__init__.py": ["/algorithm/datastruct/listnode.py", "/algorithm/datastruct/tree.py"], "/algorithm/sorting/merge.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/quick.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/traverse/binary_tree_traverse.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/insertion.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/selection.py": ["/algorithm/datastruct/__init__.py"]} |
62,412 | itisianlee/pyaccepted | refs/heads/master | /algorithm/datastruct/listnode.py | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def createlink(arr=None):
assert arr
head = ListNode(arr[0])
p = head
for x in arr[1:]:
tmp = ListNode(x)
p.next = tmp
p = p.next
return head
def traverse(head):
if head is None:
return
p = head
while p:
print(p.val, end=' ')
p = p.next
| {"/algorithm/sorting/bubble.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/datastruct/__init__.py": ["/algorithm/datastruct/listnode.py", "/algorithm/datastruct/tree.py"], "/algorithm/sorting/merge.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/quick.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/traverse/binary_tree_traverse.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/insertion.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/selection.py": ["/algorithm/datastruct/__init__.py"]} |
62,413 | itisianlee/pyaccepted | refs/heads/master | /algorithm/traverse/binary_tree_traverse.py | import ipt
from algorithm.datastruct import TreeNode, Tree
# 二叉树的递归遍历太过简单,省略
def pretty_print_tree(node, prefix="", isLeft=True):
if not node:
print("Empty Tree")
return
if node.right:
pretty_print_tree(node.right, prefix + ("│ " if isLeft else " "),
False)
print(prefix + ("└── " if isLeft else "┌── ") + str(node.val))
if node.left:
pretty_print_tree(node.left, prefix + (" " if isLeft else "│ "),
True)
def pre_order(root):
st = []
res = []
p = root
while p or st:
while p:
res.append(p.val)
st.append(p)
p = p.left
if st:
p = st.pop(-1)
p = p.right
return res
def in_order(root):
st = []
res = []
p = root
while p or st:
while p:
st.append(p)
p = p.left
if st:
p = st.pop()
res.append(p.val)
p = p.right
return res
# 使用访问次数标识,来说明某个节点是否为第二次访问,第二次访问时可进行遍历该节点
def post_order1(root):
st = []
p = root
res = []
while p or st:
while p:
st.append(p)
p.visited = True
p = p.left
if st:
p = st.pop()
if p.visited:
p.visited = False
st.append(p)
p = p.right
else:
res.append(p.val)
p = None
return res
# 要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。
# 如果P不存在左孩子和右孩子,则可以直接访问它;
# 或者P存在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了,则同样可以直接访问该结点。
# 若非上述两种情况,则将P的右孩子和左孩子依次入栈,这样就保证了每次取栈顶元素的时候,
# 左孩子在右孩子前面被访问,左孩子和右孩子都在根结点前面被访问。
def post_order2(root):
if root is None:
return []
res = []
st = [root]
pre = None
while st:
cur = st[-1]
if (cur.left is None and cur.right is None) or (
pre is not None and (pre == cur.left or pre == cur.right)):
cur = st.pop()
res.append(cur.val)
pre = cur
else:
if cur.right:
st.append(cur.right)
if cur.left:
st.append(cur.left)
return res
if __name__ == '__main__':
btree = Tree([4, 3, 2, None, 6, 7, None, 8])
pretty_print_tree(btree.root)
# res = pre_order(btree.root)
# res = in_order(btree.root)
res = post_order2(btree.root)
print(res)
| {"/algorithm/sorting/bubble.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/datastruct/__init__.py": ["/algorithm/datastruct/listnode.py", "/algorithm/datastruct/tree.py"], "/algorithm/sorting/merge.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/quick.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/traverse/binary_tree_traverse.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/insertion.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/selection.py": ["/algorithm/datastruct/__init__.py"]} |
62,414 | itisianlee/pyaccepted | refs/heads/master | /algorithm/sorting/ipt.py | import os
import sys
absp = os.path.abspath('.')
sys.path.append(absp)
sys.path.append('/' + os.path.join(*absp.split('/')[:-2])) | {"/algorithm/sorting/bubble.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/datastruct/__init__.py": ["/algorithm/datastruct/listnode.py", "/algorithm/datastruct/tree.py"], "/algorithm/sorting/merge.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/quick.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/traverse/binary_tree_traverse.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/insertion.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/selection.py": ["/algorithm/datastruct/__init__.py"]} |
62,415 | itisianlee/pyaccepted | refs/heads/master | /algorithm/sorting/shell.py | def shellsort(arr):
l = len(arr)
gap = l // 2
while gap > 0:
for i in range(gap, l):
j = i
cur = arr[i]
while j-gap >= 0 and cur < arr[j-gap]:
arr[j] = arr[j-gap]
j = j - gap
arr[j] = cur
gap = gap // 2
# shell sort 涉及步长,不适合链表的操作,没有链表的shell sort
if __name__ == '__main__':
arr = [3, 1, 5, 10, 2, 8, 6]
shellsort(arr)
print(arr) | {"/algorithm/sorting/bubble.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/datastruct/__init__.py": ["/algorithm/datastruct/listnode.py", "/algorithm/datastruct/tree.py"], "/algorithm/sorting/merge.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/quick.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/traverse/binary_tree_traverse.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/insertion.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/selection.py": ["/algorithm/datastruct/__init__.py"]} |
62,416 | itisianlee/pyaccepted | refs/heads/master | /algorithm/sorting/insertion.py | import ipt
from algorithm.datastruct import ListNode, createlink, traverse
def insertionsort_a(arr):
l = len(arr)
for i in range(1, l):
cur = arr[i]
idx = i-1
while idx >= 0 and arr[idx] > cur:
arr[idx+1] = arr[idx]
idx -= 1
arr[idx+1] = cur
def insertionsort_l(head):
if head is None or head.next is None:
return head
# For convenience, add headnode
pstart = ListNode(-1)
p = head.next
pstart.next = head
pend = head
while p:
t = pstart.next
pre = pstart
while t is not p and p.val >= t.val:
t = t.next
pre = pre.next
if t is p:
pend = p
else:
pend.next = p.next
pre.next = p
p.next = t
p = pend.next
head = pstart.next
del pstart
return head
if __name__ == '__main__':
arr = [3, 1, 5, 10, 2, 8, 6]
# insertionsort_a(arr)
head = createlink(arr)
head = insertionsort_l(head)
traverse(head)
| {"/algorithm/sorting/bubble.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/datastruct/__init__.py": ["/algorithm/datastruct/listnode.py", "/algorithm/datastruct/tree.py"], "/algorithm/sorting/merge.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/quick.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/traverse/binary_tree_traverse.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/insertion.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/selection.py": ["/algorithm/datastruct/__init__.py"]} |
62,417 | itisianlee/pyaccepted | refs/heads/master | /algorithm/datastruct/heap.py | '''
# 堆中父节点i与子节点left、right的位置关系
parent = int((i-1) / 2) # 取整
left = 2 * i + 1
right = 2 * i + 2
'''
class Array(object):
def __init__(self, size = 32):
self._size = size
self._items = [None] * size
def __getitem__(self, index):
return self._items[index]
def __setitem__(self, index, value):
self._items[index] = value
def __len__(self):
return self._size
def clear(self, value=None):
for i in range(self._size):
self._items[i] = value
def __iter__(self):
for item in self._items:
yield item
class MaxHeap(object):
def __init__(self, maxsize=None):
self.maxsize = maxsize
self._elements = Array(maxsize)
self._count = 0
def __len__(self):
return self._count
def add(self, value):
if self._count >= self.maxsize:
raise Exception('full')
self._elements[self._count] = value
self._count += 1
self._siftup(self._count-1) # 维持堆的特性
def _siftup(self, ndx):
if ndx > 0:
parent = int((ndx-1)/2)
if self._elements[ndx] > self._elements[parent]: # 如果插入的值大于 parent,一直交换
self._elements[ndx], self._elements[parent] = self._elements[parent], self._elements[ndx]
self._siftup(parent) # 递归
def extract(self):
if self._count <= 0:
raise Exception('empty')
value = self._elements[0] # 保存 root 值
self._count -= 1
self._elements[0] = self._elements[self._count] # 最右下的节点放到root后siftDown
self._siftdown(0) # 维持堆特性
return value
def _siftdown(self, ndx):
left = 2 * ndx + 1
right = 2 * ndx + 2
# determine which node contains the larger value
largest = ndx
if (left < self._count and # 有左孩子
self._elements[left] >= self._elements[largest] and
self._elements[left] >= self._elements[right]): # 原书这个地方没写实际上找的未必是largest
largest = left
elif right < self._count and self._elements[right] >= self._elements[largest]:
largest = right
if largest != ndx:
self._elements[ndx], self._elements[largest] = self._elements[largest], self._elements[ndx]
self._siftdown(largest)
class MinHeap(object):
def __init__(self, maxsize = None):
self.maxsize = maxsize
self._elements = Array(maxsize)
self._count = 0
def __len__(self):
return self._count
def add(self, value):
if self._count >= self.maxsize:
raise Exception("The heap is full!")
self._elements[self._count] = value
self._count += 1
self._siftup(self._count-1)
def _siftup(self, index):
if index > 0:
parent = int((index - 1) / 2)
if self._elements[parent] > self._elements[index]:
self._elements[parent], self._elements[index] = self._elements[index], self._elements[parent]
self._siftup(parent)
def extract(self):
if self._count <= 0:
raise Exception('The heap is empty!')
value = self._elements[0]
self._count -= 1
self._elements[0] = self._elements[self._count]
self._siftdown(0)
return value
def _siftdown(self, index):
if index < self._count:
left = 2 * index + 1
right = 2 * index + 2
if left < self._count and right < self._count \
and self._elements[left] <= self._elements[right] \
and self._elements[left] <= self._elements[index]:
self._elements[left], self._elements[index] = self._elements[index], self._elements[left]
self._siftdown(left)
elif left < self._count and right < self._count \
and self._elements[left] >= self._elements[right] \
and self._elements[right] <= self._elements[index]:
self._elements[right], self._elements[index] = self._elements[index], self._elements[right]
self._siftdown(left)
if left < self._count and right > self._count \
and self._elements[left] <= self._elements[index]:
self._elements[left], self._elements[index] = self._elements[index], self._elements[left]
self._siftdown(left)
if __name__ == '__main__':
import random
n = 5
h = MinHeap(n)
a = [3,2,5,1,4]
for i in a:
h.add(i)
for i in range(n):
print(h.extract()) | {"/algorithm/sorting/bubble.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/datastruct/__init__.py": ["/algorithm/datastruct/listnode.py", "/algorithm/datastruct/tree.py"], "/algorithm/sorting/merge.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/quick.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/traverse/binary_tree_traverse.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/insertion.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/selection.py": ["/algorithm/datastruct/__init__.py"]} |
62,418 | itisianlee/pyaccepted | refs/heads/master | /algorithm/sorting/selection.py | import ipt
from algorithm.datastruct import ListNode, createlink, traverse
def selectionsort_a(arr):
l = len(arr)
for i in range(l):
minidx = i
for j in range(i, l):
if arr[j] < arr[minidx]:
minidx = j
arr[i], arr[minidx] = arr[minidx], arr[i]
def selectionsort_l1(head):
p = head
while p:
q = p
minnode = q
while q:
if q.val < minnode.val:
minnode = q
q = q.next
p.val, minnode.val = minnode.val, p.val
p = p.next
if __name__ == '__main__':
arr = [3, 1, 5, 10, 2, 8, 6]
# selectionsort_a(arr)
head = createlink(arr)
selectionsort_l1(head)
traverse(head)
| {"/algorithm/sorting/bubble.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/datastruct/__init__.py": ["/algorithm/datastruct/listnode.py", "/algorithm/datastruct/tree.py"], "/algorithm/sorting/merge.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/quick.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/traverse/binary_tree_traverse.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/insertion.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/selection.py": ["/algorithm/datastruct/__init__.py"]} |
62,419 | itisianlee/pyaccepted | refs/heads/master | /algorithm/datastruct/tree.py | class TreeNode:
def __init__(self, val=None):
self.val = val
self.left = None
self.right = None
self.visited = False
class Tree:
def __init__(self, valList=None):
assert isinstance(valList, list)
self.root = Tree.createtree(valList)
@staticmethod
def createtree(inputValues):
root = TreeNode(int(inputValues[0]))
nodeQueue = [root]
front = 0
index = 1
while index < len(inputValues):
node = nodeQueue[front]
front = front + 1
item = inputValues[index]
index = index + 1
if item:
leftNumber = int(item)
node.left = TreeNode(leftNumber)
nodeQueue.append(node.left)
if index >= len(inputValues):
break
item = inputValues[index]
index = index + 1
if item:
rightNumber = int(item)
node.right = TreeNode(rightNumber)
nodeQueue.append(node.right)
return root
| {"/algorithm/sorting/bubble.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/datastruct/__init__.py": ["/algorithm/datastruct/listnode.py", "/algorithm/datastruct/tree.py"], "/algorithm/sorting/merge.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/quick.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/traverse/binary_tree_traverse.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/insertion.py": ["/algorithm/datastruct/__init__.py"], "/algorithm/sorting/selection.py": ["/algorithm/datastruct/__init__.py"]} |
62,420 | uborzz/ocr-search | refs/heads/master | /rady_messages.py | # -*- coding: utf-8 -*-
import cv2
import rady_functions as rfs
class Messages(object):
__instance = None
def __new__(cls):
if cls.__instance is None:
cls.__instance = object.__new__(cls)
cls.__instance.__init__()
return cls.__instance
def __init__(self):
self.head = ""
self.information = ""
self.question = ""
self.answers = ""
def set_header(self, name):
self.head = name
def clear_info(self):
self.information = ""
def set_info(self, text):
self.information = text
def print_info_on_image(self, frame):
# CURRENT INFO
cv2.putText(frame, f"{self.head}", (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.55, rfs.color("white"), 1)
cv2.putText(frame, f"{self.information}", (10, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.55, rfs.color("red"), 1)
cv2.putText(frame, f"{self.question}", (10, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.55, rfs.color("yellow"), 1)
cv2.putText(frame, f"{self.answers}", (10, 100), cv2.FONT_HERSHEY_SIMPLEX, 0.55, rfs.color("blue"), 1)
| {"/rady_messages.py": ["/rady_functions.py"], "/rady_functions.py": ["/modes.py", "/rady_messages.py"], "/rady_searcher.py": ["/rady_functions.py", "/rady_messages.py"], "/__init__.py": ["/config.py", "/modes.py", "/rady_functions.py", "/rady_messages.py", "/rady_searcher.py", "/rady_stream.py"]} |
62,421 | uborzz/ocr-search | refs/heads/master | /pruebas.py | text = " el mismº preciº qprint(new_text)ue en Pcmuy inter"
new_text = text.replace('º', 'o')
| {"/rady_messages.py": ["/rady_functions.py"], "/rady_functions.py": ["/modes.py", "/rady_messages.py"], "/rady_searcher.py": ["/rady_functions.py", "/rady_messages.py"], "/__init__.py": ["/config.py", "/modes.py", "/rady_functions.py", "/rady_messages.py", "/rady_searcher.py", "/rady_stream.py"]} |
62,422 | uborzz/ocr-search | refs/heads/master | /rady_functions.py | # -*- coding: utf-8 -*-
import cv2
import numpy as np
from PIL import Image
import pytesseract
import modes
from rady_messages import Messages
msgs = Messages()
def cv2pil(image):
"""
Recibe imagen -np.array- de opencv (BGR)
Devuelve imagen Image de PIL
"""
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
pil_image = Image.fromarray(rgb_image)
return pil_image
def extract_text(image):
"""
:param image: Image. PIL.Image or np.ndarray (OpenCV image)
:return: text in image.
"""
# if type(image) is np.ndarray:
# # case image is and opencv image
# image = cv2pil(image)
text = pytesseract.image_to_string(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY), config="--psm 6", lang="spa")
# text = pytesseract.image_to_string(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY), config="--psm 6", lang="eng")
parsed_text = text.replace('º', 'o')
# print(image.shape)
print(parsed_text)
return parsed_text
def evaluate_key(key_pressed, camera, searcher, frame):
"""
:param key_pressed: identificacion tecla pulsada (return del waitKey de opencv)
:param camera:
:param searcher:
:param frame: imagen fresca
:return: Retorna True si el programa principal debe acabaaaaaaaaaaaaarr
"""
k = key_pressed
if k == ord('q'):
return True
elif k == 27:
return True
elif k == ord('w'):
camera.menu_config()
elif k == ord('z'):
# clicka zona preguntas
msgs.set_info("Clicka dos puntos para seleccionar el area de la pregunta!")
searcher.mode = modes.QUESTION_SET_FIRST_POINT
elif k == ord('x'):
# click zona respuestas
msgs.set_info("Clicka dos puntos para seleccionar el area de las respuestas!")
searcher.mode = modes.ANSWERS_SET_FIRST_POINT
elif k == ord('r'):
searcher.running = True
text = "Running..."
print(text)
msgs.set_info(text)
# corre deteccion en las zonas
elif k == ord('s'):
searcher.running = False
elif k == ord('m'):
# analiza a mano foto actual:
filtered_image = filter_image(frame)
text = extract_text(filtered_image)
print("\nBinarization", text)
elif k == ord('n'):
text = extract_text(frame)
print("\nSin filtros", text)
def color(color_name="white"):
"""
:param color_text: name of the color
:return: BGR tuple of that color
"""
if color_name == "green": bgr = (0, 255, 0)
elif color_name == "cyan": bgr = (255, 255, 0)
elif color_name == "yellow": bgr = (0, 255, 255)
elif color_name == "blue": bgr = (255, 0, 0)
elif color_name == "red": bgr = (0, 0, 255)
elif color_name == "black": bgr = (0,0,0)
else: bgr = (255, 255, 255) # white
return bgr
def print_overlays(frame, searcher):
cv2.rectangle(frame, (420, 205), (595, 385), (0, 0, 255), -1)
cv2.addWeighted(frame, alpha, output, 1 - alpha, 0, output)
def filter_image(image):
# load the example image and convert it to grayscale)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
# make a check to see if median blurring should be done to remove
# noise
gray = cv2.medianBlur(gray, 3)
result = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
print("Tamano gray:", gray.shape)
print("Tamano result:", result.shape)
cv2.imshow("Filtrada", gray)
return result
| {"/rady_messages.py": ["/rady_functions.py"], "/rady_functions.py": ["/modes.py", "/rady_messages.py"], "/rady_searcher.py": ["/rady_functions.py", "/rady_messages.py"], "/__init__.py": ["/config.py", "/modes.py", "/rady_functions.py", "/rady_messages.py", "/rady_searcher.py", "/rady_stream.py"]} |
62,423 | uborzz/ocr-search | refs/heads/master | /modes.py | # -*- coding: utf-8 -*-
QUESTION_SET_FIRST_POINT = 0
QUESTION_SET_SECOND_POINT = 1
ANSWERS_SET_FIRST_POINT = 2
ANSWERS_SET_SECOND_POINT = 3
| {"/rady_messages.py": ["/rady_functions.py"], "/rady_functions.py": ["/modes.py", "/rady_messages.py"], "/rady_searcher.py": ["/rady_functions.py", "/rady_messages.py"], "/__init__.py": ["/config.py", "/modes.py", "/rady_functions.py", "/rady_messages.py", "/rady_searcher.py", "/rady_stream.py"]} |
62,424 | uborzz/ocr-search | refs/heads/master | /rady_searcher.py | # -*- coding: utf-8 -*-
import cv2
import numpy as np
import rady_functions as rfs
from rady_messages import Messages
msgs = Messages()
class Searcher:
def __init__(self):
# initialize the video camera stream and read the first frame
# from the stream
self.running = False
self.mode = "normal"
self.__point = ()
self.roi_question_coords = ()
self.roi_answers_coords = ()
self.roi_question_mask = None
self.roi_answers_mask = None
self.question_text = None
self.answers_text = []
self.frame_shape = ()
self.mask_initialized = False
def initialize_masks(self, frame_shape):
self.frame_shape = frame_shape
self.roi_answers_mask = self.empty_mask()
self.roi_question_mask = self.empty_mask()
self.mask_initialized = True
def empty_mask(self):
if self.frame_shape:
return np.zeros(self.frame_shape, dtype=np.uint8)
else:
return None
def save_aux_point(self, x, y, next_mode):
self.__point = (x, y)
self.mode = next_mode
def save_roi_question(self, x, y):
if self.__point[0] < x:
x1 = self.__point[0]
x2 = x
else:
x1 = x
x2 = self.__point[0]
if self.__point[1] < y:
y1 = self.__point[1]
y2 = y
else:
y1 = y
y2 = self.__point[1]
self.__point = ()
self.roi_question_mask = self.empty_mask()
self.roi_question_coords = (x1, y1, x2, y2)
cv2.rectangle(self.roi_question_mask, (x1,y1), (x2,y2), color=rfs.color("yellow"), thickness=-1)
msgs.clear_info()
self.mode = "normal"
def save_roi_answers(self, x, y):
if self.__point[0] < x:
x1 = self.__point[0]
x2 = x
else:
x1 = x
x2 = self.__point[0]
if self.__point[1] < y:
y1 = self.__point[1]
y2 = y
else:
y1 = y
y2 = self.__point[1]
self.__point = ()
self.roi_answers_mask = self.empty_mask()
self.roi_answers_coords = (x1, y1, x2, y2)
cv2.rectangle(self.roi_answers_mask, (x1, y1), (x2, y2), color=rfs.color("blue"), thickness=-1)
msgs.clear_info()
self.mode = "normal"
def print_rois_on_image(self, frame):
# print(frame.shape, frame.dtype)
if self.roi_question_mask is not None:
frame = cv2.addWeighted(frame, 1, self.roi_question_mask, 0.3, 1, 0)
if self.roi_answers_mask is not None:
frame = cv2.addWeighted(frame, 1, self.roi_answers_mask, 0.3, 0.1, 0)
return frame | {"/rady_messages.py": ["/rady_functions.py"], "/rady_functions.py": ["/modes.py", "/rady_messages.py"], "/rady_searcher.py": ["/rady_functions.py", "/rady_messages.py"], "/__init__.py": ["/config.py", "/modes.py", "/rady_functions.py", "/rady_messages.py", "/rady_searcher.py", "/rady_stream.py"]} |
62,425 | uborzz/ocr-search | refs/heads/master | /rady_stream.py | from threading import Thread
import cv2
"""
rady
basado en webcamvideostream de pyimagesearch para raspi camera.
Camera props:
CAP_PROP_POS_MSEC Current position of the video file in milliseconds.
CAP_PROP_POS_FRAMES 0-based index of the frame to be decoded/captured next.
CAP_PROP_POS_AVI_RATIO Relative position of the video file: 0 - start of the film, 1 - end of the film.
CAP_PROP_FRAME_WIDTH Width of the frames in the video stream.
CAP_PROP_FRAME_HEIGHT Height of the frames in the video stream.
CAP_PROP_FPS Frame rate.
CAP_PROP_FOURCC 4-character code of codec.
CAP_PROP_FRAME_COUNT Number of frames in the video file.
CAP_PROP_FORMAT Format of the Mat objects returned by retrieve() .
CAP_PROP_MODE Backend-specific value indicating the current capture mode.
CAP_PROP_BRIGHTNESS Brightness of the image (only for cameras).
CAP_PROP_CONTRAST Contrast of the image (only for cameras).
CAP_PROP_SATURATION Saturation of the image (only for cameras).
CAP_PROP_HUE Hue of the image (only for cameras).
CAP_PROP_GAIN Gain of the image (only for cameras).
CAP_PROP_EXPOSURE Exposure (only for cameras).
CAP_PROP_CONVERT_RGB Boolean flags indicating whether images should be converted to RGB.
CAP_PROP_WHITE_BALANCE Currently unsupported
CAP_PROP_RECTIFICATION Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently)
"""
class Stream:
def __init__(self, src=0, resolution=None, framerate=30):
# initialize the video camera stream and read the first frame
# from the stream
self.stream = cv2.VideoCapture(src)
self.stream.set(cv2.CAP_PROP_FPS, framerate)
if resolution:
self.stream.set(cv2.CAP_PROP_FRAME_WIDTH, resolution[0])
self.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, resolution[1])
(self.grabbed, self.frame) = self.stream.read()
# initialize the variable used to indicate if the thread should
# be stopped
self.stopped = False
self.records = list()
def start(self):
# start the thread to read frames from the video stream
t = Thread(target=self.update, args=())
t.daemon = True
t.start()
return self
def update(self):
# keep looping infinitely until the thread is stopped
while True:
# if the thread indicator variable is set, stop the thread
if self.stopped:
return
# otherwise, read the next frame from the stream
(self.grabbed, self.frame) = self.stream.read()
def read(self):
# return the frame most recently read
return self.frame
def stop(self):
# indicate that the thread should be stopped
self.stopped = True
def menu_config(self):
# muestra menu configuracion params de la camara
self.stream.set(cv2.CAP_PROP_SETTINGS, 0)
| {"/rady_messages.py": ["/rady_functions.py"], "/rady_functions.py": ["/modes.py", "/rady_messages.py"], "/rady_searcher.py": ["/rady_functions.py", "/rady_messages.py"], "/__init__.py": ["/config.py", "/modes.py", "/rady_functions.py", "/rady_messages.py", "/rady_searcher.py", "/rady_stream.py"]} |
62,426 | uborzz/ocr-search | refs/heads/master | /__init__.py | # -*- coding: utf-8 -*-
from datetime import datetime, timedelta
import cv2
import config as cfg
import modes
import rady_functions as rfs
from rady_messages import Messages
from rady_searcher import Searcher
from rady_stream import Stream
t_start = datetime.now()
print("Comenzando LisaSimpson! Hora actual: {:%Y_%m_%d_%H_%M}".format(t_start))
# Camera
width, height = 640, 480
fps_camera = 30 # a mano, fps de captura de la camara (va en otro hilo).
rotate, undistort = False, False
# Workning params
fps_main = 25
cam = Stream(src=cfg.camera_src, resolution=(width, height), framerate=fps_camera).start()
schr = Searcher()
msgs = Messages()
msgs.set_header(f"{cfg.name} v{cfg.version}")
def clicks_callback(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONUP:
print(f"Clicked on {x}, {y}!")
if schr.mode == modes.QUESTION_SET_FIRST_POINT:
schr.save_aux_point(x, y, next_mode=modes.QUESTION_SET_SECOND_POINT)
elif schr.mode == modes.QUESTION_SET_SECOND_POINT:
schr.save_roi_question(x, y)
elif schr.mode == modes.ANSWERS_SET_FIRST_POINT:
schr.save_aux_point(x, y, next_mode=modes.ANSWERS_SET_SECOND_POINT)
elif schr.mode == modes.ANSWERS_SET_SECOND_POINT:
schr.save_roi_answers(x, y)
def main():
# handle clicks
cv2.namedWindow('General')
# cv2.moveWindow('General', 200, 100)
cv2.setMouseCallback('General', clicks_callback)
timer_fps = datetime.now() # guarda tiempo de ultimo procesamiento.
micros_para_procesar = timedelta(microseconds=int(1000000 / fps_main))
while True:
toca_procesar = datetime.now() - timer_fps >= micros_para_procesar
if not toca_procesar:
continue
timer_fps = datetime.now()
frame = cam.read()
if not schr.mask_initialized:
schr.initialize_masks(frame.shape)
# Espejo/rotate si/no?
if rotate:
frame = cv2.flip(frame, -1) # 0 eje x, 1 eje y. -1 ambos (rota 180).
# Lectura teclas apretadas
k = cv2.waitKey(1)
if rfs.evaluate_key(key_pressed=k, camera=cam, searcher=schr, frame=frame):
break
# # Tiempo de tregua
# if datetime.now() - t_start <= timedelta(seconds=1):
# continue
if schr.running == True:
# analiza imagenes -> obtiene cadenas texto -> busca google
# Question
(x1, y1, x2, y2) = schr.roi_question_coords
question_image_crop = frame[y1:y2, x1:x2]
cv2.imshow("RECORTE", question_image_crop)
msgs.question = rfs.extract_text(question_image_crop)
# # Answers
# (x1, y1, x2, y2) = schr.roi_answers_coords
# answers_image_crop = frame[y1:y2, x1:x2]
# cv2.imshow("RECORTE", answers_image_crop)
# msgs.answers = rfs.extract_text(answers_image_crop)
# filtered_image = rfs.filter_image(frame)
# # msgs.question = rfs.extract_text(filtered_image)
msgs.print_info_on_image(frame)
resultado = schr.print_rois_on_image(frame)
cv2.imshow('General', resultado)
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
| {"/rady_messages.py": ["/rady_functions.py"], "/rady_functions.py": ["/modes.py", "/rady_messages.py"], "/rady_searcher.py": ["/rady_functions.py", "/rady_messages.py"], "/__init__.py": ["/config.py", "/modes.py", "/rady_functions.py", "/rady_messages.py", "/rady_searcher.py", "/rady_stream.py"]} |
62,427 | uborzz/ocr-search | refs/heads/master | /config.py | # -*- coding: utf-8 -*-
name = "LisaSimpson"
version = 0.0
camera_src = 0 # primera camara del pc. | {"/rady_messages.py": ["/rady_functions.py"], "/rady_functions.py": ["/modes.py", "/rady_messages.py"], "/rady_searcher.py": ["/rady_functions.py", "/rady_messages.py"], "/__init__.py": ["/config.py", "/modes.py", "/rady_functions.py", "/rady_messages.py", "/rady_searcher.py", "/rady_stream.py"]} |
62,440 | kosi2109/restraunt | refs/heads/master | /table/migrations/0001_initial.py | # Generated by Django 3.2.5 on 2021-08-08 12:46
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('menu', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Table',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('table_no', models.CharField(max_length=50, null=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='table', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='TableOrder',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('order_date', models.DateField(blank=True, null=True)),
('order_time', models.TimeField(blank=True, null=True)),
('order_id', models.CharField(blank=True, max_length=100, null=True)),
('slug', models.SlugField(blank=True, null=True, unique=True)),
('ckecked', models.BooleanField(default=False, null=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='table.table')),
],
options={
'verbose_name_plural': 'Orders',
'ordering': ('-order_time',),
},
),
migrations.CreateModel(
name='TableOrderItem',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('quatity', models.IntegerField(default=1)),
('cooked', models.BooleanField(default=False, null=True)),
('ordered', models.BooleanField(default=False, null=True)),
('item', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='menu.menu')),
('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='table.tableorder')),
],
),
]
| {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,441 | kosi2109/restraunt | refs/heads/master | /owner/decorators.py | from django.shortcuts import redirect
def unauthenticated_user(view_func):
def wrapper_func(request, *args , **kwargs ):
if request.user.is_authenticated:
if request.user.is_superuser:
return redirect('owner:home')
else:
return redirect('menu:menu')
else:
return view_func(request, *args , **kwargs )
return wrapper_func
def admin_only(view_func):
def wrapper_function(request, *args, **kwargs):
if request.user.is_superuser:
return view_func(request, *args, **kwargs)
else:
return redirect('menu:menu')
return wrapper_function
def chef(view_func):
def wrapper_function(request, *args, **kwargs):
if request.user.is_chef or request.user.is_superuser:
return view_func(request, *args, **kwargs)
else:
return redirect('menu:menu')
return wrapper_function | {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,442 | kosi2109/restraunt | refs/heads/master | /menu/form.py | from .models import UserNew
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = UserNew
fields = ('username','is_table','is_user','is_chef')
class CustomUserChangeForm(UserChangeForm):
class Meta(UserChangeForm):
model = UserNew
fields = ('username','is_table','is_user','is_chef') | {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,443 | kosi2109/restraunt | refs/heads/master | /owner/views.py | from django.shortcuts import render,redirect
from table.models import TableOrder
from menu.models import Order,MUser,Menu,Category
# Create your views here.
from datetime import datetime, timedelta
import operator
from django.db.models import Q
from .forms import *
from django.http import JsonResponse
import json
from .filters import OrderFilter,MenuFilter
from .decorators import *
from django.contrib.auth.decorators import login_required
class Sales:
def __init__(self,order,table):
self.order = order
self.table = table
def dalySale(self):
today = datetime.now().date()
order = self.order.objects.filter(ckecked = True,order_date=today)
table = self.table.objects.filter(ckecked = True,order_date=today)
total = 0
for i in order:
total += i.get_order_total
for i in table:
total += i.get_order_total
return total
def monthlySale(self):
dt = datetime.now().date()
this_mo = dt.month
nex_mo = dt.month +1
timestamp_from = datetime(2021,this_mo,1)
timestamp_to = datetime(2021,nex_mo,1)
order = self.order.objects.filter(ckecked = True,order_date__range=[timestamp_from, timestamp_to])
table = self.table.objects.filter(ckecked = True,order_date__range=[timestamp_from, timestamp_to])
total = 0
for i in order:
total += i.get_order_total
for i in table:
total += i.get_order_total
return total
def yearSale(self):
dt = datetime.now().date()
this_mo = dt.year
nex_mo = dt.year +1
timestamp_from = datetime(this_mo,1,1)
timestamp_to = datetime(nex_mo,1,1)
order = self.order.objects.filter(ckecked = True,order_date__range=[timestamp_from, timestamp_to])
table = self.table.objects.filter(ckecked = True,order_date__range=[timestamp_from, timestamp_to])
total = 0
for i in order:
total += i.get_order_total
for i in table:
total += i.get_order_total
return total
class MostCommonUser():
def most_order():
users = MUser.objects.all()
li = {}
for index,i in enumerate(users):
orders = i.get_total_order
li[index] = orders
sorted_li = sorted(li.items(), key=operator.itemgetter(1),reverse=True)
most_order_user = []
for i in sorted_li[0:5]:
ind = i[0]
user = MUser.objects.all()
most_order_user.append(users[ind])
return most_order_user
def most_money_spend():
users = MUser.objects.all()
li = {}
for index,i in enumerate(users):
orders = i.get_total_spend
li[index] = orders
sorted_li = sorted(li.items(), key=operator.itemgetter(1),reverse=True)
most_order_user = []
for i in sorted_li[0:5]:
ind = i[0]
user = MUser.objects.all()
most_order_user.append(users[ind])
return most_order_user
class BestMenu():
def get_best_item():
menu = Menu.objects.all()
li = {}
for index,i in enumerate(menu):
itemtotal = i.get_total_selling
li[index] = itemtotal
sorted_li = sorted(li.items(), key=operator.itemgetter(1),reverse=True)
most_order_item = []
for i in sorted_li[0:5]:
ind = i[0]
menu = Menu.objects.all()
most_order_item.append(menu[ind])
return most_order_item
def get_best_cate():
cate = Category.objects.all()
li = {}
for index,i in enumerate(cate):
catetotal = i.get_total_selling
li[index] = catetotal
sorted_li = sorted(li.items(), key=operator.itemgetter(1),reverse=True)
most_order_cate = []
for i in sorted_li[0:5]:
ind = i[0]
cate = Category.objects.all()
most_order_cate.append(cate[ind])
return most_order_cate
@admin_only
@login_required(login_url='menu:login')
def home(request):
sale = Sales(Order,TableOrder)
year = sale.yearSale()
month = sale.monthlySale()
daily = sale.dalySale()
sales = dict(year=year,month=month,daily=daily)
most_order = MostCommonUser.most_order()
most_spent = MostCommonUser.most_money_spend()
most_order_item = BestMenu.get_best_item()
most_order_cate = BestMenu.get_best_cate()
ctx = {'sales':sales,'most_order':most_order,'most_spent':most_spent,'most_order_item':most_order_item,'most_order_cate':most_order_cate,'nav':'home'}
return render(request,'owner/index.html',ctx)
@admin_only
@login_required(login_url='menu:login')
def order(request):
filterform = OrderFilter()
today = datetime.now().date()
activeorders = []
allorders = []
activeorder = Order.objects.filter(Q(status='Cooking',ckecked=True) | Q(status='Delivering',ckecked=True))
completeorder = Order.objects.filter(status='Delivered',ckecked=True,order_date=today)
activetableorder = TableOrder.objects.filter(ckecked=False)
completetableorder = TableOrder.objects.filter(ckecked=True,order_date=today)
for i in activeorder:
activeorders.append(i)
for i in activetableorder:
activeorders.append(i)
for i in completeorder:
allorders.append(i)
for i in completetableorder:
allorders.append(i)
ctx = {'allorders':allorders,'activeorders':activeorders,'filterform':filterform,'nav':'order'}
return render(request,'owner/orders.html',ctx)
@admin_only
@login_required(login_url='menu:login')
def menu(request):
category = Category.objects.all()
menu = Menu.objects.all()
menuform = MenuForm()
menufilter = MenuFilter()
if request.method == "POST":
menuform = MenuForm(request.POST,request.FILES)
if menuform.is_valid():
menuform.save()
return redirect('owner:menu')
else:
menuform = MenuForm()
if request.method == "GET":
menufilter = MenuFilter(request.GET,queryset=menu)
menu = menufilter.qs
ctx ={'category':category,'menu':menu,'menuform':menuform,'menufilter':menufilter,'nav':'menu'}
return render(request,'owner/menu.html',ctx)
@admin_only
@login_required(login_url='menu:login')
def addcategory(request):
if request.method == "POST":
name = request.POST.get('category')
image = request.FILES.get('image')
Category.objects.create(name=name,image=image)
return redirect('owner:menu')
@admin_only
@login_required(login_url='menu:login')
def menuDelete(request,slug):
item = Menu.objects.get(slug=slug)
if request.method == "POST":
item.delete()
return redirect('owner:menu')
return render(request,'owner/delete.html',{'item':item,'nav':'menu'})
@admin_only
@login_required(login_url='menu:login')
def cateDelete(request,slug):
item = Category.objects.get(slug=slug)
if request.method == "POST":
item.delete()
return redirect('owner:menu')
return render(request,'owner/delete.html',{'item':item,'nav':'menu'})
@admin_only
@login_required(login_url='menu:login')
def statusControl(request):
data = json.loads(request.body)
orderSlug = data['order']
value = data['value']
order = Order.objects.get(slug=orderSlug)
order.status = value
order.save()
return JsonResponse(data)
@admin_only
@login_required(login_url='menu:login')
def filterorder(request):
order = Order.objects.all()
filterform = OrderFilter(request.GET,queryset=order)
order = filterform.qs
ctx = {'order':order,'nav':'order'}
return render(request,'owner/filter.html',ctx)
| {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,444 | kosi2109/restraunt | refs/heads/master | /chef/views.py | from django.shortcuts import render
from menu.models import Order,OrderItem
from table.models import TableOrder,TableOrderItem,Table
from django.http import HttpResponse , JsonResponse
import json
from owner.decorators import *
from django.contrib.auth.decorators import login_required
@login_required(login_url='menu:login')
@chef
def orderView(request):
return render(request,'chef/orderView.html')
@login_required(login_url='menu:login')
@chef
def getOrders(request):
total_orders = []
table_order = TableOrderItem.objects.filter(ordered=True,cooked=False)
for i in table_order:
total_orders.append(dict(slug=i.slug,order_by = i.order.user.table_no,order_id = i.order.slug,order_item = i.item.name , quantity = i.quatity))
orders = Order.objects.filter(ckecked=True)
for order in orders:
od = order.orderitem_set.filter(cooked=False)
for i in od:
total_orders.append(dict(slug=i.slug,order_by = i.order.order_id,order_id = i.order.slug,order_item = i.item.name , quantity = i.quatity))
data = {'data':total_orders}
return JsonResponse(data)
@login_required(login_url='menu:login')
@chef
def cookControl(request):
data = json.loads(request.body)
cook_id = data['cook_id']
action = data['action']
table_no = data['table']
if action == 'cooked':
if OrderItem.objects.filter(slug=cook_id).exists():
item = OrderItem.objects.get(slug=cook_id)
item.cooked = True
item.save()
else:
table_no = data['table']
tableorder = TableOrder.objects.get(order_id=table_no)
cooked = tableorder.tableorderitem_set.filter(ordered=True,cooked=True)
not_cooked = TableOrderItem.objects.get(slug=cook_id)
if len(cooked) > 0:
for j in cooked:
if not_cooked.item.slug == j.item.slug:
print('Same')
j.quatity += not_cooked.quatity
j.save()
not_cooked.delete()
else:
print('Not Same')
not_cooked.cooked =True
not_cooked.save()
else:
item = TableOrderItem.objects.get(slug=cook_id)
item.cooked = True
item.save()
elif action == 'cancelcook':
if OrderItem.objects.filter(slug=cook_id).exists():
item = OrderItem.objects.get(slug=cook_id)
item.delete()
else:
item = TableOrderItem.objects.get(slug=cook_id)
item.delete()
return JsonResponse(data) | {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,445 | kosi2109/restraunt | refs/heads/master | /table/migrations/0003_alter_tableorder_options.py | # Generated by Django 3.2.5 on 2021-08-13 06:39
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('table', '0002_tableorderitem_slug'),
]
operations = [
migrations.AlterModelOptions(
name='tableorder',
options={},
),
]
| {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,446 | kosi2109/restraunt | refs/heads/master | /menu/views.py | from django.shortcuts import render,redirect
from .models import *
from datetime import date
from django.http import JsonResponse
import json
from django.utils import timezone
from django import forms
from django.contrib.auth import authenticate, login, logout
from datetime import datetime
from table.models import *
from django.contrib.auth.forms import UserCreationForm
from owner.views import BestMenu
from owner.decorators import *
from django.contrib.auth.decorators import login_required
class CreateUserForm(UserCreationForm):
class Meta:
model = UserNew
fields = ['username','email','first_name','last_name','password1','password2']
widgets = {
'username': forms.TextInput(attrs={'id':'username','placeholder':'Username'}),
'email': forms.TextInput(attrs={'id':'exampleInputEmail1','placeholder':'Email'}),
'password1': forms.PasswordInput(attrs={'id':'Password1'}),
'password2': forms.PasswordInput(attrs={'id':'Password2'}),
'first_name': forms.TextInput(attrs={'placeholder':'First Name'}),
'last_name': forms.TextInput(attrs={'placeholder':'Last Name'}),
}
@unauthenticated_user
def registerPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
email = form.cleaned_data.get('email')
first_name = form.cleaned_data.get('first_name')
last_name = form.cleaned_data.get('last_name')
phone = request.POST.get('phone')
address = request.POST.get('address')
MUser.objects.create(
user = user ,
F_Name = first_name,
L_Name = last_name,
email = email,
phone = phone,
address=address
)
return redirect('menu:userLogin')
ctx = {'form':form}
return render(request,'menu/signup.html',ctx)
@unauthenticated_user
def userLogin(request):
if request.method == 'POST' or None:
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request,username=username,password=password)
if user is not None:
login(request,user)
if request.user.is_table:
logout(request)
return redirect('menu:userLogin')
elif request.user.is_superuser:
return redirect('owner:home')
else:
return redirect('menu:menu')
else:
return redirect('menu:userLogin')
return render(request ,'menu/login.html' )
def userLogout(request):
logout(request)
return redirect('menu:menu')
def home(request):
return render(request , 'menu/index.html')
def getorder(request):
if request.user.is_authenticated:
if request.user.is_user:
user = request.user.muser
order = list(user.order_set.all())
if len(order) > 0:
last_order = order[-1]
if last_order.ckecked == False:
current_order = last_order
order_item = current_order.orderitem_set.all()
cart_item = []
else:
current_order = None
order_item = []
cart_item = []
else:
current_order = None
order_item = []
cart_item = []
elif request.user.is_table:
user = request.user.table
order = list(user.tableorder_set.all())
if len(order) > 0:
last_order = order[-1]
if last_order.ckecked == False:
current_order = last_order
order_item = current_order.tableorderitem_set.filter(ordered=True)
cart_item = current_order.tableorderitem_set.filter(ordered=False)
else:
current_order = None
order_item = []
cart_item = []
else:
current_order = None
order_item = []
cart_item = []
else:
current_order = None
order_item = []
cart_item = []
else:
order = []
current_order = None
order_item = []
cart_item = []
ctx = {'order_item':order_item,'current_order':current_order,'cart_item':cart_item}
return ctx
def menu(request):
category = Category.objects.all()
menu = Menu.objects.all()
bestselling = BestMenu.get_best_item
cx = getorder(request)
order_item = cx['order_item']
current_order = cx['current_order']
cart_item = cx['cart_item']
ctx = {'menu':menu,'bestselling':bestselling,'category':category,'order_item':order_item,'current_order':current_order,'cart_item':cart_item}
return render(request,'menu/menu.html',ctx)
def category(request,slug):
category = Category.objects.all()
ct = Category.objects.get(slug=slug)
menu = Menu.objects.filter(category=ct)
cx = getorder(request)
order_item = cx['order_item']
current_order = cx['current_order']
cart_item = cx['cart_item']
ctx = {'menu':menu,'category':category,'order_item':order_item,'current_order':current_order,'cart_item':cart_item}
return render(request , 'menu/category.html',ctx)
def add_to_cart(request,menuSlug,last_order):
if request.user.is_authenticated:
if request.user.is_user:
user = request.user.muser
item = Menu.objects.get(slug=menuSlug)
if last_order.ckecked == False:
if OrderItem.objects.filter(order=last_order,item=item).exists():
ordered_item = OrderItem.objects.get(order=last_order,item=item)
ordered_item.quatity += 1
ordered_item.save()
else:
OrderItem.objects.create(order=last_order,item=item)
else:
new = Order.objects.create(user=user)
OrderItem.objects.create(order=new,item=item)
elif request.user.is_table:
item = Menu.objects.get(slug=menuSlug)
if last_order.ckecked == False:
if TableOrderItem.objects.filter(order=last_order,item=item,ordered=False).exists():
ordered_item = TableOrderItem.objects.get(order=last_order,item=item,ordered=False)
ordered_item.quatity += 1
ordered_item.save()
else:
TableOrderItem.objects.create(order=last_order,item=item)
else:
new = TableOrder.objects.create(user=user)
TableOrderItem.objects.create(order=new,item=item)
def increse_decrese(action,data,typeO):
if action == 'increase':
menuSlug = data['menuSlug']
item = typeO.objects.get(slug=menuSlug)
item.quatity += 1
item.save()
if action == 'decrease':
menuSlug = data['menuSlug']
item = typeO.objects.get(slug=menuSlug)
item.quatity -= 1
item.save()
if item.quatity < 1:
item.delete()
def handleOrder(request):
if request.user.is_authenticated:
if request.user.is_user:
user = request.user.muser
order = list(user.order_set.all())
data = json.loads(request.body)
action = data['action']
if len(order) > 0 :
last_order = order[-1]
if action == 'add':
menuSlug = data['menuSlug']
add_to_cart(request,menuSlug,last_order)
if action == 'increase':
increse_decrese(action,data,OrderItem)
if action == 'decrease':
increse_decrese(action,data,OrderItem)
else:
menuSlug = data['menuSlug']
item = Menu.objects.get(slug=menuSlug)
new = Order.objects.create(user=user)
OrderItem.objects.create(order=new,item=item)
elif request.user.is_table:
user = request.user.table
order = list(user.tableorder_set.all())
data = json.loads(request.body)
action = data['action']
if len(order) > 0 :
last_order = order[-1]
if action == 'add':
menuSlug = data['menuSlug']
add_to_cart(request,menuSlug,last_order)
if action == 'comfirm':
not_ordered = TableOrderItem.objects.filter(order=last_order,ordered=False)
for i in not_ordered:
i.ordered = True
i.save()
if action == 'increase':
increse_decrese(action,data,TableOrderItem)
if action == 'decrease':
increse_decrese(action,data,TableOrderItem)
else:
new = TableOrder.objects.create(user=user)
TableOrderItem.objects.create(order=new,item=item)
return JsonResponse(data)
@login_required(login_url='menu:login')
def checkout(request,slug):
if request.user.is_user:
user = request.user.muser
order = Order.objects.get(user=user,slug=slug)
item = order.orderitem_set.all()
if request.method == 'POST':
order.order_date = datetime.now().date()
order.order_time = datetime.now().time()
order.ckecked = True
order.save()
return redirect('menu:menu')
elif request.user.is_table:
user = request.user.table
order = TableOrder.objects.get(user=user,slug=slug)
item = order.tableorderitem_set.filter(ordered=True)
not_order = order.tableorderitem_set.filter(ordered=False)
if request.method == 'POST':
for i in not_order:
i.delete()
order.order_date = datetime.now().date()
order.order_time = datetime.now().time()
order.ckecked = True
order.save()
logout(request)
return redirect('menu:menu')
else:
order = None
item = []
ctx = {'order':order,'item':item}
return render(request , 'menu/checkout.html',ctx)
def search(request):
category = Category.objects.all()
menu = Menu.objects.all()
cx = getorder(request)
order_item = cx['order_item']
current_order = cx['current_order']
cart_item = cx['cart_item']
if request.method == "POST":
data = request.POST['searched']
menu = Menu.objects.filter(name__icontains=data)
if len(data) > 0:
ctx = {'menu':menu,'category':category,'order_item':order_item,'current_order':current_order,'data':data}
return render(request,'menu/search.html',ctx)
else:
return redirect('menu:menu')
else:
ctx = {'category':category,'order_item':order_item,'current_order':current_order,'cart_item':cart_item}
return render(request,'menu/search.html',ctx)
@login_required(login_url='menu:login')
def orderHistory(request):
if request.user.is_user:
user = request.user.muser
order = Order.objects.filter(user=user,ckecked=True).order_by('-order_date')
totalorder = len(order)
ctx = {'order':order,'totalorder':totalorder,'user':user}
return render(request,'menu/history.html',ctx)
def jointable(request):
if request.method == 'POST' or None:
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request,username=username,password=password)
if user is not None:
login(request,user)
return redirect('menu:menu')
else:
return redirect('menu:userLogin')
return render(request,'menu/tableRequest.html')
def handlestatus(request):
user = request.user.table
order = list(user.tableorder_set.all())
if len(order) > 0:
last_order = order[-1]
if last_order.ckecked == False:
current_order = last_order
order_item = current_order.tableorderitem_set.filter(ordered=True)
data = list(order_item.values())
return JsonResponse(data,safe=False)
else:
data = []
return JsonResponse(data,safe=False)
| {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,447 | kosi2109/restraunt | refs/heads/master | /menu/admin.py | from django.contrib import admin
from .models import *
from django.contrib.auth.admin import UserAdmin
# Register your models here.
from .form import CustomUserCreationForm,CustomUserChangeForm
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = UserNew
list_display = ['username', 'is_table','is_user','is_chef',]
fieldsets = UserAdmin.fieldsets + (
(None, {'fields': ('is_table','is_user','is_chef',)}),
)
admin.site.register(MUser)
admin.site.register(Category)
admin.site.register(Menu)
admin.site.register(Order)
admin.site.register(OrderItem)
admin.site.register(UserNew, CustomUserAdmin) | {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,448 | kosi2109/restraunt | refs/heads/master | /menu/migrations/0007_auto_20210811_1858.py | # Generated by Django 3.2.5 on 2021-08-11 12:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('menu', '0006_orderitem_slug'),
]
operations = [
migrations.AddField(
model_name='usernew',
name='is_chef',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='usernew',
name='is_user',
field=models.BooleanField(default=True),
),
]
| {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,449 | kosi2109/restraunt | refs/heads/master | /menu/migrations/0008_auto_20210813_1309.py | # Generated by Django 3.2.5 on 2021-08-13 06:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('menu', '0007_auto_20210811_1858'),
]
operations = [
migrations.AlterModelOptions(
name='order',
options={},
),
migrations.AlterField(
model_name='category',
name='image',
field=models.ImageField(blank=True, default='category/category.png', upload_to='category/'),
),
]
| {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,450 | kosi2109/restraunt | refs/heads/master | /menu/migrations/0003_alter_category_image.py | # Generated by Django 3.2.5 on 2021-08-10 04:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('menu', '0002_category_image'),
]
operations = [
migrations.AlterField(
model_name='category',
name='image',
field=models.ImageField(default='category.png', upload_to='category/'),
),
]
| {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,451 | kosi2109/restraunt | refs/heads/master | /owner/urls.py | from django.urls import path
from .views import *
app_name = 'owner'
urlpatterns = [
path('',home,name='home'),
path('menu/',menu,name='menu'),
path('order/',order,name='order'),
path('addcategory/',addcategory,name='addcategory'),
path('menuDelete/<slug:slug>/',menuDelete,name='menuDelete'),
path('cateDelete/<slug:slug>/',cateDelete,name='cateDelete'),
path('statusControl/',statusControl,name='statusControl'),
path('filterorder/',filterorder,name='filterorder'),
] | {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,452 | kosi2109/restraunt | refs/heads/master | /menu/urls.py | from django.urls import path
from .views import *
app_name = 'menu'
urlpatterns =[
path('signup/',registerPage ,name='registerPage'),
path('login/',userLogin ,name='userLogin'),
path('logout/',userLogout ,name='userLogout'),
path('',home ,name='home'),
path('menu/',menu ,name='menu'),
path('handleOrder/',handleOrder ,name='handleOrder'),
path('checkout/<slug:slug>',checkout ,name='checkout'),
path('menu/<slug:slug>/',category ,name='category'),
path('search/',search ,name='search'),
path('jointable/',jointable ,name='jointable'),
path('orderHistory/',orderHistory ,name='orderHistory'),
path('handlestatus/',handlestatus ,name='handlestatus'),
] | {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,453 | kosi2109/restraunt | refs/heads/master | /owner/filters.py | import django_filters
from menu.models import Order,Menu
from django import forms
class OrderFilter(django_filters.FilterSet):
order_id = django_filters.CharFilter(field_name='order_id',lookup_expr='icontains',widget=forms.TextInput(attrs={'placeholder':'Order Id','class':'form-control mb-3'}))
order_date__gt = django_filters.DateFilter(field_name='order_date', lookup_expr='gte',widget=forms.TextInput(attrs={'class':'form-control mb-3','type':'date'}))
order_date__lt = django_filters.DateFilter(field_name='order_date', lookup_expr='lte',widget=forms.TextInput(attrs={'class':'form-control mb-3','type':'date'}))
class Meta:
model = Order
fields = ['order_id']
class MenuFilter(django_filters.FilterSet):
name = django_filters.CharFilter(field_name='name',lookup_expr='icontains',widget=forms.TextInput(attrs={'placeholder':'Name','class':'form-control me-2'}))
class Meta:
model = Order
fields = ['name'] | {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,454 | kosi2109/restraunt | refs/heads/master | /menu/migrations/0001_initial.py | # Generated by Django 3.2.5 on 2021-08-08 12:46
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='UserNew',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('is_table', models.BooleanField(default=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.CreateModel(
name='Category',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, null=True)),
('slug', models.SlugField(blank=True, editable=False, null=True, unique=True)),
],
options={
'verbose_name_plural': 'Categories',
'ordering': ('name',),
},
),
migrations.CreateModel(
name='Menu',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, null=True)),
('size', models.CharField(blank=True, choices=[('S', 'Small'), ('M', 'Medium'), ('L', 'Large')], max_length=20)),
('price', models.IntegerField()),
('slug', models.SlugField(blank=True, editable=False, null=True, unique=True)),
('image', models.ImageField(upload_to='menu/')),
('category', models.ManyToManyField(to='menu.Category')),
],
options={
'verbose_name_plural': 'Menus',
'ordering': ('name',),
},
),
migrations.CreateModel(
name='MUser',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('F_Name', models.CharField(max_length=50, null=True)),
('L_Name', models.CharField(max_length=50, null=True)),
('email', models.CharField(max_length=100, null=True)),
('phone', models.CharField(max_length=100, null=True)),
('address', models.TextField()),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Order',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('order_date', models.DateField(blank=True, null=True)),
('order_time', models.TimeField(blank=True, null=True)),
('order_id', models.CharField(blank=True, max_length=100, null=True)),
('slug', models.SlugField(blank=True, null=True, unique=True)),
('ckecked', models.BooleanField(default=False, null=True)),
('status', models.CharField(blank=True, choices=[('C', 'Cooking'), ('D', 'Delivering'), ('F', 'Delivered')], default='C', max_length=20, null=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='menu.muser')),
],
options={
'verbose_name_plural': 'Orders',
'ordering': ('-order_time',),
},
),
migrations.CreateModel(
name='OrderItem',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('quatity', models.IntegerField(default=1)),
('cooked', models.BooleanField(default=False, null=True)),
('item', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='menu.menu')),
('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='menu.order')),
],
),
]
| {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,455 | kosi2109/restraunt | refs/heads/master | /menu/migrations/0005_alter_order_status.py | # Generated by Django 3.2.5 on 2021-08-10 06:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('menu', '0004_alter_category_image'),
]
operations = [
migrations.AlterField(
model_name='order',
name='status',
field=models.CharField(blank=True, choices=[('Cooking', 'Cooking'), ('Delivering', 'Delivering'), ('Delivered', 'Delivered')], default='Cooking', max_length=20, null=True),
),
]
| {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,456 | kosi2109/restraunt | refs/heads/master | /table/models.py | from django.db import models
from menu.models import Menu,UserNew
import uuid
class Table(models.Model):
user = models.OneToOneField(UserNew,on_delete=models.CASCADE,related_name='table')
table_no = models.CharField(max_length=50,null=True)
def __str__(self):
return self.table_no
class TableOrder(models.Model):
user = models.ForeignKey(Table, on_delete=models.CASCADE)
order_date = models.DateField(blank=True,null=True)
order_time = models.TimeField(blank=True,null=True)
order_id = models.CharField(max_length=100,null=True,blank=True)
slug = models.SlugField(max_length=50,null=True,unique=True,editable=True,blank=True)
ckecked = models.BooleanField(default=False,null=True)
def save(self,*args,**kwargs):
if not self.order_id:
counter = 1
self.order_id = f'T_{counter}'
while TableOrder.objects.filter(order_id=self.order_id).exists():
counter += 1
self.order_id = f'T_{counter}'
if not self.slug:
self.slug = self.order_id
super().save(*args,**kwargs)
@property
def get_order_total(self):
orderitems = self.tableorderitem_set.all()
total_list = []
for item in orderitems:
if item.ordered == True:
total_list.append(item.get_sub_total)
total = sum(total_list)
return total
@property
def get_order_qty(self):
orderitems = self.tableorderitem_set.all()
total = sum([x.quatity for x in orderitems])
return total
class TableOrderItem(models.Model):
order = models.ForeignKey(TableOrder,on_delete=models.CASCADE)
item = models.ForeignKey(Menu,on_delete=models.PROTECT)
quatity = models.IntegerField(default=1)
cooked = models.BooleanField(default=False,null=True)
ordered = models.BooleanField(default=False,null=True)
slug = models.SlugField(max_length=50,null=True,unique=True,editable=True,blank=True)
def save(self,*args,**kwargs):
if not self.slug:
self.slug = uuid.uuid4()
super().save(*args,**kwargs)
@property
def get_sub_total(self):
return self.item.price * self.quatity
| {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,457 | kosi2109/restraunt | refs/heads/master | /chef/urls.py | from django.urls import path
from .views import *
app_name = 'chef'
urlpatterns =[
path('',orderView,name='orderView'),
path('getOrders/',getOrders,name='getOrders'),
path('cookControl/',cookControl,name='cookControl'),
] | {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,458 | kosi2109/restraunt | refs/heads/master | /menu/migrations/0009_auto_20210813_2245.py | # Generated by Django 3.2.5 on 2021-08-13 16:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('menu', '0008_auto_20210813_1309'),
]
operations = [
migrations.AlterField(
model_name='category',
name='slug',
field=models.SlugField(blank=True, null=True, unique=True),
),
migrations.AlterField(
model_name='menu',
name='slug',
field=models.SlugField(blank=True, null=True, unique=True),
),
]
| {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,459 | kosi2109/restraunt | refs/heads/master | /owner/forms.py | from django import forms
from menu.models import Menu,Category
class MenuForm(forms.ModelForm):
class Meta:
model = Menu
fields = '__all__'
exclude = ("slug",)
category = forms.MultipleChoiceField()
widgets = {
'category': forms.CheckboxSelectMultiple(attrs={'id':'multicb','class':'form-control','multiple': True,'type':'checkbox'}),
'name': forms.TextInput(attrs={'placeholder':'Menu Name','class':'form-control mb-3'}),
'size': forms.Select(attrs={'placeholder':'size','class':'form-control mb-3'}),
'price': forms.NumberInput(attrs={'placeholder':'price','class':'form-control mb-3'}),
'image': forms.ClearableFileInput(attrs={'class':'form-control','accept':"image/*"}),
}
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = '__all__'
exclude = ("slug",)
widgets = {
'name': forms.TextInput(attrs={'placeholder':'Category Name','class':'form-control mb-3'}),
'image': forms.ClearableFileInput(attrs={'class':'form-control','accept':"image/*"}),
} | {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,460 | kosi2109/restraunt | refs/heads/master | /menu/models.py | from django.db import models
import uuid
from django.contrib.auth.models import User,AbstractUser,AbstractBaseUser,PermissionsMixin
from datetime import date
from datetime import datetime
from django.utils import timezone
from cloudinary.models import CloudinaryField
class UserNew(AbstractUser):
is_table = models.BooleanField(default=False)
is_user = models.BooleanField(default=True)
is_chef = models.BooleanField(default=False)
class MUser(models.Model):
user = models.OneToOneField(UserNew,on_delete=models.CASCADE)
F_Name = models.CharField(max_length=50,null=True)
L_Name = models.CharField(max_length=50,null=True)
email = models.CharField(max_length=100,null=True)
phone = models.CharField(max_length=100,null=True)
address = models.TextField(blank=False)
@property
def get_total_spend(self):
orders = self.order_set.all()
total = 0
for order in orders:
total += order.get_order_total
return total
@property
def get_total_order(self):
orders = self.order_set.count()
return orders
def __str__(self):
return f"{self.F_Name} {self.L_Name}"
class Category(models.Model):
image = CloudinaryField('image')
name = models.CharField(max_length=100,null=True)
slug = models.SlugField(null=True,blank=True,unique=True)
def save(self,*args,**kwargs):
if not self.slug:
name = self.name.split(" ")
name = ''.join(name)
self.slug = f"c_{name.lower()}"
count = 1
while Category.objects.filter(slug=self.slug).exists():
self.slug = f"c_{name.lower()}_{str(count)}"
count += 1
super().save(*args,**kwargs)
def __str__(self):
return self.name
@property
def get_total_selling(self):
menu = self.menu_set.all()
total = 0
for i in menu:
for k in i.orderitem_set.all():
total += k.quatity
for k in i.tableorderitem_set.all():
total += k.quatity
return total
class Meta:
verbose_name_plural = 'Categories'
ordering = ('name',)
class Menu(models.Model):
SIZE_CHOICE = (
('S','Small'),
('M','Medium'),
('L','Large')
)
category = models.ManyToManyField(Category)
name = models.CharField(max_length=100,null=True)
size = models.CharField(max_length=20,choices= SIZE_CHOICE,blank=True)
price = models.IntegerField()
slug = models.SlugField(max_length=50,unique=True,null=True,blank=True)
image = CloudinaryField('image')
def save(self,*args,**kwargs):
if not self.slug:
name = self.name.split(' ')
name = ''.join(name)
self.slug = f"m_{name.lower()}"
count = 1
while Menu.objects.filter(slug=self.slug).exists():
self.slug = f"m_{name.lower()}_{str(count)}"
count += 1
super().save(*args,**kwargs)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'Menus'
ordering = ('name',)
@property
def get_total_selling(self):
orderitem = self.orderitem_set.all()
tableorder = self.tableorderitem_set.all()
total = 0
for i in orderitem:
total += i.quatity
for i in tableorder:
total += i.quatity
return total
class Order(models.Model):
STATUS_CHOICE = (
('Cooking','Cooking'),
('Delivering','Delivering'),
('Delivered','Delivered')
)
user = models.ForeignKey(MUser, on_delete=models.CASCADE)
order_date = models.DateField(blank=True,null=True)
order_time = models.TimeField(blank=True,null=True)
order_id = models.CharField(max_length=100,null=True,blank=True)
slug = models.SlugField(max_length=50,null=True,unique=True,editable=True,blank=True)
ckecked = models.BooleanField(default=False,null=True)
status = models.CharField(max_length=20,choices= STATUS_CHOICE,blank=True,default='Cooking',null=True)
def save(self,*args,**kwargs):
if not self.order_id:
counter = 1
self.order_id = f'O_{counter}'
while Order.objects.filter(order_id=self.order_id).exists():
counter += 1
self.order_id = f'O_{counter}'
if not self.slug:
self.slug = self.order_id
super().save(*args,**kwargs)
@property
def get_order_total(self):
orderitems = self.orderitem_set.all()
total = sum([item.get_sub_total for item in orderitems])
return total
@property
def get_order_qty(self):
orderitems = self.orderitem_set.all()
total = sum([x.quatity for x in orderitems])
return total
class OrderItem(models.Model):
order = models.ForeignKey(Order,on_delete=models.CASCADE)
item = models.ForeignKey(Menu,on_delete=models.PROTECT)
quatity = models.IntegerField(default=1)
cooked = models.BooleanField(default=False,null=True)
slug = models.SlugField(max_length=50,null=True,unique=True,editable=True,blank=True)
def save(self,*args,**kwargs):
if not self.slug:
self.slug = uuid.uuid4()
super().save(*args,**kwargs)
@property
def get_sub_total(self):
return self.item.price * self.quatity
| {"/menu/form.py": ["/menu/models.py"], "/owner/views.py": ["/table/models.py", "/menu/models.py", "/owner/forms.py", "/owner/filters.py", "/owner/decorators.py"], "/chef/views.py": ["/menu/models.py", "/table/models.py", "/owner/decorators.py"], "/menu/views.py": ["/menu/models.py", "/table/models.py", "/owner/views.py", "/owner/decorators.py"], "/menu/admin.py": ["/menu/models.py", "/menu/form.py"], "/owner/urls.py": ["/owner/views.py"], "/menu/urls.py": ["/menu/views.py"], "/owner/filters.py": ["/menu/models.py"], "/table/models.py": ["/menu/models.py"], "/chef/urls.py": ["/chef/views.py"], "/owner/forms.py": ["/menu/models.py"]} |
62,462 | Todai88/cron-admin | refs/heads/master | /test/test_next_run.py | # -*- coding: utf-8 -*-
from unittest import TestCase
from nextrun.next_run import NextRun
class TestNextRun(TestCase):
def test_find_next_run_times(self):
expected = [
[u'1:30', u'tomorrow', u'/bin/run_me_daily'],
[u'16:45', u'today', u'/bin/run_me_hourly'],
[u'16:10', u'today', u'/bin/run_me_every_minute'],
[u'19:00', u'today', u'/bin/run_me_sixty_times']
]
response = NextRun().find_next_run_times(u'16:10', u'crontab.txt')
self.assertEqual(expected, response, response)
def test_validate_datetime(self):
# Normal case
current_time = u'12:20'
expected = {u'hour': 12, u'minute': 20}
response = NextRun().validate_datetime(current_time)
self.assertEqual(expected, response, response)
# Fail on invalid hour
current_time = u'24:20'
expected = {u'hour': None, u'minute': None}
response = NextRun().validate_datetime(current_time)
self.assertEqual(expected, response, response)
# Fail on invalid minute
current_time = u'23:60'
expected = {u'hour': None, u'minute': None}
response = NextRun().validate_datetime(current_time)
self.assertEqual(expected, response, response)
def test_find_next_run_time(self):
# Case 1: 30 1 /bin/run_me_daily -> 1:30 tomorrow
response = NextRun().find_next_run_time(1, 30, 16, 10)
self.assertEqual(1, response[u'hour'], response[u'hour'])
self.assertEqual(30, response[u'minute'], response[u'minute'])
self.assertEqual(u'tomorrow', response[u'day'], response[u'day'])
# Case 2: 45 * /bin/run_me_hourly -> 16:45 today
response = NextRun().find_next_run_time(u'*', 45, 16, 10)
self.assertEqual(16, response[u'hour'], response[u'hour'])
self.assertEqual(45, response[u'minute'], response[u'minute'])
self.assertEqual(u'today', response[u'day'], response[u'day'])
# Case 3: * * /bin/run_me_every_minute -> 16:10 today
response = NextRun().find_next_run_time(u'*', u'*', 16, 10)
self.assertEqual(16, response[u'hour'], response[u'hour'])
self.assertEqual(10, response[u'minute'], response[u'minute'])
self.assertEqual(u'today', response[u'day'], response[u'day'])
# Case 4: * 19 /bin/run_me_sixty_times -> 19:00 today
response = NextRun().find_next_run_time(19, u'*', 16, 10)
self.assertEqual(19, response[u'hour'], response[u'hour'])
self.assertEqual(0, response[u'minute'], response[u'minute'])
self.assertEqual(u'today', response[u'day'], response[u'day'])
def test_find_time_delta(self):
pass
def test_format_date(self):
pass
| {"/test/test_next_run.py": ["/nextrun/next_run.py"], "/test/test_cron_parser.py": ["/nextrun/cron_parser.py"]} |
62,463 | Todai88/cron-admin | refs/heads/master | /setup.py | import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="cron-admin",
version="0.0.1",
author="Ian Wilson",
author_email="ian@emotionai.com",
description="Find when cron jobs will next run",
keywords="python cron-admin cron run",
url="https://github.com/emotionai/cron-admin",
packages=['nextrun'],
entry_points={
"console_scripts":
['cron-admin = nextrun.__main__:main'],
},
package_dir={'nextrun': 'nextrun'},
package_data={
'nextrun': ['config/*cfg'],
},
data_files=[('', ['README.md'])],
long_description=read('README.md'),
)
| {"/test/test_next_run.py": ["/nextrun/next_run.py"], "/test/test_cron_parser.py": ["/nextrun/cron_parser.py"]} |
62,464 | Todai88/cron-admin | refs/heads/master | /test/test_cron_parser.py | # -*- coding: utf-8 -*-
from unittest import TestCase
import os
from nextrun.cron_parser import CronParser
class TestCronParser(TestCase):
def test_parse_cron_string(self):
pass
def test_parse_cron_file(self):
pass
def test_is_valid_path(self):
cron_file_path = os.path.abspath(u'crontab.txt')
expected = True
response = CronParser(None).is_valid_file_path(cron_file_path)
self.assertEqual(expected, response, response)
cron_file_path = os.path.abspath(u'fail_file.txt')
expected = False
response = CronParser(None).is_valid_file_path(cron_file_path)
self.assertEqual(expected, response, response)
def test_get_cron_data(self):
cron_file_path = os.path.abspath(u'crontab.txt')
expected = [
u'30 1 /bin/run_me_daily',
u'45 * /bin/run_me_hourly',
u'* * /bin/run_me_every_minute',
u'* 19 /bin/run_me_sixty_times'
]
response = CronParser(None).get_cron_data(cron_file_path)
self.assertEqual(expected, response, response)
def test_parse_cron_data(self):
cron_data = [
u'30 1 /bin/run_me_daily',
u'45 * /bin/run_me_hourly',
u'* * /bin/run_me_every_minute',
u'* 19 /bin/run_me_sixty_times'
]
expected = [
[u'30', u'1', u'/bin/run_me_daily'],
[u'45', u'*', u'/bin/run_me_hourly'],
[u'*', u'*', u'/bin/run_me_every_minute'],
[u'*', u'19', u'/bin/run_me_sixty_times']
]
response = CronParser(None).parse_cron_data(cron_data)
self.assertEqual(expected, response, response)
def test_format_cron_data(self):
pass
def test_validate_in_range(self):
pass | {"/test/test_next_run.py": ["/nextrun/next_run.py"], "/test/test_cron_parser.py": ["/nextrun/cron_parser.py"]} |
62,465 | Todai88/cron-admin | refs/heads/master | /nextrun/__main__.py | # -*- coding: utf-8 -*-
import argparse
from next_run import NextRun
if __name__ == u'__main__':
# Parse command line arguments
parser = argparse.ArgumentParser(
description=u'Cron Admin tool.'
)
parser.add_argument(
u'-t',
dest=u'current_time',
default=u'16:10',
help=u'The time from which to check'
)
parser.add_argument(
u'-p',
dest=u'cron_path',
default=None,
help=u'Full path to the cron file to check'
)
parser.add_argument(
u'-s',
dest=u'cron_string',
default=None,
help=u'A newline separated string of cron data'
)
args = parser.parse_args()
# Call the class controller to run the script
next_run_times = NextRun().find_next_run_times(
args.current_time, args.cron_path, args.cron_string
)
# Output results to console
for cron_data in next_run_times:
print u' '.join(cron_data) | {"/test/test_next_run.py": ["/nextrun/next_run.py"], "/test/test_cron_parser.py": ["/nextrun/cron_parser.py"]} |
62,466 | Todai88/cron-admin | refs/heads/master | /nextrun/next_run.py | # -*- coding: utf-8 -*-
import logging
import sys
from cron_parser import CronParser
class NextRun(object):
def __init__(self):
self.logger = logging.Logger(u'cron-admin')
self.logger.setLevel(logging.WARNING)
# create console handler
console_log = logging.StreamHandler(sys.stdout)
console_log.setLevel(logging.WARNING)
# create formatter and add it to the handlers
formatter = logging.Formatter(
u'[%(asctime)s %(name)s %(filename)s:%'
u'(lineno)d - %(levelname)s]: %(message)s',
u'%d-%m-%Y %H:%M:%S'
)
console_log.setFormatter(formatter)
# add the handlers to logger
self.logger.addHandler(console_log)
def find_next_run_times(
self, current_time, cron_file_path=None, cron_string=None):
"""
Given cron path / data and current time find next times each cron runs
:param cron_string:
:param cron_file_path:
:param current_time:
:return:
"""
next_run_times = []
# Check that a valid date and time have been passed
valid_current = self.validate_datetime(current_time)
# If we have been passed a valid current time
if valid_current[u'minute'] and valid_current[u'hour']:
if cron_file_path and not cron_string:
# Parse data from a given file
cron_data = (
CronParser(self.logger).parse_cron_file(cron_file_path)
)
else:
# Parse data from a given string
cron_data = (
CronParser(self.logger).parse_cron_string(cron_string)
)
for cron in cron_data:
# Find how many hours until the next run time
hour_delta = self.find_time_delta(
cron[u'hour'], valid_current[u'hour']
)
# Find how many minutes past the hour until the next run time
minute_delta = self.find_time_delta(
cron[u'minute'], valid_current[u'minute']
)
# Calculate the next run time from the deltas
next_run = self.find_next_run_time(
cron[u'hour'], cron[u'minute'],
valid_current[u'hour'], valid_current[u'minute'],
hour_delta, minute_delta
)
# Create a results list entry for each cron
next_run_times.append([
self.format_date(next_run[u'hour'], next_run[u'minute']),
next_run[u'day'],
cron[u'path']
])
return next_run_times
def validate_datetime(self, current_date):
"""
Check the given hour and minute figures are valid
:param current_date:
:return:
"""
valid_minute = None
valid_hour = None
MIN_HOUR = 0
MAX_HOUR = 23
MIN_MINUTE = 0
MAX_MINUTE = 59
TIME_SEPARATOR = u':'
hour, minute = current_date.split(TIME_SEPARATOR)
try:
if ((MIN_HOUR <= int(hour) <= MAX_HOUR) and
(MIN_MINUTE <= int(minute) <= MAX_MINUTE)):
valid_minute = int(minute)
valid_hour = int(hour)
except ValueError as e:
logging.error(u'Given current time is invalid %s', e)
valid_datetime = {u'hour': valid_hour, u'minute': valid_minute}
return valid_datetime
def find_next_run_time(self, cron_hour, cron_minute, current_hour,
current_minute, hour_delta, minute_delta):
"""
Find the next time / day to run the cron given the current time
:param current_hour:
:param current_minute:
:param hour_delta:
:param minute_delta:
:param cron_minute:
:param cron_hour:
:return: the next time and next day
"""
NOW = 0
LAST_HOUR_OF_DAY = 23
EVERY_MINUTE = u'*'
EVERY_HOUR = u'*'
CURRENT_DAY = u'today'
NEXT_DAY = u'tomorrow'
if cron_minute == EVERY_MINUTE and cron_hour == EVERY_HOUR:
# Should run every minute of every hour in a day
next_run_minute = current_minute
next_run_hour = current_hour
next_run_day = CURRENT_DAY
elif cron_hour == EVERY_HOUR:
# Minute is set but should run every hour of a day
# Cron run time has passed
if minute_delta < NOW:
# Check for time going into next day (after 23:00)
if current_hour != LAST_HOUR_OF_DAY:
next_run_hour = current_hour + 1
next_run_day = CURRENT_DAY
else:
next_run_hour = NOW
next_run_day = NEXT_DAY
else:
next_run_hour = current_hour
next_run_day = CURRENT_DAY
next_run_minute = cron_minute
elif cron_minute == EVERY_MINUTE:
# Hour is set but should run every minute of that hour
# Cron run time has passed
if hour_delta < NOW:
next_run_minute = NOW
next_run_day = NEXT_DAY
elif hour_delta == NOW:
next_run_minute = current_minute
next_run_day = CURRENT_DAY
else:
next_run_minute = NOW
next_run_day = CURRENT_DAY
next_run_hour = cron_hour
else:
# Both Hour and minute are specified and should only run then
# Cron run time has passed
if hour_delta < NOW:
next_run_day = NEXT_DAY
elif hour_delta == NOW:
if minute_delta < NOW:
next_run_day = NEXT_DAY
else:
next_run_day = CURRENT_DAY
else:
next_run_day = CURRENT_DAY
next_run_minute = cron_minute
next_run_hour = cron_hour
# Convenient structure
next_run_time = {
u'day': next_run_day,
u'hour': next_run_hour,
u'minute': next_run_minute
}
return next_run_time
def find_time_delta(self, cron, current):
"""
Find difference (time to/from next/previous cron)
:param cron:
:param current:
:return:
"""
delta = 0
EVERY_TIME = u'*'
if not cron == EVERY_TIME and not current == EVERY_TIME:
delta = cron - current
return delta
def format_date(self, hour, minute):
"""
Create a formatted date string
:param hour:
:param minute:
:return:
"""
SINGLE_DIGIT = 9
PADDING_DIGIT = u'0'
TIME_SEPARATOR = u':'
hour = unicode(hour)
minute = (unicode(minute)
if minute > SINGLE_DIGIT
else PADDING_DIGIT + unicode(minute))
date = TIME_SEPARATOR.join([hour, minute])
return date
| {"/test/test_next_run.py": ["/nextrun/next_run.py"], "/test/test_cron_parser.py": ["/nextrun/cron_parser.py"]} |
62,467 | Todai88/cron-admin | refs/heads/master | /nextrun/cron_parser.py | # -*- coding: utf-8 -*-
import os
class CronParser(object):
def __init__(self, logger=None):
self.logger = logger
def parse_cron_string(self, cron_string):
"""
Parse a cron data string
:param cron_string:
:return:
"""
formatted_cron_data = []
if cron_string:
cron_data = cron_string.split(u'\\n')
parsed_cron_data = self.parse_cron_data(cron_data)
formatted_cron_data = self.format_cron_data(parsed_cron_data)
return formatted_cron_data
def parse_cron_file(self, cron_file_path):
"""
Given a cron file return its contents in a list of dict
:param cron_file_path:
:return: formatted_cron_data dict
"""
formatted_cron_data = []
if self.is_valid_file_path(cron_file_path):
cron_data = self.get_cron_data(cron_file_path)
parsed_cron_data = self.parse_cron_data(cron_data)
formatted_cron_data = self.format_cron_data(parsed_cron_data)
return formatted_cron_data
def is_valid_file_path(self, cron_file_path):
"""
Check if the cron file exists / path is valid
:param cron_file_path:
:return:
"""
is_valid = False
if os.path.isfile(cron_file_path):
is_valid = True
return is_valid
def get_cron_data(self, cron_file_path):
"""
Read in a cron file
:param cron_file_path:
:return: list of cron config strings
"""
cron_data = []
try:
with open(cron_file_path, u'r') as cron_file:
for cron_config in cron_file:
if cron_config and len(cron_config) > 5:
cron_data.append(cron_config.strip(u'\n'))
except IOError as e:
if self.logger:
self.logger.error(u'Could not read cron file %s', e)
return cron_data
def parse_cron_data(self, cron_data):
"""
Parse and separate config string into constituent parts
:param cron_data:
:return list of lists of cron data
"""
parsed_cron_data = []
for cron_config in cron_data:
try:
cron_parts = cron_config.strip().split()
parsed_cron_data.append(cron_parts)
except ValueError as e:
if self.logger:
self.logger.warning(u'Malformed cron config %s', e)
return parsed_cron_data
def format_cron_data(self, cron_data):
"""
Put data into a desired list of dicts format
:param cron_data:
:return: structured list of dicts
"""
formatted_cron_data = []
for data in cron_data:
try:
format_data = {
u'minute': self.validate_in_range(data[0], 0, 59),
u'hour': self.validate_in_range(data[1], 0, 23),
u'path': data[2]
}
formatted_cron_data.append(format_data)
except IndexError as e:
if self.logger:
self.logger.error(u'Malformed cron entry %s', e)
return formatted_cron_data
def validate_in_range(self, value, low, high):
"""
Check a value is in range or return None
:param number:
:param low:
:param high:
:return:
"""
validated = None
try:
if low <= int(value) <= high:
validated = int(value)
except ValueError:
# Is usually '*'
if value == u'*':
validated = u'*'
return validated | {"/test/test_next_run.py": ["/nextrun/next_run.py"], "/test/test_cron_parser.py": ["/nextrun/cron_parser.py"]} |
62,468 | Terrabits/app-server | refs/heads/main | /app_server/command_line.py | import argparse
def parse():
parser = argparse.ArgumentParser(description='')
parser.add_argument('--host', default='0.0.0.0')
parser.add_argument('--port', default=8080, type=int)
parser.add_argument('--instr-address', default='localhost')
parser.add_argument('--instr-port', default=5025, type=int)
parser.add_argument('--open-browser', action='store_true')
parser.add_argument('directory', default='.')
return parser.parse_args()
| {"/__main__.py": ["/app_server/__init__.py"], "/app_server/__init__.py": ["/app_server/command_line.py", "/app_server/handler.py"]} |
62,469 | Terrabits/app-server | refs/heads/main | /app_server/handler.py | import asyncio
import aiohttp
from aiohttp import web
def get(address, port):
async def handler(request):
# open websocket
websocket = web.WebSocketResponse()
await websocket.prepare(request)
# open instrument connection
instr_reader, instr_writer = \
await asyncio.open_connection(address, port)
async def incoming_handler():
async for msg in websocket:
if msg.type == aiohttp.WSMsgType.TEXT:
instr_writer.write(msg.data.strip().encode() + b'\n')
await instr_writer.drain()
elif msg.type == aiohttp.WSMsgType.ERROR:
exception = websocket.exception
print(f'websocket closed: {exception}', flush=True)
async def outgoing_handler():
while True:
data = await instr_reader.read(64_000)
await websocket.send_str(data.decode())
await asyncio.gather(incoming_handler(), outgoing_handler())
return websocket
return handler
| {"/__main__.py": ["/app_server/__init__.py"], "/app_server/__init__.py": ["/app_server/command_line.py", "/app_server/handler.py"]} |
62,470 | Terrabits/app-server | refs/heads/main | /__main__.py | from aiohttp import web
import app_server
import sys
import webbrowser
if __name__ == '__main__':
args = app_server.command_line.parse()
app = web.Application()
# routes
handler = app_server.handler.get(args.instr_address, args.instr_port)
instr_route = web.get('/instr', handler)
static_route = web.static('/', args.directory, show_index=True)
# note instr must be first!??
routes = [instr_route, static_route]
app.add_routes(routes)
# open browser?
if args.open_browser:
if args.host == '0.0.0.0':
webbrowser.open_new_tab(f'http://localhost:{args.port}')
else:
webbrowser.open_new_tab(f'http://{host}:{args.port}')
host = 'localhost' if args.host == '0.0.0.0' else args.host
# start
web.run_app(app, host=args.host, port=args.port)
| {"/__main__.py": ["/app_server/__init__.py"], "/app_server/__init__.py": ["/app_server/command_line.py", "/app_server/handler.py"]} |
62,471 | Terrabits/app-server | refs/heads/main | /app_server/__init__.py | import app_server.command_line
import app_server.handler
| {"/__main__.py": ["/app_server/__init__.py"], "/app_server/__init__.py": ["/app_server/command_line.py", "/app_server/handler.py"]} |
62,472 | codephillip/tunga-api | refs/heads/master | /tunga_utils/decorators.py | from functools import wraps
def catch_all_exceptions(func):
"""
This decorator is used to abstract the try except block for functions that don't affect the final status of an action.
"""
@wraps(func)
def func_wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
except:
pass
return func_wrapper
def convert_first_arg_to_instance(model):
"""
Convert the first argument of the function into an instance of the declared model
"""
def real_decorator(func):
def func_wrapper(*args, **kwargs):
if model and len(args):
param = args[0]
if isinstance(param, model):
func(*args, **kwargs)
else:
try:
instance = model.objects.get(id=param)
except:
instance = model(id=param)
func(instance, *args[1:], **kwargs)
else:
func(*args, **kwargs)
return func_wrapper
return real_decorator
| {"/tunga_tasks/management/commands/tunga_manage_task_progress.py": ["/tunga_tasks/notifications.py"]} |
62,473 | codephillip/tunga-api | refs/heads/master | /tunga_tasks/management/commands/tunga_manage_task_progress.py | import datetime
from dateutil.relativedelta import relativedelta
from django.core.management.base import BaseCommand
from django.db.models.query_utils import Q
from tunga_tasks.notifications import remind_progress_event
from tunga_tasks.models import Task, ProgressEvent
from tunga_tasks.tasks import initialize_task_progress_events
class Command(BaseCommand):
def handle(self, *args, **options):
"""
Update periodic update events and send notifications for upcoming update events.
"""
# command to run: python manage.py tunga_manage_task_progress
# Periodic updates will continue to be scheduled for unclosed tasks for up to a week past their deadlines
min_deadline = datetime.datetime.utcnow() - relativedelta(days=7)
tasks = Task.objects.filter(Q(deadline__isnull=True) | Q(deadline__gte=min_deadline), closed=False)
for task in tasks:
# Creates the next periodic events and reconciles submit events if necessary
initialize_task_progress_events(task)
min_date = datetime.datetime.utcnow()
max_date = min_date + relativedelta(hours=24)
# Send reminders for tasks updates due in the current 24 hr period
events = ProgressEvent.objects.filter(
task__closed=False, due_at__range=[min_date, max_date], last_reminder_at__isnull=True
)
for event in events:
remind_progress_event(event.id)
| {"/tunga_tasks/management/commands/tunga_manage_task_progress.py": ["/tunga_tasks/notifications.py"]} |
62,474 | codephillip/tunga-api | refs/heads/master | /tunga_tasks/notifications.py | import datetime
import time
from django.contrib.auth import get_user_model
from django.db.models import When, Case, IntegerField
from django.db.models.aggregates import Sum
from django.db.models.expressions import F
from django.template.defaultfilters import truncatewords, floatformat
from django_rq.decorators import job
from tunga.settings import TUNGA_URL, TUNGA_STAFF_UPDATE_EMAIL_RECIPIENTS, SLACK_ATTACHMENT_COLOR_TUNGA, \
SLACK_ATTACHMENT_COLOR_RED, SLACK_ATTACHMENT_COLOR_GREEN, SLACK_ATTACHMENT_COLOR_NEUTRAL, \
SLACK_ATTACHMENT_COLOR_BLUE, SLACK_DEVELOPER_INCOMING_WEBHOOK, SLACK_STAFF_INCOMING_WEBHOOK, \
SLACK_STAFF_UPDATES_CHANNEL, SLACK_DEVELOPER_UPDATES_CHANNEL, SLACK_PMS_UPDATES_CHANNEL, \
MAILCHIMP_NEW_USER_AUTOMATION_WORKFLOW_ID, MAILCHIMP_NEW_USER_AUTOMATION_EMAIL_ID, \
TUNGA_STAFF_LOW_LEVEL_UPDATE_EMAIL_RECIPIENTS
from tunga_auth.filterbackends import my_connections_q_filter
from tunga_tasks import slugs
from tunga_tasks.models import Task, Participation, Application, ProgressEvent, ProgressReport, Quote, Estimate
from tunga_utils import slack_utils, mailchimp_utils
from tunga_utils.constants import USER_TYPE_DEVELOPER, VISIBILITY_DEVELOPER, VISIBILITY_MY_TEAM, TASK_SCOPE_TASK, \
USER_TYPE_PROJECT_MANAGER, TASK_SOURCE_NEW_USER, STATUS_INITIAL, STATUS_SUBMITTED, STATUS_APPROVED, STATUS_DECLINED, \
STATUS_ACCEPTED, STATUS_REJECTED, PROGRESS_EVENT_TYPE_PM, PROGRESS_EVENT_TYPE_CLIENT
from tunga_utils.emails import send_mail
from tunga_utils.helpers import clean_instance, convert_to_text
@job
def possibly_trigger_schedule_call_automation(instance, wait=15*60):
# Wait for user to possibly schedule a call
time.sleep(wait)
instance = clean_instance(isinstance(instance, Task) and instance.id or instance, Task) # needs to be refreshed
if not instance.schedule_call_start:
# Make sure user is in mailing list
mailchimp_utils.subscribe_new_user(
instance.user.email, **dict(FNAME=instance.user.first_name, LNAME=instance.user.last_name)
)
# Trigger email from automation
mailchimp_utils.add_email_to_automation_queue(
email_address=instance.user.email,
workflow_id=MAILCHIMP_NEW_USER_AUTOMATION_WORKFLOW_ID,
email_id=MAILCHIMP_NEW_USER_AUTOMATION_EMAIL_ID
)
def create_task_slack_msg(task, summary='', channel='#general', show_schedule=True, show_contacts=False):
task_url = '{}/work/{}/'.format(TUNGA_URL, task.id)
attachments = [
{
slack_utils.KEY_TITLE: task.summary,
slack_utils.KEY_TITLE_LINK: task_url,
slack_utils.KEY_TEXT: task.excerpt,
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_TUNGA
}
]
extra_details = ''
if task.type:
extra_details += '*Type*: {}\n'.format(task.get_type_display())
if task.skills:
extra_details += '*Skills*: {}\n'.format(task.skills_list)
if task.deadline:
extra_details += '*Deadline*: {}\n'.format(task.deadline.strftime("%d %b, %Y"))
if task.fee:
amount = task.is_developer_ready and task.pay_dev or task.pay
extra_details += '*Fee*: EUR {}\n'.format(floatformat(amount, arg=-2))
if show_schedule and task.schedule_call_start:
extra_details += '*Available*: \nDate: {}\nTime: {} {} UTC\n'.format(
task.schedule_call_start.strftime("%d %b, %Y"),
task.schedule_call_start.strftime("%I:%M%p"),
task.schedule_call_end and ' - {}'.format(task.schedule_call_end.strftime("%I:%M%p")) or ''
)
if show_contacts:
extra_details += '*Email*: {}\n'.format(task.user.email)
if task.skype_id:
extra_details += '*Skype ID or Call URL*: {}\n'.format(task.skype_id)
if extra_details:
attachments.append({
slack_utils.KEY_TEXT: extra_details,
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_GREEN
})
if task.deliverables:
attachments.append({
slack_utils.KEY_TITLE: 'Deliverables',
slack_utils.KEY_TEXT: task.deliverables,
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_BLUE
})
if task.stack_description:
attachments.append({
slack_utils.KEY_TITLE: 'Tech Stack',
slack_utils.KEY_TEXT: task.stack_description,
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_NEUTRAL
})
if not summary:
summary = "New {} created by {} | <{}|View on Tunga>".format(
task.scope == TASK_SCOPE_TASK and 'task' or 'project',
task.user.display_name, task_url)
return {
slack_utils.KEY_TEXT: summary,
slack_utils.KEY_CHANNEL: channel,
slack_utils.KEY_ATTACHMENTS: attachments
}
@job
def notify_new_task(instance, new_user=False):
notify_new_task_client_receipt_email(instance)
if not new_user:
# Task from new users need to be qualified before they get to the community
notify_new_task_community(instance)
notify_new_task_admin(instance, new_user=new_user)
@job
def notify_task_approved(instance, new_user=False):
notify_new_task_client_receipt_email(instance)
notify_new_task_admin(instance, new_user=new_user, completed=True)
notify_new_task_community(instance)
@job
def notify_new_task_client_receipt_email(instance, new_user=False, reminder=False):
instance = clean_instance(instance, Task)
subject = "Your {} has been posted on Tunga".format(
instance.scope == TASK_SCOPE_TASK and 'task' or 'project'
)
if instance.is_task and not instance.approved:
subject = "{}Finalize your {}".format(
reminder and 'Reminder: ' or '',
instance.scope == TASK_SCOPE_TASK and 'task' or 'project'
)
to = [instance.user.email]
if instance.owner:
to.append(instance.owner.email)
ctx = {
'owner': instance.owner or instance.user,
'task': instance,
'task_url': '%s/task/%s/' % (TUNGA_URL, instance.id),
'task_edit_url': '%s/task/%s/edit/complete-task/' % (TUNGA_URL, instance.id)
}
if instance.source == TASK_SOURCE_NEW_USER and not instance.user.is_confirmed:
url_prefix = '{}/reset-password/confirm/{}/{}?new_user=true&next='.format(
TUNGA_URL, instance.user.uid, instance.user.generate_reset_token()
)
ctx['task_url'] = '{}{}'.format(url_prefix, ctx['task_url'])
ctx['task_edit_url'] = '{}{}'.format(url_prefix, ctx['task_edit_url'])
if instance.is_task:
if instance.approved:
email_template = 'tunga/email/email_new_task_client_approved'
else:
if reminder:
email_template = 'tunga/email/email_new_task_client_more_info_reminder'
else:
email_template = 'tunga/email/email_new_task_client_more_info'
else:
email_template = 'tunga/email/email_new_task_client_approved'
if send_mail(subject, email_template, to, ctx, **dict(deal_ids=[instance.hubspot_deal_id])):
if not instance.approved:
instance.complete_task_email_at = datetime.datetime.utcnow()
if reminder:
instance.reminded_complete_task = True
instance.save()
@job
def notify_new_task_admin(instance, new_user=False, completed=False, call_scheduled=False):
notify_new_task_admin_slack(instance, new_user=new_user, completed=completed, call_scheduled=call_scheduled)
if not (completed or call_scheduled):
# Only initial task creation will be reported via email
notify_new_task_admin_email(instance, new_user=new_user, completed=completed, call_scheduled=call_scheduled)
@job
def notify_new_task_admin_email(instance, new_user=False, completed=False, call_scheduled=False):
instance = clean_instance(instance, Task)
completed_phrase_subject = ''
completed_phrase_body = ''
if call_scheduled:
completed_phrase_subject = 'availability window shared'
completed_phrase_body = 'shared an availability window'
elif completed:
completed_phrase_subject = 'details completed'
completed_phrase_body = 'completed the details'
subject = "New{} {} {} by {}{}".format(
(completed or call_scheduled) and ' wizard' or '',
instance.scope == TASK_SCOPE_TASK and 'task' or 'project',
completed_phrase_subject or 'created',
instance.user.first_name, new_user and ' (New user)' or ''
)
to = TUNGA_STAFF_LOW_LEVEL_UPDATE_EMAIL_RECIPIENTS # Notified via Slack so limit receiving admins
ctx = {
'owner': instance.owner or instance.user,
'task': instance,
'task_url': '%s/task/%s/' % (TUNGA_URL, instance.id),
'completed_phrase': completed_phrase_body
}
send_mail(subject, 'tunga/email/email_new_task', to, ctx, **dict(deal_ids=[instance.hubspot_deal_id]))
@job
def notify_new_task_admin_slack(instance, new_user=False, completed=False, call_scheduled=False):
instance = clean_instance(instance, Task)
task_url = '{}/work/{}/'.format(TUNGA_URL, instance.id)
completed_phrase = ''
if call_scheduled:
completed_phrase = 'availability window shared'
elif completed:
completed_phrase = 'details completed'
summary = "{} {} {} by {}{} | <{}|View on Tunga>".format(
(completed or call_scheduled) and 'New wizard' or 'New',
instance.scope == TASK_SCOPE_TASK and 'task' or 'project',
completed_phrase or 'created',
instance.user.first_name, new_user and ' (New user)' or '',
task_url
)
slack_msg = create_task_slack_msg(instance, summary=summary, channel=SLACK_STAFF_UPDATES_CHANNEL, show_contacts=True)
slack_utils.send_incoming_webhook(SLACK_STAFF_INCOMING_WEBHOOK, slack_msg)
@job
def remind_no_task_applications(instance, admin=True):
remind_no_task_applications_slack(instance, admin=admin)
@job
def remind_no_task_applications_slack(instance, admin=True):
instance = clean_instance(instance, Task)
if not instance.is_task:
return
task_url = '{}/work/{}/'.format(TUNGA_URL, instance.id)
new_user = instance.source == TASK_SOURCE_NEW_USER
summary = "Reminder: No applications yet for {} {} | <{}|View on Tunga>".format(
instance.scope == TASK_SCOPE_TASK and 'task' or 'project',
new_user and admin and ' (New user)' or '',
task_url
)
slack_msg = create_task_slack_msg(
instance, summary=summary,
channel=admin and SLACK_STAFF_UPDATES_CHANNEL or SLACK_DEVELOPER_UPDATES_CHANNEL,
show_contacts=admin
)
slack_utils.send_incoming_webhook(
admin and SLACK_STAFF_INCOMING_WEBHOOK or SLACK_DEVELOPER_INCOMING_WEBHOOK,
slack_msg
)
@job
def notify_review_task_admin(instance):
notify_review_task_admin_slack(instance)
@job
def notify_review_task_admin_slack(instance):
instance = clean_instance(instance, Task)
task_url = '{}/work/{}/'.format(TUNGA_URL, instance.id)
new_user = instance.source == TASK_SOURCE_NEW_USER
summary = "Reminder: Review {} {} | <{}|View on Tunga>\nCreated: {}".format(
instance.scope == TASK_SCOPE_TASK and 'task' or 'project',
new_user and ' (New user)' or '',
task_url,
instance.created_at.strftime("%d %b, %Y"),
instance.approved_at and 'Approved: {}'.format(instance.approved_at.strftime("%d %b, %Y")) or '',
)
slack_msg = create_task_slack_msg(
instance, summary=summary,
channel=SLACK_STAFF_UPDATES_CHANNEL,
show_contacts=True
)
slack_utils.send_incoming_webhook(SLACK_STAFF_INCOMING_WEBHOOK, slack_msg)
@job
def notify_new_task_community(instance):
notify_new_task_community_email(instance)
notify_new_task_community_slack(instance)
def get_suggested_community_receivers(instance, user_type=USER_TYPE_DEVELOPER, respect_visibility=True):
# Filter users based on nature of work
queryset = get_user_model().objects.filter(
type=user_type
)
# Only developers on client's team
if respect_visibility and instance.visibility == VISIBILITY_MY_TEAM and user_type == USER_TYPE_DEVELOPER:
queryset = queryset.filter(
my_connections_q_filter(instance.user)
)
ordering = []
# Order by matching skills
task_skills = instance.skills.all()
if task_skills:
when = []
for skill in task_skills:
new_when = When(
userprofile__skills=skill,
then=1
)
when.append(new_when)
queryset = queryset.annotate(matches=Sum(
Case(
*when,
default=0,
output_field=IntegerField()
)
))
ordering.append('-matches')
# Order developers by tasks completed
if user_type == USER_TYPE_DEVELOPER:
queryset = queryset.annotate(
tasks_completed=Sum(
Case(
When(
participation__task__closed=True,
participation__user__id=F('id'),
participation__status=STATUS_ACCEPTED,
then=1
),
default=0,
output_field=IntegerField()
)
)
)
ordering.append('-tasks_completed')
if ordering:
queryset = queryset.order_by(*ordering)
if queryset:
return queryset[:15]
return
@job
def notify_new_task_community_email(instance):
instance = clean_instance(instance, Task)
# Notify Devs or PMs
community_receivers = None
if instance.is_developer_ready:
# Notify developers
if instance.approved and instance.visibility in [VISIBILITY_DEVELOPER, VISIBILITY_MY_TEAM]:
community_receivers = get_suggested_community_receivers(instance, user_type=USER_TYPE_DEVELOPER)
elif instance.is_project and not instance.pm:
community_receivers = get_suggested_community_receivers(instance, user_type=USER_TYPE_PROJECT_MANAGER)
if instance.is_project and instance.pm:
community_receivers = [instance.pm]
subject = "New {} created by {}".format(
instance.scope == TASK_SCOPE_TASK and 'task' or 'project',
instance.user.first_name
)
if community_receivers:
to = [community_receivers[0].email]
bcc = None
if len(community_receivers) > 1:
bcc = [user.email for user in community_receivers[1:]] if community_receivers[1:] else None
ctx = {
'owner': instance.owner or instance.user,
'task': instance,
'task_url': '{}/work/{}/'.format(TUNGA_URL, instance.id)
}
send_mail(subject, 'tunga/email/email_new_task', to, ctx, bcc=bcc, **dict(deal_ids=[instance.hubspot_deal_id]))
@job
def notify_new_task_community_slack(instance):
instance = clean_instance(instance, Task)
# Notify Devs or PMs via Slack
if (not instance.is_developer_ready) or (instance.approved and instance.visibility == VISIBILITY_DEVELOPER):
slack_msg = create_task_slack_msg(
instance,
channel=instance.is_developer_ready and SLACK_DEVELOPER_UPDATES_CHANNEL or SLACK_PMS_UPDATES_CHANNEL
)
slack_utils.send_incoming_webhook(SLACK_DEVELOPER_INCOMING_WEBHOOK, slack_msg)
VERB_MAP_STATUS_CHANGE = {
STATUS_SUBMITTED: 'submitted',
STATUS_APPROVED: 'approved',
STATUS_DECLINED: 'declined',
STATUS_ACCEPTED: 'accepted',
STATUS_REJECTED: 'rejected'
}
@job
def notify_estimate_status_email(instance, estimate_type='estimate', target_admins=False):
instance = clean_instance(instance, estimate_type == 'quote' and Quote or Estimate)
if instance.status == STATUS_INITIAL:
return
actor = None
target = None
action_verb = VERB_MAP_STATUS_CHANGE.get(instance.status, None)
recipients = None
if instance.status in [STATUS_SUBMITTED]:
actor = instance.user
recipients = TUNGA_STAFF_UPDATE_EMAIL_RECIPIENTS
elif instance.status in [STATUS_APPROVED, STATUS_DECLINED]:
actor = instance.moderated_by
target = instance.user
recipients = [instance.user.email]
elif instance.status in [STATUS_ACCEPTED, STATUS_REJECTED]:
actor = instance.reviewed_by
if target_admins:
recipients = TUNGA_STAFF_UPDATE_EMAIL_RECIPIENTS
else:
target = instance.user
recipients = [instance.user.email]
# Notify staff in a separate email
notify_estimate_status_email.delay(instance.id, estimate_type=estimate_type, target_admins=True)
subject = "{} {} {}".format(
actor.first_name,
action_verb,
estimate_type == 'estimate' and 'an estimate' or 'a quote'
)
to = recipients
ctx = {
'owner': instance.user,
'estimate': instance,
'task': instance.task,
'estimate_url': '{}/work/{}/{}/{}'.format(TUNGA_URL, instance.task.id, estimate_type, instance.id),
'actor': actor,
'target': target,
'verb': action_verb,
'noun': estimate_type
}
if send_mail(
subject, 'tunga/email/email_estimate_status', to, ctx, **dict(deal_ids=[instance.task.hubspot_deal_id])
):
if instance.status == STATUS_SUBMITTED:
instance.moderator_email_at = datetime.datetime.utcnow()
instance.save()
if instance.status in [STATUS_ACCEPTED, STATUS_REJECTED]:
instance.reviewed_email_at = datetime.datetime.utcnow()
instance.save()
if instance.status == STATUS_APPROVED:
notify_estimate_approved_client_email(instance, estimate_type=estimate_type)
def notify_estimate_approved_client_email(instance, estimate_type='estimate'):
instance = clean_instance(instance, estimate_type == 'quote' and Quote or Estimate)
if instance.status != STATUS_APPROVED:
return
subject = "{} submitted {}".format(
instance.user.first_name,
estimate_type == 'estimate' and 'an estimate' or 'a quote'
)
to = [instance.task.user.email]
if instance.task.owner:
to.append(instance.task.owner.email)
ctx = {
'owner': instance.user,
'estimate': instance,
'task': instance.task,
'estimate_url': '{}/work/{}/{}/{}'.format(TUNGA_URL, instance.task.id, estimate_type, instance.id),
'actor': instance.user,
'target': instance.task.owner or instance.task.user,
'verb': 'submitted',
'noun': estimate_type
}
if instance.task.source == TASK_SOURCE_NEW_USER and not instance.task.user.is_confirmed:
url_prefix = '{}/reset-password/confirm/{}/{}?new_user=true&next='.format(
TUNGA_URL, instance.user.uid, instance.user.generate_reset_token()
)
ctx['estimate_url'] = '{}{}'.format(url_prefix, ctx['estimate_url'])
if send_mail(
subject, 'tunga/email/email_estimate_status', to, ctx, **dict(deal_ids=[instance.task.hubspot_deal_id])
):
instance.reviewer_email_at = datetime.datetime.utcnow()
instance.save()
@job
def notify_task_invitation_email(instance):
instance = clean_instance(instance, Participation)
subject = "Task invitation from {}".format(instance.created_by.first_name)
to = [instance.user.email]
ctx = {
'inviter': instance.created_by,
'invitee': instance.user,
'task': instance.task,
'task_url': '%s/work/%s/' % (TUNGA_URL, instance.task.id)
}
send_mail(
subject, 'tunga/email/email_new_task_invitation', to, ctx, **dict(deal_ids=[instance.task.hubspot_deal_id])
)
@job
def notify_task_invitation_project_owner_email(instance):
instance = clean_instance(instance, Task)
if not instance.owner:
return
subject = "{} invited you to a {}".format(instance.user.first_name, instance.is_task and 'task' or 'project')
to = [instance.owner.email]
ctx = {
'inviter': instance.user,
'invitee': instance.owner,
'task': instance,
'task_url': '%s/work/%s/' % (TUNGA_URL, instance.id)
}
if not instance.owner.is_confirmed:
url_prefix = '{}/reset-password/confirm/{}/{}?new_user=true&next='.format(
TUNGA_URL, instance.owner.uid, instance.owner.generate_reset_token()
)
ctx['task_url'] = '{}{}'.format(url_prefix, ctx['task_url'])
send_mail(
subject, 'tunga/email/email_new_task_invitation_po', to, ctx, **dict(deal_ids=[instance.hubspot_deal_id])
)
@job
def notify_task_invitation_response(instance):
notify_task_invitation_response_email(instance)
notify_task_invitation_response_slack(instance)
@job
def notify_task_invitation_response_email(instance):
instance = clean_instance(instance, Participation)
if instance.status not in [STATUS_ACCEPTED, STATUS_REJECTED]:
return
subject = "Task invitation {} by {}".format(
instance.status == STATUS_ACCEPTED and 'accepted' or 'rejected', instance.user.first_name
)
to = list({instance.task.user.email, instance.created_by.email})
ctx = {
'inviter': instance.created_by,
'invitee': instance.user,
'accepted': instance.status == STATUS_ACCEPTED,
'task': instance.task,
'task_url': '%s/work/%s/' % (TUNGA_URL, instance.task.id)
}
send_mail(
subject, 'tunga/email/email_task_invitation_response', to, ctx, **dict(deal_ids=[instance.task.hubspot_deal_id])
)
@job
def notify_task_invitation_response_slack(instance):
instance = clean_instance(instance, Participation)
if not slack_utils.is_task_notification_enabled(instance.task, slugs.EVENT_APPLICATION):
return
task_url = '%s/work/%s/' % (TUNGA_URL, instance.task_id)
slack_msg = "Task invitation %s by %s %s\n\n<%s|View details on Tunga>" % (
instance.status == STATUS_ACCEPTED and 'accepted' or 'rejected', instance.user.short_name,
instance.status == STATUS_ACCEPTED and ':smiley: :fireworks:' or ':unamused:',
task_url
)
slack_utils.send_integration_message(instance.task, message=slack_msg)
@job
def notify_new_task_application(instance):
# Notify project owner
notify_new_task_application_owner_email(instance)
notify_new_task_application_slack(instance, admin=False)
# Send email confirmation to applicant
confirm_task_application_to_applicant_email.delay(instance.id)
# Notify admins
notify_new_task_application_slack.delay(instance.id, admin=True)
@job
def notify_new_task_application_owner_email(instance):
instance = clean_instance(instance, Application)
subject = "New application from {}".format(instance.user.short_name)
to = [instance.task.user.email]
if instance.task.owner:
to.append(instance.task.owner.email)
ctx = {
'owner': instance.task.owner or instance.task.user,
'applicant': instance.user,
'task': instance.task,
'task_url': '%s/work/%s/applications/' % (TUNGA_URL, instance.task_id)
}
if instance.task.source == TASK_SOURCE_NEW_USER and not instance.user.is_confirmed:
url_prefix = '{}/reset-password/confirm/{}/{}?new_user=true&next='.format(
TUNGA_URL, instance.user.uid, instance.user.generate_reset_token()
)
ctx['task_url'] = '{}{}'.format(url_prefix, ctx['task_url'])
send_mail(
subject, 'tunga/email/email_new_task_application', to, ctx, **dict(deal_ids=[instance.task.hubspot_deal_id])
)
@job
def notify_new_task_application_slack(instance, admin=True):
instance = clean_instance(instance, Application)
if not slack_utils.is_task_notification_enabled(instance.task, slugs.EVENT_APPLICATION):
return
application_url = '%s/work/%s/applications/' % (TUNGA_URL, instance.task_id)
slack_msg = "New application from %s" % instance.user.short_name
attachments = [
{
slack_utils.KEY_TITLE: instance.task.summary,
slack_utils.KEY_TITLE_LINK: application_url,
slack_utils.KEY_TEXT: '%s%s%s%s\n\n<%s|View details on Tunga>' %
(truncatewords(convert_to_text(instance.pitch), 100),
instance.hours_needed and '\n*Workload:* {} hrs'.format(instance.hours_needed) or '',
instance.deliver_at and '\n*Delivery Date:* {}'.format(
instance.deliver_at.strftime("%d %b, %Y")
) or '',
instance.remarks and '\n*Remarks:* {}'.format(
truncatewords(convert_to_text(instance.remarks), 100)
) or '',
application_url),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_TUNGA
}
]
if admin:
slack_utils.send_incoming_webhook(
SLACK_STAFF_INCOMING_WEBHOOK,
{
slack_utils.KEY_TEXT: slack_msg,
slack_utils.KEY_ATTACHMENTS: attachments,
slack_utils.KEY_CHANNEL: SLACK_STAFF_UPDATES_CHANNEL
}
)
else:
slack_utils.send_integration_message(instance.task, message=slack_msg, attachments=attachments)
@job
def confirm_task_application_to_applicant_email(instance):
instance = clean_instance(instance, Application)
subject = "You applied for a task: {}".format(instance.task.summary)
to = [instance.user.email]
ctx = {
'owner': instance.task.owner or instance.task.user,
'applicant': instance.user,
'task': instance.task,
'task_url': '%s/work/%s/' % (TUNGA_URL, instance.task.id)
}
send_mail(
subject, 'tunga/email/email_new_task_application_applicant', to, ctx,
**dict(deal_ids=[instance.task.hubspot_deal_id])
)
@job
def notify_task_application_response(instance):
# Notify owner
notify_task_application_response_owner_email(instance)
# Notify admins
notify_task_application_response_admin_email(instance)
notify_task_application_response_slack(instance, admin=True)
@job
def notify_task_application_response_owner_email(instance):
instance = clean_instance(instance, Application)
subject = "Task application {}".format(instance.status == STATUS_ACCEPTED and 'accepted' or 'rejected')
to = [instance.user.email]
ctx = {
'owner': instance.task.owner or instance.task.user,
'applicant': instance.user,
'accepted': instance.status == STATUS_ACCEPTED,
'task': instance.task,
'task_url': '%s/work/%s/' % (TUNGA_URL, instance.task.id)
}
send_mail(
subject, 'tunga/email/email_task_application_response', to, ctx,
**dict(deal_ids=[instance.task.hubspot_deal_id])
)
@job
def notify_task_application_response_admin_email(instance):
instance = clean_instance(instance, Application)
subject = "Task application {}".format(instance.status == STATUS_ACCEPTED and 'accepted' or 'rejected')
to = TUNGA_STAFF_UPDATE_EMAIL_RECIPIENTS
ctx = {
'owner': instance.task.owner or instance.task.user,
'applicant': instance.user,
'accepted': instance.status == STATUS_ACCEPTED,
'task': instance.task,
'task_url': '%s/work/%s/' % (TUNGA_URL, instance.task.id)
}
send_mail(
subject, 'tunga/email/email_task_application_response', to, ctx,
**dict(deal_ids=[instance.task.hubspot_deal_id])
)
@job
def notify_task_application_response_slack(instance, admin=True):
instance = clean_instance(instance, Application)
application_url = '%s/work/%s/applications/' % (TUNGA_URL, instance.task_id)
task_url = '%s/work/%s/' % (TUNGA_URL, instance.task.id)
slack_msg = "Task Application {} | <{}|View on Tunga>".format(
instance.status == STATUS_ACCEPTED and 'accepted' or 'rejected',
task_url
)
attachments = [
{
slack_utils.KEY_TITLE: instance.task.summary,
slack_utils.KEY_TITLE_LINK: application_url,
slack_utils.KEY_TEXT: '%s%s%s%s\n\n<%s|View details on Tunga>' %
(truncatewords(convert_to_text(instance.pitch), 100),
instance.hours_needed and '\n*Workload:* {} hrs'.format(instance.hours_needed) or '',
instance.deliver_at and '\n*Delivery Date:* {}'.format(
instance.deliver_at.strftime("%d %b, %Y")
) or '',
instance.remarks and '\n*Remarks:* {}'.format(
truncatewords(convert_to_text(instance.remarks), 100)
) or '',
application_url),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_TUNGA
}
]
if admin:
slack_utils.send_incoming_webhook(
SLACK_STAFF_INCOMING_WEBHOOK,
{
slack_utils.KEY_TEXT: slack_msg,
slack_utils.KEY_ATTACHMENTS: attachments,
slack_utils.KEY_CHANNEL: SLACK_STAFF_UPDATES_CHANNEL
}
)
else:
slack_utils.send_integration_message(instance.task, message=slack_msg, attachments=attachments)
@job
def send_task_application_not_selected_email(instance):
instance = clean_instance(instance, Task)
rejected_applicants = instance.application_set.filter(
status=STATUS_REJECTED
)
if rejected_applicants:
subject = "Your application was not accepted for: {}".format(instance.summary)
to = [rejected_applicants[0].user.email]
bcc = [dev.user.email for dev in rejected_applicants[1:]] if len(rejected_applicants) > 1 else None
ctx = {
'task': instance,
'task_url': '%s/work/%s/' % (TUNGA_URL, instance.id)
}
send_mail(
subject, 'tunga/email/email_task_application_not_selected', to, ctx, bcc=bcc,
**dict(deal_ids=[instance.hubspot_deal_id])
)
@job
def remind_progress_event(instance):
remind_progress_event_email(instance)
@job
def remind_progress_event_email(instance):
instance = clean_instance(instance, ProgressEvent)
is_pm_report = instance.type == PROGRESS_EVENT_TYPE_PM
is_client_report = instance.type == PROGRESS_EVENT_TYPE_CLIENT
is_pm_or_client_report = is_pm_report or is_client_report
if is_pm_report and not instance.task.is_project:
return
pm = instance.task.pm
if not pm and instance.task.user.is_project_manager:
pm = instance.task.user
if is_pm_report and not pm:
return
owner = instance.task.owner
if not owner:
owner = instance.task.user
if is_client_report and not owner:
return
subject = is_client_report and "Weekly Survey" or "Upcoming {} Update".format(instance.task.is_task and 'Task' or 'Project')
to = []
bcc = None
if is_pm_report:
to = [pm.email]
bcc = None
elif is_client_report:
to = [owner.email]
if owner.email != instance.task.user.email:
to.append(instance.task.user.email)
bcc = None
else:
participants = instance.task.participation_set.filter(status=STATUS_ACCEPTED)
if participants:
to = [participants[0].user.email]
bcc = [participant.user.email for participant in participants[1:]] if participants.count() > 1 else None
ctx = {
'owner': instance.task.owner or instance.task.user,
'event': instance,
'update_url': '%s/work/%s/event/%s/' % (TUNGA_URL, instance.task.id, instance.id)
}
if to:
email_template = is_client_report and 'client_survey_reminder' or 'progress_event_reminder'
if send_mail(
subject, 'tunga/email/{}'.format(email_template), to, ctx, bcc=bcc,
**dict(deal_ids=[instance.task.hubspot_deal_id])
):
instance.last_reminder_at = datetime.datetime.utcnow()
instance.save()
@job
def notify_new_progress_report(instance):
notify_new_progress_report_email(instance)
notify_new_progress_report_slack(instance)
@job
def notify_new_progress_report_email(instance):
instance = clean_instance(instance, ProgressReport)
is_pm_report = instance.event.type == PROGRESS_EVENT_TYPE_PM
is_client_report = instance.event.type == PROGRESS_EVENT_TYPE_CLIENT
is_pm_or_client_report = is_pm_report or is_client_report
subject = "{} submitted a {}".format(instance.user.display_name, is_client_report and "Weekly Survey" or "Progress Report")
to = is_pm_or_client_report and TUNGA_STAFF_UPDATE_EMAIL_RECIPIENTS or [instance.event.task.user.email]
if instance.event.task.owner and not is_pm_or_client_report:
to.append(instance.event.task.owner.email)
ctx = {
'owner': instance.event.task.user,
'reporter': instance.user,
'event': instance.event,
'report': instance,
'update_url': '%s/work/%s/event/%s/' % (TUNGA_URL, instance.event.task.id, instance.event.id)
}
email_template = is_client_report and 'new_client_survey' or 'new_progress_report{}'.format(is_pm_report and '_pm' or '')
send_mail(
subject, 'tunga/email/{}'.format(email_template), to, ctx,
**dict(deal_ids=[instance.event.task.hubspot_deal_id])
)
@job
def notify_new_progress_report_slack(instance, updated=False):
instance = clean_instance(instance, ProgressReport)
is_pm_report = instance.event.type == PROGRESS_EVENT_TYPE_PM
is_client_report = instance.event.type == PROGRESS_EVENT_TYPE_CLIENT
is_pm_or_client_report = is_pm_report or is_client_report
is_dev_report = not is_pm_or_client_report
#if not (slack_utils.is_task_notification_enabled(instance.event.task, slugs.EVENT_PROGRESS)):
# return
report_url = '%s/work/%s/event/%s/' % (TUNGA_URL, instance.event.task_id, instance.event_id)
slack_msg = "{} {} a {} | {}".format(
instance.user.display_name,
updated and 'updated' or 'submitted',
is_client_report and "Weekly Survey" or "Progress Report",
'<{}|View details on Tunga>'.format(report_url)
)
slack_text_suffix = ''
if not is_client_report:
slack_text_suffix += '*Status:* {}\n*Percentage completed:* {}{}'.format(
instance.get_status_display(), instance.percentage, '%')
if instance.last_deadline_met is not None:
slack_text_suffix += '\n*Was the last deadline met?:* {}'.format(
instance.last_deadline_met and 'Yes' or 'No'
)
if instance.next_deadline:
slack_text_suffix += '\n*Next deadline:* {}'.format(instance.next_deadline.strftime("%d %b, %Y"))
if is_client_report:
if instance.deliverable_satisfaction is not None:
slack_text_suffix += '\n*Are you satisfied with the deliverables?:* {}'.format(
instance.deliverable_satisfaction and 'Yes' or 'No'
)
if not is_pm_or_client_report:
if instance.stuck_reason:
slack_text_suffix += '\n*Reason for being stuck:*\n {}'.format(
convert_to_text(instance.get_stuck_reason_display())
)
attachments = [
{
slack_utils.KEY_TITLE: instance.event.task.summary,
slack_utils.KEY_TITLE_LINK: report_url,
slack_utils.KEY_TEXT: slack_text_suffix,
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_BLUE
}
]
if instance.deadline_miss_communicated is not None:
attachments.append({
slack_utils.KEY_TITLE: '{} promptly about not making the deadline?'.format(is_client_report and 'Did the project manager/ developer(s) inform you' or 'Did you inform the client'),
slack_utils.KEY_TEXT: '{}'.format(instance.deadline_miss_communicated and 'Yes' or 'No'),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_RED
})
if instance.deadline_report:
attachments.append({
slack_utils.KEY_TITLE: 'Report about the last deadline:',
slack_utils.KEY_TEXT: convert_to_text(instance.deadline_report),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_RED
})
if is_client_report:
if instance.rate_deliverables:
attachments.append({
slack_utils.KEY_TITLE: 'How would you rate the deliverables on a scale from 1 to 5?',
slack_utils.KEY_TEXT: '{}/5'.format(instance.rate_deliverables),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_BLUE
})
if instance.pm_communication:
attachments.append({
slack_utils.KEY_TITLE: 'Is the communication between you and the project manager/developer(s) going well?',
slack_utils.KEY_TEXT: '{}'.format(instance.pm_communication and 'Yes' or 'No'),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_GREEN
})
else:
# Status
if instance.stuck_details:
attachments.append({
slack_utils.KEY_TITLE: 'Explain Further why you are stuck/what should be done:',
slack_utils.KEY_TEXT: convert_to_text(instance.stuck_details),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_GREEN
})
if instance.started_at:
attachments.append({
slack_utils.KEY_TITLE: 'When did you start this sprint/task/project?',
slack_utils.KEY_TEXT: instance.started_at.strftime("%d %b, %Y"),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_BLUE
})
# Last
if instance.accomplished:
attachments.append({
slack_utils.KEY_TITLE: 'What has been accomplished since last update?',
slack_utils.KEY_TEXT: convert_to_text(instance.accomplished),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_GREEN
})
if instance.rate_deliverables:
attachments.append({
slack_utils.KEY_TITLE: 'Rate Deliverables:',
slack_utils.KEY_TEXT: '{}/5'.format(instance.rate_deliverables),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_RED
})
# Current
if instance.todo:
attachments.append({
slack_utils.KEY_TITLE: is_dev_report and 'What do you intend to achieve/complete today?' or 'What are the next next steps?',
slack_utils.KEY_TEXT: convert_to_text(instance.todo),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_GREEN
})
# Next
if instance.next_deadline:
attachments.append({
slack_utils.KEY_TITLE: 'When is the next deadline?',
slack_utils.KEY_TEXT: instance.next_deadline.strftime("%d %b, %Y"),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_RED
})
if instance.next_deadline_meet is not None:
attachments.append({
slack_utils.KEY_TITLE: 'Do you anticipate to meet this deadline?',
slack_utils.KEY_TEXT: '{}'.format(instance.next_deadline_meet and 'Yes' or 'No'),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_GREEN
})
if instance.next_deadline_fail_reason:
attachments.append({
slack_utils.KEY_TITLE: 'Why will you not be able to make the next deadline?',
slack_utils.KEY_TEXT: convert_to_text(instance.next_deadline_fail_reason),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_RED
})
if instance.obstacles:
attachments.append({
slack_utils.KEY_TITLE: 'What obstacles are impeding your progress?',
slack_utils.KEY_TEXT: convert_to_text(instance.obstacles),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_RED
})
if is_pm_report:
if instance.team_appraisal:
attachments.append({
slack_utils.KEY_TITLE: 'Team appraisal:',
slack_utils.KEY_TEXT: convert_to_text(instance.team_appraisal),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_NEUTRAL
})
if instance.remarks:
attachments.append({
slack_utils.KEY_TITLE: 'Other remarks or questions',
slack_utils.KEY_TEXT: convert_to_text(instance.remarks),
slack_utils.KEY_MRKDWN_IN: [slack_utils.KEY_TEXT],
slack_utils.KEY_COLOR: SLACK_ATTACHMENT_COLOR_NEUTRAL
})
# All reports go to Tunga #updates Slack
slack_utils.send_incoming_webhook(SLACK_STAFF_INCOMING_WEBHOOK, {
slack_utils.KEY_TEXT: slack_msg,
slack_utils.KEY_CHANNEL: SLACK_STAFF_UPDATES_CHANNEL,
slack_utils.KEY_ATTACHMENTS: attachments
})
if not is_pm_or_client_report:
slack_utils.send_integration_message(instance.event.task, message=slack_msg, attachments=attachments)
@job
def notify_task_invoice_request_email(instance):
instance = clean_instance(instance, Task)
subject = "{} requested for an invoice".format(instance.user.display_name)
to = TUNGA_STAFF_UPDATE_EMAIL_RECIPIENTS
ctx = {
'owner': instance.owner or instance.user,
'task': instance,
'task_url': '%s/work/%s/' % (TUNGA_URL, instance.id),
'invoice_url': '%s/api/task/%s/download/invoice/?format=pdf' % (TUNGA_URL, instance.id)
}
send_mail(
subject, 'tunga/email/email_task_invoice_request', to, ctx, **dict(deal_ids=[instance.hubspot_deal_id])
)
| {"/tunga_tasks/management/commands/tunga_manage_task_progress.py": ["/tunga_tasks/notifications.py"]} |
62,475 | codephillip/tunga-api | refs/heads/master | /tunga_utils/serializers.py | from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django_countries.serializer_fields import CountryField
from rest_framework import serializers
from rest_framework.fields import SkipField
from tunga_profiles.models import Skill, City, UserProfile, Education, Work, Connection, BTCWallet
from tunga_profiles.utils import profile_check
from tunga_utils.models import GenericUpload, ContactRequest, Upload, AbstractExperience, Rating
class CreateOnlyCurrentUserDefault(serializers.CurrentUserDefault):
def set_context(self, serializer_field):
self.is_update = serializer_field.parent.instance is not None
super(CreateOnlyCurrentUserDefault, self).set_context(serializer_field)
def __call__(self):
if hasattr(self, 'is_update') and self.is_update:
# TODO: Make sure this check is sufficient for all update scenarios
raise SkipField()
user = super(CreateOnlyCurrentUserDefault, self).__call__()
if user and user.is_authenticated():
return user
return None
class ContentTypeAnnotatedModelSerializer(serializers.ModelSerializer):
content_type = serializers.SerializerMethodField(read_only=True, required=False)
def get_content_type(self, obj):
return ContentType.objects.get_for_model(self.Meta.model).id
class DetailAnnotatedModelSerializer(serializers.ModelSerializer):
details = serializers.SerializerMethodField(read_only=True, required=False)
class Meta:
details_serializer = None
def get_details(self, obj):
try:
if self.Meta.details_serializer:
return self.Meta.details_serializer(obj).data
except AttributeError:
return None
class SkillSerializer(serializers.ModelSerializer):
class Meta:
model = Skill
fields = ('id', 'name', 'slug')
class CitySerializer(serializers.ModelSerializer):
class Meta:
model = City
fields = ('id', 'name', 'slug')
class SimpleBTCWalletSerializer(serializers.ModelSerializer):
class Meta:
model = BTCWallet
exclude = ('token', 'token_secret')
class SimpleUserSerializer(serializers.ModelSerializer):
company = serializers.CharField(read_only=True, required=False, source='userprofile.company')
can_contribute = serializers.SerializerMethodField(required=False, read_only=True)
class Meta:
model = get_user_model()
fields = (
'id', 'username', 'email', 'first_name', 'last_name', 'display_name', 'short_name', 'type', 'image',
'is_developer', 'is_project_owner', 'is_project_manager', 'is_staff', 'verified', 'company', 'avatar_url',
'can_contribute'
)
def get_can_contribute(self, obj):
return profile_check(obj)
class SimpleProfileSerializer(serializers.ModelSerializer):
city = serializers.CharField()
skills = SkillSerializer(many=True)
country = CountryField()
country_name = serializers.CharField()
btc_wallet = SimpleBTCWalletSerializer()
class Meta:
model = UserProfile
exclude = ('user',)
class InvoiceUserSerializer(serializers.ModelSerializer):
profile = SimpleProfileSerializer(read_only=True, required=False, source='userprofile')
class Meta:
model = get_user_model()
fields = (
'id', 'username', 'email', 'first_name', 'last_name', 'display_name', 'type',
'is_developer', 'is_project_owner', 'is_staff', 'verified', 'profile'
)
class SimpleAbstractExperienceSerializer(serializers.ModelSerializer):
start_month_display = serializers.CharField(read_only=True, required=False, source='get_start_month_display')
end_month_display = serializers.CharField(read_only=True, required=False, source='get_end_month_display')
class Meta:
model = AbstractExperience
exclude = ('user', 'created_at')
class AbstractExperienceSerializer(SimpleAbstractExperienceSerializer):
user = SimpleUserSerializer(required=False, read_only=True, default=CreateOnlyCurrentUserDefault())
class Meta:
model = AbstractExperience
exclude = ('created_at',)
class SimpleWorkSerializer(SimpleAbstractExperienceSerializer):
class Meta(SimpleAbstractExperienceSerializer.Meta):
model = Work
class SimpleEducationSerializer(SimpleAbstractExperienceSerializer):
class Meta(SimpleAbstractExperienceSerializer.Meta):
model = Education
class SimpleConnectionSerializer(serializers.ModelSerializer):
class Meta:
model = Connection
fields = '__all__'
class SimpleUploadSerializer(serializers.ModelSerializer):
url = serializers.CharField(required=False, read_only=True, source='file.url')
name = serializers.SerializerMethodField(required=False, read_only=True)
size = serializers.IntegerField(required=False, read_only=True, source='file.size')
display_size = serializers.SerializerMethodField(required=False, read_only=True)
class Meta:
model = GenericUpload
fields = ('id', 'url', 'name', 'created_at', 'size', 'display_size')
def get_name(self, obj):
return obj.file.name.split('/')[-1]
def get_display_size(self, obj):
filesize = obj.file.size
converter = {'KB': 10**3, 'MB': 10**6, 'GB': 10**9, 'TB': 10**12}
units = ['TB', 'GB', 'MB', 'KB']
for label in units:
conversion = converter[label]
if conversion and filesize > conversion:
return '%s %s' % (round(filesize/conversion, 2), label)
return '%s %s' % (filesize, 'bytes')
class UploadSerializer(SimpleUploadSerializer):
user = SimpleUserSerializer()
class Meta(SimpleUploadSerializer.Meta):
model = Upload
fields = SimpleUploadSerializer.Meta.fields + ('user',)
class ContactRequestSerializer(serializers.ModelSerializer):
class Meta:
model = ContactRequest
fields = ('email', 'item')
class SimpleRatingSerializer(ContentTypeAnnotatedModelSerializer):
created_by = SimpleUserSerializer(
required=False, read_only=True, default=CreateOnlyCurrentUserDefault()
)
display_criteria = serializers.CharField(required=False, read_only=True, source='get_criteria_display')
class Meta:
model = Rating
exclude = ('content_type', 'object_id', 'created_at')
| {"/tunga_tasks/management/commands/tunga_manage_task_progress.py": ["/tunga_tasks/notifications.py"]} |
62,476 | codephillip/tunga-api | refs/heads/master | /tunga_tasks/utils.py | import json
from allauth.socialaccount.providers.github.provider import GitHubProvider
from tunga_profiles.utils import get_app_integration
from tunga_tasks.models import Integration, IntegrationMeta
from tunga_utils.constants import APP_INTEGRATION_PROVIDER_SLACK, APP_INTEGRATION_PROVIDER_HARVEST
from tunga_utils.helpers import clean_meta_value, get_social_token, GenericObject
def get_task_integration(task, provider):
try:
return Integration.objects.filter(task_id=task, provider=provider).latest('updated_at')
except Integration.DoesNotExist:
return None
def get_integration_token(user, provider, task=None):
if task:
task_integration = get_task_integration(task, provider)
if task_integration and task_integration.token:
return GenericObject(
**dict(
token=task_integration.token,
token_secret=task_integration.token_secret,
extra=task_integration.token_extra
)
)
if provider == GitHubProvider.id:
return get_social_token(user=user, provider=provider)
else:
return get_app_integration(user=user, provider=provider)
def save_task_integration_meta(task_id, provider, meta_info):
integration = get_task_integration(task_id, provider)
if integration and isinstance(meta_info, dict):
for meta_key in meta_info:
IntegrationMeta.objects.update_or_create(
integration=integration, meta_key=meta_key, defaults=dict(meta_value=clean_meta_value(meta_info[meta_key]))
)
def save_integration_tokens(user, task_id, provider):
token_info = dict()
if provider == GitHubProvider.id:
social_token = get_social_token(user=user, provider=provider)
if social_token:
token_info = dict(
token=social_token.token,
token_secret=social_token.token_secret,
token_expires_at=social_token.expires_at
)
else:
app_integration = get_app_integration(user=user, provider=provider)
if app_integration:
token_info = dict(
token=app_integration.token,
token_secret=app_integration.token_secret,
token_expires_at=app_integration.expires_at,
token_extra=app_integration.extra
)
if provider == APP_INTEGRATION_PROVIDER_SLACK:
token_info.pop('token_secret')
response = json.loads(app_integration.extra)
if 'bot' in response:
token_info['bot_access_token'] = response['bot'].get('bot_access_token')
token_info['bot_user_id'] = response['bot'].get('bot_user_id')
elif provider == APP_INTEGRATION_PROVIDER_HARVEST:
token_info.pop('token_secret')
token_info['refresh_token'] = app_integration.token_secret
save_task_integration_meta(task_id, provider, token_info)
| {"/tunga_tasks/management/commands/tunga_manage_task_progress.py": ["/tunga_tasks/notifications.py"]} |
62,477 | codephillip/tunga-api | refs/heads/master | /tunga_tasks/filters.py | import django_filters
from tunga_tasks.models import Task, Application, Participation, TimeEntry, Project, ProgressReport, ProgressEvent, \
Estimate, Quote, TaskPayment, ParticipantPayment
from tunga_utils.filters import GenericDateFilterSet
class ProjectFilter(GenericDateFilterSet):
class Meta:
model = Project
fields = ('user', 'closed')
class TaskFilter(GenericDateFilterSet):
applicant = django_filters.NumberFilter(name='applications__user', label='Applicant')
participant = django_filters.NumberFilter(name='participants__user', label='Participant')
payment_status = django_filters.CharFilter(method='filter_payment_status')
skill = django_filters.CharFilter(name='skills__name', label='skills')
skill_id = django_filters.NumberFilter(name='skills', label='skills (by ID)')
class Meta:
model = Task
fields = (
'user', 'project', 'parent', 'type', 'scope', 'source', 'closed', 'applicant', 'participant',
'paid', 'pay_distributed', 'payment_status',
'skill', 'skill_id'
)
def filter_payment_status(self, queryset, name, value):
queryset = queryset.filter(closed=True)
if value in ['paid', 'processing']:
queryset = queryset.filter(paid=True)
if value == 'paid':
return queryset.filter(pay_distributed=True)
else:
return queryset.filter(pay_distributed=False)
elif value == 'pending':
queryset = queryset.filter(paid=False)
return queryset
class ApplicationFilter(GenericDateFilterSet):
class Meta:
model = Application
fields = ('user', 'task', 'status')
class ParticipationFilter(GenericDateFilterSet):
class Meta:
model = Participation
fields = ('user', 'task', 'status')
class EstimateFilter(GenericDateFilterSet):
class Meta:
model = Estimate
fields = ('user', 'task', 'status', 'moderated_by')
class QuoteFilter(GenericDateFilterSet):
class Meta:
model = Quote
fields = ('user', 'task', 'status', 'moderated_by')
class TimeEntryFilter(GenericDateFilterSet):
min_date = django_filters.IsoDateTimeFilter(name='spent_at', lookup_expr='gte')
max_date = django_filters.IsoDateTimeFilter(name='spent_at', lookup_expr='lte')
min_hours = django_filters.IsoDateTimeFilter(name='hours', lookup_expr='gte')
max_hours = django_filters.IsoDateTimeFilter(name='hours', lookup_expr='lte')
class Meta:
model = TimeEntry
fields = ('user', 'task', 'spent_at', 'hours')
class ProgressEventFilter(GenericDateFilterSet):
class Meta:
model = ProgressEvent
fields = ('created_by', 'task', 'type')
class ProgressReportFilter(GenericDateFilterSet):
task = django_filters.NumberFilter(name='event__task')
event_type = django_filters.NumberFilter(name='event__type')
class Meta:
model = ProgressReport
fields = ('user', 'event', 'task', 'event_type', 'status')
class TaskPaymentFilter(GenericDateFilterSet):
user = django_filters.NumberFilter(name='task_user')
owner = django_filters.NumberFilter(name='task_owner')
class Meta:
model = TaskPayment
fields = ('task', 'ref', 'payment_type', 'btc_address', 'processed', 'paid', 'captured', 'user', 'owner')
class ParticipantPaymentFilter(GenericDateFilterSet):
user = django_filters.NumberFilter(name='participant__user')
task = django_filters.NumberFilter(name='source__task')
class Meta:
model = ParticipantPayment
fields = ('participant', 'source', 'destination', 'ref', 'idem_key', 'status', 'user', 'task') | {"/tunga_tasks/management/commands/tunga_manage_task_progress.py": ["/tunga_tasks/notifications.py"]} |
62,489 | marcinnowo307/BIAI_Rain_Prediction | refs/heads/main | /neural_network/network.py | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 11 17:07:34 2021
@author: Marcinek
"""
import tensorflow as tf
def create_model():
model = tf.keras.Sequential([
tf.keras.layers.Dense(units = 32, kernel_initializer = 'uniform', activation = 'relu', input_dim = 22),
tf.keras.layers.Dense(units = 32, kernel_initializer = 'uniform', activation = 'relu'),
tf.keras.layers.Dense(units = 16, kernel_initializer = 'uniform', activation = 'relu'),
tf.keras.layers.Dense(units = 8, kernel_initializer = 'uniform', activation = 'relu'),
tf.keras.layers.Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid')
])
#opt = tf.keras.optimizers.Adam(learning_rate=0.00009)
model.compile(optimizer='adam',
loss = 'binary_crossentropy',
metrics = ['accuracy'])
return model | {"/train_model.py": ["/neural_network/network.py"], "/predict.py": ["/neural_network/network.py"]} |
62,490 | marcinnowo307/BIAI_Rain_Prediction | refs/heads/main | /train_model.py | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 11 17:06:47 2021
@author: Marcinek
"""
import pandas as pd #for loading csv files
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from neural_network.network import create_model
np.random.seed(2137)
#loading and splitting data
data = pd.read_csv("clean_dataset/weatherAUS.csv")
x = data.drop(['RainTomorrow'], axis=1)
y = data['RainTomorrow']
x_train, x_test, y_train, y_test = train_test_split(x,
y,
test_size = 0.2,
random_state = 40)
# train a model
model = create_model()
model.fit(x_train, y_train, batch_size = 32, epochs = 20, validation_split = 0.2)
model.save_weights('neural_network/weights')
# check accuracy
predicted = model.predict(x_test)
predicted = (predicted > 0.5)
print(classification_report(y_test, predicted))
| {"/train_model.py": ["/neural_network/network.py"], "/predict.py": ["/neural_network/network.py"]} |
62,491 | marcinnowo307/BIAI_Rain_Prediction | refs/heads/main | /predict.py | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 14 18:00:59 2021
@author: Marcinek
"""
import tensorflow as tf
import sys
import pandas as pd
import numpy as np
import sklearn as sk
from neural_network.network import create_model
from sklearn import preprocessing
from pickle import load
def load_json_data(json_name):
return pd.read_json(json_name)
def preprocess_data(df):
#drop columns
df['Date'] = pd.to_datetime(df["Date"])
df['Month'] = df.Date.dt.month
df = df.drop(['Date'], axis=1)
# turn object cols to ints
tmp = (df.dtypes == "object")
object_columns = list(tmp[tmp].index)
for i in object_columns:
encoder = sk.preprocessing.LabelEncoder()
encoder.classes_ = np.load("neural_network/encodings/{0}.npy".format(i), allow_pickle=True)
df[i] = encoder.transform(df[i])
#scale the values
column_names = list(df.columns)
standard_scaler = load(open('neural_network/scaling/scaler.pkl', 'rb'))
df = standard_scaler.transform(df)
df = pd.DataFrame(df, columns=column_names)
return df
def predict(df):
model = create_model()
model.load_weights('neural_network/weights').expect_partial() # not everything is used from the weights
pred = model.predict(df)
return (pred > 0.5)
if __name__ == "__main__":
print("will it rain tomorrow?")
# data = pd.read_csv("original_dataset/weatherAUS.csv")
# data.drop( labels = 'RainTomorrow', axis = 1, inplace = True)
# data.dropna(inplace = True)
# data.reset_index(drop = True, inplace = True)
# frame = data.loc[data['Date'] == "2009-01-22"]
# frame = frame.loc[frame['Location'] == "Cobar"]
# frame.to_json("input.json")
data = pd.read_json(sys.argv[1])
dateTimes = data['Date']
data = preprocess_data(data)
predictions = predict(data)
output = pd.DataFrame()
output['Date'] = dateTimes
output['RainTomorrow'] = predictions
if output['RainTomorrow'][0] == True:
print('it will')
else:
print("it won't") | {"/train_model.py": ["/neural_network/network.py"], "/predict.py": ["/neural_network/network.py"]} |
62,492 | marcinnowo307/BIAI_Rain_Prediction | refs/heads/main | /preparing_data.py | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 6 23:15:58 2021
@author: Marcinek
"""
import matplotlib.pyplot as plt # for plotting
import pandas as pd #for loading csv files
import numpy
import sklearn as sk
from sklearn import preprocessing
from pathlib import Path #to manipulate files
from pickle import dump
#create a directory for the clean datasets
Path("clean_dataset").mkdir(exist_ok=True)
Path("neural_network").mkdir(exist_ok=True)
Path("neural_network/scaling").mkdir(exist_ok=True)
Path("neural_network/encodings").mkdir(exist_ok=True)
#Load the original csv file
original = pd.read_csv("original_dataset/weatherAUS.csv")
original.head()
original.info()
original.isnull().sum()
# Datetime conversion
original['Date'] = pd.to_datetime(original["Date"])
original['Month'] = original.Date.dt.month
# if target variable is null, drop it
original.dropna(subset = ['RainTomorrow'], inplace = True)
original.reset_index(drop = True, inplace = True)
# fill categorical NaN values with mode
tmp = (original.dtypes == "object")
object_columns = list(tmp[tmp].index)
for i in object_columns:
original[i].fillna(original[i].mode()[0] , inplace=True)
# fill continous NaN values with median
tmp = (original.dtypes == "float64")
float_columns = list(tmp[tmp].index)
for i in float_columns:
original[i].fillna(original[i].median() , inplace=True)
#preprocessing data
# turn object cols to ints
for i in object_columns:
encoder = sk.preprocessing.LabelEncoder()
encoder.fit(original[i])
numpy.save( 'neural_network/encodings/{0}'.format(i), encoder.classes_)
original[i] = encoder.transform(original[i])
#original[i] = encoder.fit_transform(original[i])
target = original['RainTomorrow']
features = original.drop(['RainTomorrow', 'Date'], axis=1)
print('Shape before deleting outliers ', features.shape)
#scale the values
column_names = list(features.columns)
standard_scaler = preprocessing.StandardScaler()
features = standard_scaler.fit_transform(features)
dump(standard_scaler, open('neural_network/scaling/scaler.pkl', 'wb'))
#features = standard_scaler.transform(features)
features = pd.DataFrame(features, columns=column_names)
# find outliers and delete them
features['RainTomorrow'] = target
##################################################################
#delete the outliers using IQR
# for i in ['Cloud3pm', 'Rainfall', 'Evaporation', 'WindSpeed9am']:
# Q1 = features[i].quantile(0.25)
# Q3 = features[i].quantile(0.75)
# IQR = Q3 - Q1
# lower_limit, upper_limit = Q1 - 7*IQR, Q3 + 7*IQR
# features = features[(features[i] >= lower_limit) & (features[i] <= upper_limit)]
# hand trimming the dataset
features = features[(features["MinTemp"]<2.3)&(features["MinTemp"]>-2.3)]
features = features[(features["MaxTemp"]<2.3)&(features["MaxTemp"]>-2)]
features = features[(features["Rainfall"]<4.5)]
features = features[(features["Evaporation"]<2.8)]
features = features[(features["Sunshine"]<2.1)]
features = features[(features["WindGustSpeed"]<4)&(features["WindGustSpeed"]>-4)]
features = features[(features["WindSpeed9am"]<4)]
features = features[(features["WindSpeed3pm"]<2.5)]
features = features[(features["Humidity9am"]>-3)]
features = features[(features["Humidity3pm"]>-2.2)]
features = features[(features["Pressure9am"]< 2)&(features["Pressure9am"]>-2.7)]
features = features[(features["Pressure3pm"]< 2)&(features["Pressure3pm"]>-2.7)]
features = features[(features["Cloud9am"]<1.8)]
features = features[(features["Cloud3pm"]<2)]
features = features[(features["Temp9am"]<2.3)&(features["Temp9am"]>-2)]
features = features[(features["Temp3pm"]<2.3)&(features["Temp3pm"]>-2)]
#plt.figure(figsize=(20,10))
#sns.boxplot(data = features)
#plt.xticks(rotation = 90)
#plt.show()
##################################################################
print('Shape after deleting outliers ', features.shape)
features.info()
features.to_csv("clean_dataset/weatherAUS.csv", index=False)
| {"/train_model.py": ["/neural_network/network.py"], "/predict.py": ["/neural_network/network.py"]} |
62,493 | dyscord/dyscord | refs/heads/master | /dyscord/error.py | # Plugin:
class PluginError(Exception):
""" General plugin error """
pass
class PluginNotFound(PluginError):
""" Throw if plugin requested for download does not exist """
pass
class PluginExists(PluginError):
""" Throw if plugin requested for download already exists """
class PluginMalformedError(PluginError):
""" Throw if downloaded plugin is malformed """
pass
# Plugin Implementation
class PluginAlreadyImported(ValueError):
""" Throw if a plugin has already been downloaded """
pass
| {"/dyscord/bot.py": ["/dyscord/plugin.py", "/dyscord/download.py", "/dyscord/error.py"], "/dyscord/__init__.py": ["/dyscord/bot.py"], "/dyscord/plugin.py": ["/dyscord/error.py", "/dyscord/redis.py", "/dyscord/download.py"], "/run.py": ["/dyscord/__init__.py", "/dyscord/download.py"], "/dyscord/download.py": ["/dyscord/error.py", "/dyscord/plugin_bin/__init__.py"]} |
62,494 | dyscord/dyscord | refs/heads/master | /dyscord/redis.py | from redis import StrictRedis
from dyscord_plugin.storage import StorageManager
class RedisStorageManager(StorageManager):
def __init__(self, redis: StrictRedis, prefix):
self.redis = redis
self.prefix = prefix
def _add_prefix(self, text, add_dot=True):
if add_dot:
sep = "."
else:
sep = ""
return "{}{}{}".format(self.prefix, sep, text)
def __len__(self):
return sum(1 for x in self.__iter__())
def __getitem__(self, key):
return self.redis.get(self._add_prefix(key))
def __setitem__(self, key, value):
self.redis.set(self._add_prefix(key), value)
def __delitem__(self, key):
self.redis.delete(self._add_prefix(key))
def __iter__(self):
for k in self.redis.scan_iter(self._add_prefix("*", add_dot=False)):
yield k[len(self._add_prefix("")):]
def __contains__(self, item):
return self._add_prefix(item) in self.redis
def get(self, key):
return self.__getitem__(key)
def set(self, key, value):
self.__setitem__(key, value)
| {"/dyscord/bot.py": ["/dyscord/plugin.py", "/dyscord/download.py", "/dyscord/error.py"], "/dyscord/__init__.py": ["/dyscord/bot.py"], "/dyscord/plugin.py": ["/dyscord/error.py", "/dyscord/redis.py", "/dyscord/download.py"], "/run.py": ["/dyscord/__init__.py", "/dyscord/download.py"], "/dyscord/download.py": ["/dyscord/error.py", "/dyscord/plugin_bin/__init__.py"]} |
62,495 | dyscord/dyscord | refs/heads/master | /dyscord/bot.py | from redis import StrictRedis
import parse
import traceback
import sys
import discord
from discord.ext.commands import Bot, command, Command, errors
from .plugin import ServerPluginHandler, PLUGIN_LIST_FMT
from .download import PluginManager
from .error import PluginError, PluginAlreadyImported
import os
from typing import Dict
# Redis:
REDIS_HOST_KEY = "DYSCORD_REDIS_HOST"
REDIS_PORT_KEY = "DYSCORD_REDIS_PORT"
REDIS_PASS_KEY = "DYSCORD_REDIS_PASS"
# Bot version
VERSION = 'v0.1'
COMMAND_PREFIX = "d/"
def _get_environ_default(key, default):
try: # Attempt to get environ at `key`, but default to `default`
return os.environ[key]
except KeyError:
return default
def _get_redis_info(): # Get redis host info from environment vars, else use defaults
return {'host': _get_environ_default(REDIS_HOST_KEY, 'localhost'), # Get redis host - default: 'localhost'
'port': int(_get_environ_default(REDIS_PORT_KEY, 6379)), # Get redis port - default: 6379
'password': _get_environ_default(REDIS_PASS_KEY, None)} # Get redis password - default: None
class Dyscord(Bot):
def __init__(self):
super().__init__(COMMAND_PREFIX)
self.server_phandlers: Dict[discord.Guild, ServerPluginHandler] = {}
self.pm = PluginManager(self)
# Create StrictRedis object:
self.redis = StrictRedis(**_get_redis_info(), charset="utf-8", decode_responses=True)
# Add all commands in class:
for m in dir(self):
attr = getattr(self, m)
if isinstance(attr, Command):
self.add_command(attr)
# Load plugin handlers for existing guilds:
search = PLUGIN_LIST_FMT.format("*", "*")
for gname in self.redis.scan_iter(search): # Search redis for plugin lists
guild_id = int(parse.parse(PLUGIN_LIST_FMT, gname)[0]) # Extract guild id
self._get_plugin_handler(guild_id) # Create all plugin handlers of existing guilds
def _get_plugin_handler(self, guild_id):
if guild_id in self.server_phandlers: # If the guild handler has been created
ph = self.server_phandlers[guild_id] # Get from list
else: # Guild is new
ph = ServerPluginHandler(guild_id, self.redis, self.pm) # Create plugin handler
self.server_phandlers[guild_id] = ph # Add handler to list
return ph
@command(pass_context=True)
async def plugin_install(self, ctx, plugin_name: str):
_guild = ctx.guild
_channel = ctx.channel
ph = self._get_plugin_handler(_guild.id) # Get plugin handler from guild id
try:
try:
ph.add_plugin(plugin_name)
except PluginAlreadyImported:
await _channel.send("Already implemented plugin: {}".format(plugin_name))
else:
await _channel.send("Successfully implemented plugin: {}".format(plugin_name))
except PluginError as e:
await _channel.send("Error implementing plugin: {}".format(e.__class__.__name__))
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
if message.author == self.user: # Ignore if message is from this bot
return
await super().on_message(message) # Run local commands
for ph in self.server_phandlers.values():
await ph.process_msg(message)
async def on_command_error(self, context, exception): # Prevent reporting of missing commands (could be in plugin)
if isinstance(exception, errors.CommandNotFound):
return
print('Ignoring exception in command {}:'.format(context.command), file=sys.stderr)
traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr)
| {"/dyscord/bot.py": ["/dyscord/plugin.py", "/dyscord/download.py", "/dyscord/error.py"], "/dyscord/__init__.py": ["/dyscord/bot.py"], "/dyscord/plugin.py": ["/dyscord/error.py", "/dyscord/redis.py", "/dyscord/download.py"], "/run.py": ["/dyscord/__init__.py", "/dyscord/download.py"], "/dyscord/download.py": ["/dyscord/error.py", "/dyscord/plugin_bin/__init__.py"]} |
62,496 | dyscord/dyscord | refs/heads/master | /dyscord/__init__.py | from .bot import VERSION
from .bot import Dyscord as Bot
| {"/dyscord/bot.py": ["/dyscord/plugin.py", "/dyscord/download.py", "/dyscord/error.py"], "/dyscord/__init__.py": ["/dyscord/bot.py"], "/dyscord/plugin.py": ["/dyscord/error.py", "/dyscord/redis.py", "/dyscord/download.py"], "/run.py": ["/dyscord/__init__.py", "/dyscord/download.py"], "/dyscord/download.py": ["/dyscord/error.py", "/dyscord/plugin_bin/__init__.py"]} |
62,497 | dyscord/dyscord | refs/heads/master | /dyscord/plugin_bin/__init__.py | import os
# Get directory of this module (which is plugin directory):
PLUGIN_DIR = os.path.dirname(os.path.abspath(__file__))
| {"/dyscord/bot.py": ["/dyscord/plugin.py", "/dyscord/download.py", "/dyscord/error.py"], "/dyscord/__init__.py": ["/dyscord/bot.py"], "/dyscord/plugin.py": ["/dyscord/error.py", "/dyscord/redis.py", "/dyscord/download.py"], "/run.py": ["/dyscord/__init__.py", "/dyscord/download.py"], "/dyscord/download.py": ["/dyscord/error.py", "/dyscord/plugin_bin/__init__.py"]} |
62,498 | dyscord/dyscord | refs/heads/master | /dyscord/plugin.py | from discord.ext.commands import Command
from dyscord_plugin.plugin import DyscordPlugin
from typing import Dict
from .error import PluginAlreadyImported
from .redis import RedisStorageManager
from .download import PluginManager
PLUGIN_LIST_BASE = "plugins.{}.plugin_list"
PLUGIN_LIST_FMT = PLUGIN_LIST_BASE + ".{}"
PLUGIN_CFG_FMT = "plugins.{}.plugin_cfgs.{}"
class ServerPluginHandler:
def __init__(self, guild_id, redis, pm: PluginManager):
self.guild_id = guild_id
self.redis = redis
self.plugin_list = RedisStorageManager(self.redis, PLUGIN_LIST_BASE.format(self.guild_id))
self.pm = pm
def add_plugin(self, name):
self.pm.get_plugin(name) # Load plugin or throw if it doesn't exist
if name in self.plugin_list:
raise PluginAlreadyImported
self.plugin_list[name] = True # Add key
async def process_msg(self, msg):
if not msg.guild.id == self.guild_id: # Not part of guild
return
for name in self.plugin_list:
p = self.pm.get_plugin(name)
await p.process_msg(msg, RedisStorageManager(self.redis, PLUGIN_CFG_FMT.format(self.guild_id, name)))
| {"/dyscord/bot.py": ["/dyscord/plugin.py", "/dyscord/download.py", "/dyscord/error.py"], "/dyscord/__init__.py": ["/dyscord/bot.py"], "/dyscord/plugin.py": ["/dyscord/error.py", "/dyscord/redis.py", "/dyscord/download.py"], "/run.py": ["/dyscord/__init__.py", "/dyscord/download.py"], "/dyscord/download.py": ["/dyscord/error.py", "/dyscord/plugin_bin/__init__.py"]} |
62,499 | dyscord/dyscord | refs/heads/master | /run.py | import os
from dyscord import Bot
from dyscord.download import delete_all_plugins
delete_all_plugins() # Delete all cached plugins
b = Bot()
b.run(os.environ["DYSCORD_TOKEN"])
| {"/dyscord/bot.py": ["/dyscord/plugin.py", "/dyscord/download.py", "/dyscord/error.py"], "/dyscord/__init__.py": ["/dyscord/bot.py"], "/dyscord/plugin.py": ["/dyscord/error.py", "/dyscord/redis.py", "/dyscord/download.py"], "/run.py": ["/dyscord/__init__.py", "/dyscord/download.py"], "/dyscord/download.py": ["/dyscord/error.py", "/dyscord/plugin_bin/__init__.py"]} |
62,500 | dyscord/dyscord | refs/heads/master | /dyscord/download.py | import importlib, pkgutil
from urllib import request
import tempfile
import tarfile
import shutil
import json
import os
from typing import List
from discord.ext.commands import Bot
from dyscord_plugin.plugin import DyscordPlugin
from .error import PluginNotFound, PluginExists, PluginMalformedError
from .plugin_bin import PLUGIN_DIR
PLUGIN_PACKAGE_NAME = os.path.basename(PLUGIN_DIR)
print("Loading plugins from: ", PLUGIN_DIR)
BASE_PACKAGE = "dyscord"
DYPI_URL = "https://github.com/dyscord/pi/archive/master.tar.gz"
DYPI_FOLDER = "pi-master/dypi"
DYPI_ENTRY_EXT = ".json"
PLUGIN_INFO_FILE = "dyscord-plugin.json"
PLUGIN_CLASS_NAME = "Plugin"
def collect_plugin_list():
with tempfile.TemporaryDirectory() as td:
download_file = os.path.join(td, "dypi.tar.gz")
request.urlretrieve(DYPI_URL, download_file)
# Open downloaded tarfile:
plugin_tarfile = tarfile.open(download_file, mode='r:gz')
# Extract:
extract_dir = os.path.join(td, "extract") # Set extraction location
plugin_tarfile.extractall(path=extract_dir) # EXTRACT!!!
dypi_dir = os.path.join(extract_dir, DYPI_FOLDER)
pkgs = {}
for p in os.listdir(dypi_dir):
with open(os.path.join(dypi_dir, p), mode='r') as f:
p_info = json.load(f)
pkgs[p[:-len(DYPI_ENTRY_EXT)]] = {"download_link": p_info["download_link"]}
return pkgs
def module_search(p: str) -> List[pkgutil.ModuleInfo]:
return list(pkgutil.iter_modules([p]))
def delete_plugins(*names):
for n in names:
if n == '__init__.py': # Prevent deletion of __init__.py file
continue
del_path = os.path.join(PLUGIN_DIR, n)
if os.path.isdir(del_path): # Is directory
shutil.rmtree(del_path)
else: # Is a file
os.remove(del_path)
def delete_all_plugins():
delete_plugins(*os.listdir(PLUGIN_DIR))
class PluginManager:
def __init__(self, bot: Bot):
self.bot = bot
self.loaded = {}
self.plugin_list = collect_plugin_list()
@property
def downloaded(self): # Get list of downloaded plugin names
return [x.name for x in pkgutil.iter_modules([PLUGIN_DIR])]
def import_plugin(self, name):
try:
plug = importlib.import_module(".{}.{}".format(PLUGIN_PACKAGE_NAME, name), BASE_PACKAGE)
plugin = getattr(plug, PLUGIN_CLASS_NAME)(self.bot)
except:
raise PluginMalformedError
if not isinstance(plugin, DyscordPlugin):
raise AttributeError
self.loaded[name] = plugin
return plugin
def get_plugin_info(self, name):
try:
return self.plugin_list[name]
except KeyError:
raise PluginNotFound
def download_plugin(self, name):
# Create temporary directory for the setup of the plugin:
td = tempfile.TemporaryDirectory()
try:
temp_dir = td.name
plugin_tar_loc = os.path.join(temp_dir, "plugin.tar.gz") # Set download location
# Request plugin info:
plugin_info = self.get_plugin_info(name)
# Download plugin to temporary location:
request.urlretrieve(plugin_info["download_link"], plugin_tar_loc)
# Open downloaded tarfile:
plugin_tarfile = tarfile.open(plugin_tar_loc, mode='r:gz')
plugin_dir_name = plugin_tarfile.getnames()[0] # Get dir name from first member - POTENTIALLY A FUTURE ISSUE
# TODO: FIX THIS DIRECTORY NAME COLLECTION
# Extract:
extract_dir = os.path.join(temp_dir, "plugin") # Set extraction location
plugin_tarfile.extractall(path=extract_dir) # EXTRACT!!!
try:
# Get plugin directory
plugin_dir = os.path.join(extract_dir, plugin_dir_name)
# Open plugin info from extraction
with open(os.path.join(plugin_dir, PLUGIN_INFO_FILE), mode='r') as pf:
plugin_info = json.load(pf)
# Get package name:
package_name = plugin_info["package"]
version = plugin_info["version"]
except FileNotFoundError: # Catch if info file is missing
raise PluginMalformedError
else:
print("Downloading {} ({})".format(name, version))
try:
# Copy tmp plugin package to plugin directory:
shutil.copytree(os.path.join(plugin_dir, package_name), os.path.join(PLUGIN_DIR, name))
except FileExistsError:
raise PluginExists
finally:
# Close temporary directory:
td.cleanup()
def get_plugin(self, name: str):
# Return plugin if already loaded
if name in self.loaded:
return self.loaded[name]
if name not in self.downloaded:
try:
self.download_plugin(name)
except PluginExists: # plugin name was different from actual package
pass
return self.import_plugin(name)
| {"/dyscord/bot.py": ["/dyscord/plugin.py", "/dyscord/download.py", "/dyscord/error.py"], "/dyscord/__init__.py": ["/dyscord/bot.py"], "/dyscord/plugin.py": ["/dyscord/error.py", "/dyscord/redis.py", "/dyscord/download.py"], "/run.py": ["/dyscord/__init__.py", "/dyscord/download.py"], "/dyscord/download.py": ["/dyscord/error.py", "/dyscord/plugin_bin/__init__.py"]} |
62,502 | jing207/cloud189-signer | refs/heads/master | /cloud189-singer.py | #!/usr/bin/env python
import PySimpleGUI as sg
import utils
import checkin
from threading import Thread
import shlex
import config
import webbrowser
def Cloud189SignGUI():
utils.load_setting()
sg.theme(config.DEFAULT_THEME)
layout = [
[sg.Text('Cloud189 Signer', size=(40, 1), font=('Any 15'))],
[sg.T('账号,多个账号用#号分割:', font=config.default_font), sg.Input(default_text=config.username, size=(40, 1), key='username')],
[sg.T('密码,多个密码用#号分割:', font=config.default_font), sg.Input(default_text=config.password, size=(40, 1), key='password')],
[sg.Button('签到', key='Sign')],
[sg.Output(size=(90, 20), font=config.default_font)],
[sg.Button('退出', key='Exit', button_color=('white', 'firebrick3')), sg.Button('源码', key='home_page',button_color=('white', 'springgreen4'))]
]
window = sg.Window('天翼云签到', layout,
text_justification='r',
default_element_size=(15, 1),
font=('Any 14'))
while True:
event, values = window.read()
if event in ('Exit', None):
utils.save_setting()
break # exit button clicked
if event == 'Sign':
window.refresh()
username = values['username']
password = values['password']
err = False
if username == "":
err = True
print("账号不能为空!")
if password == "":
err = True
print("密码不能为空!")
if not err:
user_list = username.split("#")
pass_list = password.split("#")
if len(user_list) != len(pass_list):
print("账号和密码个数不对应!")
else:
config.username = username
config.password = password
print('开始签到....')
try:
for i in range(len(user_list)):
str_paras = utils.to_command_paras(user_list[i], pass_list[i])
thread_download = Thread(target=checkin.main, args=[
shlex.split(str_paras)])
thread_download.start()
except Exception as e:
print(e)
elif event == 'home_page':
webbrowser.open_new('https://github.com/xiaogouxo/cloud189-signer')
window.close()
if __name__ == '__main__':
Cloud189SignGUI() | {"/cloud189-singer.py": ["/utils.py", "/config.py"], "/utils.py": ["/config.py"]} |
62,503 | jing207/cloud189-signer | refs/heads/master | /utils.py | import config, os, json
def locate_setting_folder():
"""check local folder and global setting folder for setting.cfg file"""
# look for previous setting file
try:
if 'setting.cfg' in os.listdir(config.current_directory):
return config.current_directory
except:
pass
# no setting file found will check local folder for writing permission, otherwise will return global sett folder
try:
folder = config.current_directory
with open(os.path.join(folder, 'test'), 'w') as test_file:
test_file.write('0')
os.unlink(os.path.join(folder, 'test'))
return config.current_directory
except PermissionError:
log("No enough permission to store setting at local folder:", folder)
config.sett_folder = locate_setting_folder()
def to_command_paras(username, password):
str_paras = ""
str_paras += ' -u ' + username
str_paras += ' -p ' + password
return str_paras
def load_setting():
settings = {}
try:
log('Load Application setting from', config.sett_folder)
file = os.path.join(config.sett_folder, 'setting.cfg')
with open(file, 'r') as f:
settings = json.load(f)
except FileNotFoundError:
log('setting.cfg not found')
except Exception as e:
handle_exceptions(e)
finally:
if not isinstance(settings, dict):
settings = {}
# update config module
config.__dict__.update(settings)
def save_setting():
settings = {key: config.__dict__.get(key) for key in config.settings_keys}
try:
file = os.path.join(config.sett_folder, 'setting.cfg')
with open(file, 'w') as f:
json.dump(settings, f)
log('setting saved')
except Exception as e:
log('save_setting() > error', e)
def handle_exceptions(error):
if config.TEST_MODE:
raise error
else:
log(error)
def log(*args, start='>> ', end='\n', sep=' '):
"""
print messages to stdout and log widget in main menu thru main window queue
:param args: comma separated messages to be printed
:param start: prefix appended to start of string
:param end: tail of string
:param sep: separator used to join text "args"
:return:
"""
text = ''
for arg in args:
text += str(arg)
text += sep
text = text[:-1] # remove last space, or sep
text = start + text
print(text, end=end)
| {"/cloud189-singer.py": ["/utils.py", "/config.py"], "/utils.py": ["/config.py"]} |
62,504 | jing207/cloud189-signer | refs/heads/master | /config.py | import os
import platform
import sys
TEST_MODE = False
DEFAULT_THEME = 'DarkGrey2'
default_font = 'Helvetica 12'
sett_folder = None
operating_system = platform.system()
settings_keys = ['username', 'password', 'DEFAULT_THEME']
username = ''
password = ''
# folders
if hasattr(sys, 'frozen'): # like if application froen by cx_freeze
current_directory = os.path.dirname(sys.executable)
else:
path = os.path.realpath(os.path.abspath(__file__))
current_directory = os.path.dirname(path)
sys.path.insert(0, os.path.dirname(current_directory))
sys.path.insert(0, current_directory)
| {"/cloud189-singer.py": ["/utils.py", "/config.py"], "/utils.py": ["/config.py"]} |
62,590 | aidasgit/staff_managment_demo_app | refs/heads/main | /employee.py | class Employee:
"""Employee class"""
def __init__(self, em_no, f_name, l_name, email="", salary=0, bonus=0):
"""employee class constructor if no email provided it generates unic email"""
self.f_name = f_name
self.l_name = l_name
self.salary = salary
self.em_no = em_no
self.email = email
self.bonus = bonus
if not self.email:
self.generate_unic_email()
def __str__(self):
"""overrides default __str__ to be useful output function"""
return "{}, {}, {}, {}, {:0.2f}".format(self.em_no, self.f_name, self.l_name, self.email, self.salary)
def generate_unic_email(self):
"""Generates unic email"""
self.email = self.f_name + "." + self.l_name + "." + self.em_no + "@cit.ie"
| {"/Aidas.Karpavicius.employee.py": ["/employee.py"]} |
62,591 | aidasgit/staff_managment_demo_app | refs/heads/main | /Aidas.Karpavicius.employee.py | # student name: Aidas Karpavicius
# student no: R00171054
# Program description
# Employee managing system, that uses file "employees.txt" for storing all data.
from employee import Employee # Employee class
import sys, datetime # sys library for proper exit in case "employees.txt" wrong format
# datetime library to get current year for bonus file name
DATA_FILE = "employees.txt" # file name in which all data is stored
emp_data = [] # list of all employees
# menu_str - menu string
menu_str = '''
1. View all employees.
2. Find employee.
3. Edit the salary of an employee.
4. Add a new employee.
5. Delete an employee.
6. Give a bonus to each employee.
7. Generate a report.
8. Save and quit.
Choice: '''
def clear_screen():
"""Clears screen"""
print("\n" * 60)
def load_data():
"""load data() loads employee list from "employees.txt"
if file not formatted by convention "id, name, surname, email, salary"
function detects file as corrupted and asks weather to overwrite it,
also if "employees.txt not found one will be created"""
# tries to read a file, if "employees.txt" doesnt exist
# creates one
try:
file_Handle = open(DATA_FILE, "r")
except FileNotFoundError:
input(DATA_FILE + " not found, press enter to create a file... ")
file_Handle = open(DATA_FILE, "w")
file_Handle.close()
return # if file not found exits here
# try block read file if its proper format
# if it's not formatted properly askes user should it
# be overwritten
try:
for entry in file_Handle:
if entry:
employee = [value.strip() for value in
entry.split(",")] # splits every line in file and stores it in []
# creates Employee object and appends it to emp_data
emp_data.append(Employee(employee[0], employee[1], employee[2], employee[3], float(employee[4])))
except IndexError:
print(DATA_FILE + " appears to be corrupted...")
# inp just if there's any value in it it will exit program preventing "employees.txt" deletion
inp = input("Press enter to continue (current database will be overwritten) or \"N\" to cancel: ")
if inp:
sys.exit()
finally:
file_Handle.close() # closes file and exits here if data was red in "employees.txt"
def show_menu():
""""show_menu()" - displays menu in a loop, reads users input
and calls appropriate function to users input"""
while True:
clear_screen()
usr_inp = getInt(menu_str, 1) # gets user input
# if block - calls appropriate function depending on user input
if usr_inp == "1":
clear_screen()
show_employees()
input("Press enter to continue ... ")
elif usr_inp == "2":
clear_screen()
show_employees(getInt("Please enter employees ID number ( 5 digits ): ", 5))
input("Press enter to continue ... ")
elif usr_inp == "3":
clear_screen()
change_salary(getInt("Please enter employees ID number ( 5 digits ): ", 5))
input("Press enter to continue ... ")
elif usr_inp == "4":
clear_screen()
add_employee()
input("Press enter to continue ... ")
elif usr_inp == "5":
clear_screen()
remove_employee(getInt("Please enter employees ID number ( 5 digits ): ", 5))
input("Press enter to continue ... ")
elif usr_inp == "6":
clear_screen()
generate_bonus_info()
input("Press enter to continue ... ")
elif usr_inp == "7":
clear_screen()
generate_reports()
input("Press enter to continue ... ")
elif usr_inp == "8":
clear_screen()
break
else:
input("Valid choice is (1-9). Press enter to continue")
def save_data():
""""save_data()" saves all changes made to employee database and saves it
to "employees.txt" file"""
file_handle = open(DATA_FILE, "w")
for employee in emp_data:
print(employee, file=file_handle)
print("Data saved")
file_handle.close()
def show_employees(id=""):
"""Prints one or all employees in emp_data[]"""
output = [] # list that will be outputted to STD
if id: # if employee id was provided in parameter list
if find_employee(id):
output.append(find_employee(id)) # adds that employee to output
else: # in case employee not found exit function
print("Employee not found")
return
else:
output = emp_data # else all employees added
# table formatting
table_l = longest("f_name") + longest("l_name") + longest("email") + 24 # overall width of the table
print("Employee Data") # title
print(" "+"_" * table_l) # top border
# t_str string contains proper formatting for the table
t_str = "|{}|{:>" + str(longest("f_name")) + "}|{:>" + str(longest("l_name")) + "}|{:>" + str(
longest("email")) + "}|{:>15}|"
# prints table attributes
print(t_str.format("Em_No", "First Name", "Last Name", "Email", "Anual Salary"))
# prints extra line under table attributes visual purposes only
print(t_str.format("_" * 5, "_" * longest("f_name"), "_" * longest("l_name"), "_" * longest("email"), "_" * 15))
# for loop outputs employee data from output[] to the table
for employee in output:
tmp = [value.strip() for value in str(employee).split(",")]
print(t_str.format(tmp[0], tmp[1], tmp[2], tmp[3], tmp[4]))
# bottom border
print(t_str.format("_" * 5, "_" * longest("f_name"), "_" * longest("l_name"), "_" * longest("email"), "_" * 15))
def longest(emp_var):
"""longest check emp_data for longest values of individual employee
for table formatting purposes only"""
padding = 4 # adds extra padding to length of the employees field
if emp_data:
if emp_var == "f_name":
length = max(len(employee.f_name) for employee in emp_data) + padding
elif emp_var == "l_name":
length = max(len(employee.l_name) for employee in emp_data) + padding
elif emp_var == "email":
length = max(len(employee.email) for employee in emp_data) + padding
else:
return 15 # in case no data in the table
return length if length > 10 else 10 # condition in case very short value fro proper table formatting
def find_employee(id):
"""Returns pointer to employee object in a emp_data[] or None"""
for employee in emp_data:
if employee.em_no == id:
return employee
return None
def getPositiveFloat(prompt, max=0):
"""Gets input from user to get valid float max value optional"""
while True:
try: # tries to convert input
p_float = float(input(prompt))
# if successful checks for bounds
if p_float >= 0 and (p_float <= max or max == 0):
return p_float # returns input if more then 0 and under max or max was not set
# for negative value or over max and if max was set continues to next cycle
elif p_float < 0 or p_float > max and max != 0:
print("Input must be a positive number of range ( 0 - ", end="")
print(str(max) + " )" if max != 0 else "unlimited" + " )") # formats string to accommodate possibility
# max=0
continue
except ValueError:
print("Input must be digits only...")
def change_salary(id=""):
"""Changes salary of employee"""
emp = find_employee(id) # finds employee
if emp:
print("Employee found:\n", emp) # Displays employee found
emp.salary = getPositiveFloat("Please enter new salary : ") # Sets new salary
else:
print("Employee not found...") # In case employee not found
def add_employee():
"""Adds new employee"""
# Creates new employee object and adds it to the list em_data
# Unic email generation in employee.py if email = ""
emp_data.append(Employee(
gen_id(),
getString("Please enter employee's first name: ", 3, 15),
getString("Please enter employee's surname: ", 3, 25),
"", getPositiveFloat("Starting salary: ")
))
def remove_employee(id):
"""Removes one employee from emp_data[]"""
t_emp = find_employee(id) # Finds employee
if t_emp: # Tests if employee found
print("Employee found:\n", t_emp) # Prints employee found
# Verifies if you still want to delete that employee
sure = input("Delete this employee? (Y/N): ")
if sure and sure.lower()[0] == "y": # just 1st letter of sure variable matters any other value does nothing
# to the emp_data
emp_data.remove(t_emp)
print("Employee deleted...")
else:
print("Process canceled")
else:
print("Employee not found...") # in case employee not found
def generate_reports():
"""Generating Report"""
print("Report") # Title
print("=" * 50)
try: # try block to catch division by zero
print("Yearly salary average - {:0.2f} euro\n".format(
sum(emp.salary for emp in emp_data) / len(emp_data))) # gets sum of employee salary and divides by amount
highest = "" # highest salary output string
h_salary = 0 # highest salary
for emp in emp_data: # cycle trough all employees
if h_salary < emp.salary: # if emp salary highest seen so far
# sets h_salary to new high
h_salary = emp.salary
# adds that employee data to highest properly formatted also deletes previous value if any
highest = "\t{:<10} {:<15} - {:<10.2f} euro\n".format(emp.f_name, emp.l_name, emp.salary)
elif h_salary == emp.salary: # in case one more employee has same salary as the highest one so far
# adds one more employee to highest
highest += "\t{:<10} {:<15} - {:<10.2f} euro\n".format(emp.f_name, emp.l_name, emp.salary)
# One liner if for singular or multiple highest earners
print("Highest earner:" if len(highest.split('\n')) == 2 else "Highest earners:")
print(highest) # outputs highest
except ZeroDivisionError:
print("No data found in employee database...")
def generate_bonus_info():
"""Requests bonus % for each employ in a list
modifies ."""
if emp_data: # Checks if there is any data in emp_data
# Creates file name string "bonus" and adds current year since its yearly bonus
file_name = "bonus" + str(datetime.datetime.now().year)+".txt"
bonus_file = open(file_name, "w") # Opens file "bonusYYYY.txt"
print("\t\tBonus year - " + str(datetime.datetime.now().year)+"\n", file=bonus_file) # Title in a file
# Prints attributes to file of data that will be displayed in "bonusYYYY.txt"
print("{:5} {:>15} {:>20} {:>20}".format("Em No", "First Name", "Last name", "Annual bonus"),
file=bonus_file)
# Cycle trough all employees
for employee in emp_data:
clear_screen()
# Gets float value up 100 to each employee in emp_data[] and saves it in each object bonus field
employee.bonus = getPositiveFloat(
"Please enter bonus procentage (1 - 100%) for \nEmployee no: " + " " + employee.em_no +
"\nEmployee name: " + employee.f_name + " " + employee.l_name + " " + \
"\n>>> ", 100)
# Properly formats output to file and converts % bonus to yearly earnings.
print("{:5} {:>15} {:>20} {:>15.2f} euro".format(employee.em_no, employee.f_name,
employee.l_name, employee.bonus / 100 * employee.salary),
file=bonus_file)
bonus_file.close()
print(file_name + " file created...") # Confirms that file with output was created
else:
print("No data found in employee database ...")
def gen_id():
"""Generates unic id and returns as a string"""
t_id = 10000 # Sets temporary id to 10000
while True: # loops until unic id was found
if str(t_id) not in (employee.em_no for employee in emp_data): # check if this id used already returns it
# if not
return str(t_id)
t_id += 1 # otherwise increases it by 1
def getInt(prompt, max):
"""This function gets valid int from STI, also max value is to make sure its certain length
for example max = 1 then (0-9); max = 2 (10-99);
Also int value is handled and return as a string, because it won't ever be used as a number.
This way preventing redundant type conversions"""
num = input(prompt) # Gets input from STI
while not (num.isdigit() and len(num) == max): # Loops until input is digit only of length = max
clear_screen()
print(prompt)
# Input string has one liner if statement to accommodate menu choice
num = input("Input must be (1-8) digit: " if max == 1 else "Input must be " + str(max) + " digits: ")
clear_screen()
return num # returns int as a string
def getString(prompt, min, max):
"""Gets string in bounds min max inclusive from STI and makes sure its only letters
with one exception allowing one occurrence of "'" """
t_str = input(prompt)
# while loop until valid input received valid surname check and bound check
while not (checkValidSurname(t_str) and len(t_str) >= min and len(t_str) <= max):
t_str = input("Input must contain letters only and it's range has to be between ( " +
str(min) + " - " + str(max) + " )")
return t_str
def checkValidSurname(surname):
"""This function checks if its valid surname containing "'" """
if "'" in surname and len(surname.split("'")) == 2: # if surname has "'" in it and only 1 occurrence of it.
for part in surname.split("'"): # cycle through parts of surname
if part.isalpha(): # if part is letters only continues
continue
else:
return False # if any of the parts contains not characters returns false
elif surname.isalpha(): # In case there was "'" none in a surname returns true
return True
else:
return False # for any other wrong value
return True # and true if there was two parts of surname between "'" all letters.
# main function
def main():
"""---Main ---"""
# Loads data from file
load_data()
# show_menu() main program loop
show_menu()
# saves data
save_data()
# main function call
main()
| {"/Aidas.Karpavicius.employee.py": ["/employee.py"]} |
62,598 | fernandomorales2003/entrechat | refs/heads/master | /principal/views.py | from principal.models import Indumentaria, Calzado
#from principal.forms import ContactForm
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.core.mail import EmailMessage
def inicio(request):
Indumentarias = Indumentaria.objects.all()
Calzados = Calzado.objects.all()
return render_to_response('inicio.html',{'Indumentarias':Indumentarias,'Calzados':Calzados})
def indumentarias (request):
Indumentarias = Indumentaria.objects.all()
return render_to_response('indumentaria.html',{'Indumentarias':Indumentarias})
def calzados(request):
Calzados = Calzado.objects.all()
return render_to_response('calzado.html',{'Calzados':Calzados})
#def Contacto(request):
# if request.method == 'POST'L
# formulario = ContactForm(request.POST)
# if formulario.is.valid():
# titulo = 'Mensaje desde WEB ENTRECHAT'
# contenido = formulario.cleaned_data['mensaje'] + "\n"
# contenido += 'Comunicarse a: ' + formulario.cleaned_data['correo']
# correo = EmailMessage(titulo,contenido,to = [entrechat.2013@gmail])
# correo.send()
# return HttpResponseRedirect('/')
# else:
# formulario = ContactoForm()
# return render_to_response('contactoform.html',{'formulario':formulario},context_instance=RequestContext(request)
| {"/principal/views.py": ["/principal/models.py"], "/principal/admin.py": ["/principal/models.py"]} |
62,599 | fernandomorales2003/entrechat | refs/heads/master | /principal/admin.py | from principal.models import Indumentaria, Calzado
from django.contrib import admin
admin.site.register(Indumentaria)
admin.site.register(Calzado) | {"/principal/views.py": ["/principal/models.py"], "/principal/admin.py": ["/principal/models.py"]} |
62,600 | fernandomorales2003/entrechat | refs/heads/master | /principal/models.py | #encoding:utf-8
from django.db import models
from django.contrib.auth.models import User
class Indumentaria(models.Model):
titulo = models.CharField(max_length=100, unique=True)
color = models.CharField(max_length=100, unique=False)
descripcion = models.TextField(help_text='descripcion')
imagen = models.ImageField(upload_to='indumentaria', verbose_name='Imagen')
tiempo_registro = models.DateTimeField(auto_now=True)
usuario = models.ForeignKey(User)
def __unicode__(self):
return self.titulo
class Calzado(models.Model):
titulo = models.CharField(max_length=100, unique=True)
color = models.CharField(max_length=100, unique=False)
descripcion = models.TextField(help_text='descripcion')
imagen = models.ImageField(upload_to='calzado', verbose_name='Imagen')
tiempo_registro = models.DateTimeField(auto_now=True)
usuario = models.ForeignKey(User)
def __unicode__(self):
return self.titulo
#class ContacForm(forms.Form):
# correo =forms.EmailField(label='entrechat.2013@gmail.com')
# mensaje = forms.CharField(widget=forms.Textarea) | {"/principal/views.py": ["/principal/models.py"], "/principal/admin.py": ["/principal/models.py"]} |
62,601 | manishsilwal03/1st-sem-billing-project | refs/heads/master | /billing_software.py | from tkinter import *
import math, random
import os
from tkinter import messagebox
class Billing:
def __init__(self, manish):
self.manish = manish
self.manish.title("Billing Software")
self.manish.geometry("1355x710+50+30")
self.manish.resizable(False, False)
background ="red"
title1 = Label(self.manish, text="Welcome To Manish Retail Billing", bd= 12, relief= GROOVE,font=("Arial", 30, "bold"),fg="white", bg=background)
title1.place(x=3,relwidth=1)
# creating variables call ==========================================================
self.name = StringVar()
self.phone = StringVar()
self.bill = StringVar()
m = random.randint(1000,9999)
self.bill.set(str(m))
self.search = StringVar()
self.soup = IntVar()
self.cream = IntVar()
self.wash = IntVar()
self.spray = IntVar()
self.gell = IntVar()
self.lotion = IntVar()
self.rice = IntVar()
self.oil = IntVar()
self.daal = IntVar()
self.wheat = IntVar()
self.sugar = IntVar()
self.tea = IntVar()
self.coke = IntVar()
self.slice = IntVar()
self.sprite = IntVar()
self.frooti= IntVar()
self.maza= IntVar()
self.litchi= IntVar()
self.cosmetic = StringVar()
self.grocery= StringVar()
self.drinks = StringVar()
self.cosmetic_tax = StringVar()
self.grocery_tax = StringVar()
self.drinks_tax = StringVar()
# =================================================================*======================================
f1 = LabelFrame(self.manish, text="Customer details", bd=7, relief= GROOVE, font=("Arial", 15, "bold"),fg="yellow", bg=background)
f1.place(x=3, y=80,relwidth=1)
c_name = Label(f1, text= "Customer Name", font=("Arial", 15, "bold",),bg= background, fg= "white")
c_name.grid(row=0, column=0, padx=20, pady=2)
e_name = Entry(f1, width= 16, textvariable=self.name, font=("Arial",14), bd=7, relief= RAISED).grid(row=0, column=1, padx= 10, pady=5)
c_phone = Label(f1, text="Phone No.", font=("Arial", 15, "bold",), bg=background, fg="white")
c_phone.grid(row=0, column=2, padx=20, pady=2)
e_phone = Entry(f1, width=16, textvariable=self.phone, font=("Arial", 14), bd=7, relief=RAISED).grid(row=0, column=3, padx=10, pady=5)
c_bill = Label(f1, text="Bill Number", font=("Arial", 15, "bold",), bg=background, fg="white")
c_bill.grid(row=0, column=4, padx=20, pady=2)
e_bill = Entry(f1, width=16, textvariable=self.search, font=("Arial", 14), bd=7, relief=RAISED).grid(row=0, column=5, padx=10, pady=5)
btn_bill = Button(f1, text="Search", command= self.search_bill, font=("Arial", 10,"bold"),cursor= "hand2", width= 10, bd=7)
btn_bill.grid(row=0, column= 6, padx=15, pady=8)
# ============================================================================================================
f2 = LabelFrame(self.manish, text="Cosmetics", bd=9, relief=GROOVE, font=("Arial", 15, "bold"), fg="yellow", bg=background)
f2.place(x=3, y=170, width= 325, height= 345)
name_soup = Label(f2, text= "Soup",font=("Arial", 15, "bold"), bg=background, fg="white")
name_soup.grid(row=0, column= 0, padx= 10, pady= 10, sticky= "w")
entry_soup = Entry(f2, width= 15, textvariable=self.soup,font=("Arial", 12, "bold"),bd= 4, relief= SUNKEN).grid(row=0, column=1, padx=10, pady=10)
name_cream = Label(f2, text="Face Cream", font=("Arial", 15, "bold"), bg=background, fg="white")
name_cream.grid(row=1, column=0, padx=10, pady=10, sticky="w")
entry_cream = Entry(f2, width=15, textvariable=self.cream, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=1, column=1, padx=10, pady=10)
name_wash = Label(f2, text="Face Wash", font=("Arial", 15, "bold"), bg=background, fg="white")
name_wash.grid(row=2, column=0, padx=10, pady=10, sticky="w")
entry_wash = Entry(f2, width=15, textvariable=self.wash, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=2, column=1, padx=10, pady=10)
name_spray = Label(f2, text="Hair Spray", font=("Arial", 15, "bold"), bg=background, fg="white")
name_spray.grid(row=3, column=0, padx=10, pady=10, sticky="w")
e_spray = Entry(f2, width=15, textvariable=self.spray, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=3, column=1, padx=10, pady=10)
name_gell = Label(f2, text="Hair Gell", font=("Arial", 15, "bold"), bg=background, fg="white")
name_gell.grid(row=4, column=0, padx=10, pady=10, sticky="w")
e_gell = Entry(f2, width=15, textvariable=self.gell, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=4, column=1, padx=10, pady=10)
name_lotion = Label(f2, text="Body lotion", font=("Arial", 15, "bold"), bg=background, fg="white")
name_lotion.grid(row=5, column=0, padx=10, pady=10, sticky="w")
entry_lotion = Entry(f2, width=15, textvariable=self.lotion, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=5, column=1, padx=10, pady=10)
# ============================================================================================================
f3 = LabelFrame(self.manish, text="Grocery", bd=9, relief=GROOVE, font=("Arial", 15, "bold"), fg="yellow", bg=background)
f3.place(x=333, y=170, width=325, height=345)
name_rice = Label(f3, text="Rice", font=("Arial", 15, "bold"), bg=background, fg="white")
name_rice.grid(row=0, column=0, padx=10, pady=10, sticky="w")
entry_soup = Entry(f3, width=15, textvariable=self.rice, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=0, column=1, padx=10, pady=10)
name_oil = Label(f3, text="Oil", font=("Arial", 15, "bold"), bg=background, fg="white")
name_oil.grid(row=1, column=0, padx=10, pady=10, sticky="w")
entry_oil = Entry(f3, width=15, textvariable=self.oil, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=1, column=1, padx=10, pady=10)
name_daal = Label(f3, text="Daal", font=("Arial", 15, "bold"), bg=background, fg="white")
name_daal.grid(row=2, column=0, padx=10, pady=10, sticky="w")
entry_daal = Entry(f3, width=15, textvariable=self.daal, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=2, column=1, padx=10, pady=10)
name_wheat = Label(f3, text="Wheat", font=("Arial", 15, "bold"), bg=background, fg="white")
name_wheat.grid(row=3, column=0, padx=10, pady=10, sticky="w")
e_wheat = Entry(f3, width=15, textvariable=self.wheat, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=3, column=1, padx=10, pady=10)
name_sugar = Label(f3, text="Sugar", font=("Arial", 15, "bold"), bg=background, fg="white")
name_sugar.grid(row=4, column=0, padx=10, pady=10, sticky="w")
e_sugar = Entry(f3, width=15, textvariable=self.sugar, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=4, column=1, padx=10, pady=10)
name_tea = Label(f3, text="Tea", font=("Arial", 15, "bold"), bg=background, fg="white")
name_tea.grid(row=5, column=0, padx=10, pady=10, sticky="w")
entry_tea = Entry(f3, width=15, textvariable=self.tea, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=5, column=1, padx=10, pady=10)
# ============================================================================================================
f4 = LabelFrame(self.manish, text="Cold Drinks", bd=9, relief=GROOVE, font=("Arial", 15, "bold"), fg="yellow", bg=background)
f4.place(x=663, y=170, width=325, height=345)
name_coke = Label(f4, text="Coke", font=("Arial", 15, "bold"), bg=background, fg="white")
name_coke.grid(row=0, column=0, padx=10, pady=10, sticky="w")
entry_coke = Entry(f4, width=15, textvariable=self.coke, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=0, column=1, padx=10, pady=10)
name_slice = Label(f4, text="Slice", font=("Arial", 15, "bold"), bg=background, fg="white")
name_slice.grid(row=1, column=0, padx=10, pady=10, sticky="w")
entry_slice = Entry(f4, width=15, textvariable=self.slice, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=1, column=1, padx=10, pady=10)
name_sprite = Label(f4, text="Sprite", font=("Arial", 15, "bold"), bg=background, fg="white")
name_sprite.grid(row=2, column=0, padx=10, pady=10, sticky="w")
entry_sprite = Entry(f4, width=15, textvariable=self.sprite, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=2, column=1, padx=10, pady=10)
name_frooti = Label(f4, text="Frooti", font=("Arial", 15, "bold"), bg=background, fg="white")
name_frooti.grid(row=3, column=0, padx=10, pady=10, sticky="w")
e_frooti = Entry(f4, width=15, textvariable=self.frooti, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=3, column=1, padx=10, pady=10)
name_maza = Label(f4, text="Maza", font=("Arial", 15, "bold"), bg=background, fg="white")
name_maza.grid(row=4, column=0, padx=10, pady=10, sticky="w")
entry_maza = Entry(f4, width=15, textvariable=self.maza, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=4, column=1, padx=10, pady=10)
name_litchi = Label(f4, text="Lichi", font=("Arial", 15, "bold"), bg=background, fg="white")
name_litchi.grid(row=5, column=0, padx=10, pady=10, sticky="w")
entry_litchi = Entry(f4, width=15, textvariable=self.litchi, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=5, column=1, padx=10,pady=10)
# ===========================bill voucher======================================================================
f5 = LabelFrame(self.manish, bd=9, relief=GROOVE,)
f5.place(x=1000, y=170, width=345, height=345)
title2 = Label(f5, text="Bill Voucher", bd=12, relief=GROOVE, font=("Arial", 15, "bold"))
title2.pack(fill= X)
scroll_bill = Scrollbar(f5,orient = VERTICAL)
self.txtarea = Text(f5, yscrollcommand= scroll_bill.set)
scroll_bill.pack(side= RIGHT, fill=Y)
scroll_bill.configure(command= self.txtarea.yview)
self.txtarea.pack(fill= BOTH, expand= 1)
f6 = LabelFrame(self.manish, text="Bill Menu", bd=8, relief=GROOVE, font=("Arial", 15, "bold"), fg="yellow", bg=background)
f6.place(x=3, y=520, relwidth=1, height= 180)
a1_label= Label(f6, text= "Total Cosmetics Price", font=("Arial", 15, "bold"),bg= background,fg="white").grid(row=0,column=0,padx=20,pady=1,sticky="w")
a1_entry= Entry(f6, width=18, textvariable=self.cosmetic, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=0, column=1, padx=10, pady=1)
a2_label = Label(f6, text="Total Grocery Price", font=("Arial", 15, "bold"), bg=background, fg="white").grid(row=1, column=0, padx=20, pady=1, sticky="w")
a2_entry = Entry(f6, width=18, textvariable=self.grocery, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=1, column=1, padx=10, pady=1)
a3_label = Label(f6, text="Total Cold Drinks Price", font=("Arial", 15, "bold"), bg=background, fg="white").grid(row=2, column=0, padx=20, pady=1, sticky="w")
a3_entry = Entry(f6, width=18, textvariable=self.drinks, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=2, column=1, padx=10, pady=1)
b1_label = Label(f6, text="Cosmetics Tax", font=("Arial", 15, "bold"), bg=background, fg="white").grid(row=0, column=2, padx=20, pady=1, sticky="w")
b1_entry = Entry(f6, width=18, textvariable=self.cosmetic_tax, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=0, column=3, padx=10,pady=1)
b2_label = Label(f6, text="Grocery Tax", font=("Arial", 15, "bold"), bg=background, fg="white").grid(row=1, column=2, padx=20, pady=1, sticky="w")
b2_entry = Entry(f6, width=18, textvariable=self.grocery_tax, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=1, column=3, padx=10,pady=1)
b3_label = Label(f6, text="Cold Drinks Tax", font=("Arial", 15, "bold"), bg=background,fg="white").grid(row=2, column=2, padx=20, pady=1, sticky="w")
b3_entry = Entry(f6, width=18, textvariable=self.drinks_tax, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=2, column=3, padx=10 ,pady=1)
fin_frame = Frame(f6, bd=10, relief=GROOVE, )
fin_frame.place(x=780, y=3, width=560, height=90)
total_button = Button(fin_frame,text= "Total", command=self.total, bg = "maroon", fg= "white", bd= 5, pady= 5,font=("Arial", 15,"bold"), width=9).grid(row=0, column=0, padx=5, pady= 5)
total_button = Button(fin_frame,text= "Print Bill", command= self.bill_print, bg = "maroon", fg= "white", bd= 5, pady= 5,font=("Arial", 15,"bold"), width=9).grid(row=0, column=1, padx=5, pady= 5)
total_button = Button(fin_frame,text= "Clear", command=self.clear_function, bg = "maroon", fg= "white", bd= 5, pady= 5,font=("Arial", 15,"bold"), width=9).grid(row=0, column=2, padx=5, pady= 5)
total_button = Button(fin_frame,text= "Exit",command=self.exit_system, bg = "maroon", fg= "white", bd= 5, pady= 5,font=("Arial", 15,"bold"), width=9).grid(row=0, column=3, padx=5, pady= 5)
info = Label(f6, text="If you have any query, please kindly mail me on lawlishsinam03@gmail.com. Thank You!!",
bd=8, relief=GROOVE, font=("Arial", 15, "bold"), fg="yellow", bg=background)
info.place(y=105, relwidth=1)
self.bill_top() # to print always, we called inside init function.
def total(self):
self.c_s_p = (self.soup.get()* 30)
self.c_c_p = (self.cream.get()* 120)
self.c_w_p = (self.wash.get()* 50)
self.c_sp_p = (self.spray.get()* 200)
self.c_g_p = (self.gell.get()* 120)
self.c_l_p = (self.lotion.get()* 160)
self.total_cosmetic = float (self.c_s_p +
self.c_c_p+
self.c_w_p+
self.c_sp_p+
self.c_g_p +
self.c_l_p)
self.cosmetic.set("Rs. " + str(self.total_cosmetic))
self.c_tax = round((self.total_cosmetic*0.05),2)
self.cosmetic_tax.set("Rs. " + str(self.c_tax))
self.g_r_p = (self.rice.get() * 75)
self.g_o_p = (self.oil.get() * 180)
self.g_d_p = (self.daal.get() * 60)
self.g_w_p = (self.wheat.get() * 240)
self.g_s_p = (self.sugar.get() * 75)
self.g_t_p = (self.tea.get() * 150)
self.total_grocery = float (self.g_r_p +
self.g_o_p+
self.g_d_p+
self.g_w_p+
self.g_s_p+
self.g_t_p)
self.grocery.set("Rs. " + str(self.total_grocery))
self.g_tax = round((self.total_grocery * 0.05),2)
self.grocery_tax.set("Rs. " + str(self.g_tax))
self.d_c_p = (self.coke.get() * 45)
self.d_s_p = (self.slice.get() * 50)
self.d_sp_p = (self.sprite.get() * 45)
self.d_f_p = (self.frooti.get() * 25)
self.d_m_p = (self.maza.get() * 60)
self.d_l_p = (self.litchi.get() * 35)
self.total_drinks = float (self.d_c_p +
self.d_s_p+
self.d_sp_p+
self.d_f_p+
self.d_m_p+
self.d_l_p)
self.drinks.set("Rs. " + str(self.total_drinks))
self.d_tax = round((self.total_drinks*0.05),2) # this is done for generating total bill in bill print.
self.drinks_tax.set("Rs. "+ str(self.d_tax))
self.total_bill_amount = float( self.total_cosmetic +
self.total_grocery +
self.total_drinks +
self.c_tax+
self. g_tax +
self.d_tax)
def bill_top(self):
self.txtarea.delete("1.0", END)
self.txtarea.insert(END, "\tWelcome to Manish Retails\n")
self.txtarea.insert(END, f"\nBill Number :{self.bill.get()} ")
self.txtarea.insert(END, f"\nCustomer Name :{self.name.get()} ")
self.txtarea.insert(END, f"\nPhone Number : {self.phone.get()}")
self.txtarea.insert(END, f"\n======================================")
self.txtarea.insert(END, f"\nProduct\t\tQuantity\t\tPrice")
self.txtarea.insert(END, f"\n======================================")
def bill_print(self):
if self.name.get() =="" or self.phone.get() =="":
messagebox.showerror("Error","Fill up Customer details")
elif self.cosmetic.get()=="Rs. 0.0" and self.grocery.get()=="Rs. 0.0" and self.drinks.get()=="Rs. 0.0":
messagebox.showerror("Error","Nothing is purchased.")
else:
# ************************** c ****************************************************************************
self.bill_top()
if self.soup.get()!=0:
self.txtarea.insert(END, f"\nSoap\t\t{self.soup.get()}\t\t{self.c_s_p}")
if self.cream.get()!=0:
self.txtarea.insert(END, f"\nFace Cream\t\t{self.cream.get()}\t\t{self.c_c_p}")
if self.wash.get()!=0:
self.txtarea.insert(END, f"\nFace Wash\t\t{self.wash.get()}\t\t{self.c_w_p}")
if self.spray.get()!=0:
self.txtarea.insert(END, f"\nHair Spray\t\t{self.spray.get()}\t\t{self.c_sp_p}")
if self.gell.get()!=0:
self.txtarea.insert(END, f"\nHair Gell\t\t{self.gell.get()}\t\t{self.c_g_p}")
if self.lotion.get()!=0:
self.txtarea.insert(END, f"\nBody Lotion \t\t{self.lotion.get()}\t\t{self.c_l_p}")
# ************************** c ****************************************************************************
if self.rice.get() != 0:
self.txtarea.insert(END, f"\nRice\t\t{self.rice.get()}\t\t{self.g_r_p}")
if self.oil.get() != 0:
self.txtarea.insert(END, f"\nOil\t\t{self.oil.get()}\t\t{self.g_o_p}")
if self.daal.get() != 0:
self.txtarea.insert(END, f"\nDaal\t\t{self.daal.get()}\t\t{self.g_d_p}")
if self.wheat.get() != 0:
self.txtarea.insert(END, f"\nWheat\t\t{self.wheat.get()}\t\t{self.g_w_p}")
if self.sugar.get() != 0:
self.txtarea.insert(END, f"\nSugar\t\t{self.sugar.get()}\t\t{self.g_s_p}")
if self.tea.get() != 0:
self.txtarea.insert(END, f"\nTea\t\t{self.tea.get()}\t\t{self.g_t_p}")
# ************************** c ****************************************************************************
if self.coke.get() != 0:
self.txtarea.insert(END, f"\nCoke\t\t{self.coke.get()}\t\t{self.d_c_p}")
if self.slice.get() != 0:
self.txtarea.insert(END, f"\nSlice\t\t{self.slice.get()}\t\t{self.d_s_p}")
if self.sprite.get() != 0:
self.txtarea.insert(END, f"\nSprite\t\t{self.sprite.get()}\t\t{self.d_sp_p}")
if self.frooti.get() != 0:
self.txtarea.insert(END, f"\nFrooti\t\t{self.frooti.get()}\t\t{self.d_f_p}")
if self.maza.get() != 0:
self.txtarea.insert(END, f"\nMaza\t\t{self.maza.get()}\t\t{self.d_m_p}")
if self.litchi.get() != 0:
self.txtarea.insert(END, f"\nLitchi\t\t{self.litchi.get()}\t\t{self.d_l_p}")
self.txtarea.insert(END, f"\n--------------------------------------")
if self.cosmetic_tax.get()!="Rs. 0.0":
self.txtarea.insert(END, f"\nCosmetic Tax\t\t\t{self.cosmetic_tax.get()}")
if self.grocery_tax.get()!="Rs. 0.0":
self.txtarea.insert(END, f"\nGrocery Tax\t\t\t{self.grocery_tax.get()}")
if self.drinks_tax.get()!="Rs. 0.0":
self.txtarea.insert(END, f"\nCold Drinks Tax\t\t\t{self.drinks_tax.get()}")
self.txtarea.insert(END, f"\n--------------------------------------")
self.txtarea.insert(END, f"\nTotal Amount: \t\t\tRs. {self.total_bill_amount}") # final bill in scrollbar.
self.txtarea.insert(END, f"\n--------------------------------------")
self.bill_record()
def bill_record(self):
op = messagebox.askyesno("Save Bill","Do you want to save bill?")
if op>0:
self.bill_data = self.txtarea.get("1.0", END) # data variable get all data of txtarea.
ab = open("Bills/" + str(self.bill.get()) + ".txt","w")
ab.write(self.bill_data)
ab.close()
messagebox.showinfo("Saved",f"Bill No. : {self.bill.get()} saved successfully.")
else:
return
def search_bill(self):
present = "no"
for value in os.listdir("Bills/"):
if value.split(".")[0] == self.search.get():
ab = open(f"Bills/{value}", "r")
self.txtarea.delete("1.0", END)
for d in ab:
self.txtarea.insert(END, d)
ab.close()
present="yes"
if present=="no":
messagebox.showerror("Error","Invalid Bill No.")
def clear_function(self):
op = messagebox.askyesno("Clear", "Do you really want to clear?")
if op > 0:
self.name.set("")
self.phone.set("")
self.bill.set("")
m = random.randint(1000, 9999)
self.bill.set(str(m))
self.search.set("")
self.soup.set(0)
self.cream.set(0)
self.wash.set(0)
self.spray.set(0)
self.gell.set(0)
self.lotion.set(0)
self.rice.set(0)
self.oil.set(0)
self.daal.set(0)
self.wheat.set(0)
self.sugar.set(0)
self.tea.set(0)
self.coke.set(0)
self.slice.set(0)
self.sprite.set(0)
self.frooti.set(0)
self.maza.set(0)
self.litchi.set(0)
self.cosmetic.set("")
self.grocery.set("")
self.drinks.set("")
self.cosmetic_tax.set("")
self.grocery_tax.set("")
self.drinks_tax.set("")
self.bill_top()
def exit_system(self):
op = messagebox.askyesno("Exit","Do you really want to exit?")
if op>0:
self.manish.destroy()
manish = Tk()
obj = Billing(manish)
manish.mainloop() | {"/login.py": ["/signup.py", "/billing_software.py"], "/signup.py": ["/login.py"]} |
62,602 | manishsilwal03/1st-sem-billing-project | refs/heads/master | /login.py | from tkinter import *
from PIL import Image, ImageTk
import pymysql
from tkinter import messagebox
class login_window:
def __init__(self,manish):
self.manish= manish
self.manish.title("Login Window")
self.manish.geometry("750x450+200+90")
self.manish.resizable(False, False)
self.bg = ImageTk.PhotoImage(file="C:/Users/Dell/Desktop/login system project/image/login4.jpg")
bg = Label(self.manish, image=self.bg).pack()
title1 = Label(self.manish, text= "Login System", font= ("garamond",30, "bold"),bg= "lime green")
title1.place(x=0, y=0, relwidth= 1)
window_frame = Frame(self.manish, bg="white")
window_frame.place(x=180, y=75, width=330, height=300)
self.icon = ImageTk.PhotoImage(file="C:/Users/Dell/Desktop/login system project/image/assistant3.png")
icon = Label(self.manish, image=self.icon).place(x=300,y=77)
eee = Label(window_frame, text="Email Address", font=("batang", 15, "bold"), bg="white", fg="black")
eee.place(x=50, y=100)
ppp = Label(window_frame, text="Password", font=("batang", 15, "bold"), bg="white", fg="black")
ppp.place(x=50, y=170)
self.e_eee= Entry(window_frame, font=("batang", 13), bg= "lightgray", width=15)
self.e_eee.place(x= 50, y=130,width=220)
self.e_ppp = Entry(window_frame, font=("batang", 13), show="*****", bg="lightgray", width=15)
self.e_ppp.place(x=50, y=200, width=220)
btn_login = Button(window_frame, text="Login", width=7, font=("batang", 15, "bold"), command= self.login_win,bd=4,
bg="maroon",fg="white",cursor="hand2").place(x=50, y=240)
btn_registers = Button(window_frame, text="Register", width=7, font=("batang", 15, "bold"), command=self.signup_window,
bd=4, bg="maroon", fg="white", cursor="hand2").place(x=163, y=240)
title2 = Label(self.manish, text="Thank You !!!", font=("garamond", 30, "bold"), bg="lime green")
title2.place(x=0, y=400, relwidth=1)
def signup_window(self):
self.manish.destroy()
import signup
def login_win(self):
if self.e_eee.get() == "" or self.e_ppp.get() =="":
messagebox.showerror("Error","please fill up all the information", parent=self.manish)
else:
try:
con = pymysql.connect(host= "localhost", user="root", password="", database= "database_billing")
cur=con.cursor()
cur.execute("select * from login where email= %s and password= %s", (self.e_eee.get(), self.e_ppp.get()))
row = cur.fetchone()
print(row)
if row == None:
messagebox.showerror("Error", "Invalid username and password.", parent=self.manish)
else:
messagebox.showinfo("Successful", "WELCOME", parent=self.manish)
self.manish.destroy()
import billing_software
except Exception as es:
messagebox.showerror("Error", f"Error due to: {str(es)}", parent=self.manish)
manish = Tk()
login= login_window(manish)
manish.mainloop()
| {"/login.py": ["/signup.py", "/billing_software.py"], "/signup.py": ["/login.py"]} |
62,603 | manishsilwal03/1st-sem-billing-project | refs/heads/master | /merge.py | from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
import math, random
import os
import pymysql
from tkinter import messagebox
def manish1():
manish = Tk()
login = login_window(manish)
manish.mainloop()
class login_window:
def __init__(self,manish):
self.manish= manish
self.manish.title("Login Window")
self.manish.geometry("750x450+200+90")
self.manish.resizable(False, False)
self.bg = ImageTk.PhotoImage(file="C:/Users/dell/Desktop/python project/login system project/image/login4.jpg")
bg = Label(self.manish, image=self.bg).pack()
title1 = Label(self.manish, text= "Login System", font= ("garamond",30, "bold"),bg= "lime green")
title1.place(x=0, y=0, relwidth= 1)
window_frame = Frame(self.manish, bg="white")
window_frame.place(x=180, y=75, width=330, height=300)
self.icon = ImageTk.PhotoImage(file="C:/Users/Dell/Desktop/python project/login system project/image/assistant3.png")
icon = Label(self.manish, image=self.icon).place(x=300,y=77)
eee = Label(window_frame, text="Email Address", font=("batang", 15, "bold"), bg="white", fg="black")
eee.place(x=50, y=100)
ppp = Label(window_frame, text="Password", font=("batang", 15, "bold"), bg="white", fg="black")
ppp.place(x=50, y=170)
self.e_eee= Entry(window_frame, font=("batang", 13), bg= "lightgray", width=15)
self.e_eee.place(x= 50, y=130,width=220)
self.e_ppp = Entry(window_frame, font=("batang", 13), show="*****", bg="lightgray", width=15)
self.e_ppp.place(x=50, y=200, width=220)
btn_login = Button(window_frame, text="Login", width=7, font=("batang", 15, "bold"), command= self.login_win,bd=4,
bg="maroon",fg="white",cursor="hand2").place(x=50, y=240)
btn_registers = Button(window_frame, text="Register", width=7, font=("batang", 15, "bold"), command=self.signup_window,
bd=4, bg="maroon", fg="white", cursor="hand2").place(x=163, y=240)
title2 = Label(self.manish, text="Thank You !!!", font=("garamond", 30, "bold"), bg="lime green")
title2.place(x=0, y=400, relwidth=1)
def signup_window(self):
self.manish.withdraw()
self.new_window = Toplevel(self.manish)
self.add = Downloader(self.new_window)
def login_win(self):
if self.e_eee.get() == "" or self.e_ppp.get() =="":
messagebox.showerror("Error","please fill up all the information", parent=self.manish)
else:
try:
con = pymysql.connect(host= "localhost", user="root", password="", database= "database_billing")
cur=con.cursor()
cur.execute("select * from login where email= %s and password= %s", (self.e_eee.get(), self.e_ppp.get()))
row = cur.fetchone()
print(row)
if row == None:
messagebox.showerror("Error", "Invalid username and password.", parent=self.manish)
else:
messagebox.showinfo("Successful", "WELCOME", parent=self.manish)
self.manish.withdraw()
self.new_window1=Toplevel(self.manish)
self.add2=Billing(self.new_window1)
except Exception as es:
messagebox.showerror("Error", f"Error due to: {str(es)}", parent=self.manish)
class Downloader:
def __init__(self, manish):
self.manish=manish
self.manish.title("Registration form")
self.manish.geometry("1250x630+100+70")
self.manish.resizable(False, False)
# insert bg for attraction.
self.bg=ImageTk.PhotoImage(file="C:/Users/dell/Desktop/python project/login system project/image/frame12.jpg")
bg=Label(self.manish,image= self.bg).pack()
# insert left image for new design.
self.left=ImageTk.PhotoImage(file="C:/Users/dell/Desktop/python project/login system project/image/frame1.png")
left=Label(self.manish,image= self.left).place(x=90, y=70, width=450, height= 500)
# downloader frame.================================Row1==================================
login_frame=Frame(self.manish, bg= "white")
login_frame.place(x= 540, y=70, width=650, height= 500)
# accessories for sign in frame,================================Row2===================================
title=Label(login_frame, text= "WELCOME", width= 9, font= ("castellar", 25, "bold"), bg= "lightgreen", fg= "black")
title.place(x= 50, y=30)
title1 = Label(login_frame, text="Register", width=10, font=("castellar", 25, "bold"), bg="lightgreen", fg="black")
title1.place(x=365, y=30)
# sign up process.(name, entry box)================================Row3===================================
var1 = StringVar()
fname = Label(login_frame, text="First Name", font=("arial", 15, "bold"), bg="white", fg="black")
fname.place(x=50, y=100)
self.e1_fname= Entry(login_frame, font=("arial", 13), textvariable=var1, bg= "lightgray", width=15)
self.e1_fname.place(x= 50, y=130,width=220)
var2=StringVar()
lname = Label(login_frame, text="Last Name", font=("arial", 15, "bold"), bg="white", fg="black")
lname.place(x=370, y=100)
self.e1_lname = Entry(login_frame, font=("arial", 13), textvar=var2, bg="lightgray", width=15)
self.e1_lname.place(x=370, y=130, width=220)
# entry and label for country and contact.================================Row4===============================
var3=StringVar()
contact = Label(login_frame, text="Contact No.", font=("arial", 15, "bold"), bg="white", fg="black")
contact.place(x=50, y=170)
self.e1_contact = Entry(login_frame, font=("arial", 13), textvar=var3, bg="lightgray", width=15)
self.e1_contact.place(x=50, y=200, width=220)
var4=StringVar()
country = Label(login_frame, text="Country", font=("arial", 15, "bold"), bg="white", fg="black")
country.place(x=370, y=170)
self.e1_country = Entry(login_frame, font=("arial", 13), textvar=var4, bg="lightgray", width=15)
self.e1_country.place(x=370, y=200, width=220)
# DOB and Gender ================================Row5==========================================
var5=StringVar()
birth = Label(login_frame, text="DOB", font=("arial", 15, "bold"), bg="white", fg="black")
birth.place(x=50, y=240)
self.e1_birth = Entry(login_frame, font=("arial", 13), textvar= var5, bg="lightgray", width=15)
self.e1_birth.place(x=50, y=270, width=220)
gender = Label(login_frame, text="Gender", font=("arial", 15, "bold"), bg="white", fg="black")
gender.place(x=370, y=240)
global var6
var6 = StringVar()
choices = ["Select","Male","Female"]
self.comb_gender = ttk.OptionMenu(login_frame, var6,*choices)
var6.set("Select")
self.comb_gender.place(x=370, y=270, width=220)
# email and password ================================Row6==========================================
var7=StringVar()
var8=StringVar()
email = Label(login_frame, text="Email", font=("arial", 15, "bold"), bg="white", fg="black").place(x=50, y=310)
self.e1_email = Entry(login_frame, font=("arial", 13), textvar=var7, bg="lightgray", width=15)
self.e1_email.place(x=50, y=340, width=220)
password = Label(login_frame, text="Password", font=("arial", 15, "bold"), bg="white", fg="black").place(x=370, y=310)
self.e1_password = Entry(login_frame, font=("arial", 13), textvar=var8, bg="lightgray",show= "*****", width=15)
self.e1_password.place(x=370, y=340, width=220)
# term and condition ================================Row7==========================================
self.var9=IntVar()
check = Checkbutton(login_frame, text= "I agree all the terms and conditions.", onvalue=1, offvalue=0, variable=self.var9, bg= "white").place(x=50, y=380)
self.btn_image = ImageTk.PhotoImage(file="C:/Users/dell/Desktop/python project/login system project/image/logo9.jfif")
btn = Button(login_frame, image=self.btn_image, bd=0, cursor= "hand2", command= self.sign_in).place(x=50,y=430, width= 220, height= 53)
# ========================left image login=================================================================
btn_started= Button(self.manish, text= "Get Started", command=self.started_window, width= 13, font=("arial",15,"bold"), bd=0, bg="yellow" , cursor="hand2").place(x=250, y=450)
def started_window(self):
self.manish.withdraw()
self.fucchhoo=Toplevel(self.manish)
self.silwal=login_window(self.fucchhoo)
def clear(self):
self.e1_fname.delete(0, END)
self.e1_lname.delete(0, END)
self.e1_contact.delete(0, END)
self.e1_country.delete(0, END)
self.e1_birth.delete(0, END)
self.var9.get()
self.e1_email.delete(0, END)
self.e1_password.delete(0, END)
def sign_in(self):
if self.e1_fname.get()=="" or self.e1_contact.get()=="" or self.e1_country.get()=="" or self.e1_birth.get()=="" or var6.get()=="Select" or self.e1_email.get()=="" or self.e1_password.get()=="":
messagebox.showerror("Error","Please! fill up all information.", parent= self.manish)
elif self.var9.get()==0:
messagebox.showerror("Error", "Don't you agree the Terms and Conditions?", parent=self.manish)
else:
try:
con=pymysql.connect(host="localhost",user="root", password="", database="database_billing")
cur=con.cursor()
cur.execute("select * from login where email = %s",self.e1_email.get())
row=cur.fetchone()
# print(row)
if row!=None:
messagebox.showerror("Error", "User already logged in, Please try another email.", parent=self.manish)
else:
cur.execute("insert into login(fname, lname, contact, country, birth, gender, email, password) values(%s,%s,%s,%s,%s,%s,%s,%s)",
(self.e1_fname.get(),
self.e1_lname.get(),
self.e1_contact.get(),
self.e1_country.get(),
self.e1_birth.get(),
self.var9.get(),
self.e1_email.get(),
self.e1_password.get()
))
con.commit()
con.close()
messagebox.showinfo("Successful", "Sign Up successfully!", parent=self.manish)
self.clear()
except Exception as es:
messagebox.showerror("Error",f"Error due to: {str(es)}", parent=self.manish)
class Billing(login_window):
def __init__(self, manish):
super(Billing, self).__init__(manish)
self.manish.title("Billing Software")
self.manish.geometry("1355x710+50+30")
self.manish.resizable(False, False)
background ="red"
title1 = Label(self.manish, text="Welcome To Manish Retail Billing", bd= 12, relief= GROOVE,font=("Arial", 30, "bold"),fg="white", bg=background)
title1.place(x=3,relwidth=1)
# creating variables call ==========================================================
self.name = StringVar()
self.phone = StringVar()
self.bill = StringVar()
m = random.randint(1000,9999)
self.bill.set(str(m))
self.search = StringVar()
self.soup = IntVar()
self.cream = IntVar()
self.wash = IntVar()
self.spray = IntVar()
self.gell = IntVar()
self.lotion = IntVar()
self.rice = IntVar()
self.oil = IntVar()
self.daal = IntVar()
self.wheat = IntVar()
self.sugar = IntVar()
self.tea = IntVar()
self.coke = IntVar()
self.slice = IntVar()
self.sprite = IntVar()
self.frooti= IntVar()
self.maza= IntVar()
self.litchi= IntVar()
self.cosmetic = StringVar()
self.grocery= StringVar()
self.drinks = StringVar()
self.cosmetic_tax = StringVar()
self.grocery_tax = StringVar()
self.drinks_tax = StringVar()
# =================================================================*======================================
f1 = LabelFrame(self.manish, text="Customer details", bd=7, relief= GROOVE, font=("Arial", 15, "bold"),fg="yellow", bg=background)
f1.place(x=3, y=80,relwidth=1)
c_name = Label(f1, text= "Customer Name", font=("Arial", 15, "bold",),bg= background, fg= "white")
c_name.grid(row=0, column=0, padx=20, pady=2)
e_name = Entry(f1, width= 16, textvariable=self.name, font=("Arial",14), bd=7, relief= RAISED).grid(row=0, column=1, padx= 10, pady=5)
c_phone = Label(f1, text="Phone No.", font=("Arial", 15, "bold",), bg=background, fg="white")
c_phone.grid(row=0, column=2, padx=20, pady=2)
e_phone = Entry(f1, width=16, textvariable=self.phone, font=("Arial", 14), bd=7, relief=RAISED).grid(row=0, column=3, padx=10, pady=5)
c_bill = Label(f1, text="Bill Number", font=("Arial", 15, "bold",), bg=background, fg="white")
c_bill.grid(row=0, column=4, padx=20, pady=2)
e_bill = Entry(f1, width=16, textvariable=self.search, font=("Arial", 14), bd=7, relief=RAISED).grid(row=0, column=5, padx=10, pady=5)
btn_bill = Button(f1, text="Search", command= self.search_bill, font=("Arial", 10,"bold"),cursor= "hand2", width= 10, bd=7)
btn_bill.grid(row=0, column= 6, padx=15, pady=8)
# ============================================================================================================
f2 = LabelFrame(self.manish, text="Cosmetics", bd=9, relief=GROOVE, font=("Arial", 15, "bold"), fg="yellow", bg=background)
f2.place(x=3, y=170, width= 325, height= 345)
name_soup = Label(f2, text= "Soup",font=("Arial", 15, "bold"), bg=background, fg="white")
name_soup.grid(row=0, column= 0, padx= 10, pady= 10, sticky= "w")
entry_soup = Entry(f2, width= 15, textvariable=self.soup,font=("Arial", 12, "bold"),bd= 4, relief= SUNKEN).grid(row=0, column=1, padx=10, pady=10)
name_cream = Label(f2, text="Face Cream", font=("Arial", 15, "bold"), bg=background, fg="white")
name_cream.grid(row=1, column=0, padx=10, pady=10, sticky="w")
entry_cream = Entry(f2, width=15, textvariable=self.cream, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=1, column=1, padx=10, pady=10)
name_wash = Label(f2, text="Face Wash", font=("Arial", 15, "bold"), bg=background, fg="white")
name_wash.grid(row=2, column=0, padx=10, pady=10, sticky="w")
entry_wash = Entry(f2, width=15, textvariable=self.wash, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=2, column=1, padx=10, pady=10)
name_spray = Label(f2, text="Hair Spray", font=("Arial", 15, "bold"), bg=background, fg="white")
name_spray.grid(row=3, column=0, padx=10, pady=10, sticky="w")
e_spray = Entry(f2, width=15, textvariable=self.spray, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=3, column=1, padx=10, pady=10)
name_gell = Label(f2, text="Hair Gell", font=("Arial", 15, "bold"), bg=background, fg="white")
name_gell.grid(row=4, column=0, padx=10, pady=10, sticky="w")
e_gell = Entry(f2, width=15, textvariable=self.gell, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=4, column=1, padx=10, pady=10)
name_lotion = Label(f2, text="Body lotion", font=("Arial", 15, "bold"), bg=background, fg="white")
name_lotion.grid(row=5, column=0, padx=10, pady=10, sticky="w")
entry_lotion = Entry(f2, width=15, textvariable=self.lotion, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=5, column=1, padx=10, pady=10)
# ============================================================================================================
f3 = LabelFrame(self.manish, text="Grocery", bd=9, relief=GROOVE, font=("Arial", 15, "bold"), fg="yellow", bg=background)
f3.place(x=333, y=170, width=325, height=345)
name_rice = Label(f3, text="Rice", font=("Arial", 15, "bold"), bg=background, fg="white")
name_rice.grid(row=0, column=0, padx=10, pady=10, sticky="w")
entry_soup = Entry(f3, width=15, textvariable=self.rice, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=0, column=1, padx=10, pady=10)
name_oil = Label(f3, text="Oil", font=("Arial", 15, "bold"), bg=background, fg="white")
name_oil.grid(row=1, column=0, padx=10, pady=10, sticky="w")
entry_oil = Entry(f3, width=15, textvariable=self.oil, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=1, column=1, padx=10, pady=10)
name_daal = Label(f3, text="Daal", font=("Arial", 15, "bold"), bg=background, fg="white")
name_daal.grid(row=2, column=0, padx=10, pady=10, sticky="w")
entry_daal = Entry(f3, width=15, textvariable=self.daal, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=2, column=1, padx=10, pady=10)
name_wheat = Label(f3, text="Wheat", font=("Arial", 15, "bold"), bg=background, fg="white")
name_wheat.grid(row=3, column=0, padx=10, pady=10, sticky="w")
e_wheat = Entry(f3, width=15, textvariable=self.wheat, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=3, column=1, padx=10, pady=10)
name_sugar = Label(f3, text="Sugar", font=("Arial", 15, "bold"), bg=background, fg="white")
name_sugar.grid(row=4, column=0, padx=10, pady=10, sticky="w")
e_sugar = Entry(f3, width=15, textvariable=self.sugar, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=4, column=1, padx=10, pady=10)
name_tea = Label(f3, text="Tea", font=("Arial", 15, "bold"), bg=background, fg="white")
name_tea.grid(row=5, column=0, padx=10, pady=10, sticky="w")
entry_tea = Entry(f3, width=15, textvariable=self.tea, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=5, column=1, padx=10, pady=10)
# ============================================================================================================
f4 = LabelFrame(self.manish, text="Cold Drinks", bd=9, relief=GROOVE, font=("Arial", 15, "bold"), fg="yellow", bg=background)
f4.place(x=663, y=170, width=325, height=345)
name_coke = Label(f4, text="Coke", font=("Arial", 15, "bold"), bg=background, fg="white")
name_coke.grid(row=0, column=0, padx=10, pady=10, sticky="w")
entry_coke = Entry(f4, width=15, textvariable=self.coke, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=0, column=1, padx=10, pady=10)
name_slice = Label(f4, text="Slice", font=("Arial", 15, "bold"), bg=background, fg="white")
name_slice.grid(row=1, column=0, padx=10, pady=10, sticky="w")
entry_slice = Entry(f4, width=15, textvariable=self.slice, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=1, column=1, padx=10, pady=10)
name_sprite = Label(f4, text="Sprite", font=("Arial", 15, "bold"), bg=background, fg="white")
name_sprite.grid(row=2, column=0, padx=10, pady=10, sticky="w")
entry_sprite = Entry(f4, width=15, textvariable=self.sprite, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=2, column=1, padx=10, pady=10)
name_frooti = Label(f4, text="Frooti", font=("Arial", 15, "bold"), bg=background, fg="white")
name_frooti.grid(row=3, column=0, padx=10, pady=10, sticky="w")
e_frooti = Entry(f4, width=15, textvariable=self.frooti, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=3, column=1, padx=10, pady=10)
name_maza = Label(f4, text="Maza", font=("Arial", 15, "bold"), bg=background, fg="white")
name_maza.grid(row=4, column=0, padx=10, pady=10, sticky="w")
entry_maza = Entry(f4, width=15, textvariable=self.maza, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=4, column=1, padx=10, pady=10)
name_litchi = Label(f4, text="Lichi", font=("Arial", 15, "bold"), bg=background, fg="white")
name_litchi.grid(row=5, column=0, padx=10, pady=10, sticky="w")
entry_litchi = Entry(f4, width=15, textvariable=self.litchi, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=5, column=1, padx=10,pady=10)
# ===========================bill voucher======================================================================
f5 = LabelFrame(self.manish, bd=9, relief=GROOVE,)
f5.place(x=1000, y=170, width=345, height=345)
title2 = Label(f5, text="Bill Voucher", bd=12, relief=GROOVE, font=("Arial", 15, "bold"))
title2.pack(fill= X)
scroll_bill = Scrollbar(f5,orient = VERTICAL)
self.txtarea = Text(f5, yscrollcommand= scroll_bill.set)
scroll_bill.pack(side= RIGHT, fill=Y)
scroll_bill.configure(command= self.txtarea.yview)
self.txtarea.pack(fill= BOTH, expand= 1)
f6 = LabelFrame(self.manish, text="Bill Menu", bd=8, relief=GROOVE, font=("Arial", 15, "bold"), fg="yellow", bg=background)
f6.place(x=3, y=520, relwidth=1, height= 180)
a1_label= Label(f6, text= "Total Cosmetics Price", font=("Arial", 15, "bold"),bg= background,fg="white").grid(row=0,column=0,padx=20,pady=1,sticky="w")
a1_entry= Entry(f6, width=18, textvariable=self.cosmetic, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=0, column=1, padx=10, pady=1)
a2_label = Label(f6, text="Total Grocery Price", font=("Arial", 15, "bold"), bg=background, fg="white").grid(row=1, column=0, padx=20, pady=1, sticky="w")
a2_entry = Entry(f6, width=18, textvariable=self.grocery, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=1, column=1, padx=10, pady=1)
a3_label = Label(f6, text="Total Cold Drinks Price", font=("Arial", 15, "bold"), bg=background, fg="white").grid(row=2, column=0, padx=20, pady=1, sticky="w")
a3_entry = Entry(f6, width=18, textvariable=self.drinks, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=2, column=1, padx=10, pady=1)
b1_label = Label(f6, text="Cosmetics Tax", font=("Arial", 15, "bold"), bg=background, fg="white").grid(row=0, column=2, padx=20, pady=1, sticky="w")
b1_entry = Entry(f6, width=18, textvariable=self.cosmetic_tax, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=0, column=3, padx=10,pady=1)
b2_label = Label(f6, text="Grocery Tax", font=("Arial", 15, "bold"), bg=background, fg="white").grid(row=1, column=2, padx=20, pady=1, sticky="w")
b2_entry = Entry(f6, width=18, textvariable=self.grocery_tax, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=1, column=3, padx=10,pady=1)
b3_label = Label(f6, text="Cold Drinks Tax", font=("Arial", 15, "bold"), bg=background,fg="white").grid(row=2, column=2, padx=20, pady=1, sticky="w")
b3_entry = Entry(f6, width=18, textvariable=self.drinks_tax, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=2, column=3, padx=10 ,pady=1)
fin_frame = Frame(f6, bd=10, relief=GROOVE, )
fin_frame.place(x=780, y=3, width=560, height=90)
total_button = Button(fin_frame,text= "Total", command=self.total, bg = "maroon", fg= "white", bd= 5, pady= 5,font=("Arial", 15,"bold"), width=9).grid(row=0, column=0, padx=5, pady= 5)
total_button = Button(fin_frame,text= "Print Bill", command= self.bill_print, bg = "maroon", fg= "white", bd= 5, pady= 5,font=("Arial", 15,"bold"), width=9).grid(row=0, column=1, padx=5, pady= 5)
total_button = Button(fin_frame,text= "Clear", command=self.clear_function, bg = "maroon", fg= "white", bd= 5, pady= 5,font=("Arial", 15,"bold"), width=9).grid(row=0, column=2, padx=5, pady= 5)
total_button = Button(fin_frame,text= "Exit",command=self.exit_system, bg = "maroon", fg= "white", bd= 5, pady= 5,font=("Arial", 15,"bold"), width=9).grid(row=0, column=3, padx=5, pady= 5)
info = Label(f6, text="If you have any query, please kindly mail me on lawlishsinam03@gmail.com. Thank You!!",
bd=8, relief=GROOVE, font=("Arial", 15, "bold"), fg="yellow", bg=background)
info.place(y=105, relwidth=1)
self.bill_top() # to print always, we called inside init function.
def total(self):
self.c_s_p = (self.soup.get()* 30)
self.c_c_p = (self.cream.get()* 120)
self.c_w_p = (self.wash.get()* 50)
self.c_sp_p = (self.spray.get()* 200)
self.c_g_p = (self.gell.get()* 120)
self.c_l_p = (self.lotion.get()* 160)
self.total_cosmetic = float (self.c_s_p +
self.c_c_p+
self.c_w_p+
self.c_sp_p+
self.c_g_p +
self.c_l_p)
self.cosmetic.set("Rs. " + str(self.total_cosmetic))
self.c_tax = round((self.total_cosmetic*0.05),2)
self.cosmetic_tax.set("Rs. " + str(self.c_tax))
self.g_r_p = (self.rice.get() * 75)
self.g_o_p = (self.oil.get() * 180)
self.g_d_p = (self.daal.get() * 60)
self.g_w_p = (self.wheat.get() * 240)
self.g_s_p = (self.sugar.get() * 75)
self.g_t_p = (self.tea.get() * 150)
self.total_grocery = float (self.g_r_p +
self.g_o_p+
self.g_d_p+
self.g_w_p+
self.g_s_p+
self.g_t_p)
self.grocery.set("Rs. " + str(self.total_grocery))
self.g_tax = round((self.total_grocery * 0.05),2)
self.grocery_tax.set("Rs. " + str(self.g_tax))
self.d_c_p = (self.coke.get() * 45)
self.d_s_p = (self.slice.get() * 50)
self.d_sp_p = (self.sprite.get() * 45)
self.d_f_p = (self.frooti.get() * 25)
self.d_m_p = (self.maza.get() * 60)
self.d_l_p = (self.litchi.get() * 35)
self.total_drinks = float (self.d_c_p +
self.d_s_p+
self.d_sp_p+
self.d_f_p+
self.d_m_p+
self.d_l_p)
self.drinks.set("Rs. " + str(self.total_drinks))
self.d_tax = round((self.total_drinks*0.05),2) # this is done for generating total bill in bill print.
self.drinks_tax.set("Rs. "+ str(self.d_tax))
self.total_bill_amount = float( self.total_cosmetic +
self.total_grocery +
self.total_drinks +
self.c_tax+
self. g_tax +
self.d_tax)
def bill_top(self):
self.txtarea.delete("1.0", END)
self.txtarea.insert(END, "\tWelcome to Manish Retails\n")
self.txtarea.insert(END, f"\nBill Number :{self.bill.get()} ")
self.txtarea.insert(END, f"\nCustomer Name :{self.name.get()} ")
self.txtarea.insert(END, f"\nPhone Number : {self.phone.get()}")
self.txtarea.insert(END, f"\n======================================")
self.txtarea.insert(END, f"\nProduct\t\tQuantity\t\tPrice")
self.txtarea.insert(END, f"\n======================================")
def bill_print(self):
if self.name.get() =="" or self.phone.get() =="":
messagebox.showerror("Error","Fill up Customer details")
elif self.cosmetic.get()=="Rs. 0.0" and self.grocery.get()=="Rs. 0.0" and self.drinks.get()=="Rs. 0.0":
messagebox.showerror("Error","Nothing is purchased.")
else:
# ************************** c ****************************************************************************
self.bill_top()
if self.soup.get()!=0:
self.txtarea.insert(END, f"\nSoap\t\t{self.soup.get()}\t\t{self.c_s_p}")
if self.cream.get()!=0:
self.txtarea.insert(END, f"\nFace Cream\t\t{self.cream.get()}\t\t{self.c_c_p}")
if self.wash.get()!=0:
self.txtarea.insert(END, f"\nFace Wash\t\t{self.wash.get()}\t\t{self.c_w_p}")
if self.spray.get()!=0:
self.txtarea.insert(END, f"\nHair Spray\t\t{self.spray.get()}\t\t{self.c_sp_p}")
if self.gell.get()!=0:
self.txtarea.insert(END, f"\nHair Gell\t\t{self.gell.get()}\t\t{self.c_g_p}")
if self.lotion.get()!=0:
self.txtarea.insert(END, f"\nBody Lotion \t\t{self.lotion.get()}\t\t{self.c_l_p}")
# ************************** c ****************************************************************************
if self.rice.get() != 0:
self.txtarea.insert(END, f"\nRice\t\t{self.rice.get()}\t\t{self.g_r_p}")
if self.oil.get() != 0:
self.txtarea.insert(END, f"\nOil\t\t{self.oil.get()}\t\t{self.g_o_p}")
if self.daal.get() != 0:
self.txtarea.insert(END, f"\nDaal\t\t{self.daal.get()}\t\t{self.g_d_p}")
if self.wheat.get() != 0:
self.txtarea.insert(END, f"\nWheat\t\t{self.wheat.get()}\t\t{self.g_w_p}")
if self.sugar.get() != 0:
self.txtarea.insert(END, f"\nSugar\t\t{self.sugar.get()}\t\t{self.g_s_p}")
if self.tea.get() != 0:
self.txtarea.insert(END, f"\nTea\t\t{self.tea.get()}\t\t{self.g_t_p}")
# ************************** c ****************************************************************************
if self.coke.get() != 0:
self.txtarea.insert(END, f"\nCoke\t\t{self.coke.get()}\t\t{self.d_c_p}")
if self.slice.get() != 0:
self.txtarea.insert(END, f"\nSlice\t\t{self.slice.get()}\t\t{self.d_s_p}")
if self.sprite.get() != 0:
self.txtarea.insert(END, f"\nSprite\t\t{self.sprite.get()}\t\t{self.d_sp_p}")
if self.frooti.get() != 0:
self.txtarea.insert(END, f"\nFrooti\t\t{self.frooti.get()}\t\t{self.d_f_p}")
if self.maza.get() != 0:
self.txtarea.insert(END, f"\nMaza\t\t{self.maza.get()}\t\t{self.d_m_p}")
if self.litchi.get() != 0:
self.txtarea.insert(END, f"\nLitchi\t\t{self.litchi.get()}\t\t{self.d_l_p}")
self.txtarea.insert(END, f"\n--------------------------------------")
if self.cosmetic_tax.get()!="Rs. 0.0":
self.txtarea.insert(END, f"\nCosmetic Tax\t\t\t{self.cosmetic_tax.get()}")
if self.grocery_tax.get()!="Rs. 0.0":
self.txtarea.insert(END, f"\nGrocery Tax\t\t\t{self.grocery_tax.get()}")
if self.drinks_tax.get()!="Rs. 0.0":
self.txtarea.insert(END, f"\nCold Drinks Tax\t\t\t{self.drinks_tax.get()}")
self.txtarea.insert(END, f"\n--------------------------------------")
self.txtarea.insert(END, f"\nTotal Amount: \t\t\tRs. {self.total_bill_amount}") # final bill in scrollbar.
self.txtarea.insert(END, f"\n--------------------------------------")
self.bill_record()
def bill_record(self):
op = messagebox.askyesno("Save Bill","Do you want to save bill?")
if op>0:
self.bill_data = self.txtarea.get("1.0", END) # data variable get all data of txtarea.
ab = open("Bills/" + str(self.bill.get()) + ".txt","w")
ab.write(self.bill_data)
ab.close()
messagebox.showinfo("Saved",f"Bill No. : {self.bill.get()} saved successfully.")
else:
return
def search_bill(self):
present = "no"
for value in os.listdir("Bills/"):
if value.split(".")[0] == self.search.get():
ab = open(f"Bills/{value}", "r")
self.txtarea.delete("1.0", END)
for d in ab:
self.txtarea.insert(END, d)
ab.close()
present="yes"
if present=="no":
messagebox.showerror("Error","Invalid Bill No.")
def clear_function(self):
op = messagebox.askyesno("Clear", "Do you really want to clear?")
if op > 0:
self.name.set("")
self.phone.set("")
self.bill.set("")
m = random.randint(1000, 9999)
self.bill.set(str(m))
self.search.set("")
self.soup.set(0)
self.cream.set(0)
self.wash.set(0)
self.spray.set(0)
self.gell.set(0)
self.lotion.set(0)
self.rice.set(0)
self.oil.set(0)
self.daal.set(0)
self.wheat.set(0)
self.sugar.set(0)
self.tea.set(0)
self.coke.set(0)
self.slice.set(0)
self.sprite.set(0)
self.frooti.set(0)
self.maza.set(0)
self.litchi.set(0)
self.cosmetic.set("")
self.grocery.set("")
self.drinks.set("")
self.cosmetic_tax.set("")
self.grocery_tax.set("")
self.drinks_tax.set("")
self.bill_top()
def exit_system(self):
op = messagebox.askyesno("Exit","Do you really want to exit?")
if op>0:
self.manish.destroy()
if __name__=="__main__":
manish1() | {"/login.py": ["/signup.py", "/billing_software.py"], "/signup.py": ["/login.py"]} |
62,604 | manishsilwal03/1st-sem-billing-project | refs/heads/master | /signup.py |
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from PIL import Image,ImageTk # pip install pillow fro terminal.
import pymysql # pip install pymysql from terminal.
class Downloader:
def __init__(self, manish):
self.manish=manish
self.manish.title("Video Downloader")
self.manish.geometry("1250x630+100+70")
self.manish.resizable(False, False)
# insert bg for attraction.
self.bg=ImageTk.PhotoImage(file="C:/Users/dell/Desktop/login system project/image/frame12.jpg")
bg=Label(self.manish,image= self.bg).pack()
# insert left image for new design.
self.left=ImageTk.PhotoImage(file="C:/Users/dell/Desktop/login system project/image/frame1.png")
left=Label(self.manish,image= self.left).place(x=90, y=70, width=450, height= 500)
# downloader frame.================================Row1==================================
login_frame=Frame(self.manish, bg= "white")
login_frame.place(x= 540, y=70, width=650, height= 500)
# accessories for sign in frame,================================Row2===================================
title=Label(login_frame, text= "WELCOME", width= 9, font= ("castellar", 25, "bold"), bg= "lightgreen", fg= "black")
title.place(x= 50, y=30)
title1 = Label(login_frame, text="Register", width=10, font=("castellar", 25, "bold"), bg="lightgreen", fg="black")
title1.place(x=365, y=30)
# sign up process.(name, entry box)================================Row3===================================
var1 = StringVar()
fname = Label(login_frame, text="First Name", font=("arial", 15, "bold"), bg="white", fg="black")
fname.place(x=50, y=100)
self.e1_fname= Entry(login_frame, font=("arial", 13), textvariable=var1, bg= "lightgray", width=15)
self.e1_fname.place(x= 50, y=130,width=220)
var2=StringVar()
lname = Label(login_frame, text="Last Name", font=("arial", 15, "bold"), bg="white", fg="black")
lname.place(x=370, y=100)
self.e1_lname = Entry(login_frame, font=("arial", 13), textvar=var2, bg="lightgray", width=15)
self.e1_lname.place(x=370, y=130, width=220)
# entry and label for country and contact.================================Row4===============================
var3=StringVar()
contact = Label(login_frame, text="Contact No.", font=("arial", 15, "bold"), bg="white", fg="black")
contact.place(x=50, y=170)
self.e1_contact = Entry(login_frame, font=("arial", 13), textvar=var3, bg="lightgray", width=15)
self.e1_contact.place(x=50, y=200, width=220)
var4=StringVar()
country = Label(login_frame, text="Country", font=("arial", 15, "bold"), bg="white", fg="black")
country.place(x=370, y=170)
self.e1_country = Entry(login_frame, font=("arial", 13), textvar=var4, bg="lightgray", width=15)
self.e1_country.place(x=370, y=200, width=220)
# DOB and Gender ================================Row5==========================================
var5=StringVar()
birth = Label(login_frame, text="DOB", font=("arial", 15, "bold"), bg="white", fg="black")
birth.place(x=50, y=240)
self.e1_birth = Entry(login_frame, font=("arial", 13), textvar= var5, bg="lightgray", width=15)
self.e1_birth.place(x=50, y=270, width=220)
gender = Label(login_frame, text="Gender", font=("arial", 15, "bold"), bg="white", fg="black")
gender.place(x=370, y=240)
global var6
var6 = StringVar()
choices = ["Select","Male","Female"]
self.comb_gender = ttk.OptionMenu(login_frame, var6,*choices)
var6.set("Select")
self.comb_gender.place(x=370, y=270, width=220)
# email and password ================================Row6==========================================
var7=StringVar()
var8=StringVar()
email = Label(login_frame, text="Email", font=("arial", 15, "bold"), bg="white", fg="black").place(x=50, y=310)
self.e1_email = Entry(login_frame, font=("arial", 13), textvar=var7, bg="lightgray", width=15)
self.e1_email.place(x=50, y=340, width=220)
password = Label(login_frame, text="Password", font=("arial", 15, "bold"), bg="white", fg="black").place(x=370, y=310)
self.e1_password = Entry(login_frame, font=("arial", 13), textvar=var8, bg="lightgray",show= "*****", width=15)
self.e1_password.place(x=370, y=340, width=220)
# term and condition ================================Row7==========================================
self.var9=IntVar()
check = Checkbutton(login_frame, text= "I agree all the terms and conditions.", onvalue=1, offvalue=0, variable=self.var9, bg= "white").place(x=50, y=380)
self.btn_image = ImageTk.PhotoImage(file="C:/Users/dell/Desktop/login system project/image/logo9.jfif")
btn = Button(login_frame, image=self.btn_image, bd=0, cursor= "hand2", command= self.sign_in).place(x=50,y=430, width= 220, height= 53)
# ========================left image login=================================================================
btn_started= Button(self.manish, text= "Get Started", command=self.started_window, width= 13, font=("arial",15,"bold"), bd=0, bg="yellow" , cursor="hand2").place(x=250, y=450)
def started_window(self):
self.manish.destroy()
import login
def clear(self):
self.e1_fname.delete(0, END)
self.e1_lname.delete(0, END)
self.e1_contact.delete(0, END)
self.e1_country.delete(0, END)
self.e1_birth.delete(0, END)
self.var9.get()
self.e1_email.delete(0, END)
self.e1_password.delete(0, END)
def sign_in(self):
if self.e1_fname.get()=="" or self.e1_contact.get()=="" or self.e1_country.get()=="" or self.e1_birth.get()=="" or var6.get()=="Select" or self.e1_email.get()=="" or self.e1_password.get()=="":
messagebox.showerror("Error","Please! fill up all information.", parent= self.manish)
elif self.var9.get()==0:
messagebox.showerror("Error", "Don't you agree the Terms and Conditions?", parent=self.manish)
else:
try:
con=pymysql.connect(host="localhost",user="root", password="", database="database_billing")
cur=con.cursor()
cur.execute("select * from login where email = %s",self.e1_email.get())
row=cur.fetchone()
# print(row)
if row!=None:
messagebox.showerror("Error", "User already logged in, Please try another email.", parent=self.manish)
else:
cur.execute("insert into login(fname, lname, contact, country, birth, gender, email, password) values(%s,%s,%s,%s,%s,%s,%s,%s)",
(self.e1_fname.get(),
self.e1_lname.get(),
self.e1_contact.get(),
self.e1_country.get(),
self.e1_birth.get(),
self.var9.get(),
self.e1_email.get(),
self.e1_password.get()
))
con.commit()
con.close()
messagebox.showinfo("Successful", "Sign Up successfully!", parent=self.manish)
self.clear()
except Exception as es:
messagebox.showerror("Error",f"Error due to: {str(es)}", parent=self.manish)
manish = Tk() # manish is the object for Tk.
video = Downloader(manish) # video is the object for class.
manish.mainloop()
| {"/login.py": ["/signup.py", "/billing_software.py"], "/signup.py": ["/login.py"]} |
62,759 | brakettech/daq_server | refs/heads/master | /apps/main/views.py | import os
import pathlib
from pprint import pprint
import re
from django import forms
from django.db import transaction
from django.db.models.functions import Lower
from django.views.generic import FormView, DeleteView, CreateView, UpdateView, TemplateView
from django.views.generic import ListView
from django.utils.text import slugify
from apps.main.models import Experiment, Configuration
from apps.main.models import Parameter
from pico import Data
APP_NAME = 'main'
DEFAULT_PATH = '/daqroot'
CHANNEL_NAMES = [
'channel_a',
'channel_b',
'channel_c',
'channel_d',
]
def path_getter(uri=DEFAULT_PATH):
if uri is None:
uri = DEFAULT_PATH
path = pathlib.Path(uri.replace('file:', ''))
if not path.exists():
path = pathlib.Path(DEFAULT_PATH)
p = path
parents = []
if p.is_dir():
parents.append(p)
while p.as_posix() != DEFAULT_PATH:
p = p.parent
parents.append(p)
parents = parents[::-1]
if parents:
parents = parents[1:]
if path.is_dir():
entries = [pth for pth in path.iterdir() if not pth.name.startswith('.')]
else:
entries = []
return parents, path, entries
class NewExperimentForm(forms.ModelForm):
class Meta:
model = Experiment
fields = ['name']
class NCView(TemplateView):
template_name = '{}/netcdf.html'.format(APP_NAME)
def get_context_data(self, **kwargs):
context = super().get_context_data()
path_uri = self.request.GET.get('path_uri')
parents, path, entries = path_getter(path_uri)
data = Data()
data.load_meta(path.as_posix())
rex_private = re.compile(r'__\S+__')
params = {}
for key, val in data.meta.items():
if not rex_private.match(key) and not key == 'notes':
params[key] = val
context['file'] = path.as_posix()
context['params'] = params
context['notes'] = data.meta.get('notes', '')
return context
class NewConfigView(CreateView):
model = Configuration
fields = ['name', 'experiment']
def get_context_data(self, **kwargs):
context = super().get_context_data()
context['experiment_id'] = self.kwargs['experiment_id']
return context
def get_form(self):
form = super().get_form()
form.fields['experiment'].widget = forms.HiddenInput()
form.fields['experiment'].initial = int(self.kwargs['experiment_id'])
return form
def get_success_url(self):
return r'/main/experiment/{}'.format(self.kwargs['experiment_id'])
class DeleteExperimentView(DeleteView):
model = Experiment
success_url = '/main/experiment'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['configs'] = Configuration.objects.filter(experiment=context['experiment']).order_by(Lower('name'))
return context
class DeleteConfigView(DeleteView):
model = Configuration
def get_success_url(self):
return r'/main/experiment/{}'.format(self.get_context_data()['configuration'].experiment_id)
class DeleteParamView(DeleteView):
model = Parameter
def get_object(self, queryset=None):
param = Parameter.objects.get(id=int(self.kwargs['param_id']))
self.config_id = param.configuration_id
return param
def get_success_url(self):
return r'/main/config/{}'.format(self.config_id)
class NewExperimentView(CreateView):
model = Experiment
fields = ['name']
def get_success_url(self):
return r'/main/experiment'
class CloneExperimentView(FormView):
template_name = '{}/experiment_update_form.html'.format(APP_NAME)
form = NewExperimentForm
form_class = form
def form_valid(self, form):
experiment = Experiment.objects.get(id=int(self.kwargs['experiment_id']))
experiment.clone(form.cleaned_data['name'])
return super().form_valid(form)
def get_success_url(self):
return r'/main/experiment'
class CloneConfigForm(forms.ModelForm):
class Meta:
model = Configuration
fields = ['name']
class CloneConfigView(FormView):
template_name = '{}/configuration_update_form.html'.format(APP_NAME)
form_class = CloneConfigForm
def form_valid(self, form):
config = Configuration.objects.get(id=int(self.kwargs['config_id']))
config.clone(new_name=form.cleaned_data['name'])
self.experiment_id = config.experiment_id
return super().form_valid(form)
def get_success_url(self):
return r'/main/experiment/{}'.format(self.experiment_id)
class ExperimentListView(ListView):
model = Experiment
def post(self, *args, **kwargs):
return self.get(*args, **kwargs)
def get_queryset(self):
return Experiment.objects.all().order_by(Lower('name'))
class ConfigListView(ListView):
model = Configuration
def get_queryset(self):
return Configuration.objects.filter(
experiment_id=int(self.kwargs['experiment_id'])
).order_by(Lower('name'))
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['experiment'] = Experiment.objects.get(id=int(self.kwargs['experiment_id']))
return context
def post(self, *args, **kwargs):
return self.get(*args, **kwargs)
class ChangeParamView(UpdateView):
# form_class = ChangeParamForm
model = Parameter
fields = ['name', 'type']
template_name = '{}/update_parameter_view.html'.format(APP_NAME)
def get_object(self):
return Parameter.objects.get(id=int(self.kwargs['param_id']))
def get_success_url(self):
param = self.get_object()
url = '/main/config/{}'.format(param.configuration_id)
return url
def form_valid(self, form):
param = self.get_object()
if Parameter.objects.filter(configuration=param.configuration, name=form.data['name']).exists():
form.add_error('name', 'A parameter named "{}" already exists'.format(form.data['name']))
return self.form_invalid(form)
return super().form_valid(form)
class NewParamForm(forms.ModelForm):
class Meta:
model = Parameter
fields = ['name', 'type', 'configuration']
def clean(self):
cleaned_data = super().clean()
if cleaned_data['type'] == 'channel':
if cleaned_data['name'] not in CHANNEL_NAMES:
self.add_error(
'name',
'Allowed channel names: {}'.format(CHANNEL_NAMES)
)
else:
slug_name = slugify(cleaned_data['name']).replace('-', '_')
if cleaned_data['name'] != slug_name:
self.add_error('name', 'Name must be a slug like: \'{}\''.format(slug_name))
return cleaned_data
class NewParamView(CreateView):
form_class = NewParamForm
model = Parameter
# fields = ['name', 'type', 'configuration']
def get_form(self):
form = super().get_form()
form.fields['configuration'].widget = forms.HiddenInput()
form.fields['configuration'].initial = int(self.kwargs['config_id'])
return form
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['config_id'] = self.kwargs['config_id']
return context
def get_success_url(self):
return '/main/config/{}'.format(self.kwargs['config_id'])
class ResultForm(forms.Form):
def clean(self):
cleaned_data = super().clean()
cleaned_data.update(self.view.request.POST)
cleaned_data.update(self.view.kwargs)
path_uri = self.view.request.GET.get('path_uri')
parents, path, entries = path_getter(path_uri)
path_uri = path.parent.as_uri()
cleaned_data.update(path_uri=path_uri)
return cleaned_data
class TagResultView(FormView):
template_name = '{}/tag_result.html'.format(APP_NAME)
form_class = ResultForm
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._success_url = ''
def get_form(self):
form = super().get_form()
form.view = self
return form
def get_context_data(self, **kwargs):
context = super().get_context_data()
context.update(self.kwargs)
return context
def get_success_url(self):
return self._success_url
def form_valid(self, form):
self._success_url = '/main/config/{}?path_uri={}'.format(
form.cleaned_data['config_id'],
form.cleaned_data['path_uri']
)
return super().form_valid(form)
class TagForm(forms.Form):
def clean(self):
cleaned_data = self.cleaned_data
cleaned_data.update(dict(self.view.request.POST))
path_uri = self.view.request.GET.get('path_uri')
cleaned_data.update(path_uri=path_uri)
return cleaned_data
class TagFileView(FormView):
template_name = '{}/tag_file.html'.format(APP_NAME)
form_class = TagForm
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._success_url = ''
def get_success_url(self):
return self._success_url
def get_form(self):
form = super().get_form()
form.view = self
return form
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
path_uri = self.request.GET.get('path_uri')
parents, path, entries = path_getter(path_uri)
netcdf_file = path.parent.joinpath(path.name.replace(path.suffix, '.nc'))
context['csv_file'] = path
context['netcdf_file'] = netcdf_file
context['config_id'] = self.kwargs['config_id']
config_id = int(self.kwargs['config_id'])
context['params'] = Parameter.objects.filter(configuration_id=config_id).order_by(Lower('name'))
context['notes'] = Configuration.objects.get(id=config_id).notes
context['will_overwrite'] = netcdf_file.is_file()
return context
def form_valid(self, form):
# self._success_url = '/main/tag_file/{}/?path_uri={}'.format(
if 'create' in form.cleaned_data:
self._success_url = '/main/tag_result/{}/saved?path_uri={}'.format(
form.cleaned_data['config_id'][0],
form.cleaned_data['path_uri']
)
self.tag_file(form)
else:
self._success_url = '/main/tag_result/{}/canceled?path_uri={}'.format(
form.cleaned_data['config_id'][0],
form.cleaned_data['path_uri']
)
return super().form_valid(form)
def tag_file(self, form):
config = Configuration.objects.get(id=int(form.cleaned_data['config_id'][0]))
params = Parameter.objects.filter(configuration=config).as_dict()
path_uri = form.cleaned_data['path_uri']
parents, csv_file, entries = path_getter(path_uri)
params.update(notes=config.notes)
nc_file = pathlib.Path(csv_file.parent.joinpath(csv_file.stem + '.nc').as_posix())
data = Data()
data.csv_to_netcdf(csv_file.as_posix(), nc_file.as_posix(), **params)
class ParamForm(forms.Form):
type_map = {
'str': forms.CharField,
'int': forms.IntegerField,
'float': forms.FloatField,
'channel': forms.CharField,
}
def clean(self):
clean_data = super().clean()
error_dict = {}
for name, value in clean_data.items():
if name in CHANNEL_NAMES:
value_slug = slugify(value).replace('-', '_')
if value != value_slug:
error_dict[name] = 'Channel names must be slugs like: \'{}\''.format(value_slug)
for name, error in error_dict.items():
self.add_error(name, error)
clean_data['selected_file'] = self.request.POST.get('selected_file')
clean_data['current_path'] = self.request.POST.get('current_path')
clean_data.update(self.view.kwargs)
return clean_data
class ParamListView(FormView):
template_name = '{}/parameter_list.html'.format(APP_NAME)
form_class = ParamForm
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._success_url = ''
def get_success_url(self):
return self._success_url
def get_form(self):
form = super().get_form()
form.request = self.request
form.view = self
config = Configuration.objects.get(id=int(self.kwargs['config_id']))
form.view.populate_params(config)
self._success_url = '/main/config/{}'.format(config.id)
for param in self.params:
field_class = form.type_map[param.type]
form.fields[param.name] = field_class(
initial=param.value, label='({}) {}'.format(param.type.lower()[0], param.name), required=False)
# form.fields[param.name].is_param = True
form.fields['notes'] = forms.CharField(
initial=config.notes, required=False, widget=forms.Textarea(attrs={'style': 'height: 100%; width: 100%;'}))
return form
def populate_params(self, config):
if not hasattr(self, 'params'):
params = Parameter.objects.filter(configuration=config)
self.params = sorted(params, key=lambda p: (p.type != 'channel', p.name))
def populate_config(self):
if not hasattr(self, 'config'):
self.config = Configuration.objects.get(id=int(self.kwargs['config_id']))
def get_context_data(self, **kwargs):
self.populate_config()
path_uri = self.request.GET.get('path_uri')
parents, path, entries = path_getter(path_uri)
netcdf_entries = [e for e in entries if e.suffix == '.nc']
self.populate_params(self.config)
context = super().get_context_data(**kwargs)
context['config'] = self.config
context['current_path'] = path
context['entries'] = entries
context['netcdf_files'] = netcdf_entries
context['parents'] = parents
context['param_names'] = [p.name for p in self.params]
return context
def save_params_values(self, form):
self.populate_config()
self.populate_params(self.config)
# save notes
self.config.notes = form.cleaned_data['notes']
self.config.save()
param_names = {p.name for p in self.params}
# loop over all cleaned data items
for key, value in form.cleaned_data.items():
# if this is a parameter
if key in param_names:
# get the parameter object
param = Parameter.objects.get(configuration=self.config, name=key)
# save the new parameter value
param.value = value
param.save()
def tag_file_if_needed(self, cleaned_data):
path, file_name = cleaned_data['current_path'], cleaned_data['selected_file']
if path and file_name:
path = pathlib.Path(os.path.join(cleaned_data['current_path'], cleaned_data['selected_file']))
self._success_url = '/main/tag_file/{}/?path_uri={}'.format(
cleaned_data['config_id'],
path.as_uri(),
)
@transaction.atomic
def form_valid(self, form):
self.save_params_values(form)
self.tag_file_if_needed(form.cleaned_data)
return super().form_valid(form)
| {"/apps/main/views.py": ["/apps/main/models.py"], "/apps/main/urls.py": ["/apps/main/views.py"]} |
62,760 | brakettech/daq_server | refs/heads/master | /apps/main/models.py | from django.db import models, transaction
from django.contrib import admin
CHAR_LENGTH = 1000
TYPE_CHOICES = [
('str', 'String'),
('int', 'Integer'),
('float', 'Float'),
('channel', 'Channel'),
]
class Experiment(models.Model):
name = models.CharField(max_length=CHAR_LENGTH, unique=True)
class Meta:
ordering = ['name']
@transaction.atomic
def clone(self, new_name):
e = Experiment.objects.get(id=self.id)
configs = Configuration.objects.filter(experiment=e)
e.id = None
e.name = new_name
e.save()
for c in configs:
c.clone(e.id)
def __str__(self):
return self.name
class Configuration(models.Model):
name = models.CharField(max_length=CHAR_LENGTH)
experiment = models.ForeignKey('main.Experiment')
notes = models.TextField(null=True, blank=True)
class Meta:
unique_together = (('experiment', 'name'))
ordering = ['name']
@transaction.atomic
def clone(self, experiment_id=None, new_name=None):
if {experiment_id, new_name} == {None}:
raise ValueError('Must supply either experiment_id or new_name')
c = Configuration.objects.get(id=self.id)
if experiment_id is None:
experiment_id = c.experiment_id
if new_name is not None:
c.name = new_name
params = Parameter.objects.filter(configuration=c)
c.id = None
c.experiment_id = experiment_id
c.save()
for p in params:
p.clone(c.id)
def __str__(self):
return self.name
class ParameterQueryset(models.QuerySet):
def as_dict(self):
return {m.name: m.value for m in self}
class ParameterManager(models.Manager):
def get_queryset(self):
return ParameterQueryset(self.model)
class Parameter(models.Model):
configuration = models.ForeignKey('main.Configuration')
name = models.CharField(max_length=CHAR_LENGTH)
value = models.CharField(max_length=CHAR_LENGTH, null=True)
type = models.CharField(max_length=CHAR_LENGTH, choices=TYPE_CHOICES)
def clone(self, config_id):
p = Parameter.objects.get(id=self.id)
p.id = None
p.configuration_id = config_id
p.save()
class Meta:
unique_together = (('configuration', 'name'))
ordering = ['name']
def __str__(self):
return self.name
objects = ParameterManager()
class TabularInlineBase(admin.TabularInline):
def has_change_permission(self, request, obj=None):
return True
def has_add_permission(self, request):
return True
def has_delete_permission(self, request, obj=None):
return True
def get_extra(self, request, obj=None, **kwargs):
return 0
def show_change_link(self):
return True
class ParameterInlineAdmin(TabularInlineBase):
model = Parameter
class ConfigurationInlineAdmin(TabularInlineBase):
model = Configuration
@admin.register(Configuration)
class ConfigurationAdmin(admin.ModelAdmin):
inlines = [
ParameterInlineAdmin,
]
@admin.register(Experiment)
class ExperimentAdmin(admin.ModelAdmin):
inlines = [
ConfigurationInlineAdmin,
]
| {"/apps/main/views.py": ["/apps/main/models.py"], "/apps/main/urls.py": ["/apps/main/views.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.