예제 #1
0
    def call(self, call_filename=None,
            update_details=None, label=None, category=None, example=None,
            update_sonogram=None, frequency_scale=FREQUENCY_SCALES[0],
            fft_step=DEFAULT_FFT_STEP,
            **ignored):
        if not call_filename:
            raise cherrypy.NotFound()

        fft_step = int(fft_step)

        if call_filename and update_details:
            self._storage.updateCall(call_filename, label, category, example)
            if ajax.isXmlHttpRequest():
                return # ajax update doesn't require a response

        call=self._storage.getCall(call_filename)
        if ajax.isXmlHttpRequest():
            # only sonogram updates are possible here
            assert(update_sonogram)
            return template.render('_sonogram.html', ajah=True,
                    sonogram_filename=self.getSonogram(call, frequency_scale,
                            fft_step), fft_step=fft_step,
                    frequency_scale=frequency_scale,
                    frequency_scales=FREQUENCY_SCALES)
        else:
            return template.render(station=self.getStationName(), call=call,
                    categories=",".join(self._storage.getCategoryNames()),
                    sonogram_filename=self.getSonogram(call, frequency_scale,
                            fft_step), fft_step=fft_step,
                    frequency_scale=frequency_scale,
                    frequency_scales=FREQUENCY_SCALES,
                    prev_next_files=self._storage.getPrevAndNextCalls(call))
예제 #2
0
 def index(self):
     self.g_user = cherrypy.session.get('g_user')
     roles = ['admin']
     self.page_for(roles)
     header = Markup('Welcome to Guido, <tt>%s</tt>' % (self.g_user.user_id))
     ipath = 'Admin:'
     return template.render(ipath = ipath, header=header)
예제 #3
0
 def question_answers(self, **data):
     cherrypy.session['focused_question']=data['q_id']
     focused_assignment = cherrypy.session.get('focused_assignment')
     self.g_user = cherrypy.session.get('g_user')
     self.g_term = cherrypy.session.get('g_term')
     roles = ['admin', 'ta', 'final']
     self.page_for(roles)
     sql="SELECT DISTINCT an.student_id FROM Answers an, Questions q, Assignment a, Associated_with aw \
     WHERE q.name='%s' AND q.q_no=an.q_no AND an.q_no=aw.q_no AND \
     aw.s_no=a.s_no AND a.name = '%s' AND a.term='%s' AND\
     an.status<>'DONE' ORDER BY an.student_id ASC" % (data['q_id'], focused_assignment, self.g_term)
     db=mysql.DB()
     results=db.do_query(sql)
     s_answers=[]
     for row in results:
         stud = {'student_id':row['student_id']}
         s_answers.append(stud)
     db.close()
     header=Markup('Grade an assignment (%s): <tt>%s</tt>' % (self.g_term, self.g_user.user_id))
     ipath=Markup('Admin/TA: <a href="assignment_list">Grade an \
     assignment</a> > <a href="assignment?a_id=%s"> \
     Assignment %s</a> > <a href=listByQuestion>List By \
     Question</a> > <b> Student List (Question %s)</b><font color="grey"> > \
     Grade </font>' % (focused_assignment,focused_assignment,data['q_id']))
     return template.render(ipath = ipath, header=header,\
     answers=s_answers, term=self.g_term,\
     focused_assignment=focused_assignment,focused_question=data['q_id'])
예제 #4
0
파일: ta.py 프로젝트: karissa/pointism
 def index(self):
     self.g_user = cherrypy.session.get('g_user')
     roles = ['ta', 'final']
     self.page_for(roles)
     header = Markup('Welcome to Gudio, <tt>%s</tt>' % (self.g_user.user_id))
     ipath = 'TA: '
     return template.render(ipath = ipath, header=header, g_user=self.g_user)
예제 #5
0
 def archive(self):
     self.g_user = cherrypy.session.get('g_user')
     roles = ['admin', 'ta']
     self.page_for(roles)
     header=Markup('Admin assignment archives: <tt>%s</tt>' % (self.g_user.user_id))
     ipath=Markup('Admin: <font color="grey">Archive/Load old assignments</font>')
     return template.render(ipath =ipath , header=header)
예제 #6
0
    def connect(self, address=None, remove=None, rescan=False, **ignored):
        # if already connected, then just bounce to the status page
        if hasSession(SESSION_STATION_ADDRESS_KEY):
            raise cherrypy.HTTPRedirect('/status')

        # ignore address if "rescan" was requested
        if not rescan and address:
            # if "Remove" button has been clicked, delete entry from history
            if remove:
                self._storage.removeConnection(address)
            else:
                # get the name from the address
                try:
                    name = self.getRemoteName(address)
                except urllib2.URLError:
                    return self.showConnectionFailure(
                            error="could not be established", address=address)

                self._storage.addConnection(name, address)
                setSession(SESSION_STATION_ADDRESS_KEY, address)
                setSession(SESSION_STATION_NAME_KEY, name)
                # make sure new connection's recordings are not filtered out
                if (hasSession(SESSION_FILTER_STATION_KEY)
                        and getSession(SESSION_FILTER_STATION_KEY) != name):
                    clearSession(SESSION_FILTER_STATION_KEY)
                raise cherrypy.HTTPRedirect('/status')

        return template.render(is_proxy=True, station=None,
                previous_connections=self._storage.getPreviousConnections(),
                local_connections=self.findLocalBowerbirds(rescan))
예제 #7
0
 def status(self, **ignored):
     return template.render(station = self.getStationName(),
             uptime = self.getUptime(),
             disk_space = self.getDiskSpace(),
             local_time = self.getLocalTime(),
             last_recording = self.getLastRecording(),
             next_recording = self.getNextRecording())
