class ECQFolder(ATFolder): """An ATFolder that calls the ECQuiz method [syncResults] when something happens that might invalidate existing result objects.""" schema = ATFolderSchema.copy() __implements__ = (ATFolder.__implements__) #global_allow = False #meta_type = 'ECQFolder' # zope type name #portal_type = meta_type # plone type name #archetype_name = 'ECQuiz Folder' # friendly type name security = ClassSecurityInfo() """Only users with privileges of PERMISSION_INTERROGATOR (see config) or higher may call this function directly or indirectly (e.g. by calling the folder_contents page template). """ #security.declareProtected(PERMISSION_INTERROGATOR, 'listFolderContents') """Declaring 'folderlistingFolderContents' as protected prevents the answers from being listed if someone without PERMISSION_INTERROGATOR tries to call the 'base_view' template for a derived type (like quiz or question group). """ #security.declareProtected(PERMISSION_INTERROGATOR, # 'folderlistingFolderContents') security.declareProtected(permissions.PERMISSION_STUDENT, 'Type') security.declareProtected(permissions.PERMISSION_STUDENT, 'title_or_id') #security.declareProtected(CMFCorePermissions.ModifyPortalContent, 'moveObjectsByDelta') def moveObjectsByDelta(self, *args, **kwargs): """ """ #log("moveObjectsByDelta: %s" % self) retVal = ATFolder.moveObjectsByDelta(self, *args, **kwargs) self.syncResults('move') return retVal security.declarePrivate('manage_afterAdd') def manage_afterAdd(self, *args, **kwargs): """ """ #log("manage_afterAdd: %s" % self) #retVal = OrderedBaseFolder.manage_afterAdd(self, *args, **kwargs) retVal = ATFolder.manage_afterAdd(self, *args, **kwargs) self.syncResults('add') return retVal security.declarePrivate('manage_beforeDelete') def manage_beforeDelete(self, *args, **kwargs): """ """ #log("manage_beforeDelete: %s" % self) retVal = ATFolder.manage_beforeDelete(self, *args, **kwargs) self.syncResults('delete') return retVal
name='frequency_of_updates', schema=frequency_of_updates_schema, schemata='default', required_for_published=True, validators=('validate_frequency_years', ), #required=True, widget=CompoundWidget( label="Frequency of updates", description="How often is this indicators assessments updates?", label_msgid='indicators_label_frequency_of_updates', description_msgid='indicators_help_frequency_of_updates', ), ), )) Specification_schema = ATFolderSchema.copy() + \ getattr(ATFolder, 'schema', Schema(())).copy() + \ schema.copy() # Batch reorder of the fields #this is created like this because we want explicit control over how the #schemata fields are ordered and changing this in the UML modeler is just too #time consuming _field_order = [ { 'name': 'default', 'fields': [ 'title', 'description', 'more_updates_on', 'definition', 'units',
from Products.PloneFormGen.config import \ PROJECTNAME, \ EDIT_TALES_PERMISSION, EDIT_ADVANCED_PERMISSION, BAD_IDS from Products.PloneFormGen.content import validationMessages from Products.PloneFormGen import PloneFormGenMessageFactory as _ from Products.PloneFormGen import implementedOrProvidedBy from Products.PloneFormGen import HAS_PLONE40 from types import StringTypes import zope.i18n logger = logging.getLogger("PloneFormGen") FormFolderSchema = ATFolderSchema.copy() + Schema(( StringField('submitLabel', required=0, searchable=0, default="Submit", widget=StringWidget( label=_(u'label_submitlabel_text', default=u"Submit Button Label"), description = _(u'help_submitlabel_text', default=u""), ), ), BooleanField('useCancelButton', required=0, searchable=0, default='0', languageIndependent=1, widget=BooleanWidget(label=_(u'label_showcancel_text',
#You can also contact Cynapse at: #802, Building No. 1, #Dheeraj Sagar, Malad(W) #Mumbai-400064, India ############################################################################### from Products.Archetypes.atapi import * from Products.ATContentTypes.content.folder \ import ATFolder as BaseClass from Products.ATContentTypes.content.folder \ import ATFolderSchema as DefaultSchema from Products.ATContentTypes.content.base import registerATCT from ubify.coretypes.config import PROJECTNAME schema = DefaultSchema.copy() from wiki_start_page import * class Wiki(BaseClass): __doc__ = BaseClass.__doc__ + "(customizable version)" # portal_type = BaseClass.portal_type # archetype_name = BaseClass.archetype_name schema = schema _at_rename_after_creation = True # enable FTP/WebDAV and friends PUT = BaseClass.PUT def manage_afterAdd(self, item, container):
from Products.PloneBooking.content.vocabulary import ( REQUIRED_FILTERS, CALENDAR_VIEWS, VIEW_MODES, LISTING_VIEWS, GLOBAL_BOOKING_REVIEW_MODES, CALENDAR_REFRESH_MODES, ) from Products.PloneBooking.config import PROJECTNAME, I18N_DOMAIN from Products.PloneBooking.interfaces import IBookingCenter from Products.PloneBooking import BookingPermissions DISPLAY_SCHEMATA = "display" BookingCenterSchema = ATFolderSchema.copy() + Schema( ( LinesField( "types", required=True, widget=LinesWidget( label=_(u"Types"), description=_( "label_bookingcenter_types", u"You can define here a list of bookable object types (1 by line)" ), ), ), LinesField( "categories", required=False, widget=LinesWidget(
expression="context.getTemporalCoverage()", widget=ComputedField._properties['widget']( visible={'view':'invisible', 'edit':'invisible'}, ), ), ComputedField( name='location', expression="context.getLocation()", widget=ComputedField._properties['widget']( visible={'view':'visible', 'edit':'invisible'}, ), ), ), ) IndicatorFactSheet_schema = ATFolderSchema.copy() + \ getattr(ATFolder, 'schema', Schema(())).copy() + \ schema.copy() IndicatorFactSheet_schema.moveField('relatedItems', after='dpsir') class IndicatorFactSheet(ATFolder, ModalFieldEditableAware, BrowserDefaultMixin, IndicatorMixin): """ IndicatorFactSheet content class """ security = ClassSecurityInfo() implements(interfaces.IIndicatorFactSheet, interfaces.IIndicatorAssessment, IHasMandatoryWorkflowFields)
from Products.ATContentTypes.content.folder import ATFolderSchema, ATFolder from Products.ATContentTypes.content.schemata import finalizeATCTSchema from Products.ATContentTypes.content.base import registerATCT from Products.PloneFormGen.config import * from Products.PloneFormGen.widgets import \ FieldsetStartWidget, FieldsetEndWidget from Products.PloneFormGen.interfaces import IPloneFormGenFieldset from Products.PloneFormGen import PloneFormGenMessageFactory as _ import zope.i18n FieldsetFolderSchema = ATFolderSchema.copy() + Schema((BooleanField( 'useLegend', required=0, searchable=0, default='1', widget=BooleanWidget( label=_(u'label_showlegend_text', default=u'Show Title as Legend'), description=_(u'help_showlegend_text', default=u''), ), ), )) FieldsetFolderSchema['description'].widget.label = _( u'label_fieldsethelp_text', default=u'Fieldset Help') FieldsetFolderSchema['description'].widget.description = None FieldsetFolderSchema.moveField('description', after='useLegend')
##code-section module-header #fill in your manual code here from xml.dom import minidom import urllib import traceback import sys import time from Products.ZMetadata import Global ##/code-section module-header schema = Schema((), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema CommunitySearch_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class CommunitySearch(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.ICommunitySearch) meta_type = 'CommunitySearch' _at_rename_after_creation = True
# You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # """ """ __docformat__ = "restructuredtext" from api import * from config import PROJECTNAME from schemata import * from Products.ATContentTypes.content.folder import ATFolderSchema CollectionSchema = ATFolderSchema.copy() CollectionSchema += CollectionBaseSchema.copy() CollectionSchema += Schema( ( StringField( "source", required=False, searchable=True, vocabulary=collection_source, widget=SelectionWidget( label="Source", label_msgid="label_collection_source", description="Aquisition source of the collection.", description_msgid="help_collection_source", domain="mars", ),
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
widget=StringField._properties['widget']( label="Feed URL", size=80, maxlength=1024, label_msgid='PloneRSS_label_remoteURL', i18n_domain='PloneRSS', ), ), ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema rss_feed_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class rss_feed(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.Irss_feed) meta_type = 'rss_feed' _at_rename_after_creation = True
'projectedAssignments', searchable=False, required=True, default=0, validators=('isInt', validators.POSITIVE_NUMBER_VALIDATOR_NAME), widget=IntegerWidget( label="Projected Number of Assignments", label_msgid="label_projected_assignments", description="Projected number of assignments, 0 means undefined", description_msgid="help_projected_assignments", i18n_domain=config.I18N_DOMAIN, ), ), ), ) ECFolder_schema = ATFolderSchema.copy() + schema.copy() class ECFolder(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.IECFolder) meta_type = 'ECFolder' _at_rename_after_creation = True schema = ECFolder_schema # Methods
label_msgid='PloneRSS_label_rss_feeds', description_msgid='PloneRSS_help_rss_feeds', i18n_domain='PloneRSS', ), allowed_types=('rss_feed',), multiValued=1, relationship='feeds', ), ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema rss_instance_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class rss_instance(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.Irss_instance) meta_type = 'rss_instance' _at_rename_after_creation = True
from Products.Archetypes.public import IntDisplayList from Products.Archetypes.public import registerType # from ATContentType from Products.ATContentTypes.content.schemata import finalizeATCTSchema from Products.ATContentTypes.interfaces import IATFolder from Products.ATContentTypes.content.folder import ATFolder from Products.ATContentTypes.content.folder import ATFolderSchema from Products.ATContentTypes.configuration import zconf from Products.CMFCore.utils import getToolByName # the configruation info for this project. from iscorpio.plonepm.config import PROJECTNAME # the schema for XPointTask. XPointTaskSchema = ATFolderSchema.copy() + Schema( ( # text field for details description for this task. TextField( 'xptask_text', searchable=True, required=True, default_output_type='text/x-html-safe', widget=RichWidget( label='Task description', rows=25, ), ), # planned completed date, 90% finish deadline
schema = Schema(( TextField('text', required=False, searchable=True, storage=AnnotationStorage(), validators=('isTidyHtmlWithCleanup',), default_output_type='text/x-html-safe', widget=RichWidget(label=_(u"Body Text"), description=_(u""), rows=25, allow_file_upload=False) ), )) TalkFolderSchema = ATFolderSchema.copy() + schema.copy() TalkFolderSchema['title'].storage = AnnotationStorage() TalkFolderSchema['description'].storage = AnnotationStorage() finalizeATCTSchema(TalkFolderSchema, folderish=True, moveDiscussion=False) class TalkFolder(ATFolder): """Talk Folder """ implements(ITalkFolder) portal_type = "Talk Folder" _at_rename_after_creation = True
searchable=False, required=True, default=0, validators=("isInt", "isPositive"), widget=IntegerWidget( label="Projected Number of Assignments", label_msgid="label_projected_assignments", description="Projected number of assignments", description_msgid="help_projected_assignments", i18n_domain=I18N_DOMAIN, ), ), ) ) ECFolderSchema = ATFolderSchema.copy() + ECFolderSchema finalizeATCTSchema(ECFolderSchema, folderish=True, moveDiscussion=False) class ECFolder(ATFolder): """A container for assignment boxes""" schema = ECFolderSchema content_icon = "ecfolder.png" portal_type = meta_type = "ECFolder" archetype_name = "ECFolder" immediate_view = "ecfolder_view" default_view = "ecfolder_view" # suppl_views = () #('all_assignments', 'by_student',) allowed_content_types = []
from Products.Archetypes import atapi from zope.interface import implements import interfaces from Products.Doormat.content.DoormatMixin import DoormatMixin from Products.ATContentTypes.content.folder import ATFolder from Products.ATContentTypes.content.folder import ATFolderSchema from Products.Doormat.config import PROJECTNAME schema = atapi.Schema(( ), ) DoormatColumn_schema = ATFolderSchema.copy() + \ getattr(DoormatMixin, 'schema', atapi.Schema(())).copy() + \ schema.copy() class DoormatColumn(ATFolder, DoormatMixin): """ """ security = ClassSecurityInfo() implements(interfaces.IDoormatColumn) meta_type = 'DoormatColumn' _at_rename_after_creation = True schema = DoormatColumn_schema
schema = Schema((LinesField( name='showFields', widget=MultiSelectionWidget( format="checkbox", label='Showfields', label_msgid='Communities_label_showFields', i18n_domain='Communities', ), vocabulary="getMyFields", searchable=1, ), ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema STDSetup_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class STDSetup(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.ISTDSetup, IStandardsSetup) meta_type = 'STDSetup' _at_rename_after_creation = True
from Products.ATContentTypes.content.schemata import finalizeATCTSchema from Products.ATContentTypes.content.folder import ATFolderSchema from Products.ATContentTypes.content.folder import ATFolder from Products.ATReferenceBrowserWidget.ATReferenceBrowserWidget \ import ReferenceBrowserWidget # local imports from Products.ECAssignmentBox.config import * from Products.ECAssignmentBox import permissions from Products.ECAssignmentBox.ECAssignment import ECAssignment from Statistics import Statistics from PlainTextField import PlainTextField ECAssignmentBoxSchema = ATFolderSchema.copy() + Schema(( ReferenceField( 'assignment_reference', allowed_types = ('ECAssignmentTask',), required = False, accessor = 'getReference', index = "FieldIndex:schema", # Adds "getRawAssignment_reference" # to catalog multiValued = False, relationship = 'alter_ego', widget = ReferenceBrowserWidget( description = 'Select an assignment task. A reference to an assignment task supersedes the assignment text and answer template below.', description_msgid = 'help_assignment_reference', i18n_domain = I18N_DOMAIN, label = 'Reference to assignment', label_msgid = 'label_assignment_reference',
required = True, default = 0, validators = ('isInt', validators.POSITIVE_NUMBER_VALIDATOR_NAME), widget = IntegerWidget( label = "Projected Number of Assignments", label_msgid = "label_projected_assignments", description = "Projected number of assignments, 0 means undefined", description_msgid = "help_projected_assignments", i18n_domain = config.I18N_DOMAIN, ), ), ), ) ECFolder_schema = ATFolderSchema.copy() + schema.copy() class ECFolder(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.IECFolder) meta_type = 'ECFolder' _at_rename_after_creation = True schema = ECFolder_schema # Methods security.declarePrivate('getCompletedStatesVocab')
schema = Schema((LinesField( name='showFields', widget=MultiSelectionWidget( format="checkbox", label='Showfields', label_msgid='Communities_label_showFields', i18n_domain='Communities', ), vocabulary="getMyFields", searchable=1, ), ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema CommonSetup_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class CommonSetup(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.ICommonSetup, IStandardsSetup) meta_type = 'CommonSetup' _at_rename_after_creation = True
# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # """ """ __docformat__ = 'restructuredtext' from api import * from config import PROJECTNAME from schemata import * from Products.ATContentTypes.content.folder import ATFolderSchema CollectionSchema = ATFolderSchema.copy() CollectionSchema += CollectionBaseSchema.copy() CollectionSchema += Schema(( StringField( 'source', required=False, searchable=True, vocabulary=collection_source, widget=SelectionWidget( label='Source', label_msgid='label_collection_source', description='Aquisition source of the collection.', description_msgid='help_collection_source', domain='mars', ), ),
widget=IntegerField._properties['widget']( description="maximum rows shown in the listing", label="Limit", label_msgid='bungeniremotecontent_label_limit', description_msgid='bungeniremotecontent_help_limit', i18n_domain='bungeniremotecontent', ), required=True, #read_permission="Add portal content", ), ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema bungeniremotefolder_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class bungeniremotefolder(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.Ibungeniremotefolder) meta_type = 'bungeniremotefolder' _at_rename_after_creation = True
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'
description="Example: $45.00", label="Single weight price", label_msgid='ATFProduct_label_SingleWeightPrice', description_msgid='ATFProduct_help_SingleWeightPrice', i18n_domain='ATFProduct', ), required=1, ), ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema RetailFont_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class RetailFont(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.IRetailFont) meta_type = 'RetailFont' _at_rename_after_creation = True
from Products.Archetypes import atapi from zope.interface import implements from . import interfaces from Products.Doormat.content.DoormatMixin import DoormatMixin from Products.ATContentTypes.content.folder import ATFolder from Products.ATContentTypes.content.folder import ATFolderSchema from Products.Doormat.config import PROJECTNAME schema = atapi.Schema(( ), ) DoormatColumn_schema = ATFolderSchema.copy() + \ getattr(DoormatMixin, 'schema', atapi.Schema(())).copy() + \ schema.copy() class DoormatColumn(ATFolder, DoormatMixin): """ """ security = ClassSecurityInfo() implements(interfaces.IDoormatColumn) meta_type = 'DoormatColumn' _at_rename_after_creation = True schema = DoormatColumn_schema
from Products.CMFDynamicViewFTI.browserdefault import BrowserDefaultMixin from Products.ATContentTypes.content.folder import ATFolder from Products.ATContentTypes.content.folder import ATFolderSchema from Products.PloneConfContentTypes.config import * ##code-section module-header #fill in your manual code here ##/code-section module-header schema = Schema((), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema PloneConfNewsItemFolder_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class PloneConfNewsItemFolder(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.IPloneConfNewsItemFolder) meta_type = 'PloneConfNewsItemFolder' _at_rename_after_creation = True
label_msgid="label_file", i18n_domain="plone", show_content_type=False, )), StringField(name='shortId', widget=StringWidget( label="Short ID", visible=-1, description=("Short ID description."), label_msgid='dataservice_label_shortid', description_msgid='dataservice_help_shortid', i18n_domain='eea', )), ), ) Datafile_schema = ATFolderSchema.copy() + \ schema.copy() class DataFile(ATFolder): """ Dataset External File Content Type """ implements(IDatafile, IFileContent) archetype_name = portal_type = meta_type = 'DataFile' _at_rename_after_creation = True schema = Datafile_schema security = ClassSecurityInfo() security.declareProtected(View, 'get_size')
widget=ComputedField._properties['widget'](visible={ 'view': 'invisible', 'edit': 'invisible' }, ), ), ComputedField( name='location', expression="context.getLocation()", widget=ComputedField._properties['widget'](visible={ 'view': 'visible', 'edit': 'invisible' }, ), ), ), ) IndicatorFactSheet_schema = ATFolderSchema.copy() + \ getattr(ATFolder, 'schema', Schema(())).copy() + \ schema.copy() IndicatorFactSheet_schema.moveField('relatedItems', after='dpsir') class IndicatorFactSheet(ATFolder, ModalFieldEditableAware, BrowserDefaultMixin, IndicatorMixin): """ IndicatorFactSheet content class """ security = ClassSecurityInfo() implements(interfaces.IIndicatorFactSheet, interfaces.IIndicatorAssessment, IHasMandatoryWorkflowFields) meta_type = 'IndicatorFactSheet'
from Products.ATContentTypes.content.folder import ATFolderSchema from Products.ATFProduct.config import * ##code-section module-header #fill in your manual code here ##/code-section module-header schema = Schema(( ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema slide_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class slide(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.Islide) meta_type = 'slide' _at_rename_after_creation = True
from Products.ATContentTypes.content.folder import ATFolderSchema from Products.PloneConfContentTypes.config import * ##code-section module-header #fill in your manual code here ##/code-section module-header schema = Schema(( ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema PloneConfFolder_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class PloneConfFolder(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.IPloneConfFolder) meta_type = 'PloneConfFolder' _at_rename_after_creation = True
from Products.ATContentTypes.content.folder import ATFolderSchema from Products.Communities.config import * ##code-section module-header #fill in your manual code here ##/code-section module-header schema = Schema(( ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema Ontologies_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class Ontologies(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.IOntologies) meta_type = 'Ontologies' _at_rename_after_creation = True
from Products.ZMetadata import Global ##code-section module-header #fill in your manual code here from Products.ATContentTypes.content.topic import ATTopic ##/code-section module-header schema = Schema(( ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema MetadataCollection_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class MetadataCollection(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.IMetadataCollection) meta_type = 'MetadataCollection' _at_rename_after_creation = True
label_msgid="PM_Task_Introduction_label", description="Presentation of the task", description_msgid="PM_Task_Introduction_description", i18n_domain="projectmanager", ), default_output_type="text/html", write_permission="Modify portal content", read_permission="View", ), ) ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema PM_Task_schema = ATFolderSchema.copy() + schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class PM_Task(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.IPM_Task) meta_type = "PM_Task" _at_rename_after_creation = True
from Products.ZMetadata import Global ##code-section module-header #fill in your manual code here from Products.ATContentTypes.content.topic import ATTopic ##/code-section module-header schema = Schema(( ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema MetadataContainer_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class MetadataContainer(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.IMetadataContainer) meta_type = 'MetadataContainer' _at_rename_after_creation = True
# import Plone translation: from Products.CMFPlone.i18nl10n import utranslate ##code-section module-header #fill in your manual code here ##/code-section module-header #schema = Schema(( # #), #) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema AnnouncementsFolderSchema = ATFolderSchema.copy() + Schema(()) ##code-section after-schema #fill in your manual code here ##/code-section after-schema class AnnouncementsFolderMeta(type): def __init__(self, name, bases, attrs): cls = super(AnnouncementsFolderMeta, self).__init__(name, bases, attrs) if cls.platform is not None: register_announcementsfolder_implementation(klass.platform, cls) return cls class AnnouncementsFolder(ATFolder): """A folder that contains all site Announcement objects."""
from Products.Archetypes.atapi import IntegerWidget from Products.Archetypes.atapi import BooleanWidget from Products.CMFCore.utils import getToolByName #from Products.ATContentTypes.content.base import registerATCT #from Products.ATContentTypes.content.schemata import finalizeATCTSchema #from Products.ATReferenceBrowserWidget.ATReferenceBrowserWidget import ReferenceBrowserWidget from archetypes.referencebrowserwidget.widget import ReferenceBrowserWidget from Products.ECAssignmentBox.content import validators from Products.ECAssignmentBox import config #from Products.ECAssignmentBox import LOG ECAssignmentBox_schema = ATFolderSchema.copy() + Schema(( ReferenceField( 'assignment_reference', allowed_types = ('ECAssignmentTask',), required = False, accessor = 'getReference', index = "FieldIndex:schema", # Adds "getRawAssignment_reference" # to catalog multiValued = False, relationship = 'alter_ego', widget = ReferenceBrowserWidget( description = 'Select an assignment task. A reference to an assignment task supersedes the assignment text and answer template below.', description_msgid = 'help_assignment_reference', i18n_domain = config.I18N_DOMAIN, label = 'Reference to assignment', label_msgid = 'label_assignment_reference',
schema = Schema(( TextField('text', required=False, searchable=True, storage=AnnotationStorage(), validators=('isTidyHtmlWithCleanup',), default_output_type='text/x-html-safe', widget=RichWidget(label=_(u"Body Text"), description=_(u""), rows=25, allow_file_upload=False) ), )) SponsorFolderSchema = ATFolderSchema.copy() + schema.copy() SponsorFolderSchema['title'].storage = AnnotationStorage() SponsorFolderSchema['description'].storage = AnnotationStorage() finalizeATCTSchema(SponsorFolderSchema, folderish=True, moveDiscussion=False) class SponsorFolder(ATFolder): """Sponsor Folder """ implements(ISponsorFolder) portal_type = "Sponsor Folder" _at_rename_after_creation = True
class Course(ATFolder): """ A Course belongs to a specific Department although it can contain tutorials from any Department. A course has a specific code which is used together with the Department code to uniquely identify the Course. Students can be enrolled in a Course. A course is implemented as a folder which can contain additional files corresponding to relevant Literature and has references to the tutorials which belong to it. It also implements a list of students which have enrolled in the course. Only registered users of the tutor-web can enroll in a course. It is implemented as an ATFolder as well as interfaces, ICourse and IOrderedTutorWebContent. """ schema = ATFolderSchema.copy() + Schema(( StringField( 'title', required=True, searchable=0, default='Course', widget=StringWidget( label='Title', descriptio='Course title', ), ), ReferenceField( 'Tutorials', widget=ReferenceBrowserWidget( label="Tutorials", description='Tutorials which belong to the course', destination=".", destination_types=("Tutorial", ), allow_sorting=1, ), multiValued=True, relationship='hasTutorial', allowed_types=("Tutorial", ), ), StringField( 'Students', vocabulary='getAvailableStudents', widget=InAndOutWidget( label='Students', description='Students enrolled in the course.', ), ), StringField( 'Code', widget=StringWidget( label='Numberic Course Code', description= 'Specify a numberid code which is used to identify the course. For example: 101, 202', ), required=1, validators=('isSameCourseCode', ), ), ComputedField( 'numTutorials', expression='context.computeNumTutorials()', widget=StringWidget(modes=('view', )), ), )) __implements__ = (ATFolder.__implements__) implements(ICourse, IOrderedTutorWebContent) global_allow = True meta_type = 'Course' # zope type name portal_type = meta_type # plone type name archetype_name = 'Course' # friendly type name _at_rename_after_creation = True security = ClassSecurityInfo() def publishAll(self, typeofobject=None, originalobj=None): """publich content""" self.tryWorkflowAction("publish", ignoreErrors=True) def computeGrades(self, userId): """return the grade for a student based on userId""" # FIXME, what is userId is not a alid id??? tutorials = self.getTutorials() numtutorials = len(tutorials) points = 0.0 for tut in tutorials: points = points + tut.computeGrades(userId) if (numtutorials > 0): return float(points / numtutorials) else: return 0.0 def addUser(self): """enroll the logged in user""" pm = self.portal_membership memberId = pm.getAuthenticatedMember().getId() member = pm.getMemberById(memberId) userfull = member.getProperty('fullname') pair = [] pair.append((userfull, memberId)) # should check if already enrolled studs = self.getStudents() if (type(studs) == type('itsastring')): l = [] l.append(studs) l.append(memberId) self.getField('Students').set(self, l) else: studs.append(memberId) self.getField('Students').set(self, studs) def getEnrolledStudents(self): """return all enrolled students""" stud = self.getStudents() if (type(stud) == type('itsastring')): l = [] l.append(stud) return l else: return self.getStudents() def getAvailableStudents(self): """return all registered members of the tutor-web""" # FIXME this could be far too big a list to be return in one go # needs to return only partly pm = self.portal_membership pair = [] for memberId in pm.listMemberIds(): member = pm.getMemberById(memberId) userfull = member.getProperty('fullname') pair.append((memberId, userfull)) return DisplayList(pair) def getAvailableStudents2(self): """return all registered users of the tutor-web""" pm = self.portal_membership results = pm.listMembers() pair = [] for r in results: pair.append((r.UID, r.Title)) return DisplayList(pair) def getAvailableStudents1(self): """return all registered members of the tutor-web""" memb = self.portal_membership portal_users = getToolByName(self, "acl_users") membership = getToolByName(self, 'portal_membership') #Beware if hundreds of students this is very expensive! # need to use search tool results = membership.listMembers() numstuds = str(len(results)) for r in results: r1 = r.getUser() userid = r1.getId() userfull1 = membership.getMemberById(userid) userfull = userfull1.getProperty('fullname') pair = [] for c in results: r = c.getUser() pair.append((r.getUserName(), r.getId())) return DisplayList(pair) def portalUrl(self): """Return the url of the site which the course belongs to """ portal = getToolByName(self, 'portal_url').getPortalObject() return portal def isLoggedOn(self): """True of user has logged in to the tutor-web else Fase""" mtool = getToolByName(self, 'portal_membership') if mtool.isAnonymousUser(): return False else: return True def getCourseCode(self): return self.getCode() security.declarePrivate('initializeObject') def initializeObject(self): """Called after course has been created for the first time, publish course and reorder department objects""" self.tryWorkflowAction("publish", ignoreErrors=True) parent = aq_parent(self) try: parent.orderObjects("id") parent.plone_utils.reindexOnReorder(parent) except: raise 'Failed to create course ' + self.getTitle( ) + ' not able to reorder courses' security.declarePrivate('tryWorkflowAction') def tryWorkflowAction(self, action, ignoreErrors=False, comment=None): """try to change actions for course""" 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 canSeeQuestions(self): """if current user has the role of a manager, editor, owner or belongs to the group: teacher then return True else False""" try: user = getSecurityManager().getUser() groups = user.getGroups() if (user.has_role('Manager')): return True elif (user.has_role('Editor')): return True elif (user.has_role('Owner')): return True elif ('teacher' in groups): return True else: return False except: '''could not establish who user is''' return False def generateNewId(self): """Suggest an id for this object based on Department code and Course code. This id is used when automatically renaming an object after creation. """ parent = aq_parent(self) title = (parent.getCode() + self.getCode()).strip() # Can't work w/o a title if not title: return None # Don't do anything without the plone.i18n package if not URL_NORMALIZER: return None if not isinstance(title, unicode): charset = self.getCharset() title = unicode(title, charset) request = getattr(self, 'REQUEST', None) if request is not None: return IUserPreferredURLNormalizer(request).normalize(title) return queryUtility(IURLNormalizer).normalize(title) security.declareProtected(View, 'computeNumTutorials') def computeNumTutorials(self): """find number of tutorials which belong to this course""" refs = self.getRawTutorials() return len(refs) def updateSlideMaterial(self): """Update all slides for every tutorial/lecture belonging to the course.""" tuts = self.getTutorials() for tut in tuts: tmp = tut.updateSlideMaterial() def getFullName(self, userid): """Return the full name of a user based on given id""" # FIXME what if id is not valid??? if PLONE_VERSION == 3: ecq_tool = getToolByName(self, 'ecq_tool') return ecq_tool.getFullNameById(userid) else: parent = aq_parent(self) return parent.getFullName(userid)
visible=-1, description=("Short ID description."), label_msgid='dataservice_label_shortid', description_msgid='dataservice_help_shortid', i18n_domain='eea', ) ), # Fields for 'relations' schemata LinesField( schemata="categorization", name='externalRelations', languageIndependent=True, widget=LinesWidget( label="External links, non EEA websites", description=("External links, non EEA websites. " "Please write http:// in front of the links."), label_msgid='dataservice_label_external', description_msgid='dataservice_help_external', i18n_domain='eea', ) ), ),) dataservice_schema = ATFolderSchema.copy() + \ getattr(ThemeTaggable, 'schema', Schema(())).copy() + \ dataservice_base_schema.copy() dataservice_schema['description'].widget.rows = 15 dataservice_schema['description'].required = True
from Products.ATContentTypes.content.folder import ATFolderSchema from Products.PloneBooking.content.vocabulary import REQUIRED_FILTERS from Products.PloneBooking.content.vocabulary import CALENDAR_VIEWS from Products.PloneBooking.content.vocabulary import VIEW_MODES from Products.PloneBooking.content.vocabulary import LISTING_VIEWS from Products.PloneBooking.content.vocabulary import GLOBAL_BOOKING_REVIEW_MODES from Products.PloneBooking.content.vocabulary import CALENDAR_REFRESH_MODES from Products.PloneBooking.config import PROJECTNAME, I18N_DOMAIN from Products.PloneBooking.interfaces import IBookingCenter from Products.PloneBooking import BookingPermissions from Products.PloneBooking import _ DISPLAY_SCHEMATA = 'display' BookingCenterSchema = ATFolderSchema.copy() + Schema(( LinesField( 'types', required=True, widget=LinesWidget( label=_( u'label_types', default=u'Types' ), description= _( u'label_bookingcenter_types', default=u'You can define here a list of bookable object'\ ' types (1 by line)' ), ), ),
label_msgid='dataservice_label_category', description_msgid='dataservice_help_category', i18n_domain='eea', )), StringField(name='shortId', widget=StringWidget( label="Short ID", visible=-1, description="Short ID description.", label_msgid='dataservice_label_shortid', description_msgid='dataservice_help_shortid', i18n_domain='eea', )), ), ) eeafigurefile_schema = ATFolderSchema.copy() + schema.copy() class EEAFigureFile(ATFolder): """ EEAFigureFile Content Type """ implements(IEEAFigureFile, IFileContent) archetype_name = portal_type = meta_type = 'EEAFigureFile' allowed_content_types = [ 'ATImage', 'File', 'Folder', 'DataFile', 'DataTable' ] _at_rename_after_creation = True schema = eeafigurefile_schema security = ClassSecurityInfo()
from Products.ATContentTypes.content.folder import ATFolderSchema from Products.Doormat.config import * ##code-section module-header #fill in your manual code here ##/code-section module-header schema = Schema(( ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema Doormat_schema = ATFolderSchema.copy() + \ getattr(DoormatMixin, 'schema', Schema(())).copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class Doormat(ATFolder, DoormatMixin): """ """ security = ClassSecurityInfo() implements(interfaces.IDoormat) meta_type = 'Doormat' _at_rename_after_creation = True
# -*- coding: utf-8 -*- from AccessControl import ClassSecurityInfo from Products.ATContentTypes.content.folder import ATFolder from Products.ATContentTypes.content.folder import ATFolderSchema from Products.Archetypes.atapi import Schema, registerType from Products.Doormat.content.DoormatMixin import DoormatMixin from Products.Doormat.config import PROJECTNAME from zope.interface import implements from . import interfaces schema = Schema((), ) Doormat_schema = ATFolderSchema.copy() + \ getattr(DoormatMixin, 'schema', Schema(())).copy() + \ schema.copy() class Doormat(ATFolder, DoormatMixin): """ """ security = ClassSecurityInfo() implements(interfaces.IDoormat) meta_type = 'Doormat' _at_rename_after_creation = True schema = Doormat_schema
schemata="Summary", ), TextField( name='additional_sum_req', allowable_content_types=('text/html'), widget=TextAreaWidget( label="Additional Summary Fields", description= 'Add any additional summary fields here. Leave a single space between fields and use the following html format for styling consistency:<br/><code> <label class="formQuestion">F. Summary Field Title</label><br/>Summary Field Body Text<br/><br/></code>', ), default_output_type='text/html', schemata="Summary", ), )) ProgramSchema = ATFolderSchema.copy() + schema.copy() ProgramSchema['title'].widget.label = "Program Title" ProgramSchema['description'].widget.label = "Program Description" class Program(ATFolder): ##ATBaseContent constructor """ Folderish type to hold Program-related information that should be contained by a Bulletin -> Department type """ security = ClassSecurityInfo() implements(interfaces.IProgram, interfaces.IBatchPrintable, ITOCRoot) archetype_name = 'Program' meta_type = 'Program'
), multiValued=1, relationship='Previous', vocabulary='getOtherActions', allowed_types=('PM_Action',), write_permission="PM : write action initial informations", read_permission="PM : read action informations", ), ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema PM_Action_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class PM_Action(ATFolder): """ Action """ security = ClassSecurityInfo() implements((interfaces.IPM_Action, ICalendarSupport)) meta_type = 'PM_Action' _at_rename_after_creation = True
from Products.PloneFormGen.config import \ PROJECTNAME, \ EDIT_TALES_PERMISSION, EDIT_ADVANCED_PERMISSION, BAD_IDS from Products.PloneFormGen.content import validationMessages from Products.PloneFormGen import PloneFormGenMessageFactory as _ from Products.PloneFormGen import implementedOrProvidedBy from Products.PloneFormGen import HAS_PLONE40 from types import StringTypes import zope.i18n logger = logging.getLogger("PloneFormGen") FormFolderSchema = ATFolderSchema.copy() + Schema(( StringField( 'submitLabel', required=0, searchable=0, default="Submit", widget=StringWidget( label=_(u'label_submitlabel_text', default=u"Submit Button Label"), description=_(u'help_submitlabel_text', default=u""), ), ), BooleanField( 'useCancelButton', required=0, searchable=0, default='0',
name='frequency_of_updates', schema=frequency_of_updates_schema, schemata='default', required_for_published=True, validators=('validate_frequency_years',), #required=True, widget=CompoundWidget( label="Frequency of updates", description="How often is this indicators assessments updates?", label_msgid='indicators_label_frequency_of_updates', description_msgid='indicators_help_frequency_of_updates', ), ), )) Specification_schema = ATFolderSchema.copy() + \ getattr(ATFolder, 'schema', Schema(())).copy() + \ schema.copy() # Batch reorder of the fields #this is created like this because we want explicit control over how the #schemata fields are ordered and changing this in the UML modeler is just too #time consuming _field_order = [ { 'name':'default', 'fields':['title', 'description', 'more_updates_on',
from Products.ATContentTypes.content.folder import ATFolder from Products.ATContentTypes.content.folder import ATFolderSchema from Products.Communities.config import * from Products.ZMetadata import Global ##code-section module-header #fill in your manual code here from Products.ATContentTypes.content.topic import ATTopic ##/code-section module-header schema = Schema((), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema MetadataContainer_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class MetadataContainer(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.IMetadataContainer) meta_type = 'MetadataContainer' _at_rename_after_creation = True
from Products.ATContentTypes.content.folder import ATFolderSchema, ATFolder from Products.ATContentTypes.content.schemata import finalizeATCTSchema from Products.ATContentTypes.content.base import registerATCT from Products.PloneFormGen.config import * from Products.PloneFormGen.widgets import \ FieldsetStartWidget, FieldsetEndWidget from Products.PloneFormGen import PloneFormGenMessageFactory as _ from Products.PloneFormGen import HAS_PLONE25 if HAS_PLONE25: import zope.i18n FieldsetFolderSchema = ATFolderSchema.copy() + Schema(( BooleanField('useLegend', required=0, searchable=0, default='1', widget=BooleanWidget(label='Show Title as Legend', label_msgid = "label_showlegend_text", description_msgid = "help_showlegend_text", i18n_domain = "ploneformgen", ), ), )) FieldsetFolderSchema['description'].widget.label = 'Fieldset Help' FieldsetFolderSchema['description'].widget.i18n_domain = 'ploneformgen' FieldsetFolderSchema['description'].widget.label_msgid = 'label_fieldsethelp_text'
# Plone 3 from zope.app.container.contained import ObjectRemovedEvent from Products.ATContentTypes.config import HAS_LINGUA_PLONE if HAS_LINGUA_PLONE: from Products.LinguaPlone.public import registerType else: from Products.Archetypes.atapi import registerType from ftw.shop import shopMessageFactory as _ from ftw.shop.interfaces import IShopCategory from ftw.shop.config import PROJECTNAME from ftw.shop.content.categorizeable import Categorizeable ShopCategorySchema = ATFolderSchema.copy() + atapi.Schema(( atapi.ReferenceField( 'supplier', required = 0, languageIndependent=True, relationship = 'item_supplier', vocabulary_factory="ftw.shop.suppliers_vocabulary", widget = atapi.ReferenceWidget( label = _(u"label_supplier", default=u"Supplier"), description = _(u"desc_supplier", default=u""), checkbox_bound = 10, ), ), ))
from Products.ATContentTypes.content.folder import ATFolder, ATFolderSchema from Products.ATContentTypes.content.base import registerATCT from Products.ATContentTypes.content.schemata import finalizeATCTSchema from Products.CMFPlone import PloneMessageFactory as _ from Products.CMFCore.permissions import View from Products.validation import V_REQUIRED from interfaces import ILocation, ILocations from ..config import PROJECTNAME from ..fields import LocationAreaField from ..widgets import LocationAreaWidget LocationSchema = ATFolderSchema.copy() + Schema(( ImageField('map', required=True, primary=True, languageIndependent=True, storage = AnnotationStorage(migrate=True), swallowResizeExceptions = zconf.swallowImageResizeExceptions.enable, pil_quality = zconf.pil_config.quality, pil_resize_algo = zconf.pil_config.resize_algo, max_size = zconf.ATImage.max_image_dimension, sizes= {'large' : (768, 768), 'preview' : (400, 400), 'mini' : (200, 200), 'thumb' : (128, 128), 'tile' : (64, 64), 'icon' : (32, 32),
LinesField( name='category', widget=LinesField._properties['widget']( label='Category', label_msgid='eduBiblio_label_category', i18n_domain='eduBiblio', ) ), ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema Biblio_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class Biblio(ATFolder): """ """ security = ClassSecurityInfo() implements(IBiblio) meta_type = 'Biblio' _at_rename_after_creation = True schema = Biblio_schema
from Products.Archetypes.public import * # ATCT from Products.ATContentTypes.content.folder import ATFolderSchema, ATFolder from Products.ATContentTypes.content.schemata import finalizeATCTSchema # Plone from Products.CMFPlone.i18nl10n import utranslate # PR from Products.PressRoom import HAS_PLONE40 from Products.PressRoom.config import * from Products.PressRoom.interfaces.content import IPressRoom ATPressRoomSchema = ATFolderSchema.copy() ATPressRoomSchema += Schema(( BooleanField('show_releases', required=0, default=True, widget = BooleanWidget( label = "Display Releases?", label_msgid = "label_show_releases", description = "If this is checked, your published releases will appear.", description_msgid = "help_show_release", i18n_domain = "pressroom",), ), IntegerField('num_releases', required=0, default=4, widget = IntegerWidget(
#802, Building No. 1, #Dheeraj Sagar, Malad(W) #Mumbai-400064, India ############################################################################### from Products.Archetypes.atapi import * from Products.ATContentTypes.content.folder \ import ATFolder as BaseClass from Products.ATContentTypes.content.folder \ import ATFolderSchema as DefaultSchema from Products.ATContentTypes.content.base import registerATCT from ubify.coretypes.config import PROJECTNAME schema = DefaultSchema.copy() class GenericContainer(BaseClass): __doc__ = BaseClass.__doc__ + "(customizable version)" # portal_type = BaseClass.portal_type # archetype_name = BaseClass.archetype_name schema = schema _at_rename_after_creation = True # enable FTP/WebDAV and friends PUT = BaseClass.PUT registerATCT(GenericContainer, PROJECTNAME)
allowable_content_types=('text/plain', 'text/structured', 'text/html', 'application/msword',), widget=RichWidget( label='Body', label_msgid='ATFProduct_label_body', i18n_domain='ATFProduct', ), default_output_type='text/html', ), ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema GenericEntry_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class GenericEntry(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.IGenericEntry) meta_type = 'GenericEntry' _at_rename_after_creation = True
from rfa.kaltura.kutils import kconnect from rfa.kaltura.kutils import kcreateEmptyFilterForPlaylist from rfa.kaltura.content import base as KalturaBase from KalturaClient.Plugins.Core import KalturaPlaylist as API_KalturaPlaylist from KalturaClient.Plugins.Core import KalturaMediaEntryFilterForPlaylist from zope.i18nmessageid import MessageFactory _ = MessageFactory('kaltura_video') BaseKalturaPlaylistSchema = schemata.ATContentTypeSchema.copy( ) + KalturaBase.KalturaBaseSchema.copy() ManualKalturaPlaylistSchema = BaseKalturaPlaylistSchema.copy() + \ ATFolderSchema.copy() + \ atapi.Schema( (atapi.ReferenceField('playlistVideos', relationship = 'playlist_videos', allowed_types=('KalturaVideo',), multiValued = True, isMetadata = False, accessor = 'getPlaylistVideos', mutator = 'setPlaylistVideos', required=False, default=(), widget = ReferenceBrowserWidget( addable = False, destination = [], allow_search = True, allow_browse = True,
), ReferenceField( 'assocFacultyListing', widget=ReferenceWidget( label="Faculty Listing", description= "Select a faculty listing to be associated with this bulletin", ), relationship="WorksWith", vocabulary_display_path_bound=-1, allowed_types=('Faculty_Listing', ), multiValued=0, ), )) BulletinSchema = ATFolderSchema.copy() + schema.copy() BulletinSchema[ 'title'].widget.description = "A generic title for the bulletin(i.e. Graduate Bulletin 2010-2012)" class Bulletin(ATFolder): """ """ faculty_listing = ATReferenceFieldProperty( 'assocFacultyListing' ) ##archetypes fields must be bridged to python properties using ATReferenceFieldProperty not ATFieldProperty security = ClassSecurityInfo() implements(interfaces.IBulletin, interfaces.IBatchPrintable, ITOCRoot)
from Products.ATContentTypes.content.folder import ATFolderSchema from Products.PloneConfContentTypes.config import * ##code-section module-header #fill in your manual code here ##/code-section module-header schema = Schema(( ), ) ##code-section after-local-schema #fill in your manual code here ##/code-section after-local-schema PloneConfNewsItemFolder_schema = ATFolderSchema.copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here ##/code-section after-schema class PloneConfNewsItemFolder(ATFolder): """ """ security = ClassSecurityInfo() implements(interfaces.IPloneConfNewsItemFolder) meta_type = 'PloneConfNewsItemFolder' _at_rename_after_creation = True
class Class(ATFolder): """ A Course belongs to a specific Department although it can contain tutorials from any Department. A course has a specific code which is used together with the Department code to uniquely identify the Course. Students can be enrolled in a Course. A course is implemented as a folder which can contain additional files corresponding to relevant Literature and has references to the tutorials which belong to it. It also implements a list of students which have enrolled in the course. Only registered users of the tutor-web can enroll in a course. It is implemented as an ATFolder as well as interfaces, ICourse and IOrderedTutorWebContent. """ schema = ATFolderSchema.copy() + Schema(( StringField( 'title', required=True, searchable=0, default='Class name', widget=StringWidget( label='Title', description='Class name', ), validators=('isSameClassName', ), ), StringField( 'classDatabaseId', widget=StringWidget( label="Database Id", visible={ 'edit': 'invisible', 'view': 'invisible' }, ), ), ReferenceField( 'Tutorials', widget=ReferenceBrowserWidget( label="Tutorials", description='Tutorials which belong to the class', destination=".", destination_types=("Tutorial", ), allow_sorting=1, ), #allow_sorting=1, multiValued=True, relationship='hasTutorial', allowed_types=("Tutorial", ), ), StringField( 'Students', vocabulary='getAvailableStudents', widget=InAndOutWidget( label='Students', description='Students enrolled in the course.', visible={ 'edit': 'invisible', 'view': 'invisible' }, ), ), StringField( 'Instructor', #vocabulary='getAvailableStudents', default='', widget=StringWidget( label='Instructor', description='Instructor of the class.', ), ), StringField( 'ContactInformation', #vocabulary='getAvailableStudents', default='', widget=StringWidget( label='Contact Information', description='How to contact instructor of the class.', ), ), ComputedField( 'numTutorials', expression='context.computeNumTutorials()', widget=StringWidget(modes=('view', )), ), )) __implements__ = (ATFolder.__implements__) implements(IClass) global_allow = True meta_type = 'Class' # zope type name portal_type = meta_type # plone type name archetype_name = 'Class' # friendly type name _at_rename_after_creation = True security = ClassSecurityInfo() def publishAll(self, typeofobject=None, originalobj=None): """publich content""" self.tryWorkflowAction("publish", ignoreErrors=True) def computeGrades(self, userId): """return the grade for a student based on userId""" # FIXME, what is userId is not a valid id??? tutorials = self.getTutorials() numtutorials = len(tutorials) points = 0.0 for tut in tutorials: points = points + tut.computeGrades(userId) if (numtutorials > 0): return float(points / numtutorials) else: return 0.0 def addUser(self): """enroll the logged in user""" pm = self.portal_membership memberId = pm.getAuthenticatedMember().getId() member = pm.getMemberById(memberId) userfull = member.getProperty('fullname') pair = [] pair.append((userfull, memberId)) # should check if already enrolled studs = self.getStudents() if (memberId in studs): return userfull + "already enrolled in " + self.getTitle() if (type(studs) == type('itsastring')): l = [] l.append(studs) l.append(memberId) self.getField('Students').set(self, l) else: studs.append(memberId) self.getField('Students').set(self, studs) updated = self.updateDatabase(member, memberId) if updated: tit = self.getTitle() if not isinstance(tit, unicode): charset = self.getCharset() tit = unicode(tit, charset) return userfull + " has been enrolled in " + tit else: return "could not update database" ##return "bla" def updateDatabase(self, member, candidateId): #start by checking if student already registered in tutorweb # has been allocated a random number, if not register # then add to database if needed. portal_catalog = getToolByName(self, 'portal_catalog') students = portal_catalog.unrestrictedSearchResults( {'portal_type': 'StudentList'}) if (len(students) > 0): numlists = str(len(students)) objid = self.unrestrictedTraverse(str(students[0].getPath()), None) ranid = objid.addStudent(candidateId) studlocator = getUtility(IStudentLocator) studentinfo = studlocator.student_by_randomnumber(ranid) 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 #NB: Code is being migrated to tutorweb.quiz #student = StudentInformation(candidateId, ranid, firstname, familyname, email) #student.addToDataBase() # now find the student just added studentinfo = studlocator.student_by_randomnumber(ranid) # now find classinfo classlocator = getUtility(IClassLocator) # should check if databaseid is not empty string classinfo = classlocator.class_by_id(int( self.getClassDatabaseId())) #check if have date start = self.getEffectiveDate() stop = self.getExpirationDate() # maybe should set default values in initialize try: '''check if start has been set''' i = len(start) except: start = 0 try: '''check if stop has been set''' i = len(stop) except: stop = 0 #NB: Code is being migrated to tutorweb.quizdb #registration = ClassRegistrationInformation(studentinfo, classinfo, start, stop) #registration.addToDataBase() return True else: return False def getEnrolledStudents(self): """return all enrolled students""" stud = self.getStudents() if (type(stud) == type('itsastring')): l = [] l.append(stud) sortedlist = l.sort() return sortedlist else: sortedlist = self.getStudents().sort() return self.getStudents().sort() def getInstructors(self): """return all instructors""" stud = self.getInstructor() if (type(stud) == type('itsastring')): l = [] l.append(stud) return l else: return stud def getAvailableStudents(self): """return all registered members of the tutor-web""" # FIXME this could be far too big a list to be return in one go # needs to return only partly pm = self.portal_membership pair = [] for memberId in pm.listMemberIds(): member = pm.getMemberById(memberId) userfull = member.getProperty('fullname') pair.append((memberId, userfull)) return DisplayList(pair) def getAvailableStudents2(self): """return all registered users of the tutor-web""" pm = self.portal_membership results = pm.listMembers() pair = [] for r in results: pair.append((r.UID, r.Title)) return DisplayList(pair) def getAvailableStudents1(self): """return all registered members of the tutor-web""" memb = self.portal_membership portal_users = getToolByName(self, "acl_users") membership = getToolByName(self, 'portal_membership') #Beware if hundreds of students this is very expensive! # need to use search tool results = membership.listMembers() numstuds = str(len(results)) for r in results: r1 = r.getUser() userid = r1.getId() userfull1 = membership.getMemberById(userid) userfull = userfull1.getProperty('fullname') pair = [] for c in results: r = c.getUser() pair.append((r.getUserName(), r.getId())) return DisplayList(pair) def portalUrl(self): """Return the url of the site which the class belongs to """ portal = getToolByName(self, 'portal_url').getPortalObject() return portal def isLoggedOn(self): """True of user has logged in to the tutor-web else Fase""" mtool = getToolByName(self, 'portal_membership') if mtool.isAnonymousUser(): return False else: return True security.declarePrivate('initializeObject') def initializeObject(self): """Called after class has been created for the first time.""" self.tryWorkflowAction("publish", ignoreErrors=True) '''add school to database when school is created''' # get correctschoolinformation parent = aq_parent(self) #schoollocator = getUtility(ISchoolLocator) #schoolinformation = schoollocator.school_by_id(int(parent.getDatabaseId())) # set char set might have for example icelandic letters in title tit = self.getTitle() if not isinstance(tit, unicode): charset = self.getCharset() tit = unicode(tit, charset) self.setTitle(tit) email = self.getContactInformation() if not isinstance(email, unicode): charset = self.getCharset() email = unicode(email, charset) self.setTitle(email) # create class and add to database #NB: This is knobbled for now, as code migrates to tutorweb.quizdb #myclass = ClassInformation(schoolinformation, tit, email) #myclass.addToDataBase() #add database id #self.setClassDatabaseId(str(myclass.class_id)) parent = aq_parent(self) try: parent.orderObjects("id") parent.plone_utils.reindexOnReorder(parent) except: raise 'Failed to create class ' + self.getTitle( ) + ' not able to reorder classes' def editedObject(self, objtype=None): '''if class name changed, change also in database''' # Need to make sure that class name is unique before # looking for class by name - have added a validator # first get handle on the school from sql # well if copy/paste school then the title will not change #classlocator = getUtility(IClassLocator) #classlocator.updateName(self.getClassDatabaseId(), self.getTitle(), self.getContactInformation()) tit = self.getTitle() if not isinstance(tit, unicode): charset = self.getCharset() tit = unicode(tit, charset) self.setTitle(tit) # set char set email = self.getContactInformation() if not isinstance(email, unicode): charset = self.getCharset() email = unicode(email, charset) self.setContactInformation(email) classlocator = getUtility(IClassLocator) classlocator.updateName(self.getClassDatabaseId(), tit, email) security.declarePrivate('tryWorkflowAction') def tryWorkflowAction(self, action, ignoreErrors=False, comment=None): """try to change actions for class""" 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 canSeeQuestions(self): """if current user has the role of a manager, editor, owner or belongs to the group: teacher then return True else False""" try: user = getSecurityManager().getUser() groups = user.getGroups() if (user.has_role('Manager')): return True elif (user.has_role('Editor')): return True elif (user.has_role('Owner')): return True elif ('teacher' in groups): return True else: return False except: '''could not establish who user is''' return False security.declareProtected(View, 'computeNumTutorials') def computeNumTutorials(self): """find number of tutorials which belong to this class""" refs = self.getRawTutorials() return len(refs) def updateSlideMaterial(self): """Update all slides for every tutorial/lecture belonging to the class.""" tuts = self.getTutorials() for tut in tuts: tmp = tut.updateSlideMaterial() def getFullName(self, userid): """Return the full name of a user based on given id""" # FIXME what if id is not valid??? if PLONE_VERSION == 3: ecq_tool = getToolByName(self, 'ecq_tool') return ecq_tool.getFullNameById(userid) else: parent = aq_parent(self) return parent.getFullName(userid)