def __call__(self): """ Post the zipfile to the remote url as set up in the configlet. """ zip_data = self.zip_csv() # get settings registry = getUtility(IRegistry) settings = registry.forInterface(ITARMIIRemoteServerSettings) # make sure that a server has been specified if settings.server_url != None: parts = urlparse.urlparse(settings.server_url) else: msg = _('Upload Server not specified in settings') IStatusMessage(self.request).addStatusMessage(msg,"error") # redirect to show the error message return self.request.response.redirect( '/'.join(self.context.getPhysicalPath())) # send zip data to server h = httplib.HTTP(parts.netloc) # ignore leading '//' h.putrequest('POST', parts.path) now = DateTime() body = '\r\n' + zip_data memberid = os.environ['TEACHERDATA_USER'] passwd = os.environ['TEACHERDATA_PASS'] authstr = "%s:%s" % (memberid, passwd) nice_filename = '%s_%s' % ('tarmii_logs_', now.strftime('%Y%m%d')) h.putheader('Authorization', 'Basic ' + base64.b64encode(authstr)) h.putheader("Content-Disposition", "attachment; filename=%s.zip" % nice_filename) h.putheader('Content-Type', 'application/octet-stream') h.putheader('Content-Length', str(len(body))) h.putheader('Last-Modified', DateTime.rfc822(DateTime())) h.endheaders() h.send(body) errcode, errmsg, headers = h.getreply() if errcode == 200: # if upload successful, set date in registry dt = DateTime().asdatetime().replace(tzinfo=None) settings.last_successful_upload = \ datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute) msg = str(errcode) + ' : ' +_('File sent to server') IStatusMessage(self.request).addStatusMessage(msg,"info") else: msg = str(errcode) + ' : ' + _('File not sent successfully') IStatusMessage(self.request).addStatusMessage(msg,"error") log = logging.getLogger('tarmii.theme.uploadtoserver') log.error(msg) # redirect to show the error message return self.request.response.redirect( '/'.join(self.context.getPhysicalPath()))
def validate(self, value): super(RatingValidator, self).validate(value) ratings_set = Set([]) for x in range(len(value)): rating = value[x]['rating'] if rating < 0: raise Invalid(_(u"All rating values must be positive or " +\ u"equal to zero")) if rating in ratings_set: raise Invalid(_(u"All rating values must be unique")) else: ratings_set.add(rating)
def updateWidgets(self): """ Customize widget options before rendering the form. """ super(ActivityAddForm, self).updateWidgets() for x in range(len(self.groups)): if 'IRating.rating_scale' in Set(self.groups[x].fields.keys()): self.groups[x].fields['IRating.rating_scale'].field.default =\ [{'rating': 4, 'label': self.context.translate(_(u'Excellent'))}, {'rating': 3, 'label': self.context.translate(_(u'Good'))}, {'rating': 2, 'label': self.context.translate(_(u'Satisfactory'))}, {'rating': 1, 'label': self.context.translate(_(u'Needs improvement'))}]
def __call__(self): """ Return csv content as http response or return info IStatusMessage """ csv_content = self.all_activities_csv() if csv_content is not None: now = DateTime() nice_filename = '%s_%s' % ('activities_', now.strftime('%Y%m%d')) self.request.response.setHeader("Content-Disposition", "attachment; filename=%s.csv" % nice_filename) self.request.response.setHeader("Content-Type", "text/csv") self.request.response.setHeader("Content-Length", len(csv_content)) self.request.response.setHeader('Last-Modified', DateTime.rfc822(DateTime())) self.request.response.setHeader("Cache-Control", "no-store") self.request.response.setHeader("Pragma", "no-cache") self.request.response.write(csv_content) else: msg = _('No activities exist') IStatusMessage(self.request).addStatusMessage(msg,"info") # redirect to show the info message self.request.response.redirect( '/'.join(self.context.getPhysicalPath())) return csv_content
def assessment_date(self): """ Return date that assessment was created with month translated """ day = self.context.created().day() month = self.context.translate(_(self.context.created().strftime('%B'))) year = self.context.created().year() return '%s %s %s' % (day, month, year)
def validate(self, value): super(ItemIdValidator, self).validate(value) # check that id is unique # (all ids when created are URLNormalized) normalizer = getUtility(IURLNormalizer) normalized_value = normalizer.normalize(value) contentFilter =\ {"portal_type" : "upfront.assessmentitem.content.assessmentitem"} existing_ids = Set([x.getObject().id for x in self.context.getFolderContents(contentFilter)]) if normalized_value in existing_ids: raise Invalid(_(u"This Item ID is already in use"))
def scores_for_learner(self, learner): """ return all the scores of a learner for all the evaluationsheets in the specified date range. """ activity_ids = self.activity_ids() scores = [''] * len(activity_ids) buckets = range(len(activity_ids)) evalsheet = self.context contentFilter = {'portal_type': 'upfront.assessment.content.evaluation'} evaluation_objects = \ [x for x in evalsheet.getFolderContents(contentFilter, full_objects=True)] # one ev object per learner for ev in evaluation_objects: # only use the score data of the specified learner if ev.learner.to_object == learner: # x iterates through the activities each learner did for x in range(len(ev.evaluation)): score = ev.evaluation[x]['rating'] scale = ev.evaluation[x]['rating_scale'] # translate score number (int) into a rating (string) if score == 0: score = '' # Unrated are left as blanks elif score == -1: score = self.context.translate(_(u'Not Rated')) else: rating_scale = ev.evaluation[x]['rating_scale'] for y in range(len(rating_scale)): if score == rating_scale[y]['rating']: score = rating_scale[y]['label'] # find correct score bucket to place this score in. act_id = uuidToObject(ev.evaluation[x]['uid']).id notfound = True idx = 0 while notfound: if act_id == activity_ids[buckets[idx]]: # found the bucket we want scores[buckets[idx]] = score notfound = False # remove the chosen index from future searches del buckets[idx] else: # point index at the next available bucket idx += 1 return [learner.Title()] + scores
def on_video_added(video, event): """ Create Thumbnail file from a video file. """ # Only create thumbnails for Files uploaded to the videos folder # and not for files uploaded elsewhere like teacher resources if video.aq_parent.aq_parent.id != 'videos': return fd, infilename = tempfile.mkstemp() fd, outfilename = tempfile.mkstemp() try: infile = open(infilename, 'w+') infile.write(video.data) finally: infile.close() cmdargs = ['avconv', '-loglevel', 'error' , '-ss', '30', '-i', infilename, '-vcodec', 'mjpeg', '-y', '-vframes', '1', '-an', '-f', 'image2', '-s', '265x150', outfilename] process = subprocess.Popen(cmdargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() if stderr == '': #if no errors from avconv - create thumbnail image video_id = video.id + '-thumb' f = open(outfilename) try: image_data = f.read() finally: f.close() video.aq_parent.invokeFactory('Image', video_id, title=video.title, image=image_data) else: #display errors in detail request = getattr(video, "REQUEST", None) IStatusMessage(request).addStatusMessage( _(u"Thumbnail generation failed"),"error") IStatusMessage(request).addStatusMessage(stderr,"info") os.remove(infilename) os.remove(outfilename) return
def teachers(self): """ return all teachers in current school+provinces from teacher_data object """ teacher_list = [] province = self.request.get('province') school = self.request.get('school') t_data = self.teacher_data[province][school].items() for teacher in range(len(t_data)): t_obj = Teacher() t_obj.fullname = t_data[teacher][1]['fullname'] t_obj.username = t_data[teacher][1]['username'] t_obj.email = t_data[teacher][1]['email'] t_obj.mobile = t_data[teacher][1]['mobile'] t_obj.qualification = t_data[teacher][1]['qualification'] t_obj.years_teaching = t_data[teacher][1]['years_teaching'] # make date human readable date_str = datetime.strptime(t_data[teacher][1]['last_login_time'], '%d/%m/%Y %H:%M:%S').strftime('%d %B %Y') if date_str == '01 January 2000': date_str = _('Never') t_obj.last_login = date_str teacher_list.append(t_obj) return teacher_list
def update(self): super(TARMIIGlobalSectionsViewlet, self).update() for x in range(len(self.portal_tabs)): self.portal_tabs[x]['name'] =\ self.context.translate(_(self.portal_tabs[x]['name']))
def translated_date(self, date): """ Translate the month part of the date """ month = self.context.translate(_(date.strftime('%B'))) return '%s %s %s' % (date.day(), month, date.year())
def mainheading(self): return self.context.translate(_("Add Evaluation Sheet"))
def mainheading(self): return self.context.translate(_("Edit Assessment"))
def mainheading(self): return self.context.translate(_("Edit Classlist"))
from five import grok from zope.schema.vocabulary import SimpleVocabulary from zope.schema.vocabulary import SimpleTerm from tarmii.theme import MessageFactory as _ PROVINCES = SimpleVocabulary( [SimpleTerm(value=u'Eastern Cape', title=_(u'Eastern Cape')), SimpleTerm(value=u'Free State', title=_(u'Free State')), SimpleTerm(value=u'Gauteng', title=_(u'Gauteng')), SimpleTerm(value=u'Kwazulu-Natal', title=_(u'Kwazulu-Natal')), SimpleTerm(value=u'Limpopo', title=_(u'Limpopo')), SimpleTerm(value=u'Mpumalanga', title=_(u'Mpumalanga')), SimpleTerm(value=u'North West', title=_(u'North West')), SimpleTerm(value=u'Northern Cape', title=_(u'Northern Cape')), SimpleTerm(value=u'Western Cape', title=_(u'Western Cape'))] )