예제 #8
0
    def connect(self, address=None, remove=None, rescan=False, **ignored):
        # if already connected, then just bounce to the status page
        if hasSession(SESSION_STATION_ADDRESS_KEY):
            raise cherrypy.HTTPRedirect('/status')

        # ignore address if "rescan" was requested
        if not rescan and address:
            # if "Remove" button has been clicked, delete entry from history
            if remove:
                self._storage.removeConnection(address)
            else:
                # get the name from the address
                try:
                    name = self.getRemoteName(address)
                except urllib2.URLError:
                    return self.showConnectionFailure(
                        error="could not be established", address=address)

                self._storage.addConnection(name, address)
                setSession(SESSION_STATION_ADDRESS_KEY, address)
                setSession(SESSION_STATION_NAME_KEY, name)
                # make sure new connection's recordings are not filtered out
                if (hasSession(SESSION_FILTER_STATION_KEY)
                        and getSession(SESSION_FILTER_STATION_KEY) != name):
                    clearSession(SESSION_FILTER_STATION_KEY)
                raise cherrypy.HTTPRedirect('/status')

        return template.render(
            is_proxy=True,
            station=None,
            previous_connections=self._storage.getPreviousConnections(),
            local_connections=self.findLocalBowerbirds(rescan))
예제 #9
0
def home():
    try:
        lib.session.check_current_session()
    except lib.session.NoSessionError:
        redirect('/login')

    return render('home.html')
예제 #10
0
 def status(self, **ignored):
     return template.render(station=self.getStationName(),
                            uptime=self.getUptime(),
                            disk_space=self.getDiskSpace(),
                            local_time=self.getLocalTime(),
                            last_recording=self.getLastRecording(),
                            next_recording=self.getNextRecording())
예제 #11
0
파일: samplequiz.py 프로젝트: noahsemu/app
def samplequiz():
    redirect_if_not_logged_in()

    # This will be a list.
    history = requests.get('https://api.spacexdata.com/v3/history').json()

    # Randomize the order of items in the list.
    random.shuffle(history)

    # Use the first one in the randomized list as the question to ask.
    question = history[0]

    title = question['title']
    details = question['details']
    correct_answer = datetime.fromtimestamp(question['event_date_unix']).year
    possible_answers = range(2000, 2021)

    # Sometimes the date is in the question, so remove the year portion.
    details = details.replace(str(correct_answer), '????')

    return render(
        'samplequiz.html', {
            'title': title,
            'details': details,
            'correct_answer': correct_answer,
            'possible_answers': possible_answers,
        })
예제 #12
0
 def manage_class(self):
     self.g_user = cherrypy.session.get('g_user')
     roles = ['admin']
     self.page_for(roles)
     self.has_started()
     header=Markup('Admin a class (%s): <tt>%s</tt>' % (cherrypy.session.get('g_term'), self.g_user.user_id))
     ipath=Markup('Admin: <b>Manage Class</b>')
     return template.render(ipath = ipath, header=header)
예제 #13
0
 def give_grade2student(self):
     roles = ['admin', 'final']
     self.page_for(roles)
     header=Markup('Grade an assignment (%s): <tt>%s</tt>' %
         (self.g_term, self.g_user.user_id))
     ipath=Markup('Final Grader: <b>Students</b> <font color="grey"> > \
     Give a grade </font>')
     return template.render(ipath =ipath , header=header)
예제 #14
0
    def export(self,
               export_partial=None,
               start_type=None,
               start_time=None,
               duration=None,
               filter_title=None,
               filter_start=None,
               filter_finish=None,
               export=None,
               **ignored):
        # HACK: this helps development slightly
        if ignored:
            print "IGNORED", ignored

        errors = []

        if export:
            try:
                start_date_ = parseDateUI(filter_start)
            except ValueError:
                errors.append('invalid start date: "%s", must be DD/MM/YYYY' %
                              filter_start)
            try:
                finish_date_ = parseDateUI(filter_finish)
            except ValueError:
                errors.append('invalid finish date: "%s", must be DD/MM/YYYY' %
                              filter_finish)

            if export_partial and int(export_partial):
                try:
                    start_time_ = parseTimeUI(start_time)
                except ValueError:
                    errors.append(
                        'invalid start time: "%s", must be HH[:MM[:SS]]' %
                        start_time)
                try:
                    duration_ = parseTimeDelta(duration)
                except ValueError:
                    errors.append(
                        'invalid duration: "%s", must be [[HH:]MM:]SS' %
                        duration)
            errors.append('Sorry: export is not implemented yet')

        # get the recording titles for the filter, and add a "show all" option
        schedule_titles = [(NO_FILTER_TITLE, '')]
        schedule_titles.extend(
            ((title, title) for title in self._storage.getRecordingTitles()))

        return template.render(station=self.getStationName(),
                               errors=errors,
                               filter_start=filter_start,
                               filter_finish=filter_finish,
                               export_partial=export_partial,
                               start_type=start_type,
                               start_time=start_time,
                               duration=duration,
                               filter_title=filter_title,
                               schedule_titles=schedule_titles)
예제 #15
0
    def distribution(self, **data):
        self.g_term = cherrypy.session.get('g_term')
        self.g_user = cherrypy.session.get('g_user')
        roles = ['admin']
        self.page_for(roles)

        selected_grader = {}
        if len(data) == 0:
            raise cherrypy.HTTPRedirect('./add_assign')

        selected_assmt = data['assmt_name']
        self.get_assignment(selected_assmt)
        new_assmt = cherrypy.session.get('new_assmt')
        t_data = self.get_ta()
        new_assmt['tas'] = t_data.values()
        new_assmt['g_term'] = self.g_term
        questions = new_assmt['questions']  # Questions of the selected assignment
        
        if cherrypy.request.method == 'POST':
            db = mysql.DB()

            myList = questions.keys()
            myList = list(set(myList))
            q_list = self.make_string(myList)
            # Clean the Distributed table 
            sql = "DELETE FROM Distributed WHERE q_no IN (%s)"
            param = (q_list)
            db.do_commit(sql, param)

            g = re.compile("grader")
            for key, value in sorted(data.items()):
                if g.match(key):
                    sql = "INSERT INTO Distributed (q_no, instructor_id, TA_id) \
                           VALUES(%s, %s, %s)"
                    q_no = key.replace('grader_', '')
                    param = (q_no, self.g_user.user_id, key)
                    db.do_commit(sql, param)
                    selected = {}
                    for ta in new_assmt['tas']:
                        if ta.user_id == value:
                            selected[ta] = "true"
                        else:
                            selected[ta] =  None
                    selected_grader[q_no] = selected
            new_assmt["selected_grader"] = selected_grader
            db.close()
            raise cherrypy.HTTPRedirect('./finalgrader' )

        if len(data) == 0 and cherrypy.session.get('new_assmt') == None :
            raise cherrypy.HTTPRedirect('./add_assign' )
            

        header=Markup('Admin an assignment (%s): <tt>%s</tt>' % (self.g_term, self.g_user.user_id))
        ipath=Markup('Admin: <a href="add_assign">Create an assignment</a> \
        > <a href="related_assign">Related Questions</a> > \
        <b>Distribution</b> \
        <font color="grey"> > Assign Final Grader </font>')
        return template.render(ipath = ipath, header=header, new_assmt=new_assmt)
