def createPDF(timePeriod, cycleId, term): if term != 0: idealTermCourses = IdealTermCourse.find(idCycle=cycleId, term=term) year = int(term / 2) + int(term) % 2 else: idealTermCourses = IdealTermCourse.find(idCycle=cycleId) year = "Todos" courses = [idealTermCourse.course for idealTermCourse in idealTermCourses] allOffers = [] for course in courses: offers = Offer.find(course=course, timePeriod=timePeriod) allOffers.append(offers) coursesTuple = zip(courses, allOffers) faculty = Faculty.find(courseCoordinations=CourseCoordination.find( cycles=[Cycle.pickById(cycleId)]))[0] path = settings.MEDIA_ROOT + 'pdf/' title = {} title['lines'] = [] title['lines'].append('Consulta discente sobre o Ensino(CDE)') title['lines'].append( str(timePeriod) + ' da ' + faculty.name + u' de Sao Paulo') title['lines'].append('Representante de Classe ' + str(year) + u'º ano - ' + Cycle.pickById(cycleId).name) name = "".join(letter for letter in str(timePeriod) if ord(letter) < 128).replace(' ', '') name += "_" name += "".join(letter for letter in Cycle.pickById(cycleId).name if ord(letter) < 128).replace(' ', '') name += "_" name += str(term) + "_Semestre" name = name.replace( '/', '_') #Bugfix - Names with '/' do not go well in an Unix environment t = render_to_string('texFiles/offersList.tex', Context({ 'courses': coursesTuple, 'title': title })) l = io.open(str(path) + str(name) + ".tex", "w", encoding='utf8') l.write(t) l.close() commands.getoutput("pdflatex -interaction=nonstopmode -output-directory=" + str(path) + " " + str(path) + str(name) + '.tex') commands.getoutput("rm " + str(path) + str(name) + '.log') commands.getoutput("rm " + str(path) + str(name) + '.aux') pdf = file(str(path) + str(name) + '.pdf').read() commands.getoutput("rm " + str(path) + str(name) + '.tex') commands.getoutput("rm " + str(path) + str(name) + '.pdf') response = HttpResponse(pdf) response['Content-Type'] = 'application/pdf' response['Content-disposition'] = 'attachment; filename=' + name + '.pdf' return response
def generateCourses(request): data = request.GET idCourses = json.loads(data['idCourses']) #Do something with this list idCourses = [int(idCourse) for idCourse in idCourses] if int(data['useProfessorsName']) == 1: useProfessorsName = True else: useProfessorsName = False if int(data['byOffer']) == 1: byOffer = 1 elif int(data['byOffer']) == 2: byOffer = 2 elif int(data['byOffer']) == 0: byOffer = 0 idTimePeriod = int(data['idTimePeriod']) idFaculty = int(data['idFaculty']) assessmentNumber = int(data['assessmentNumber']) user= request.user user_name = request.user.username time = get_time() timePeriod = str(TimePeriod.pickById(idTimePeriod)) courses = [str(Course.pickById(idCourse).courseCode) for idCourse in idCourses] cycle = Cycle.pickById(int(data['idCycle'])).name action = u"Usuário " + str(user_name) + u" gerou relatório: " \ + u"{ Curso: " + cycle \ + u"; Semestre: " + data['term'] \ + u"; Matérias: " + str(courses) \ + u"; Período: " + timePeriod \ + u"; Avaliação: " + data['assessmentNumber'] + " }" report_generate_log = Log(user=user, action=action, time=time) report_generate_log.save() CourseReportGenerator(idTimePeriod, idCourses, useProfessorsName, byOffer, idFaculty, assessmentNumber) return HttpResponse('Relatórios Gerados')
class CrawlerForm(forms.Form): cycles = Cycle.find() timePeriods = TimePeriod.find(year=datetime.datetime.now().year) for cycle in cycles: cycle.completeMandatoryIdealTerms() cycleTuple = ((cycle.idCycle, cycle.name + ' - ' + cycle.dayPeriod + ' - id: ' + str(cycle.idCycle)) for cycle in cycles if len(cycle.mandatoryIdealTerms)) timePeriodTuple = ((timePeriod.idTimePeriod, str(timePeriod)) for timePeriod in timePeriods) cycle = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=cycleTuple, label='Ciclo') timePeriod = forms.ChoiceField(choices=timePeriodTuple, label='Período')
def createPDF(timePeriod, cycleId, term): if term != 0: idealTermCourses = IdealTermCourse.find(idCycle=cycleId, term=term) year = int(term/2) + int(term)%2 else: idealTermCourses = IdealTermCourse.find(idCycle=cycleId) year = "Todos" courses = [idealTermCourse.course for idealTermCourse in idealTermCourses] allOffers = [] for course in courses: offers = Offer.find(course=course, timePeriod=timePeriod) allOffers.append(offers) coursesTuple = zip(courses, allOffers) faculty = Faculty.find(courseCoordinations = CourseCoordination.find(cycles = [Cycle.pickById(cycleId)]))[0] path = settings.MEDIA_ROOT + 'pdf/' title = {} title['lines'] = [] title['lines'].append('Consulta discente sobre o Ensino(CDE)') title['lines'].append(str(timePeriod) + ' da ' + faculty.name + u' de Sao Paulo') title['lines'].append('Representante de Classe ' + str(year) + u'º ano - ' + Cycle.pickById(cycleId).name) name = "".join(letter for letter in str(timePeriod) if ord(letter)<128).replace(' ','') name += "_" name += "".join(letter for letter in Cycle.pickById(cycleId).name if ord(letter)<128).replace(' ','') name += "_" name += str(term) + "_Semestre" name = name.replace('/','_') #Bugfix - Names with '/' do not go well in an Unix environment t = render_to_string('texFiles/offersList.tex', Context({'courses': coursesTuple, 'title': title})) l = io.open(str(path) + str(name) + ".tex", "w", encoding='utf8') l.write(t) l.close() commands.getoutput("pdflatex -interaction=nonstopmode -output-directory=" + str(path) + " " + str(path) + str(name) + '.tex') commands.getoutput("rm " + str(path) + str(name) + '.log') commands.getoutput("rm " + str(path) + str(name) + '.aux') pdf = file(str(path) + str(name) + '.pdf').read() commands.getoutput("rm " + str(path) + str(name) + '.tex') commands.getoutput("rm " + str(path) + str(name) + '.pdf') response = HttpResponse(pdf) response['Content-Type'] = 'application/pdf' response['Content-disposition'] = 'attachment; filename=' + name + '.pdf' return response
def updateForm(self): timePeriods = TimePeriod.find() timePeriods.reverse() timePeriodNames = [str(timePeriod) for timePeriod in timePeriods] timePeriodIds = [t.idTimePeriod for t in timePeriods] timePeriodInfo = zip(timePeriodIds, timePeriodNames) cycles = Cycle.find() cycleName = [cycle.name for cycle in cycles] cycleIds = [cycle.idCycle for cycle in cycles] cycleInfo = zip(cycleIds, cycleName) termInfo = [[0,"Todos"],[1,'1º Semestre'],[2,'2º Semestre'],[3,'3º Semestre'],[4,'4º Semestre'],[5,'5º Semestre'],[6,'6º Semestre'],[7,'7º Semestre'],[8,'8º Semestre'],[9,'9º Semestre'],[10,'10º Semestre']] self.fields['dropDownCycle'] = forms.ChoiceField(widget=forms.Select, choices=cycleInfo, label = 'Curso') self.fields['dropDownTimePeriod'] = forms.ChoiceField(widget=forms.Select, choices=timePeriodInfo, label = 'Periodo') self.fields['dropDownTerm'] = forms.ChoiceField(widget=forms.Select, choices=termInfo, label = 'Semestre')
def fillPossibleOffers(self, idCycle, term): cycle = Cycle.pickById(idCycle) cycle.completeMandatoryIdealTerms() cycle.completeElectiveIdealTerms() possibleCourses = [] for term in cycle.mandatoryIdealTerms: for course in cycle.mandatoryIdealTerms[term]: possibleCourses.append(course) for term in cycle.electiveIdealTerms: for course in cycle.electiveIdealTerms[term]: possibleCourses.append(course) for idealTermCourse in possibleCourses: for offer in Offer.find(course = idealTermCourse.course, timePeriod = TimePeriod.pickById(self.idTimePeriod)): self.possibleOffers.append(offer)
def __init__(self, idTimePeriod, idCycle, term): """ Initialization method. @param int idTimPeriod : The database id of the timePeriod if this QualitativeQuestionnaire. @param int idCycle : The database id of the cycle if this QualitativeQuestionnaire. @param int term : The term this QualitativeQuestionnaire. @return : @author """ Printer.__init__(self) self.cycle = Cycle.pickById(idCycle) self.timePeriod = TimePeriod.pickById(idTimePeriod) self.term = term self.createName()
def __init__(self,idCycle, term, idTimePeriod): """ Initialization method. @param int idTimPeriod : The database id of the timePeriod if this QualitativeQuestionnaire. @param int idCycle : The database id of the cycle if this QualitativeQuestionnaire. @param int term : The term this QualitativeQuestionnaire. @return : @author """ Printer.__init__(self) self.timePeriod = TimePeriod.pickById(idTimePeriod) self.cycle = Cycle.pickById(idCycle) self.term = term self.createName()
def store(request): data = request.POST data = json.loads(data['json']) user= request.user user_name = request.user.username time = get_time() cycle_name = Cycle.pickById(int(data['idCycle'])).name timePeriod = str(TimePeriod.pickById(int(data['idTimePeriod']))) response = OpticalSheetController.storeOpticalSheet(data['idOpticalSheet'], data['surveyType'], data['idCycle'], data['term'], data['idTimePeriod'], data['fields'], data['surveys'], data['encoded']) action = u"Usuário " + str(user_name) + u" salvou idOpticalSheet " + str(data['idOpticalSheet']) \ + u" { Periodo: " + timePeriod \ + u"; Curso: " + cycle_name \ + u"; Semestre: " + str(data['term']) + " }" opticalSheet_store_log = Log(user=user, action=action, time=time) opticalSheet_store_log.save() return HttpResponse(json.dumps(response))
def store(request): data = request.POST data = json.loads(data['json']) user = request.user user_name = request.user.username time = get_time() cycle_name = Cycle.pickById(int(data['idCycle'])).name timePeriod = str(TimePeriod.pickById(int(data['idTimePeriod']))) response = OpticalSheetController.storeOpticalSheet( data['idOpticalSheet'], data['surveyType'], data['idCycle'], data['term'], data['idTimePeriod'], data['fields'], data['surveys'], data['encoded']) action = u"Usuário " + str(user_name) + u" salvou idOpticalSheet " + str(data['idOpticalSheet']) \ + u" { Periodo: " + timePeriod \ + u"; Curso: " + cycle_name \ + u"; Semestre: " + str(data['term']) + " }" opticalSheet_store_log = Log(user=user, action=action, time=time) opticalSheet_store_log.save() return HttpResponse(json.dumps(response))
def openSite(request): header = Header() header.setTermFunction('$("#file").show()') if request.method == 'POST': data = request.POST NoteReader.readNote(request.FILES['arq'].name, request.FILES['arq'].file.getvalue(),int(data['headerCycle']), int(data['headerTerm']), int(data['headerTimePeriod']), int(data['bSheet']), int(data['assessmentNumber'])) user= request.user user_name = request.user.username time = get_time() cycle_name = Cycle.pickById(int(data['headerCycle'])).name timePeriod = str(TimePeriod.pickById(int(data['headerTimePeriod']))) b_sheet = "A" if int(data['bSheet']) == 0 else "B" action = u"Usuário " + str(user_name) + " inseriu datafile " + request.FILES['arq'].name \ + u" { Curso: " + cycle_name \ + u"; Semestre: " + data['headerTerm'] \ + u"; Período: " + timePeriod \ + u"; Folha(A ou B): " + b_sheet \ + u"; Avaliação: " + data['assessmentNumber'] + " }" datafile_insert_log = Log(user=user, action=action, time=time) datafile_insert_log.save() return render_to_response('datafile.html',{'divs':header.getHtml()},context_instance=RequestContext(request))
def generateCourses(request): data = request.GET idCourses = json.loads(data['idCourses']) #Do something with this list idCourses = [int(idCourse) for idCourse in idCourses] if int(data['useProfessorsName']) == 1: useProfessorsName = True else: useProfessorsName = False if int(data['byOffer']) == 1: byOffer = 1 elif int(data['byOffer']) == 2: byOffer = 2 elif int(data['byOffer']) == 0: byOffer = 0 idTimePeriod = int(data['idTimePeriod']) idFaculty = int(data['idFaculty']) assessmentNumber = int(data['assessmentNumber']) user = request.user user_name = request.user.username time = get_time() timePeriod = str(TimePeriod.pickById(idTimePeriod)) courses = [ str(Course.pickById(idCourse).courseCode) for idCourse in idCourses ] cycle = Cycle.pickById(int(data['idCycle'])).name action = u"Usuário " + str(user_name) + u" gerou relatório: " \ + u"{ Curso: " + cycle \ + u"; Semestre: " + data['term'] \ + u"; Matérias: " + str(courses) \ + u"; Período: " + timePeriod \ + u"; Avaliação: " + data['assessmentNumber'] + " }" report_generate_log = Log(user=user, action=action, time=time) report_generate_log.save() CourseReportGenerator(idTimePeriod, idCourses, useProfessorsName, byOffer, idFaculty, assessmentNumber) return HttpResponse('Relatórios Gerados')
def setcycle(self, idcycle): "Sets the cycle of this reader by searching for the cycle in the bank" self.cycle = Cycle.pickById(idcycle) self.offerreader.cycle = self.cycle
def findOpticalSheetByTimePeriod_Cycle_Term(idTimePeriod, idCycle, term): """ Returns the getOpticalSheetData of the opticalSheet belonging to the given idTimePeriod, idCycle and term. If the number of opticalSheets found by those parameters is different than 1 the return is the number of opticalSheets found. @param int idTimePeriod : The database id of the timePeriod of the wanted opticalSheet. @param int idCycle : The database id of the cycle of the wanted opticalSheet. @param int term : The term of the wanted opticalSheet. @return [] : @author """ opticalSheet = OpticalSheet.find(timePeriod = TimePeriod.pickById(idTimePeriod), cycles = [Cycle.pickById(idCycle)], term = term) if len(opticalSheet) != 1: return len(opticalSheet) opticalSheet = opticalSheet[0] return OpticalSheetController.getOpticalSheetData(opticalSheet)
def storeOpticalSheet(idOpticalSheet, surveyType, idCycle, term, idTimePeriod, fields, surveys, encoded): """ Tries to store the opticalSheet and returns a mensage explaning what happend. @param int idOpticalSheet : Id of the opticalSheet to be store, if it is a new one it should be None. @param string surveyType : A string defining the type of the opticalSheets survey, must be in minitableSurveyType. @param int idCycle : The database id of the cycle to be added in this opticalSheet, it can't be None, it is ok if this cycle is alredy related to this opticalSheet. @param int term : Term to be added in the relation cycle opticalSheet . @param int idTimePeriod : Database id of the timePeriod in which this opticalSheet exist. @param [] fields : If not encoded: A list of dicts, where each dict represent a field and contain the keys: idsOffer, courseIndex, abbreviation, idCourse. Else is just the encoding name @param [] surveys : A list of dicts where each dict represents a survey with the keys: assessmentNumber, idQuestionnaire: None or the IdQuestionnaire, questions: [{questionWording, questionIndex} @param string encoded : A boolean to define if this opticalSheet is encoded @return string: @author """ timePeriod = TimePeriod.pickById(idTimePeriod) cycle = Cycle.pickById(idCycle) storedFields = False storedQuestionnaire = False if idOpticalSheet != None: opticalSheet = OpticalSheet.pickById(idOpticalSheet) if opticalSheet.surveyType != surveyType: raise OpticalSheetError("ERROR: Given surveyType is different than opticalSheet's surveyType.") #clear opticalSheets surveys opticalSheet.surveys = [] else: #Before creating a new one check if it already exist if encoded: if len(OpticalSheet.find(encodingName = fields)) > 0: raise OpticalSheetError("There can only be one opticalSheet per encoding!") if len(OpticalSheet.find(cycles = [cycle], term = term, timePeriod = timePeriod)) > 0: #Even encoded opticalSheets have to pass through this raise OpticalSheetError("There can be only one opticalSheet per cycle, term and timePeriod") #Now it is ok to store opticalSheet = OpticalSheet(surveyType) if encoded: opticalSheet.setEncodingName(fields) opticalSheet.store() hasAnswers = False answers = Answer.countAnswers(opticalSheet = opticalSheet) for key in answers: if answers[key] > 0: hasAnswers = True if not hasAnswers: #Can't alter offers with answers #First deal with the fields if not encoded: for field in fields: idsOffer = [int(offer) for offer in field['idOffers']] if len(idsOffer) > 0: course = Course.pickById(field['idCourse']) abbreviation = field['abbreviation'].split('(')[0].split('[')[0] course.setAbbreviation(abbreviation) course.store() opticalSheet.addOpticalSheetField(Offer.find(idOffer = idsOffer), int(field['courseIndex']) + 1) else: opticalSheet.removeOpticalSheetField(int(field['courseIndex']) + 1) print field['courseIndex'] storedFields = True #Next the cycle if not {'term':term, 'cycle':cycle} in opticalSheet.cycles: opticalSheet.addCycle_Term(cycle, term) for survey in surveys: hasAnswers = False answers = Answer.countAnswers(opticalSheet = opticalSheet, assessmentNumber = survey['assessmentNumber']) for key in answers: if answers[key] > 0: hasAnswers = True if not hasAnswers: #Can't alter a survey with answers #prepare the questionDict questionDict = {} for questionData in survey['questions']: if questionData['idQuestion'] != None: question = Question.pickById(questionData['idQuestion']) questionDict[int(questionData['questionIndex']) + 1] = question #Create or find the questionnaire if survey['idQuestionnaire'] != None: questionnaire = Questionnaire.pickById(survey['idQuestionnaire']) #If the questionnaire exist update its questions if questionnaire.questions != questionDict: questionnaire.questions = questionDict questionnaire.store() else: #Create it if encoded: #this is only to know the questionnaire's discription questionnaire = Questionnaire(questionDict, fields + str(timePeriod)) else: questionnaire = Questionnaire(questionDict, cycle.name + '-' + str(term) + '-' + str(timePeriod)) questionnaire.store() #Now remove old survey of this assessment in this opticalSheet (this method works even if there are no surveys in this opticalSheet) opticalSheet.removeSurvey(survey['assessmentNumber']) opticalSheet.addSurvey(questionnaire, survey['assessmentNumber']) storedQuestionnaire = True if storedQuestionnaire or storedFields: opticalSheet.store() if storedFields: return 'OpticalSheet was stored' elif storedQuestionnaire: return 'Only Questionnaire was stored' else: raise OpticalSheetError("Can't save a opticalSheet with answers in the same assessment!!")