from bika.lims.workflow import in_state from bika.lims.workflow.analysis import STATE_RETRACTED, STATE_REJECTED from zope.interface import implements # A reference back to the original analysis from which this one was duplicated. Analysis = UIDReferenceField( 'Analysis', required=1, allowed_types=('Analysis', 'ReferenceAnalysis'), ) # TODO Analysis - Duplicates shouldn't have this attribute, only ReferenceAns ReferenceAnalysesGroupID = StringField('ReferenceAnalysesGroupID', ) schema = schema.copy() + Schema(( Analysis, ReferenceAnalysesGroupID, )) class DuplicateAnalysis(AbstractRoutineAnalysis): implements(IDuplicateAnalysis) security = ClassSecurityInfo() displayContentsTab = False schema = schema @security.public def getRequest(self): """Returns the Analysis Request of the original analysis. """ analysis = self.getAnalysis() if analysis:
# Copyright 2018-2019 by it's authors. # Some rights reserved, see README and LICENSE. from AccessControl.SecurityInfo import ClassSecurityInfo from Products.Archetypes.public import BaseFolder from Products.Archetypes.public import DisplayList from Products.Archetypes.public import Schema from Products.Archetypes.public import registerType from Products.CMFCore.utils import getToolByName from bika.lims.config import PROJECTNAME from bika.lims.content.bikaschema import BikaSchema from bika.lims.interfaces import IDeactivable from zope.interface import implements schema = BikaSchema.copy() + Schema(( )) schema['description'].schemata = 'default' schema['description'].widget.visible = True class SampleCondition(BaseFolder): implements(IDeactivable) security = ClassSecurityInfo() displayContentsTab = False schema = schema _at_rename_after_creation = True def _renameAfterCreation(self, check_auto_id=False):
from zope.interface import implements from bika.lims import api from bika.lims.config import PROJECTNAME from bika.lims.config import STD_TYPES from bika.lims.content.abstractanalysis import AbstractAnalysis from bika.lims.content.abstractanalysis import schema from bika.lims.content.analysisspec import ResultsRangeDict from bika.lims.interfaces import IReferenceAnalysis schema = schema.copy() + Schema(( StringField( "ReferenceType", vocabulary=STD_TYPES, ), BlobField( "RetractedAnalysesPdfReport", ), StringField( "ReferenceAnalysesGroupID", ) )) class ReferenceAnalysis(AbstractAnalysis): """Reference Analysis Content """ implements(IReferenceAnalysis) security = ClassSecurityInfo() schema = schema @security.public
class QuestionResult(ATFolder): """A results to a specific question for a student taking a specific quiz.""" schema = ATFolderSchema.copy() + Schema(( StringField('title', required=True, searchable=0, default='Result to question', widget=StringWidget( label='Title', description='The main title of the tutorial.', i18n_domain='plone'), ), StringField('chosenquestid', default='', widget=StringWidget(description='id of chosen quiz question', visible={'edit':'invisible', 'view':'invisible',}, ), ), StringField('chosenquestpath', default='', widget=StringWidget(description='path to where question comes from', visible={'edit':'invisible','view':'invisible'}, ), ), BooleanField('openquest', default=0, widget=BooleanWidget(description='True if student already has requested a question but not answered it.', visible={'edit':'invisible','view':'invisible'}, ), ), StringField('anslist', default='0', widget=StringWidget(description='The students selected answer.', visible={'edit':'invisible','view':'invisible'}, ), ), StringField('candidateans', default='-1', widget=StringWidget(description='the students submitted answer', visible={'edit':'invisible', 'view':'invisible'}, ), ), StringField('suggestedans', default='', widget=StringWidget(description='Suggested answers to student.', visible={'edit':'invisible', 'view':'invisible'}, ), ), StringField('correctans', default='', widget=StringWidget(description='correctanswer.', visible={'edit':'invisible', 'view':'invisible'}, ), ), StringField('lecturepath', default='', widget=StringWidget(description='lecture quiz path.', visible={'edit':'invisible', 'view':'invisible'}, ), ), StringField('studid', default='', widget=StringWidget(description='id of student.', visible={'edit':'invisible', 'view':'invisible'}, ), ), StringField('timeofquest', default='', widget=StringWidget(description='time when student gets question.', visible={'edit':'invisible', 'view':'invisible'}, ), ), StringField('quizresultinfo', default='', widget=StringWidget(description='Result of quiz for logging purposes.', visible={'edit':'invisible','view':'invisible' }, ), ), )) __implements__ = (ATFolder.__implements__) implements(IQuestionResult) global_allow = False meta_type = 'QuestionResult' # zope type name portal_type = meta_type # plone type name archetype_name = 'QuestionResult' # friendly type name #_at_rename_after_creation = True #automatically create id security = ClassSecurityInfo() #chosenquestionid = '' chosenquestionid = atapi.ATFieldProperty('chosenquestid') #chosenquestionpath = '' chosenquestionpath = atapi.ATFieldProperty('chosenquestpath') #openquestion = False openquestion = atapi.ATFieldProperty('openquest') NO_ANSWER = ['-1'] # an arbitrary object # the student's selected answer #answerlist = '0' answerlist = atapi.ATFieldProperty('anslist') # the students submitted answer #candidateAnswer = ['-1'] candidateAnswer = atapi.ATFieldProperty('candidateans') # the answers the student got #suggestedAnswer = [] suggestedAnswer = atapi.ATFieldProperty('suggestedans') #correct = [] correct = atapi.ATFieldProperty('correctans') lecquizpath = atapi.ATFieldProperty('lecturepath') studentid = atapi.ATFieldProperty('studid') #timenow = strftime("%d-%m-%Y %H:%M:%S") timenow = atapi.ATFieldProperty('timeofquest') quizinfo = atapi.ATFieldProperty('quizresultinfo') #def __init__(self, oid=None, **kwargs): # self.changed = True # ATFolder.__init__(self, oid, **kwargs) def setLecPath(self, p): self.lecquizpath = p def setNewQuestion(self, suggestedanswer, correctids, questpath, qid): '''set new question info''' #self.suggestedAnswer = suggestedanswer tmp = '' counter = 0 num = len(suggestedanswer) while (counter < num): tmp = tmp + suggestedanswer[counter] if (counter < num-1): tmp = tmp + '\t' else: tmp = tmp counter = counter + 1 self.setSuggestedans(tmp) #self.chosenquestionpath = questpath self.setChosenquestpath(questpath) #self.timenow = strftime("%d-%m-%Y %H:%M:%S") #self.setTimeofquest(strftime("%d-%m-%Y %H:%M:%S")) self.setTimeofquest(datetime.now()) #self.openquestion = True self.setOpenquest(1) #self.chosenquestionid = qid self.setChosenquestid(qid) #self.correct = correctids tmp = '' counter = 0 num = len(correctids) while (counter < num): tmp = tmp + correctids[counter] if (counter < num-1): tmp = tmp + '\t' else: tmp = tmp counter = counter + 1 self.setCorrectans(tmp) self.setQuizresultinfo(self.getStudid() + '\t' + str(self.getTimeofquest()) + '\t' + ('/'.join(self.getLecturepath())) + '\t' + ('/'.join(self.getChosenquestpath())) + '\t' + "['"+ str(self.getCorrectans())+"']" + '\t') #self.writetolog() def getQuestionId(self): #return self.chosenquestionid return self.getChosenquestid() def setStudentId(self, sid): #self.studentid = sid self.setStudid(sid) def getQuizInfo(self): return self.getQuizresultinfo() def getCorrectAnswer(self): #return self.correct return self.getCorrectans().split('\t') def gotAnswer(self): #self.openquestion = False self.setOpenquest(0) self.reindexObject() ##self._p_changes = True #self.writetolog() security.declareProtected(PERMISSION_STUDENT, 'writetolog') def writetolog(self): # FIXME !!!! # add code to check if dir exists and then create.. logdir = productdir + '/log' if (not (os.path.exists(logdir))): os.mkdir(logdir) f = open(logdir+'/questionandanswer.txt','a') #qr = self.getStudentQuestionResult() #qresults = self.getFolderContents(contentFilter={"portal_type": "QuestionResult"}) #qr = qresults[0].getObject() text = self.getQuizInfo() text = text + str(datetime.now()) + "\n" f.write(text) f.close() def hasSubmittedQuestion(self): #return self.openquestion return self.getOpenquest() def setSelectedAnswer(self, value): #self.answerlist = value self.setAnslist(value) self.reindexObject() def getSelectedAnswer(self): #return self.answerlist return self.getAnslist() def getSuggestedAnswer(self): #return self.suggestedAnswer tempa = self.getSuggestedans() return self.getSuggestedans().split('\t') def getCandidateAnswer(self): #return self.candidateAnswer return self.getCandidateans().split('\t') def updateDatabase(self, new, origquestion): '''write quiz information to database''' # start by finding student information studlocator = getUtility(IStudentLocator) studentinfo = studlocator.student_by_randomnumber(self.getStudid()) if (not studentinfo): '''student has not been added database''' email = 'not known' firstname = '' familyname = '' loginname = '' membership = self.portal_membership member = membership.getAuthenticatedMember() if member: loginname = member.getUserName() email = member.getProperty('email') fullname = member.getProperty('fullname') tempname = fullname.split() if (len(tempname) > 1): familyname = tempname[1] firstname = tempname[0] elif (len(tempname) == 1): familyname = fullname student = StudentInformation(loginname, self.getStudid(), firstname, familyname, email) student.addToDataBase() # now find the student just added studentinfo = studlocator.student_by_randomnumber(self.getStudid()) # find the question from the database questlocator = getUtility(IQuestionLocator) questioninfo = questlocator.question_by_uid(self.getChosenquestid()) if (not questioninfo): '''question has not been added to database''' qpath = '/'.join(self.getChosenquestpath()) # number of time askefor has already been updated # will be updated again in TakeQuiz, so subtract by one try: int(self.getCorrectans()) corrans = int(self.getCorrectans()) except: #just setting coorect answer to BIG number, indicating error in the database' corrans = 333 question = QuestionInformation(qpath, (origquestion.numaskedfor-1), origquestion.numcorrect, corrans, self.getChosenquestid()) question.addToDataBase() # get the newly added question questioninfo = questlocator.question_by_uid(self.getChosenquestid()) # also add question to question-modification table qm = QuestionModification(questioninfo.question_id, datetime.now()) qm.addToDataBase() # now add the quiz info takequiz = getUtility(ITakeQuiz) takequiz(QuizInformation(studentinfo, questioninfo, ('/'.join(self.getLecturepath())), self.getTimeofquest(), new, datetime.now())) def setCandidateAnswer(self, new, origquestion): '''update candidate answer and write information to database''' temp = '' num = len(new) counter = 0 l = self.getSuggestedans().split('\t') while (counter < num): if new[counter] == "no answer": temp = temp + new[counter] else: temp = temp + l[int(new[counter])-1] #temp = temp + new[counter] if (counter < num-1): temp = temp + '\t' else: temp = temp counter = counter + 1 #tmpout = tempfile.mkdtemp() #tex_fd, tex_absname = tempfile.mkstemp(dir=tmpout, suffix='.setCandidateAns') #os.write(tex_fd, 'Set answer from quiz\n') #os.write(tex_fd, temp) ##transaction.begin() if self.getCandidateans() != temp: self.setCandidateans(temp) self.setQuizresultinfo(self.getStudid() + '\t' + str(self.getTimeofquest()) + '\t' + ('/'.join(self.getLecturepath())) + '\t' + ('/'.join(self.getChosenquestpath())) + '\t' + "['" + str(self.getCorrectans()) + "']" + '\t' + '['+ temp + ']' + '\t') self.reindexObject() # need to write to database if new[0] == "no answer": self.updateDatabase(new, origquestion) else: self.updateDatabase(str(l[int(new[0])-1]), origquestion) ##transaction.commit() def unsetCandidateAnswer(self): #self.setCandidateAnswer(self.NO_ANSWER) self.setCandidateans('-1') self.reindexObject() def haveCandidateAnswer(self): #return self.candidateAnswer is not self.NO_ANSWER return self.getCandidateans() is not '-1'
from Products.Archetypes.public import (Schema, StringField, StringWidget, registerType) schema = Schema(( StringField( name='topic', required=True, widget=StringWidget( label='Topics', label_msgid='eea.soer_label_topics', i18n_domain='eea.soer', description='use any environmental term, you can find all terms at'\ ' <a href="http://glossary.eea.europa.eu/">ETDS</a>' ), ), StringField( name='question', required=True, widget=StringWidget( label='Title', label_msgid='eea.soer_label_questions', i18n_domain='eea.soer', description='Custom title for this report', ), ), ), ) schema = getattr(SOERReport, 'schema').copy() + schema.copy() schema['title'].required = False
CommonEditSchema = Schema(( StringField('title', schemata="default", required=True, widget=StringWidget( size=25, label=_(u"Friendly name"), description=_(u"Title for widget to display in view page"), )), StringField('position', schemata="layout", vocabulary_factory="eea.faceted.vocabularies.WidgetPositions", widget=SelectionWidget( format='select', label=_(u'Position'), description=_(u"Widget position in page"), )), StringField('section', schemata="layout", vocabulary_factory="eea.faceted.vocabularies.WidgetSections", widget=SelectionWidget( format='select', label=_(u"Section"), description=_("Display widget in section"), )), BooleanField('hidden', schemata="layout", widget=BooleanWidget( label=_(u'Hidden'), description=_(u"Hide widget"), )), ))
schema = BikaSchema.copy() + Schema(( StringField( "Salutation", widget=StringWidget( label=_("Salutation"), description=_("Greeting title eg. Mr, Mrs, Dr"), ), ), StringField( "Firstname", required=1, widget=StringWidget( label=_("Firstname"), ), ), StringField( "Middleinitial", required=0, widget=StringWidget( label=_("Middle initial"), ), ), StringField( "Middlename", required=0, widget=StringWidget( label=_("Middle name"), ), ), StringField( "Surname", required=1, widget=StringWidget( label=_("Surname"), ), ), ComputedField( "Fullname", expression="context.getFullname()", searchable=1, widget=ComputedWidget( label=_("Full Name"), visible={"edit": "invisible", "view": "invisible"}, ), ), StringField( "Username", widget=StringWidget( visible=False ), ), StringField( "EmailAddress", schemata="Email Telephone Fax", searchable=1, widget=StringWidget( label=_("Email Address"), ), validators=("isEmail", ) ), StringField( "BusinessPhone", schemata="Email Telephone Fax", widget=StringWidget( label=_("Phone (business)"), ), ), StringField( "BusinessFax", schemata="Email Telephone Fax", widget=StringWidget( label=_("Fax (business)"), ), ), StringField( "HomePhone", schemata="Email Telephone Fax", widget=StringWidget( label=_("Phone (home)"), ), ), StringField( "MobilePhone", schemata="Email Telephone Fax", widget=StringWidget( label=_("Phone (mobile)"), ), ), StringField( "JobTitle", widget=StringWidget( label=_("Job title"), ), ), StringField( "Department", widget=StringWidget( label=_("Department"), ), ), AddressField( "PhysicalAddress", schemata="Address", widget=AddressWidget( label=_("Physical address"), ), ), ComputedField( "City", expression="context.getPhysicalAddress().get('city')", searchable=1, widget=ComputedWidget( visible=False ), ), ComputedField( "District", expression="context.getPhysicalAddress().get('district')", searchable=1, widget=ComputedWidget( visible=False ), ), ComputedField( "PostalCode", expression="context.getPhysicalAddress().get('postalCode')", searchable=1, widget=ComputedWidget( visible=False ), ), ComputedField( "Country", expression="context.getPhysicalAddress().get('country')", searchable=1, widget=ComputedWidget( visible=False ), ), AddressField( "PostalAddress", schemata="Address", widget=AddressWidget( label=_("Postal address"), ), ), ))
class QuizResult(ATFolder): """Keeps together all the questions results for a specific student from a quiz in a specific lecture.""" schema = ATFolderSchema.copy() + Schema(( StringField('title', required=True, searchable=0, default='Quiz result', widget=StringWidget( label='Title', description='The main title of the tutorial.', i18n_domain='plone'), ), BooleanField('openquest', default=0, widget=BooleanWidget(visible={'edit':'invisible', 'view':'invisible'}, ),), BooleanField('haveanswer', default=0, widget=BooleanWidget(visible={'edit':'invisible', 'view':'invisible'}, ), ), ImageField('CurrentQuestionImage', #original_size=(600,600), #max_size=(600,600), sizes={ 'mini' : (80,80), 'normal' : (200,200), 'big' : (100,100), 'maxi' : (500,500), }, widget=ImageWidget(label='quis question image', description='Image for the current question, displayed to the right of main text of the slide. Possible formats for uploaded images are: png, gif and jpeg.', #macro='tutorwebimage', # condition ='object/isImageFormat', )), ReferenceField('StudentQuestions', #vocabulary="getAvailableCourses", widget=ReferenceWidget( label="quiz question", description='A question student has been asked', destination=".", #destination_types=("QuestionResult",), #visible={'edit':'invisible'}, ), multiValued=True, relationship='hasQuestion', allowed_types= ("InvisibleQuestion",), ), ReferenceField('CurrentQuestion', #vocabulary="getAvailableCourses", widget=ReferenceWidget( label="quiz question which is open", description='A question student is being asked', destination=".", #destination_types=("QuestionResult",), #visible={'edit':'invisible'}, ), multiValued=False, relationship='hasOpenQuiz', allowed_types= ("InvisibleQuestion",), ), ComputedField('grade', expression='context.computeGrade()', widget=StringWidget(visible={'edit':'invisible','view':'invisible' },), ), IntegerField('totalattempts', default='0', widget=IntegerWidget(description='Number of times students has submitted a questions to quiz.', visible={'edit':'invisible','view':'invisible'}, ), ), IntegerField('correctattempts', default='0', widget=IntegerWidget(description='Number of times students has submitted a questions to quiz.', visible={'edit':'invisible', 'view':'invisible'}, ), ), FloatField('totscore', default=0.0, widget=IntegerWidget(description='total score so far.', visible={'edit':'invisible','view':'invisible' }, ), ), StringField('lasteightgrades', default='[]', widget=StringWidget(description='Number of times students has submitted a questions to quiz.', visible={'edit':'invisible','view':'invisible' }, ),), StringField('studentRandId', default='', widget=StringWidget(description='random generated id to identify student.', visible={'edit':'invisible','view':'invisible' }, ), ), StringField('studentId', default='', widget=StringWidget(description='login id of student.', visible={'edit':'invisible','view':'invisible' }, ), ), #StringField('chosenquestid', # default='', # widget=StringWidget(description='Number of times students has submitted a questions to quiz.', # visible={'view':'invisible', 'edit':'invisible'}, ), # ), #StringField('chosenquestpath', # default='', # widget=StringWidget(description='Number of times students has submitted a questions to quiz.', # visible={'view': 'invisible', 'edit':'invisible'}, ), # ), )) __implements__ = (ATFolder.__implements__) global_allow = False meta_type = 'QuizResult' # zope type name portal_type = meta_type # plone type name archetype_name = 'QuizResult' # friendly type name #_at_rename_after_creation = True #automatically create id security = ClassSecurityInfo() # ATT: Make sure this work when create from twmigrate.py changed = True studentgrade = atapi.ATFieldProperty('grade') totalscore = atapi.ATFieldProperty('totscore') scoresofar = [] # REMEMBER check if reversed or not when displayed???????? lasteight = atapi.ATFieldProperty('lasteightgrades') quizattempts = atapi.ATFieldProperty('totalattempts') correctquizattempts = atapi.ATFieldProperty('correctattempts') chosenquestionid = atapi.ATFieldProperty('chosenquestid') chosenquestionpath = atapi.ATFieldProperty('chosenquestpath') #openquestion = atapi.ATFieldProperty('openquest') def __init__(self, oid=None, **kwargs): self.changed = True ATFolder.__init__(self, oid, **kwargs) # Must add: # getVocabulary is now in Lecture.py # returns the answers # getSelectedItem() in Lecture.py # questionIsInline in Lecture.py # isCorrect(item) in Lecture.py # # get chosen question already here # then must transformR(True) # then transformquizquestion # getQuestionData() # inlineAnswer() # getQuestImg and getQuestionImageTag # def getQuestionResultForQuestion(self, question): qresults = question.getFolderContents(contentFilter={"portal_type": "QuestionResult"}) return qresults[0].getObject() def getVocabulary(self): """return the possible answers formatted as vocabulary""" question = self.getCurrentQuestion() if (question): qr = self.getQuestionResultForQuestion(question) suggestedAnswerIds = (qr.getSuggestedAnswer()) idl = DisplayList() ans = question.getAnswerDisplay().values() for id in suggestedAnswerIds: idl.add(id, ans[int(id)]) return Vocabulary(idl, self, None) else: '''bad error no open question''' return '' def isCorrect(self, item): question = self.getCurrentQuestion() if (question): answers = question.getAnswerList() for row in answers: if (row['answerid'] == str(item)): if (row['correct'] == '1'): return True return False else: return False def startQuiz(self): '''student has asked for a question in quiz''' parent = aq_parent(self) lec = aq_parent(parent) if (DEBUG): tmpout = tempfile.mkdtemp() tex_fd, tex_absname = tempfile.mkstemp(dir=tmpout, suffix='.startQuiz') os.write(tex_fd, 'Starting selection of quiz question\n') hasq = self.openQuiz() msg = [] msg.append(True) # taken care of that - set no answer and written to log # close that question if (hasq): msg.append('question replaced') else: msg.append('A question has been saved to quiz') msg.append(self.Creator()) #parent = aq_parent(self) if (DEBUG): usable_question = lec.getQuizQuestion(tex_fd, True) else: usable_question = lec.getQuizQuestion() if (usable_question[0] == -1): '''no questions available''' msg[0] = False msg[1] = 'Sorry but no questions available in Lecture ' + usable_question[1] + '. Please contact your instructor if you believe you have found an error in the system, including the given error message' return msg elif(usable_question[0] == False): '''False could not create result for student''' msg[0] = False msg[1] = 'Fatal error could not start quiz in Lecture ' + usable_question[1] + '. Please contact your instructor if you believe you have found an error in the system, including the error message' return msg elif (usable_question[0] == -2): '''no answers set for the question''' msg[0] = False msg[1] = 'Sorry but no answers have been set for the selected question: ' + usable_question[2] + ' located in ' + usable_question[3] + '. Please try again or contact your instructor if you believe you have found and error in the system, including this message' return msg elif (usable_question[0] == -3): '''no answer set as correct in question''' msg[0] = False msg[1] = 'Sorry but no correct answer has been set to the selected question: ' + usable_question[2] + ' located in ' + usable_question[3] + '. Please try again or contact your instructor if you believe you have found an error in the system, including this error message' return msg else: '''have a valid question''' origquest = usable_question[0] if (DEBUG): os.write(tex_fd, '###########################\n') os.write(tex_fd, 'question used in quiz\n') os.write(tex_fd, str(origquest.getId()) + '\n') os.write(tex_fd, str(origquest.getRawQuestion()) + '\n') # set as invisble question with questionresult newq = self.createQuestion() qr = newq.createQuestionResult() # this info is repeated, but leave for now # FIXME if (len(self.getStudentRandId()) > 0): qr.setStudentId(self.getStudentRandId()) else: # find from other location quiz = aq_parent(self) lec = aq_parent(quiz) tut = aq_parent(lec) dep = aq_parent(tut) mysite = aq_parent(dep) studentlistobj = mysite.getFolderContents(contentFilter={"portal_type": "StudentList"}) if (len(studentlistobj) > 0): studentlist = studentlistobj[0].getObject() studentlist.addStudent(self.Creator()) randid = studentlist.getStudentIdNumber(self.Creator()) self.setStudentRandId(randid) qr.setStudentId(randid) qr.setLecPath(lec.getPhysicalPath()) # have created a quiz question with corresponding questuionresults # now set information from original question to quiz question # I probably don't need all the info but lets start by that questiontext = origquest.getRawQuestion() texttype = origquest.question.getContentType() mutated = origquest.getAnswerList() answertype = origquest.getAnswerFormat() newq.setQuestionText(questiontext, mimetype=texttype) newq.setAnswerList(mutated) newq.setAnswerFormat(answertype) # if its r or r/latex questions then need to be updated if (texttype == 'text/r' or texttype == 'text/r-latex'): newq.initializeObject() else: newq.ans = origquest.ans newq.NOTAinQuestion = origquest.NOTAinQuestion newq.inlineanswer = origquest.inlineanswer newq.transformrquestion = origquest.transformrquestion newq.setQuizQuestion(origquest.getRawQuizQuestion(), mimetype=origquest.quizQuestion.getContentType()) # add the image if any # ATT # asuming r-images do not contain image # would be generated within the r code itself? # HMMMMM img = origquest.getQuestionImage() newq.setQuestionImage(img) # add image url if any imgurl = origquest.getImageUrl() if (len(imgurl) > 0): newq.setImageUrl(imgurl) newq.numcorrect = origquest.numcorrect newq.numaskedfor = origquest.numaskedfor # need additionally to set: # quisQuestion newq.setQuizQuestionExplanation(origquest.getRawQuizQuestionExplanation(), mimetype='text/html') newq.setOriginalQuestion(origquest) # instead of using original question # use the invisible question suggestedanswers = newq.makeNewTest() grid = newq.getWrappedField('AnswerList') correctAnswerIds = [] rowcorrect = grid.search(newq, correct='1') for row in rowcorrect: correctAnswerIds.append(row['answerid']) qr.setNewQuestion(suggestedanswers, correctAnswerIds, origquest.getPhysicalPath(), origquest.UID()) if (len(suggestedanswers) > 0): '''set the first element in value as selected answer, anything will do''' qr.setSelectedAnswer(suggestedanswers[0]) else: '''what to do bad error''' msg[0] == False msg[1] = 'Fatal error' return msg qr.reindexObject() newq.reindexObject() self.reindexObject() if (DEBUG): os.write(tex_fd, str(newq.getId()) + '\n') os.write(tex_fd, str(newq.getRawQuestion()) + '\n') os.close(tex_fd) return msg def setTotalscore(self, val): self.setTotscore(val) #self.totalscore = val def setLastEightList(self, val): tmp = [] for s in val: tmp.append(int(s)) self.scoresofar = tmp tmpstr0 = str(val) tmpstr1 = tmpstr0.replace(',', '') self.setLasteightgrades(tmpstr1) def setLastEight(self, val): # value is a string tmpstr0 = val.replace(',', '') tmpstr1 = tmpstr0.replace('[', '') tmpstr2 = tmpstr1.replace(']','') scorelist = tmpstr2.split() tmp = [] for s in scorelist: if (len(s) > 0): tmp.append(int(s)) self.scoresofar = tmp self.setLasteightgrades(tmpstr0) def setScoresofar(self, val): self.scoresofar = val def getCreator(self): return self.Creator() def getSelectedAnswerToQuestion(self, question): #qr = self.getStudentQuestionResult() qr = self.getQuestionResultForQuestion(question) value = qr.getSelectedAnswer() #value = qr.getCandidateAnswer() answerdisplay = question.getAnswerDisplay() #index = int(value[0]) return answerdisplay.getValue(value) def getSelectedItem(self): question = self.getCurrentQuestion() qr = self.getQuestionResultForQuestion(question) return qr.getSelectedAnswer() def questionIsInline(self): question = self.getCurrentQuestion() if (question > 0): return question.inlineAnswer() else: return False def getCandidateAnswerInTest(self): question = self.getCurrentQuestion() if (question): qr = self.getQuestionResultForQuestion(question) return (qr.getCandidateAnswer()) security.declareProtected(PERMISSION_STUDENT, 'getOriginalQuestion') def getOriginalQuestion(self, quest): return quest.getOriginalQuestion() security.declareProtected(PERMISSION_STUDENT, 'getChosenQuestion') def getChosenQuestion(self): # always assume we are dealing with the last question question = self.getCurrentQuestion() if (question): return question else: return False def computeGrade(self): return float(self.getTotscore()) def getSuggestedAnswerInTest(self): qr = self.getQuestionResultForQuestion(question) return (qr.getSuggestedAnswer()) def setSelectedAnswerInTest(self, value): question = self.getCurrentQuestion() if (question): qr = self.getQuestionResultForQuestion(question) qr.setSelectedAnswer(value) qr.reindexObject() def unsetCandidateAnswerToQuestion(self): #qr = self.getStudentQuestionResult() #qresults = self.getFolderContents(contentFilter={"portal_type": "QuestionResult"}) #qr = qresults[0].getObject() question = self.getCurrentQuestion() if (question): qr = self.getQuestionResultForQuestion(question) qr.unsetCandidateAnswer() qr.reindexObject() def setCandidateAnswerToQuestion(self, value): question = self.getCurrentQuestion() if (question): qr = self.getQuestionResultForQuestion(question) qr.gotAnswer() origquestion = question.getOriginalQuestion() qr.setCandidateAnswer([value], origquestion) qr.writetolog() correctans = qr.getCorrectAnswer() l = qr.getSuggestedans().split('\t') v = l[int(value)-1] if v in correctans: # this can lead ot database conflict error origquestion.numcorrect = origquestion.numcorrect + 1 correct = 1 else: correct = 0 #qr.gotAnswer() self.setScore(correct) qr.reindexObject() def computeAverageGrade(self): '''return average grade of student''' # compute the average grade of the student for this lecture # Average grade is at the moment computed according to points given # for the last eight answers: # Correct answer gives +1 points # Wrong answer gives -0.5 points # no answers given or all answers incorrect, grade starts at -0.5 # Highest average grade is +1, all answers correct # r = number correct answers of last m= 8 answers # average grade = ((-0.5)*(m-r)+r)/m # later more complex methods of computing grades need to be specified. numcorrect = 0 for i in self.scoresofar: if float(i) > 0.0: numcorrect = numcorrect + 1 # average grade is computed from the last 8 answers m = 8.0 return ((-0.5)*(m-float(numcorrect))+float(numcorrect))/m def computeGrade1(self, remove): #tmpout = tempfile.mkdtemp() #tex_fd, tex_absname = tempfile.mkstemp(dir=tmpout, suffix='.computegradae1') #os.write(tex_fd, 'computegrade1\n') #tmp1 = self.getTotscore() #tmp = float(tmp1) #if (remove == 0): # tmp = tmp + 0.5 #else: # tmp = tmp - 1.0 #lastscore = self.scoresofar[0] #if (lastscore == 0): # tmp = tmp - 0.5 #else: # tmp = tmp + 1.0 total = 0.0 for i in self.scoresofar: if float(i) == 0.0: total = total - 0.5 else: total = total + 1 self.setTotscore(total) #questions = self.getStudentQuestions() #portal_catalog = getToolByName(self, 'portal_catalog') ##questions = self.portal_catalog.searchResults( ## portal_type = "InvisibleQuestion", ## sort_on="Date", ## path='/'.join(self.getPhysicalPath()), ## ) ##total = 0.0 ##self.scoresofar = [] ##for q in questions: ## qr = self.getQuestionResultForQuestion(q.getObject()) ## if (qr.candidateAnswer == qr.correct): ## total = total + 1.0 ## self.scoresofar.insert(0,1) ## else: ## total = total - 0.5 ## self.scoresofar.insert(0,0) ##self.setLasteightgrades(str(self.scoresofar)) ##self.setTotscore(total) self.reindexObject() #os.write(tex_fd, str(self.scoresofar) + '\n') #os.write(tex_fd, str(total) + '\n') #os.write(tex_fd, str(self.getPhysicalPath()) + '\n') #bla = '/'.join(self.getPhysicalPath()) #os.write(tex_fd, str(bla) + '\n') #os.write(tex_fd, str(len(questions)) + '\n') return self.getLasteightgrades() def getLastPoint(self): if (len(self.scoresofar) > 0): return self.scoresofar[0] else: return None security.declarePublic('setScore') def setScore(self, s): numinscore = 8 if (len(self.scoresofar) == numinscore): tmp = self.scoresofar[numinscore-1] self.scoresofar = self.scoresofar[:numinscore-1] #self.scoresofar = self.scoresofar + [s] self.scoresofar.insert(0, s) self.setLasteightgrades(str(self.scoresofar)) self.computeGrade1(tmp) #self.setLasteightgrades(str(self.scoresofar)) else: tmp = float(self.getTotscore()) if (s is 0): tmp = tmp - 0.5 else: tmp = tmp + 1.0 self.setTotscore(tmp) #tmp = 0 #self.computeGrade1(tmp) #self.scoresofar = self.scoresofar + [s] self.scoresofar.insert(0, s) self.setLasteightgrades(str(self.scoresofar)) #self.computeGrade1(tmp) temp = self.getTotalattempts() temp = temp + 1 self.setTotalattempts(temp) if (s is not 0): temp = self.getCorrectattempts() temp = temp + 1 self.setCorrectattempts(temp) self.reindexObject() def closedQuiz(self): msg = [] question = self.getCurrentQuestion() if (question): qr = self.getQuestionResultForQuestion(question) if (not qr.hasSubmittedQuestion()): '''this could only happen if double click on button''' # what to do, student want to submit the same answer twice # no don't allow that msg.append(True) msg.append('Already answered') return msg else: msg.append(False) msg.append('Your answer has been saved.') return msg def openQuiz(self): #qr = self.getStudentQuestionResult() # get the last question question = self.getCurrentQuestion() if (question): qr = self.getQuestionResultForQuestion(question) if (qr.hasSubmittedQuestion()): #Set this question as false # For the moment the result is not restored # should print out results for wrong question #self.setCandidateAnswerToQuestion('no answer') value = 'no answer' qr.setCandidateAnswer([value], question.getOriginalQuestion()) correctans = qr.getCorrectAnswer() if value in correctans: origquestion = question.getOriginalQuestion() # this can lead to database conflict error # WHAT TO DO???? #qobj = question[0].getObject() origquestion.numcorrect = origquestion.numcorrect + 1 correct = 1 else: correct = 0 qr.gotAnswer() self.setScore(correct) qr.reindexObject() #quizquestionstring = qr.getQuizInfo() self.writetolog(qr) return True else: return False else: '''no question set yet''' return False security.declareProtected(PERMISSION_STUDENT, 'writetolog') def writetolog(self, qr): # FIXME !!!! # add code to check if dir exists and then create.. logdir = productdir + '/log' if (not (os.path.exists(logdir))): os.mkdir(logdir) f = open(logdir+'/questionandanswer.txt','a') #qr = self.getStudentQuestionResult() #qresults = self.getFolderContents(contentFilter={"portal_type": "QuestionResult"}) #qr = qresults[0].getObject() text = qr.getQuizInfo() text = text + str(datetime.now()) + "\n" f.write(text) f.close() #os.system('echo ' + text + ' >> /tmp/twquiz/questionandanswer.txt') def setNewQuestionInTest(self, suggestedanswer, correctids, questpath, qid): #notify(NewQuizQuestionEvent(self, suggestedanswer, correctids, questpath, qid)) question = self.getCurrentQuestion() if (question): qr = self.getQuestionResultForQuestion(question) #qresults = self.getFolderContents(contentFilter={"portal_type": "QuestionResult"}) #qr = qresults[0].getObject() #self.manage_delObjects(qresults) ##randid = qr.getStudid() ##lecpath = qr.getLecturepath() ##ids = self.objectIds() # Plone 3 or older #ids = folder.keys() # Plone 4 or newer #ids = [] ##if len(ids) > 0: #manage_delObject will mutate the list # so we cannot give it tuple returned by objectIds() ## ids = list(ids) ## self.manage_delObjects(ids) ##qr = self.createQuestionResult() ##qr.setStudentId(self.Creator()) #parent = aq_parent(self) #lecpath = parent.getPhyisicalPath() ##qr.setLecturepath(lecpath) ##self.setStudentQuestionResult(qr) ##transaction.begin() qr.setNewQuestion(suggestedanswer, correctids, questpath, qid) ##qr._p_changed = True ##self._p_changed = True ##transaction.commit() #portal_catalog = getToolByName(self, 'portal_catalog') #students = portal_catalog.unrestrictedSearchResults({'portal_type' : 'StudentList'}) #if (len(students) > 0): # numlists = str(len(students)) # objid = students[0].getObject() #objid.addStudent(candidateId) # randid = objid.getStudentIdNumber(self.Creator()) ##qr.setStudentId(randid) qr.reindexObject() # This method is only called once after object creation. #security.declarePrivate('at_post_create_script') #def at_post_create_script(self): # self.tryWorkflowAction("publish", ignoreErrors=True) def at_post_edit_script(self): '''function called after edit in the main edit view of the tutorial.''' # self.changed = True #qresults = self.getFolderContents(contentFilter={"portal_type": "QuestionResult"}) #if (len(qresults) > 0): # qr = qresults[0].getObject() # self.setStudentQuestionResult(qr) #security.declarePrivate('tryWorkflowAction') #def tryWorkflowAction(self, action, ignoreErrors=False, comment=None): # wtool = self.portal_workflow # wf = wtool.getWorkflowsFor(self)[0] # if wf.isActionSupported(self, action): # if comment is None: # #userId = getSecurityManager().getUser().getId() # comment = 'State changed' # wtool.doActionFor(self, action, comment=comment) # elif not ignoreErrors: # raise TypeError('Unsupported workflow action %s for object %s.' # % (repr(action), repr(self))) #def getError(self): # self.portal_factory.doCr() #def createQuestionResult(self): # """Create a new questionresult object for student and initialize it.""" # typeName = 'QuestionResult' # id=self.generateUniqueId(typeName) # if self.portal_factory.getFactoryTypes().has_key(typeName): # o = self.restrictedTraverse('portal_factory/' + typeName + '/' + id) # else: # newId = self.invokeFactory(id=id, type_name=typeName) # if newId is None or newId == '': # newId = id # o=getattr(self, newId, None) # if o is None: # raise Exception # o = self.portal_factory.doCreate(o, id) # o.setTitle('Question result') # o.reindexObject() # return o def removeQuestion(self): portal_catalog = getToolByName(self, 'portal_catalog') questions = self.portal_catalog.searchResults( portal_type = "InvisibleQuestion", sort_on="Date", path='/'.join(self.getPhysicalPath()), ) if (len(questions) > 7): '''should removes the oldest one''' self.manage_delObjects([questions[0].getId]) def createQuestion(self): """Create a new questionresult object for student and initialize it.""" # if neede delete a question # only keep 8 questons going typeName = 'InvisibleQuestion' self.removeQuestion() id=self.generateUniqueId(typeName) if self.portal_factory.getFactoryTypes().has_key(typeName): o = self.restrictedTraverse('portal_factory/' + typeName + '/' + id) else: newId = self.invokeFactory(id=id, type_name=typeName) if newId is None or newId == '': newId = id o=getattr(self, newId, None) if o is None: raise Exception o = self.portal_factory.doCreate(o, id) #o.setTitle('Question result') invquest = self.getStudentQuestions() invquest.append(o) self.setStudentQuestions(invquest) self.setCurrentQuestion(o) return o
schema = BikaSchema.copy() + Schema(( BlobFileField("InvoicePDF", widget=FileWidget(label=_("Invoice PDF"), )), ReferenceField( "Client", required=1, vocabulary_display_path_bound=sys.maxsize, allowed_types=("Client", ), relationship="ClientInvoice", ), ReferenceField( "AnalysisRequest", required=1, vocabulary_display_path_bound=sys.maxsize, allowed_types=("AnalysisRequest", ), relationship="AnalysisRequestInvoice", ), ReferenceField( "SupplyOrder", required=1, vocabulary_display_path_bound=sys.maxsize, allowed_types=("SupplyOrder", ), relationship="SupplyOrderInvoice", ), DateTimeField( "InvoiceDate", required=1, default_method="get_current_date", widget=DateTimeWidget(label=_("Date"), ), ), ))
from Products.Archetypes.public import Schema from Products.Archetypes.public import ImageField from Products.Archetypes.public import ImageWidget from Products.Archetypes.public import BaseContent from Products.Archetypes.public import registerType from Products.Archetypes.Marshall import PrimaryFieldMarshaller from Products.CMFCore import permissions from Products.CMFCore.utils import getToolByName from Products.Quills.config import PROJECTNAME WeblogTopicSchema = BaseSchema.copy() + Schema(( ImageField('topicImage', required=1, sizes={'64' : (64,64),}, widget=ImageWidget(label="Image", description="An image for your topic. The image should be 64x64. If the image is larger it will be scaled down automatically to fit within a 64x64 square."), ), ), marshall=PrimaryFieldMarshaller(), ) WeblogTopicSchema['allowDiscussion'].default=0 class WeblogTopic(BaseContent): """Weblog Topic""" topicImage = '' default_topic_image='default-topic-icon.jpg', schema = WeblogTopicSchema archetype_name = "Topic"
StringField, Schema, BaseFolder from plone.app.blob.field import BlobField from Products.Archetypes.references import HoldingReference from bika.lims.config import PROJECTNAME from bika.lims.content.bikaschema import BikaSchema schema = BikaSchema.copy() + Schema(( ReferenceField( 'AnalysisRequest', allowed_types=('AnalysisRequest', ), relationship='ReportAnalysisRequest', referenceClass=HoldingReference, required=1, ), BlobField('Pdf', ), StringField('Html', ), BlobField('CSV', ), StringField('SMS', ), StringField('COANR', ), RecordsField( 'Recipients', type='recipients', subfields=('UID', 'Username', 'Fullname', 'EmailAddress', 'PublicationModes'), ), )) schema['id'].required = False schema['title'].required = False class ARReport(BaseFolder):
EditSchema = Schema(( StringField('index', schemata="default", required=True, vocabulary_factory='eea.faceted.vocabularies.CatalogIndexes', widget=SelectionWidget( label=_(u'Catalog index'), description=_(u'Catalog index to use for search'), i18n_domain="eea")), StringField( 'vocabulary', schemata="default", vocabulary_factory='eea.faceted.vocabularies.PortalVocabularies', widget=SelectionWidget( label=_(u'Vocabulary'), description=_(u'Vocabulary to use to render widget items'), i18n_domain="eea")), StringField('catalog', schemata="default", vocabulary_factory='eea.faceted.vocabularies.UseCatalog', widget=SelectionWidget( format='select', label=_(u'Catalog'), description=_( u'Get unique values from catalog as an alternative ' u'for vocabulary'), i18n_domain="eea")), BooleanField('hidealloption', schemata="default", default=False, widget=BooleanWidget( label=_(u"Hide 'All' option"), description=_( u'If this checkbox is checked, hides the All ' u'option'), i18n_domain="eea")), IntegerField('maxitems', schemata="display", default=0, widget=IntegerWidget( label=_(u'Maximum items'), description=_(u'Number of items visible in widget'), i18n_domain="eea")), BooleanField('sortreversed', schemata="display", widget=BooleanWidget(label=_(u'Reverse options'), description=_(u'Sort options reversed'), i18n_domain="eea")), StringField('default', schemata="default", widget=StringWidget(size=25, label=_(u'Default value'), description=_(u'Default selected item'), i18n_domain="eea")), ))
XPointProjectSchema = ATFolderSchema.copy() + Schema(( # detail description for this project, it allows rich text. TextField( 'xpproject_text', searchable = True, required = True, default_output_type = 'text/x-html-safe', widget = RichWidget( label = 'Project body', rows = 22, ), ), # developers for this project LinesField( 'xpproject_developers', searchable = False, required = True, vocabulary = 'vocabulary_allMembersList', widget = InAndOutWidget( label = 'Developers', descrpiton = "Please select developers for this project", ), ), # modules LinesField( 'xpproject_modules', searchable = False, required = True, widget = LinesWidget( label = 'Project Modules', description = 'Please specify the module for your project, one per line', cols = 40, ), ), ) )
from eea.facetednavigation.widgets import ViewPageTemplateFile from eea.facetednavigation.widgets.widget import Widget as AbstractWidget from eea.facetednavigation import EEAMessageFactory as _ EditSchema = Schema(( StringField('vocabulary', schemata="default", vocabulary_factory='eea.faceted.vocabularies.PortalVocabularies', widget=SelectionWidget( label=_(u'Filter from vocabulary'), description=_(u'Vocabulary to use to filter sorting criteria. ' u'Leave empty for default sorting criteria.'), i18n_domain="eea" ) ), StringField('default', schemata="default", widget=StringWidget( size=25, label=_(u'Default value'), description=_(u"Default sorting index " u"(e.g. 'effective' or 'effective(reverse)')"), i18n_domain="eea" ) ), )) class Widget(AbstractWidget): """ Widget """ # Widget properties
schema = BikaSchema.copy() + Schema(( CoordinateField( 'Latitude', schemata='Location', widget=CoordinateWidget( label=_("Latitude"), description= _("Enter the Sample Point's latitude in degrees 0-90, minutes 0-59, seconds 0-59 and N/S indicator" ), ), ), CoordinateField( 'Longitude', schemata='Location', widget=CoordinateWidget( label=_("Longitude"), description= _("Enter the Sample Point's longitude in degrees 0-180, minutes 0-59, seconds 0-59 and E/W indicator" ), ), ), StringField( 'Elevation', schemata='Location', widget=StringWidget( label=_("Elevation"), description=_( "The height or depth at which the sample has to be taken"), ), ), DurationField( 'SamplingFrequency', vocabulary_display_path_bound=sys.maxint, widget=DurationWidget( label=_("Sampling Frequency"), description= _("If a sample is taken periodically at this sample point, enter frequency here, e.g. weekly" ), ), ), ReferenceField( 'SampleTypes', required=0, multiValued=1, allowed_types=('SampleType', ), relationship='SamplePointSampleType', widget=BikaReferenceWidget( label=_("Sample Types"), description=_("The list of sample types that can be collected " "at this sample point. If no sample types are " "selected, then all sample types are available."), catalog_name='bika_setup_catalog', base_query={ "is_active": True, "sort_on": "sortable_title", "sort_order": "ascending" }, showOn=True, ), ), BooleanField( 'Composite', default=False, widget=BooleanWidget( label=_("Composite"), description= _("Check this box if the samples taken at this point are 'composite' " "and put together from more than one sub sample, e.g. several surface " "samples from a dam mixed together to be a representative sample for the dam. " "The default, unchecked, indicates 'grab' samples"), ), ), BlobFileField( 'AttachmentFile', widget=FileWidget(label=_("Attachment"), ), ), ))
schema = Schema(( TextField( 'keyMessage', required=False, searchable=True, primary=False, storage=AnnotationStorage(migrate=True), validators=('isTidyHtmlWithCleanup', ), default_content_type=zconf.ATNewsItem.default_content_type, default_output_type='text/x-html-safe', allowable_content_types=('text/html', ), widget=RichWidget( description="Optional", description_msgid="help_body_text", label="Key message", label_msgid="label_body_text", rows=5, i18n_domain="plone", allow_file_upload=False, ), ), TextField( 'text', required=True, searchable=True, primary=True, storage=AnnotationStorage(migrate=True), validators=('isTidyHtmlWithCleanup', ), default_content_type=zconf.ATNewsItem.default_content_type, default_output_type='text/x-html-safe', allowable_content_types=('text/html', ), widget=RichWidget( description="", description_msgid="help_body_text", label="Assessment", label_msgid="label_body_text", rows=25, i18n_domain="plone", allow_file_upload=zconf.ATDocument.allow_document_upload), ), StringField( name='soerCountry', required=False, mode='r', widget=SelectionWidget( label='Country', label_msgid='eea.soer_label_country', i18n_domain='eea.soer', format='select', ), vocabulary=NamedVocabulary('eea.soer.vocab.european_countries'), enforceVocabulary=False, ), StringField( name='geoCoverage', required=True, widget=SelectionWidget( label='Geographic coverage', label_msgid='eea.soer_label_geocoverage', description='Required', i18n_domain='eea.soer', format='select', ), vocabulary="getGeoCoverageVocabulary", enforceVocabulary=False, ), StringField( name='topic', required=True, widget=SelectionWidget( label='Topics', label_msgid='eea.soer_label_topics', i18n_domain='eea.soer', format='select', ), vocabulary=NamedVocabulary('eea.soer.vocab.topics'), enforceVocabulary=True, ), StringField( name='question', required=True, widget=SelectionWidget( label='Question', label_msgid='eea.soer_label_questions', i18n_domain='eea.soer', format='select', ), vocabulary=NamedVocabulary('eea.soer.vocab.questions'), enforceVocabulary=True, ), StringField( name='evaluation', required=0, searchable=0, default=u'http://www.eea.europa.eu/soer/evaluations#XX', widget=SelectionWidget( label='Evaluation', label_msgid='label_evaluation', description='This is a two letter value which indicates quickly ' 'what the evaluation and trend is.', visible={ 'view': 'invisible', 'edit': 'invisible' }, format='select', ), vocabulary='getEvaluationVocabulary', ), ), )
COREBlogTrackbackSchema = ATContentTypeSchema.copy() + Schema( ( #Comment content data StringField( 'url', searchable=1, widget=StringWidget( label='URL', description='', label_msgid="label_coreblog_trackback_url", description_msgid="help_coreblog_trackback_url", i18n_domain="plone", size=60), ), StringField( 'excerpt', searchable=1, primary=True, index='TextIndex', default_output_type='text/html', default_content_type='text/html', widget=StringWidget( label='excerpt', description='', label_msgid="label_coreblog_trackback_excerpt", description_msgid="help_coreblog_trackback_excerpt", i18n_domain="plone", size=60), ), StringField( 'blog_name', searchable=1, widget=StringWidget( label='blog_name', description='', label_msgid="label_coreblog_trackback_blog_name", description_msgid="help_coreblog_trackback_blog_name", i18n_domain="plone", size=60), ), StringField( 'post_ip', searchable=1, index='FieldIndex', widget=StringWidget( label='IP', description='', label_msgid="label_coreblog_comment_post_ip", description_msgid="help_coreblog_comment_post_ip", i18n_domain="plone", size=60), ), ), marshall=RFC822Marshaller(), )
NewsletterReferenceSchema = BaseSchema.copy() + Schema(( TextField('description', default='', searchable=1, isMetadata=1, accessor="Description", widget=TextAreaWidget( description='An administrative summary of the content', description_msgid='help_description', i18n_domain="plone", label='Description', label_msgid='label_description', )), OrderableReferenceField( 'references', languageIndependent=1, required=0, allowed_types=(), multiValued=1, relationship='references', widget=ReferenceBrowserWidget( allow_browse=1, allow_search=1, allow_sorting=1, description='Select one or more remote objects', description_msgid='help_references', i18n_domain='plonegazette', label='References', label_msgid='label_references', show_indexes=0, )), ))
schema = Organisation.schema.copy() + Schema(( StringField( "ClientID", required=1, searchable=True, validators=("uniquefieldvalidator", "standard_id_validator"), widget=StringWidget(label=_("Client ID"), ), ), BooleanField( "BulkDiscount", default=False, widget=BooleanWidget(label=_("Bulk discount applies"), ), ), BooleanField( "MemberDiscountApplies", default=False, widget=BooleanWidget(label=_("Member discount applies"), ), ), EmailsField( "CCEmails", schemata="Preferences", mode="rw", widget=StringWidget( label=_("CC Emails"), description=_( "Default Emails to CC all published Samples for this client"), visible={ "edit": "visible", "view": "visible", }, ), ), ReferenceField( "DefaultCategories", schemata="Preferences", required=0, multiValued=1, allowed_types=("AnalysisCategory", ), relationship="ClientDefaultCategories", widget=ReferenceWidget( label=_("Default categories"), description=_( "Always expand the selected categories in client views"), showOn=True, catalog_name=SETUP_CATALOG, base_query=dict( is_active=True, sort_on="sortable_title", sort_order="ascending", ), ), ), ReferenceField( "RestrictedCategories", schemata="Preferences", required=0, multiValued=1, validators=("restrictedcategoriesvalidator", ), allowed_types=("AnalysisCategory", ), relationship="ClientRestrictedCategories", widget=ReferenceWidget( label=_("Restrict categories"), description=_("Show only selected categories in client views"), showOn=True, catalog_name=SETUP_CATALOG, base_query=dict( is_active=True, sort_on="sortable_title", sort_order="ascending", ), ), ), BooleanField( "DefaultDecimalMark", schemata="Preferences", default=True, widget=BooleanWidget( label=_("Default decimal mark"), description=_( "The decimal mark selected in Bika Setup will be used."), )), StringField( "DecimalMark", schemata="Preferences", vocabulary=DECIMAL_MARKS, default=".", widget=SelectionWidget( label=_("Custom decimal mark"), description=_( "Decimal mark to use in the reports from this Client."), format="select", )), ))
from zope import event from zope.interface import implements # from zope.interface import Interface from zope.interface import providedBy PBConversationBaseBTreeFolderSchema = BaseBTreeFolderSchema.copy() PBConversationBaseBTreeFolderSchema['title'].read_permission = ViewBoard PBConversationBaseBTreeFolderSchema['title'].write_permission = EditComment schema = PBConversationBaseBTreeFolderSchema + Schema((TextField( 'description', searchable=1, read_permission=ViewBoard, write_permission=EditComment, default_content_type='text/plain', default_output_type='text/plain', widget=TextAreaWidget( description="Enter a brief description of the conversation.", description_msgid="help_description_conversation", label="Description", label_msgid="label_description_conversation", i18n_domain="ploneboard", rows=5)), )) utils.finalizeSchema(schema) class PloneboardConversation(BrowserDefaultMixin, BaseBTreeFolder): """Conversation contains comments.""" implements(IConversation, INonStructuralFolder) meta_type = 'PloneboardConversation' schema = schema
from plone.app.blob.field import ImageField from plone.app.blob.tests.base import changeAllowedSizes from plone.app.blob.tests.base import ReplacementTestCase from plone.app.blob.tests.utils import getFile from Products.Archetypes.public import BaseContent from Products.Archetypes.public import BaseSchema from Products.Archetypes.public import FileWidget from Products.Archetypes.public import ImageWidget from Products.Archetypes.public import registerType from Products.Archetypes.public import Schema SampleSchema = BaseSchema.copy() + Schema(( FileField(name='foo', widget=FileWidget(label='File', description='a file')), ImageField(name='bar', widget=ImageWidget(label='Image', description='an image')), ImageField(name='hmm', sizes={'tiny': (42, 42)}, widget=ImageWidget(label='Image', description='an image')), )) class SampleType(BaseContent): portal_type = 'SampleType' schema = SampleSchema permissions['SampleType'] = packageName + ': SampleType' registerType(SampleType, packageName)
schema = BikaSchema.copy() + Schema( (StringField( "Type", required=1, vocabulary=PRICELIST_TYPES, widget=SelectionWidget( format="select", label=_("Pricelist for"), ), ), BooleanField( "BulkDiscount", default=False, widget=SelectionWidget(label=_("Bulk discount applies"), ), ), FixedPointField( "BulkPrice", widget=DecimalWidget( label=_("Discount %"), description=_("Enter discount percentage value"), ), ), BooleanField( "Descriptions", default=False, widget=BooleanWidget( label=_("Include descriptions"), description=_("Select if the descriptions should be included"), ), ), RemarksField( "Remarks", searchable=True, widget=RemarksWidget(label=_("Remarks"), ), )), )
schema = ATBTreeFolderSchema + Schema(( TextField('description', searchable=1, default_content_type='text/html', default_output_type='text/plain', widget=TextAreaWidget( description="Enter a brief description of the board.", description_msgid="help_description_board", i18n_domain="ploneboard", label="Description", label_msgid="label_description_board", rows=5 ) ), TextField('text', required=False, searchable=True, storage=AnnotationStorage(), validators=('isTidyHtmlWithCleanup',), default_output_type='text/x-html-safe', widget=RichWidget( i18n_domain="ploneboard", label="Text", label_msgid="label_text", rows=25), ), LinesField('categories', widget = LinesWidget( description = \ "Enter the categories you want to have available for " "forums, one category on each line.", description_msgid = "help_categories_board", label = "Categories", label_msgid = "label_categories_board", i18n_domain = "ploneboard")), ))
""" RejectAnalysis """ from Products.Archetypes.public import ReferenceField, Schema, registerType from bika.lims.content.analysis import Analysis from bika.lims.config import PROJECTNAME from bika.lims.content.analysis import schema as analysis_schema schema = analysis_schema + Schema(( # The analysis that was originally rejected ReferenceField('Analysis', allowed_types=('Analysis',), relationship = 'RejectAnalysisAnalysis', ), )) class RejectAnalysis(Analysis): archetype_name = 'RejectAnalysis' schema = schema registerType(RejectAnalysis, PROJECTNAME)
schema = Schema(( UIDReferenceField( 'SampleType', vocabulary="getSampleTypes", allowed_types=('SampleType',), widget=ReferenceWidget( checkbox_bound=0, label=_("Sample Type"), ), ), ComputedField( 'SampleTypeTitle', expression="context.getSampleType().Title() if context.getSampleType() else ''", widget=ComputedWidget( visible=False, ), ), ComputedField( 'SampleTypeUID', expression="context.getSampleType().UID() if context.getSampleType() else ''", widget=ComputedWidget( visible=False, ), ), )) + BikaSchema.copy() + Schema(( RecordsField(
"Select a manager from the available personnel configured under " "the 'lab contacts' setup item. Departmental managers are " "referenced on analysis results reports containing analyses by " "their department."), showOn=True, catalog_name=SETUP_CATALOG, base_query=dict( is_active=True, sort_on="sortable_title", sort_order="ascending", ), ), ) schema = BikaSchema.copy() + Schema(( Manager, )) schema['description'].widget.visible = True schema['description'].schemata = 'default' class Department(BaseContent): implements(IDepartment, IDeactivable) security = ClassSecurityInfo() displayContentsTab = False schema = schema _at_rename_after_creation = True def _renameAfterCreation(self, check_auto_id=False):
from bika.lims.interfaces import ISamplePartition from zope.interface import implements schema = BikaSchema.copy() + Schema(( ReferenceField( 'Container', allowed_types=('Container', ), relationship='SamplePartitionContainer', required=1, multiValued=0, ), ReferenceField( 'Preservation', allowed_types=('Preservation', ), relationship='SamplePartitionPreservation', required=0, multiValued=0, ), BooleanField('Separate', default=False), UIDReferenceField( 'Analyses', allowed_types=('Analysis', ), required=0, multiValued=1, ), DateTimeField('DatePreserved', ), StringField('Preserver', searchable=True), DurationField('RetentionPeriod', ), )) schema['title'].required = False
from Products.CMFPlone.interfaces import IConstrainTypes from Products.CMFCore.utils import getToolByName from plone.app.folder.folder import ATFolder from zope.interface import implements from bika.lims.content.bikaschema import BikaFolderSchema from baobab.lims.interfaces import IMonitoringDevice from baobab.lims import bikaMessageFactory as _ from baobab.lims import config schema = BikaFolderSchema.copy() + Schema((StringField( 'MACAddress', required=1, searchable=True, validators=('uniquefieldvalidator', ), widget=StringWidget(label=_("MAC Address"), description=_("Monitoring Device MAC Address"), visible={ 'edit': 'visible', 'view': 'visible' })), )) schema['description'].schemata = 'default' schema['description'].widget.visible = True class MonitoringDevice(ATFolder): security = ClassSecurityInfo() implements(IMonitoringDevice, IConstrainTypes) displayContentsTab = False schema = schema
schema = BaseBTreeFolderSchema + Schema(( TextField('description', searchable = 1, default_content_type = 'text/html', default_output_type = 'text/plain', widget = TextAreaWidget( description = "Brief description of the forum topic.", description_msgid = "help_description_forum", label = "Description", label_msgid = "label_description_forum", i18n_domain = "ploneboard", rows = 5)), LinesField('category', write_permission = ManageForum, vocabulary = 'getCategories', widget = MultiSelectionWidget( description = "Select which category the forum should be listed under. A forum can exist in multiple categories, although using only one category is recommended.", description_msgid = "help_category", condition="object/getCategories", label = "Category", label_msgid = "label_category", i18n_domain = "ploneboard", )), IntegerField('maxAttachments', write_permission = ManageForum, default = 1, widget = IntegerWidget( description = "Select the maximum number of attachments per comment.", description_msgid = "help_maxattachments", label = "Maximum number of attachments", label_msgid = "label_maxattachments", i18n_domain = "ploneboard", )), IntegerField('maxAttachmentSize', write_permission = ManageForum, vocabulary = AttachmentSizes, default = 100, widget = SelectionWidget( description = "Select the maximum size for attachments.", description_msgid = "help_maxattachmentsize", label = "Maximum attachment size", label_msgid = "label_maxattachmentsize", i18n_domain = "ploneboard", )), BooleanField('allowEditComment', default=False, languageIndependent=0, widget = BooleanWidget( label = u'Allow users to edit their comments', description = u'If selected, this will give users the ability to edit their own comments.', label_msgid = 'label_allow_edit_comment', description_msgid = 'help_allow_edit_comment', # Only show when no conversations exist condition = "not:object/getNumberOfConversations|nothing", ), ), BooleanField('showCaptcha', write_permission = ManageForum, default = False, widget = BooleanWidget( description = _(u'help_showcaptcha', default=u'Select if show or not captcha for anonymous (if recaptcha installed and configured).'), label = _(u'label_show_captcha', default=u"Show Captcha"), )), ))
def testSwapTwoFields(self): schema = Schema() schema.addField(MockField("one")) schema.addField(MockField("two")) set_schema_order(schema, {"default": ["two", "one"]}) self.assertEqual(schema._names, ["two", "one"])