예제 #16
0
파일: auth.py 프로젝트: noahsemu/app
def get_signup():
    try:
        lib.session.check_current_session()
    except lib.session.NoSessionError:
        pass
    else:
        redirect('/')

    return render('signup.html')
예제 #17
0
 def give_grade(self):
     roles = ['admin', 'final']
     self.page_for(roles)
     self.g_user = cherrypy.session.get('g_user')
     header=Markup('Grade an assignment (%s): <tt>%s</tt>' % (self.g_term, self.g_user.user_id))
     ipath=Markup('Final Grader: <a \
     href="give_grade2student">Students</a> > \
     <b>Give a grade to ???</b>')
     return template.render(ipath =ipath , header=header)
예제 #18
0
def api_show_collections(db_name=None, collection_name=None):
    db = MongoWrapper(db_name).getCollection(collection_name)
    datas = []
    for d in db.find():
        if "_id" in d.keys():
            d["_id"] = str(d["_id"])
        d.update(json=json.dumps(d))
        datas.append(d)
    return render("list_data.jade", loader(locals()))
예제 #19
0
 def calls(self,
           sort='date_and_time',
           sort_order='asc',
           category=None,
           **ignored):
     return template.render(station=self.getStationName(),
                            calls=self._storage.getCalls(
                                sort, sort_order, category),
                            sort=sort,
                            sort_order=sort_order)
예제 #20
0
 def selected_student(self):
     roles = ['admin','ta']
     self.page_for(roles)
     header=Markup('Grade an assignment (%s): <tt>%s</tt>' % (self.g_term, self.g_user.user_id))
     ipath=Markup('Admin/TA: <a href="assignment_list">Grade an \
     assignment</a> > <a href="assignment3"> \
     Assignment 3</a> > <a href="listByStudent">List By \
     Student</a> > <b>Student 1</b> <font color="grey"> > Grade \
     </font>')
     return template.render(ipath = ipath, header=header)
예제 #21
0
    def call(self,
             call_filename=None,
             update_details=None,
             label=None,
             category=None,
             example=None,
             update_sonogram=None,
             frequency_scale=FREQUENCY_SCALES[0],
             fft_step=DEFAULT_FFT_STEP,
             **ignored):
        if not call_filename:
            raise cherrypy.NotFound()

        fft_step = int(fft_step)

        if call_filename and update_details:
            self._storage.updateCall(call_filename, label, category, example)
            if ajax.isXmlHttpRequest():
                return  # ajax update doesn't require a response

        call = self._storage.getCall(call_filename)
        if ajax.isXmlHttpRequest():
            # only sonogram updates are possible here
            assert (update_sonogram)
            return template.render('_sonogram.html',
                                   ajah=True,
                                   sonogram_filename=self.getSonogram(
                                       call, frequency_scale, fft_step),
                                   fft_step=fft_step,
                                   frequency_scale=frequency_scale,
                                   frequency_scales=FREQUENCY_SCALES)
        else:
            return template.render(
                station=self.getStationName(),
                call=call,
                categories=",".join(self._storage.getCategoryNames()),
                sonogram_filename=self.getSonogram(call, frequency_scale,
                                                   fft_step),
                fft_step=fft_step,
                frequency_scale=frequency_scale,
                frequency_scales=FREQUENCY_SCALES,
                prev_next_files=self._storage.getPrevAndNextCalls(call))
예제 #22
0
def systemd_units(_, res):

    data = {'units': systemd.units()}
    res_body = template.render('units.html', data)

    res_headers = [('Content-Type', 'text/html; charset="UTF-8"'),
                   ('Content-Length', str(len(res_body)))]

    res(wsgi.HTTP_STATUS_CODE[200], res_headers)

    return [res_body]
예제 #23
0
    def index(self, path='/', filter='type:', category=0, chart=0):

        lastupdate = time.strftime(
            "%a, %d %b %Y %H:%M %p",
            time.localtime(os.path.getmtime("%s/output/sherman.h5" % SHERMAN)))

        return template.render(path=path,
                               filter=filter,
                               category=category,
                               chart=chart,
                               lastupdate=lastupdate)
예제 #24
0
파일: xmlapp.py 프로젝트: spapadim/xmllab
 def xpath(self, xpath=None):
   exc = None  # traceback
   elts = []
   if xpath:
     try:
       elts = self.doc.xpath(xpath)
       if type(elts) != type([]):
         elts = [elts]
     except:
       exc = sys.exc_info()
   return template.render(xpath=xpath, elts=elts, exc=exc)
예제 #25
0
 def assignment(self,**data):
     cherrypy.session['focused_assignment']=data['a_id']
     self.g_user = cherrypy.session.get('g_user')
     self.g_term = cherrypy.session.get('g_term')
     roles =['admin', 'ta', 'final']
     self.page_for(roles)
     header=Markup('Admin an assignment (%s): <tt>%s</tt>' % (self.g_term, self.g_user.user_id))
     ipath=Markup('Admin/TA: <a href="assignment_list">Grade an \
     assignment</a> > \
     <b>Assignment %s</b><font color="grey">  > List By Student / \
     List By Question > Grade </font>' % (data['a_id']))
     return template.render(ipath =ipath , header=header, focused_assignment=data['a_id'], term=self.g_term)
예제 #26
0
    def show_stats(self,**data):
        self.g_user = cherrypy.session.get('g_user')
        roles = ['admin', 'ta', 'final']
        self.page_for(roles)
        header = 'Statistical Graph'
        ipath = Markup('Admin/TA <a href="../statistics">Assignment Statistics</a> > <b>Statistics by Assignment</b>')
        self.s_data = {}
        errors = {}
        s_data = {}
     
        if (self.g_term == ""):
            self.g_term = cherrypy.session.get('g_term')
        
        s = ""
        if data['split2'] == 'year':
           s = ", s.year"

        st = " order by g.finalGrade"   
        
        if data['assignment_all'] == 'all':
           sql = "Select g.s_no s_no, g.finalGrade finalGrade, count(distinct g.student_id) number, s.year Year, \
                  5*count(distinct g.student_id) ncount FROM Student s, Grade g  where \
                  g.student_id=s.user_id group by g.finalGrade"
        else:       
           sql = "SELECT g.s_no s_no, g.finalGrade finalGrade,\
                  count(distinct g.student_id) number, s.year Year, \
                  5*count(distinct g.student_id) ncount FROM Grade g, \
                  Student s, Assignment a WHERE g.student_id=s.user_id and \
                  g.s_no=a.s_no and a.name='%s' group by g.s_no, \
                  g.finalGrade" % (data['assignment_all'])
            

        sql = sql + s + st     
    
        db = mysql.DB()
        results = db.do_query(sql)
        for row in results:
            tmp_row = {'s_no':row['s_no'], 'finalGrade':row['finalGrade'], 'number':row['number']}
            stat = Stat(**tmp_row)
            
            if data['split2'] == 'year':
               stat.set_year(row['Year'])
            else:
               stat.set_year('')
            stat.set_ncount(row['ncount'])
            s_data[stat.s_no, stat.finalGrade, stat.Year]= stat
            db.close()
        self.s_data = s_data
	    
        stats = self.s_data.values()
        
        
        return template.render(ipath=ipath, header=header, stats=stats)
예제 #27
0
    def view_assign(self):
        self.g_user = cherrypy.session.get('g_user')
        self.g_term = cherrypy.session.get('g_term')
        roles = ['admin', 'ta', 'final']

        if(self.g_term == ""):
            self.g_term = cherrypy.session.get('g_term');

        result = self.assignment_status(self.g_term)

        header=Markup('View an assignment (%s): <tt>%s</tt>' % (self.g_term, self.g_user.user_id))
        ipath=Markup('Public: <b>View an assignment</b>')
        return template.render(ipath = ipath, header=header, results=result)
예제 #28
0
    def ta_details(self):
        self.g_term = cherrypy.session.get('g_term')
        self.g_user = cherrypy.session.get('g_user')
        roles = ['admin']
        self.page_for(roles)

        self.t_data = {}
        self.t_data = self.get_ta()

        header=Markup('Admin a class (%s): <tt>%s</tt>' % (self.g_term, self.g_user.user_id))
        ipath=Markup('Admin: <a href="manage_class">Manage Class</a> > \
        <b>Current TAs </b>')
        tas = self.t_data.values()
        return template.render(ipath = ipath, header=header, tas=tas)
예제 #29
0
    def index(self, A=40,B=25,C=30,D=10,F=5,Z=2):
        roles = ['admin', 'ta']
        self.page_for(roles)
        self.g_user = cherrypy.session.get('g_user')
        header=Markup('Histogram example')
        ipath=Markup('histogram example')

        A,B,C,D,F,Z = map(int,[A,B,C,D,F,Z])
        timesfive = lambda x: x * 5
        awidth,bwidth,cwidth,dwidth,fwidth,zwidth = map(timesfive,[A,B,C,D,F,Z])

        return template.render(header=header, ipath=ipath,
            awidth=awidth, bwidth=bwidth, cwidth=cwidth, dwidth=dwidth,
            fwidth=fwidth, zwidth=zwidth,
            acount=A, bcount=B, ccount=C, dcount=D, fcount=F, zcount=Z)
예제 #30
0
파일: samplequiz.py 프로젝트: noahsemu/app
def samplequiz():
    redirect_if_not_logged_in()

    title = request.POST['title']
    details = request.POST['details']
    user_answer = request.POST['user_answer']
    correct_answer = request.POST['correct_answer']

    return render(
        'samplequiz.html', {
            'title': title,
            'details': details,
            'user_answer': user_answer,
            'correct_answer': correct_answer,
        })
예제 #31
0
    def category(self, label=None, new_label=None, update_details=None,
            sort='date_and_time', sort_order='asc', **ignored):
        if update_details and new_label and new_label != label:
            self._storage.updateCategory(label, new_label)
            raise cherrypy.HTTPRedirect('/category/%s' % new_label)

        calls = self._storage.getCalls(sort, sort_order, label)
        call_sonograms = {}
        for call in calls:
            call_sonograms[call['filename']] = self.getSonogram(call,
                    FREQUENCY_SCALES[0], DEFAULT_FFT_STEP)
        return template.render(station=self.getStationName(),
                category=self._storage.getCategory(label),
                calls=calls, call_sonograms=call_sonograms, sort=sort,
                sort_order=sort_order)
예제 #32
0
    def queue(self, recording_id=None, cancel_transfer=None,
            cancel_all_transfers=None, **ignored):
        # HACK: this helps development slightly
        if ignored:
            print "IGNORED",ignored

        if cancel_all_transfers:
            self._transfer_manager.clear()
            raise cherrypy.HTTPRedirect('/recordings')

        if recording_id and cancel_transfer:
            self._transfer_manager.remove(int(recording_id))

        return template.render(is_proxy=True,
                station=getSession(SESSION_STATION_NAME_KEY),
                transfer_queue=self._transfer_manager.queue)
예제 #33
0
    def assignment_list(self):
	
        self.g_term = cherrypy.session.get('g_term')
        self.g_user = cherrypy.session.get('g_user')
        roles = ['admin', 'ta', 'final']
        self.page_for(roles)
        self.has_started()

        if(self.g_term == ""):
            self.g_term = cherrypy.session.get('g_term');

        result = self.assignment_status(self.g_term)

        header=Markup('Admin an assignment (%s): <tt>%s</tt>' % (self.g_term, self.g_user.user_id))
        ipath=Markup('Admin/TA: <b>Grade an assignment</b>')
        return template.render(ipath = ipath, header=header, results=result)
예제 #34
0
파일: base.py 프로젝트: Eric-Sun/lemon-api
 def render_string(self, template_name, **context):
     """Template render by Jinja2."""
     default_context = {
         "xsrf": self.xsrf_form_html,
         "request": self.request,
         "settings": self.settings,
         "me": self.current_user,
         "static": self.static_url,
         "handler": self,
         "config": appConfig,
     }
     context.update(default_context)
     context.update(self.ui)  # Enabled tornado UI methods.
     return render(
         path=self.settings["template_path"], filename=template_name, auto_reload=self.settings["debug"], **context
     )
예제 #35
0
    def showConnectionFailure(self, error='was lost', name=None, address=None):
        if address:
            station_address = address
        else:
            station_address = getSession(SESSION_STATION_ADDRESS_KEY)
            clearSession(SESSION_STATION_ADDRESS_KEY)

        if name:
            station_name = name
        else:
            station_name = getSession(SESSION_STATION_NAME_KEY)
            clearSession(SESSION_STATION_NAME_KEY)

        return template.render(is_proxy=True, station=None, error=error,
                station_name=station_name, station_address=station_address,
                timeout=CONNECT_FAILURE_REDIRECTION_TIMEOUT)
예제 #36
0
    def finalgrader(self, **data):
        self.g_term = cherrypy.session.get('g_term')
        self.g_user = cherrypy.session.get('g_user')
        roles = ['admin']
        self.page_for(roles)

        selected_assmt = data['assmt_name']
        self.get_assignment(selected_assmt)
        new_assmt = cherrypy.session.get('new_assmt')

        t_data = self.get_ta()
        new_assmt['g_term'] = self.g_term
        check_final = ""
        for ta in t_data.values():
            if ta.role == 'final':
                check_final = ta.user_id

        if cherrypy.request.method == 'POST':
            db = mysql.DB()
            if check_final != "":
                sql = "UPDATE User SET role='ta' WHERE user_id=%s"
                param = (check_final)
                db.do_commit(sql, param)
            sql = "UPDATE User SET role='final' WHERE user_id=%s"
            param = (data['user_id'])
            db.do_commit(sql, param)
            sql = "UPDATE Assignment SET status='Not Graded' WHERE s_no=%s"
            param = (new_assmt['s_no'])
            db.do_commit(sql, param)
            db.close()
            if len(data) > 0:
                check_final = data['user_id']

        for ta in t_data.values():
            if ta.user_id == check_final:
                ta.set_role("final")
                ta.set_final("true")

        new_assmt['check_final'] = check_final
        new_assmt['tas'] = t_data.values()

        header=Markup('Admin an assignment (%s): <tt>%s</tt>' % (self.g_term, self.g_user.user_id))
        ipath=Markup('Admin: <a href="add_assign">Create an assignment</a> \
        > <a href="related_assign">Related Questions</a> > <a \
        href="distribution">Distribution</a> \
         > <b>Assign Final Grader</b>')
        return template.render(ipath =ipath , header=header, new_assmt=new_assmt)
예제 #37
0
    def index(self, assignment=None, student=None, query=None):
        roles = ['admin', 'ta']
        self.page_for(roles)
        self.g_user = cherrypy.session.get('g_user')

        codeblocks = []
        if (assignment and student and query and present(student,assignment)):
            needle = str(query)
            student = str(student)
            assignment = str(assignment)
            codeblocks = getcodeblocks(student,assignment,query)

        header=Markup('code search')
        ipath=Markup('code search')
        return template.render(codeblocks=codeblocks,
                               ipath=ipath,
                               header=header)
예제 #38
0
파일: xmlapp.py 프로젝트: spapadim/xmllab
 def xslt(self, xslt_s=None, xslt_f=None):
   exc = None
   xslt = None
   filename = None
   doc = None
   if xslt_f and xslt_f.file:
     xslt = xslt_f.file.read()
     filename = xslt_f.filename
   elif xslt_s:
     xslt = xslt_s
   if xslt:
     try:
       xslt_doc = etree.fromstring(xslt)
       doc = self.doc.xslt(xslt_doc)
     except:
       exc = sys.exc_info()
   return template.render(xslt_s=xslt, filename=filename, doc=doc, exc=exc)
예제 #39
0
 def remove_ta(self, **data):
     self.g_term = cherrypy.session.get('g_term')
     self.g_user = cherrypy.session.get('g_user')
     roles = ['admin']
     self.page_for(roles)
     sql = ""
     if cherrypy.request.method == 'POST':
         db = mysql.DB()
         sql = "DELETE FROM TA WHERE user_id=%s AND term=%s"
         param = (data['user_id'],self.g_term)
         db.do_commit(sql, param)
         db.close()
         raise cherrypy.HTTPRedirect('./ta_details' )
     header=Markup('Admin a class (%s): <tt>%s</tt>' % (self.g_term, self.g_user.user_id))
     ipath=Markup('Admin: <a href="manage_class">Manage Class</a> > \
     <b>Current Students %s</b> %s, %s' % (sql, data['user_id'], self.g_term))
     return template.render(ipath = ipath, header=header, student=data['user_id'])
예제 #40
0
    def show_stats_answers(self,**data):
         self.g_user = cherrypy.session.get('g_user')
         roles = ['admin', 'ta', 'final']
         self.page_for(roles)
         header = 'Statistics Graph:'
         ipath = Markup('TA/Admin: <a href="../statistics">Assignment Statistics</a> > <b>Statistics by Answers</b>')
         self.s_data = {}
         s_data = {}
         
         sql = """
             SELECT a.q_no q_no, s.score score, q.name question,
                    count(distinct a.student_id) number
             FROM Score_and_comment s, Answers a, Assignment asg,
                  Questions q, Associated_with aw 
             WHERE  asg.name=%s
               and asg.s_no=aw.s_no
               and aw.q_no=a.q_no
               and q.q_no = a.q_no
               and a.a_no=s.a_no 
          group by s.score, a.q_no
          order by s.score, a.q_no
                """
         db = mysql.DB()
         results = db.do_query(sql, (data['assignment'],))

         for row in results:
             tmp_row = {'s_no':row['q_no'],
                        'finalGrade':row['score'], 'number':row['number']}  
              
             stat = Stat(**tmp_row)
             stat.set_year('')
             stat.question = row['question']

             s_data[stat.s_no, stat.finalGrade, stat.Year]= stat
         self.s_data = s_data

         def compareStat(s1,s2):
            if s1.question != s2.question:
                return cmp(s1.question, s2.question)
            if s1.finalGrade != s2.finalGrade:
                return cmp(s1.finalGrade, s2.finalGrade)
            return 0
         stats = sorted(self.s_data.values(),cmp=compareStat)

         return template.render(ipath = ipath, header=header, stats=stats)
예제 #41
0
    def export(self, export_partial=None, start_type=None, start_time=None,
            duration=None,
            filter_title=None, filter_start=None, filter_finish=None,
            export=None, **ignored):
        # HACK: this helps development slightly
        if ignored:
            print "IGNORED",ignored

        errors = []

        if export:
            try:
                start_date_ = parseDateUI(filter_start)
            except ValueError:
                errors.append('invalid start date: "%s", must be DD/MM/YYYY'
                        % filter_start)
            try:
                finish_date_ = parseDateUI(filter_finish)
            except ValueError:
                errors.append('invalid finish date: "%s", must be DD/MM/YYYY'
                        % filter_finish)

            if export_partial and int(export_partial):
                try:
                    start_time_ = parseTimeUI(start_time)
                except ValueError:
                    errors.append('invalid start time: "%s", must be HH[:MM[:SS]]'
                            % start_time)
                try:
                    duration_ = parseTimeDelta(duration)
                except ValueError:
                    errors.append('invalid duration: "%s", must be [[HH:]MM:]SS'
                            % duration)
            errors.append('Sorry: export is not implemented yet')

        # get the recording titles for the filter, and add a "show all" option
        schedule_titles = [(NO_FILTER_TITLE, '')]
        schedule_titles.extend(((title, title) for title in
                self._storage.getRecordingTitles()))

        return template.render(station=self.getStationName(), errors=errors,
                filter_start=filter_start, filter_finish=filter_finish,
                export_partial=export_partial,
                start_type=start_type, start_time=start_time, duration=duration,
                filter_title=filter_title, schedule_titles=schedule_titles)
예제 #42
0
def make_response(status, error=None, token=None, state=None):
    # NOTE: yes, this is very dissimilar to how the existing template system
    # is designed to be used. We want to use as much as the code as possible,
    # but the existing system is deeply tied to meta.yaml, and this page isn't
    # really a part of that whole system (since it's not a project page).
    data = {
        "site": {
            "token": token,
            "error": error,
            "state": state,
        }
    }

    return webapp2.Response(status=status,
                            content_type='text/html',
                            body=template.render(
                                project='bitly-api-token-handler',
                                template_data=data))
예제 #43
0
    def showConnectionFailure(self, error='was lost', name=None, address=None):
        if address:
            station_address = address
        else:
            station_address = getSession(SESSION_STATION_ADDRESS_KEY)
            clearSession(SESSION_STATION_ADDRESS_KEY)

        if name:
            station_name = name
        else:
            station_name = getSession(SESSION_STATION_NAME_KEY)
            clearSession(SESSION_STATION_NAME_KEY)

        return template.render(is_proxy=True,
                               station=None,
                               error=error,
                               station_name=station_name,
                               station_address=station_address,
                               timeout=CONNECT_FAILURE_REDIRECTION_TIMEOUT)
예제 #44
0
    def queue(self,
              recording_id=None,
              cancel_transfer=None,
              cancel_all_transfers=None,
              **ignored):
        # HACK: this helps development slightly
        if ignored:
            print "IGNORED", ignored

        if cancel_all_transfers:
            self._transfer_manager.clear()
            raise cherrypy.HTTPRedirect('/recordings')

        if recording_id and cancel_transfer:
            self._transfer_manager.remove(int(recording_id))

        return template.render(is_proxy=True,
                               station=getSession(SESSION_STATION_NAME_KEY),
                               transfer_queue=self._transfer_manager.queue)
예제 #45
0
파일: ta.py 프로젝트: karissa/pointism
    def give_grade2student(self, **data):
        self.g_user = cherrypy.session.get('g_user')
        self.g_term = cherrypy.session.get('g_term')
        roles = ['final']
        self.page_for(roles)


        db = mysql.DB()
        sql = "SELECT * FROM Assignment WHERE term='%s'" % (self.g_term)
        results = db.do_query(sql)
        current_assignment = {}
        for row in results:
            if row['status'] == "Not Graded":
                current_assignment['a_id'] = row['s_no']
                current_assignment['a_name'] = row['name']

        cherrypy.session['current_assmt'] = current_assignment

            
        sql = "SELECT DISTINCT u.user_id, u.user_name, u.user_email FROM \
               User u, Answers a, Associated_with aw WHERE aw.q_no=a.q_no AND \
               u.user_id=a.student_id AND aw.s_no=%s ORDER BY \
               u.user_name" %(current_assignment['a_id'])
        db = mysql.DB()
        results = db.do_query(sql)
        students = []
        student_ids = []
        for row in results:
            tmp_row = {'user_id':row['user_id'],
                       'name':row['user_name'], 'email':row['user_email'],
                       'role':'student'}
            student = User(**tmp_row)
            students.append(student)
            student_ids.append(row['user_id'])
        db.close()
        cherrypy.session['student_ids'] = student_ids
        header = Markup('Grade an assignment (%s): <tt>%s</tt>' % (self.g_term, self.g_user.user_id))
        ipath = Markup('Final Grader: <b>Students</b><font color="grey"> > Give a grade</font>')
        return template.render(ipath=ipath , header=header,
        students=students, curr_assmt=current_assignment)
예제 #46
0
    def category(self,
                 label=None,
                 new_label=None,
                 update_details=None,
                 sort='date_and_time',
                 sort_order='asc',
                 **ignored):
        if update_details and new_label and new_label != label:
            self._storage.updateCategory(label, new_label)
            raise cherrypy.HTTPRedirect('/category/%s' % new_label)

        calls = self._storage.getCalls(sort, sort_order, label)
        call_sonograms = {}
        for call in calls:
            call_sonograms[call['filename']] = self.getSonogram(
                call, FREQUENCY_SCALES[0], DEFAULT_FFT_STEP)
        return template.render(station=self.getStationName(),
                               category=self._storage.getCategory(label),
                               calls=calls,
                               call_sonograms=call_sonograms,
                               sort=sort,
                               sort_order=sort_order)
예제 #47
0
 def get(self, project='index', page='index'):
   html = template.render(project, page)
   self.response.write(html)
예제 #48
0
        if view == 'month':
            calendar = RecordingsHTMLCalendar(year, month, today,
                                              self._storage, None,
                                              filter_title, filter_start,
                                              filter_finish, selected_date,
                                              selected_recording).showMonth()
        else:
            calendar = ('<h2>Unimplemented</h2>'
                        'That calendar format is not supported')
        return template.render(station=self.getStationName(),
                               errors=errors,
                               schedule_titles=schedule_titles,
                               filter_title=filter_title,
                               filter_start=formatDateUI(filter_start),
                               filter_finish=formatDateUI(filter_finish),
                               calendar=genshi.HTML(calendar),
                               selected_date=selected_date,
                               selected_recording=selected_recording,
                               selected_recordings=selected_recordings,
                               selected_action_mode=selected_action_mode,
                               selected_action_size=selected_action_size)

    @cherrypy.expose
    def recordings_json(self):
        return jsonpickle.encode(list(self._storage.getRecordings()))

    @cherrypy.expose
    def recording_by_hash(self, hash=None):
        if not hash:
            raise cherrypy.HTTPError(
                404, 'You must provide the hash of the '
예제 #49
0
    def config(self,
               config_timestamp=0,
               load_defaults=False,
               cancel=False,
               apply=False,
               export_config=False,
               new_config=None,
               import_config=False,
               **data):
        error = None
        values = None

        if cancel:
            raise cherrypy.HTTPRedirect('/')
        elif export_config:
            # use cherrypy utility to push the file for download. This also
            # means that we don't have to move the config file into the
            # web-accessible filesystem hierarchy
            return cherrypy.lib.static.serve_file(
                os.path.realpath(self._config.filename),
                "application/x-download", "attachment",
                os.path.basename(self._config.filename))
        elif apply:
            # if someone else has modified the config, then warn the user
            # before saving their changes (overwriting the other's changes)
            if int(config_timestamp) == self._config.getTimestamp():
                self.updateConfigFromPostData(self._config, data)

                # update file
                try:
                    self._config.saveToFile()
                    self._config.exportForShell(self._config.filename + ".sh")
                    # bounce back to homepage
                    raise cherrypy.HTTPRedirect('/')
                except IOError as e:
                    # if save failed, put up error message and stay on the page
                    error = 'Error saving: %s' % e
            else:
                error = genshi.HTML('''WARNING:
                        Configuration has been changed externally.<br />
                        If you wish to keep your changes and lose the external
                        changes, then click on 'Apply' again. <br />
                        To lose your changes and preserve the external changes,
                        click 'Cancel'.''')
                # load the post data into a temporary configparser to preserve
                # the user's changes when the page is loaded again. This means
                # we don't have to duplicate the horrible POST-to-config code
                temp_conf = ConfigParser()
                self.updateConfigFromPostData(temp_conf, data)
                values = temp_conf.getValues()
                # the page loading below will send the new config timestamp so
                # we don't have to anything else here.

        if load_defaults:
            values = self._config.getDefaultValues()
        elif import_config:
            if new_config.filename:
                try:
                    values = self._config.parseFile(new_config.file)
                except Exception as e:
                    values = None
                    error = 'Unable to parse config file: "%s"' % e
            else:
                error = 'No filename provided for config import'

        if not values:
            values = self._config.getValues()
        return template.render(station=self.getStationName(),
                               config_timestamp=self._config.getTimestamp(),
                               error=error,
                               using_defaults=load_defaults,
                               values=values,
                               file=self._config.filename,
                               defaults_file=self._config.defaults_filename)
예제 #50
0
    def export(self,
               filter_start=None,
               filter_finish=None,
               filter_station=None,
               export_partial=None,
               start_type=None,
               start_time=None,
               duration=None,
               filter_title=None,
               export=None,
               sync_with_station=False,
               **ignored):
        # HACK: this helps development slightly
        if ignored:
            print "IGNORED", ignored

        errors = []

        # handle requests to sync remote bowerbird by adding any missing
        # recording files to the transfer queue
        if sync_with_station and hasSession(SESSION_STATION_ADDRESS_KEY):
            station_address = getSession(SESSION_STATION_ADDRESS_KEY)
            for recording in self._storage.getRecordings(
                    station=getSession(SESSION_STATION_NAME_KEY)):
                if not recording.fileExists():
                    self._transfer_manager.add(recording, station_address)

        if export:
            try:
                start_date_ = parseDateUI(filter_start)
            except ValueError:
                errors.append('invalid start date: "%s", must be DD/MM/YYYY' %
                              filter_start)
            try:
                finish_date_ = parseDateUI(filter_finish)
            except ValueError:
                errors.append('invalid finish date: "%s", must be DD/MM/YYYY' %
                              filter_finish)

            if export_partial and int(export_partial):
                try:
                    start_time_ = parseTimeUI(start_time)
                except ValueError:
                    errors.append(
                        'invalid start time: "%s", must be HH[:MM[:SS]]' %
                        start_time)
                try:
                    duration_ = parseTimeDelta(duration)
                except ValueError:
                    errors.append(
                        'invalid duration: "%s", must be [[HH:]MM:]SS' %
                        duration)
            errors.append('Sorry: export is not implemented yet')

        # get the station titles for the filter, and add a "show all" option
        station_names = [(NO_FILTER_STATION, '')]
        station_names.extend(
            ((title, title) for title in self._storage.getRecordingStations()))

        # get the recording titles for the filter, and add a "show all" option
        schedule_titles = [(NO_FILTER_TITLE, '')]
        schedule_titles.extend(
            ((title, title) for title in self._storage.getRecordingTitles()))

        return template.render(
            is_proxy=True,
            transfer_queue_ids=self._transfer_manager.queue_ids,
            station=getSession(SESSION_STATION_NAME_KEY),
            errors=errors,
            filter_start=filter_start,
            filter_finish=filter_finish,
            filter_station=filter_station,
            station_names=station_names,
            export_partial=export_partial,
            start_type=start_type,
            start_time=start_time,
            duration=duration,
            filter_title=filter_title,
            schedule_titles=schedule_titles)
예제 #51
0
def api_show_collection(db_name=None):
    collections = MongoWrapper(db_name).getCollectionNames()
    return render("home.jade", loader(locals()))
예제 #52
0
def index():
    return render("home.jade", loader(locals()))
예제 #53
0
    def schedule(self, cancel=None, apply=None, add=None, **data):
        error = None
        if cancel:
            raise cherrypy.HTTPRedirect('/')
        elif apply:

            # use dictionary so we can untangle the POST data
            schedules = {}
            # we must check for uniqueness of titles
            titles = set()
            # just get the titles
            for key in data:
                # each schedule comes in three parts: ?.title, ?.start, ?.finish
                if key.endswith('title'):
                    id = key.split('.')[0]
                    title = data[key]
                    if title in titles:
                        error = ('Schedule titles must be unique. Found '
                                 'duplicate of "%s"' % title)
                        return template.render(
                            station=self.getStationName(),
                            recording_specs=self._schedule.getScheduleSpecs(),
                            error=error,
                            file=self._schedule.filename,
                            add=None)
                    schedules[id] = title
                    titles.add(title)

            # clear all schedules
            # and add them back in the order they were on the webpage
            self._schedule.clearScheduleSpecs()

            # sort the labels by their id, then add them in that order
            schedule_ids = schedules.keys()
            schedule_ids.sort()
            for id in schedule_ids:
                start_key = "%s.start" % id
                finish_key = "%s.finish" % id
                if data.has_key(start_key) and data.has_key(finish_key):
                    self._schedule.setScheduleSpec(
                        ScheduleParser.parseRecordingSpec(
                            schedules[id], data[start_key], data[finish_key]))

            # update file
            try:
                self._schedule.saveToFile()
                # bounce back to homepage
                raise cherrypy.HTTPRedirect('/')
            except IOError as e:
                # if save failed, put up error message and stay on the page
                error = "Error saving: %s" % e

        elif not add:
            # this should only happen when a remove button has been clicked
            # find the remove key
            for key in data:
                if key.endswith('remove'):
                    # get the schedule key from the title
                    id = key.split('.')[0]
                    title_key = "%s.title" % id
                    if data.has_key(title_key):
                        schedule_key = data[title_key]
                        self._schedule.deleteScheduleSpec(schedule_key)

        return template.render(
            station=self.getStationName(),
            error=error,
            recording_specs=self._schedule.getScheduleSpecs(),
            add=add,
            file=self._schedule.filename)
예제 #54
0
    def get(self):
        data = template.get_data('embed-api', 'server-side-authorization')
        data['site']['access_token'] = service_account.get_access_token()
        html = template.render('embed-api', 'server-side-authorization', data)

        self.response.write(html)
예제 #55
0
 def categories(self, sort='label', sort_order='asc', **ignored):
     categories = self._storage.getCategories(sort, sort_order)
     return template.render(station=self.getStationName(),
                            categories=categories,
                            sort=sort,
                            sort_order=sort_order)
예제 #56
0
                                              self._storage, filter_station,
                                              filter_title, filter_start,
                                              filter_finish, selected_date,
                                              selected_recording).showMonth()
        else:
            calendar = ('<h2>Unimplemented</h2>'
                        'That calendar format is not supported')

        return template.render(is_proxy=True,
                               station=station,
                               errors=errors,
                               station_names=station_names,
                               schedule_titles=schedule_titles,
                               filter_station=filter_station,
                               filter_title=filter_title,
                               filter_start=formatDateUI(filter_start),
                               filter_finish=formatDateUI(filter_finish),
                               calendar=genshi.HTML(calendar),
                               selected_date=selected_date,
                               selected_recording=selected_recording,
                               selected_recordings=selected_recordings,
                               selected_action_mode=selected_action_mode,
                               selected_action_size=selected_action_size,
                               transfer_queue_ids=transfer_queue_ids)

    @cherrypy.expose
    @template.output('export.html')
    def export(self,
               filter_start=None,
               filter_finish=None,
               filter_station=None,
               export_partial=None,