def sendTPIReportBackDate(score, duration, count, params, c_date): extraParam = { 'transactionId': uuid.uuid4(), 'timeStamp': TPIUtils.timestampstr(c_date), 'score': float(score) * float(params['custom_points_' + params['custom_currentquestion']]), 'duration': duration, 'submissionCount': count, 'problem_guid': params['custom_target_' + params['custom_currentquestion']], 'problemNumber': params['custom_currentquestion'], 'dataSourceName': 'CA', } url = settings.OUTCOMES_URL body = TPIUtils.outcome_xml(params, **extraParam) auth = (settings.OUTCOMES_USER, settings.OUTCOMES_PW) resp = requests.post(url, data=body, auth=auth) msg = TPI_Launch_Log(message='TPI report : %d' % resp.status_code) msg.save() msg = TPI_Launch_Log(message=body) msg.save() print body print 'resp:', resp, resp.content return body
def saveInflationLevel(request): if not request.method == 'POST': return HttpResponse(status=400) try: iSession = request.session['interactives']['inflation'] except: return HttpResponse(status=401) history = request.session['inflationHistory'] try: params = json.loads(request.body) level = params['level'] score = params['score'] levelData = json.dumps(params['data']) except: return HttpResponse(status=400) inflationState = InteractiveState.objects.get(iSession=iSession, active=True) activated_levels = json.loads(inflationState.activated_levels) bestScore = inflationState.saveLevel(level=level, score=score, data=levelData) history['attempts'][activated_levels.index(level)] += 1 if inflationState.isComplete() and bestScore: TPIUtils.sendTPIReport(inflationState, inflationState.levels) resp = {'nextLevel': inflationState.currentLevel, 'savedLevel': level, 'score': score, 'retry': inflationState.getCurrentOp(), 'highScore': bestScore, 'attempts': history['attempts'] } return HttpResponse(json.dumps(resp), status=200, content_type='application/json' )
def manualgradepostreport(request): dstring = "<table><tr><td>User Id</td><td>Resource Id</td><td>Target App</td><td>Score</td><td>Start Date</td><td>End Date</td></tr>" sobjects = SimsSession.objects.filter( manualupdatefor='topscore', topScore=True).order_by('id').values_list( 'iSession__user_id', 'iSession__resource_id', 'iSession__target_app', 'score', 'start', 'end')[0:10000] for item in sobjects: try: dstring = dstring + "<tr><td>" + item[0] + "</td><td> " + item[ 1] + "</td><td>" + item[2] + "</td><td>" + str( item[3]) + "</td><td>" + TPIUtils.timestampstr( item[4]) + "</td><td>" + TPIUtils.timestampstr( item[5]) + "</td></tr>" except Exception, e: dstring = dstring + "<tr><td>" + str(e) + "</td><tr>"
def sendTPIReport(caState, params): print 'send TPI Report' try: mode = LevelSetting.objects.get( class_id=caState.iSession.resource_id).setting except: print 'Failed to get level setting' mode = 'all' if mode == 'all': score = (scoreWeights[0] * caState.l1Score + scoreWeights[1] * caState.l2Score + scoreWeights[2] * caState.l3Score + scoreWeights[3] * caState.l4Score) / 100 elif mode == '1to3': score = (scoreWeights[0] * caState.l1Score + scoreWeights[1] * caState.l2Score + scoreWeights[2] * caState.l3Score) / 50 else: score = caState.l4Score / 100 score = score * float( params['custom_points_' + params['custom_currentquestion']]) levels = CALevel.objects.filter(parent__iSession=caState.iSession, completed=True) duration = 0 for l in levels: duration += int((l.closed - l.started).seconds) count = CAState.objects.filter(iSession=caState.iSession).count() extraParam = { 'transactionId': uuid.uuid4(), 'timeStamp': TPIUtils.timestamp(), 'score': score, 'duration': duration, 'submissionCount': count, 'problem_guid': params['custom_target_' + params['custom_currentquestion']], 'problemNumber': params['custom_currentquestion'], 'dataSourceName': 'CA', } url = settings.OUTCOMES_URL body = TPIUtils.outcome_xml(params, **extraParam) auth = (settings.OUTCOMES_USER, settings.OUTCOMES_PW) # print body resp = requests.post(url, data=body, auth=auth) print 'resp:', resp, resp.content return resp
def sendTPIReport(iSession): params = json.loads(iSession.launchParam) state = InteractiveState.objects.get(iSession=iSession, active=True) levels = InteractiveLevel.objects.filter(parent=state, completed=True) score = 0 for l in levels: score += l.score score = float(score) / 100 score = score * float( params['custom_points_' + params['custom_currentquestion']]) completedLevels = InteractiveLevel.objects.filter(Q(restarted=True) | Q(completed=True), parent=state) count = len(completedLevels) / 4 if len(completedLevels) % 4 > 0: count += 1 duration = 0 for l in completedLevels: duration += int((l.closed - l.started).seconds) extraParam = { 'transactionId': uuid.uuid4(), 'timeStamp': TPIUtils.timestamp(), 'score': score, 'duration': duration, 'submissionCount': count, 'problem_guid': params['custom_target_' + params['custom_currentquestion']], 'problemNumber': params['custom_currentquestion'], 'dataSourceName': 'UE', } url = settings.OUTCOMES_URL body = TPIUtils.outcome_xml(params, **extraParam) auth = (settings.OUTCOMES_USER, settings.OUTCOMES_PW) print 'body:', body msg = TPI_Launch_Log(message=body) msg.save() resp = requests.post(url, data=body, auth=auth) print 'resp:', resp, resp.content return resp
def postatmsimgrades(request): data = [] try: #sobjects = SimsSession.objects.filter(iSession__user_id = 'urn:udson:pearson.com/xl/highered:user/29782202', score__gt = 0, active=False).values_list('iSession__id').distinct()[:3000] sobjects = SimsSession.objects.filter( score__gt=0, active=False, manualupdatefor='topscore', topScore=True).exclude( manualupdatefor='completiondateissue').values_list( 'iSession__id').distinct()[:3000] for item in sobjects: udata = {} udata['iSession__id'] = item[0] simSessions = SimsSession.objects.filter( iSession__id=item[0], active=False).order_by('-score') score = 0 duration = 0 attempts = len(simSessions) #c_date = timezone.now() if len(simSessions) > 0: udata['usertopscore'] = simSessions[0].score udata['userminscore'] = simSessions[attempts - 1].score for r in simSessions: try: duration += int((r.end - r.start).seconds) except Exception, e: duration = duration r.topScore = False r.manualupdatefor = 'completiondateissue' r.save() score = simSessions[0].score c_date = simSessions[0].end simSessions[0].topScore = True simSessions[0].manualupdatefor = 'completiondateissue' simSessions[0].save() udata['duration'] = duration udata['score'] = score udata['attempts'] = attempts udata['enddate'] = TPIUtils.timestampstr(c_date) #udata['LaunchParam'] = simSessions[0].iSession.getLaunchParam() #data.append(udata) try: sendTPIReportBackDate( score, duration, attempts, simSessions[0].iSession.getLaunchParam(), c_date) except Exception, inne: udata['error'] = str(inne) data.append(udata)
def tool_launch(request): launch_data = {} for k, v in request.POST.items(): launch_data[k] = v logTPIRequest(request) if TPIUtils.has_valid_signature(launch_data): session = SessionData.getOrCreateSession(launch_data) return redirect(settings.APP_REDIRECT_URL + '/#/' + session.session_id + '/') else: return HttpResponse('Unauthorized', status=401)
def launchSim(request): launch_data = {} for k, v in request.POST.items(): launch_data[k] = v TPI_Launch_Log.logTPIRequest(request) if TPIUtils.has_valid_signature(launch_data, url=settings.XLSIMS_LAUNCH_URL, key='bphsc2014'): return processLaunch(request, False) else: return HttpResponseRedirect(settings.SIMS_ROOT + 'message.html?op=auth')
def econ_tool_launch(request, check_valid=True): launch_data = {} trace = "" for k, v in request.POST.items(): launch_data[k] = v #logTPIRequest(request) if not check_valid or TPIUtils.has_valid_signature( launch_data, '', request.META['HTTP_REFERER']): k_identifier_val = launch_data['custom_target_' + launch_data['custom_currentquestion']] if (k_identifier_val == 'cpi_inflation' or k_identifier_val == 'monetary_policy' or k_identifier_val == 'opp_cost' or k_identifier_val == 'unemp' or k_identifier_val == 'demand_supply' or k_identifier_val == 'gdp' or k_identifier_val == 'elasticity' or k_identifier_val == 'production_possibilities_frontier' or k_identifier_val == 'gains_from_trade' or k_identifier_val.find('qualsims') != -1 or k_identifier_val.find('econ_blair') != -1): k_UpdateFredData(k_identifier_val) try: pkgPath = '' if (k_identifier_val.find('/business/it/') != -1): pkgPath = k_identifier_val pkgPath = pkgPath.replace('-', '_') pkgPath = '/content/' + pkgPath elif (k_identifier_val.find('qualsims') != -1): pkgPath = k_identifier_val # read LO user config file try: urlorigin = "https://" + request.META.get("HTTP_HOST") data = getUserMappings(urlorigin) except Exception: #if json file not found then jsonconf = '{"projects": [{"id":"qualsims","users": ["armstrong"]}]}' data = json.loads(jsonconf) # replace the users for project in data["projects"]: if (project["id"] == "qualsims"): lousers = project['users'] lousers.sort(key=lambda s: len(s), reverse=True) for louser in lousers: pkgPath = rreplace( pkgPath, '/' + louser, '', 1) #pkgPath.replace('/'+louser, '') ''' pkgPath = k_identifier_val.replace('/armstrong','').replace('/kotler','').replace('/solomon','') pkgPath = pkgPath.replace('/ebert','').replace('/bovee','') pkgPath = pkgPath.replace('/certo','').replace('/robbins10 Simulation','').replace('/robbins10','').replace('/robbins14','').replace('/robbins17','').replace('/wheelen','') pkgPath = pkgPath.replace('/david','').replace('/barringer','').replace('/dressler','').replace('/mariotti','').replace('/scarborough','') pkgPath = pkgPath.replace('/cheeseman','').replace('/robbins8e', '').replace('/gibson10e', '').replace('/armstrong7e', '') ''' pkgPath = pkgPath.replace('-', '_') pkgPath = '/content/' + pkgPath if (pkgPath != ''): if launch_data['custom_mode'] == 'setup' or ( launch_data['custom_mode'] == 'review' and launch_data['roles'] != 'Learner') or ( launch_data['custom_mode'] == 'review' and launch_data['roles'] == 'Learner'): pkgPath = '/content/qualsims/commonfiles' if launch_data['custom_mode'] == 'setup': return redirect( pkgPath + '/settings.html?pid=' + k_identifier_val + '&resid=' + launch_data['custom_resource_id'] + '&restitle=' + launch_data['custom_questiontitle_' + launch_data['custom_currentquestion']]) elif launch_data['custom_mode'] == 'preview': mediaarry = k_identifier_val.split('/') mediauser = '' if len(mediaarry) > 0: mediauser = mediaarry[len(mediaarry) - 1] return redirect(pkgPath + '/#/preview/' + mediauser) elif launch_data['custom_mode'] == 'review' and launch_data[ 'roles'] != 'Learner': session = SessionData.getOrCreateSession(launch_data) return redirect(pkgPath + '/review.html?' + session.session_id) elif launch_data['custom_mode'] == 'review' and launch_data[ 'roles'] == 'Learner': #interactive = InteractiveSession.startInteractiveSession(launch_data) session = SessionData.getOrCreateSession(launch_data) return redirect(pkgPath + '/learner_review.html?sid=' + session.session_id) else: session = SessionData.getOrCreateSession(launch_data) #interactive = InteractiveSession.startInteractiveSession(launch_data) return redirect(pkgPath + '/#/' + session.session_id + '/') else: if launch_data['custom_mode'] == 'setup': return redirect('/content/' + k_identifier_val + '/settings.html?pid=' + k_identifier_val + '&resid=' + launch_data['custom_resource_id']) elif launch_data['custom_mode'] == 'preview': return redirect('/content/' + k_identifier_val + '/#/') elif launch_data['custom_mode'] == 'review' and launch_data[ 'roles'] != 'Learner': session = SessionData.getOrCreateSession(launch_data) return redirect('/content/' + k_identifier_val + '/review.html?' + session.session_id) else: session = SessionData.getOrCreateSession(launch_data) interactive = InteractiveSession.startInteractiveSession( launch_data) return redirect('/content/' + k_identifier_val + '/#/' + session.session_id + '/') except Exception, e: response = HttpResponse( 'Error: 1235no application ' + k_identifier_val + str(e), 404) return response else: trace = "" interactive = InteractiveSession.startInteractiveSession( launch_data) try: if launch_data['custom_mode'] == 'setup': response = handleSettingsRequest(launch_data) elif launch_data['custom_mode'] == 'review' and launch_data[ 'roles'] != 'Learner': response = HttpResponseRedirect( settings.COURSE_REVIEW_LAUNCH_TABLE[ interactive.target_app]) else: response = HttpResponseRedirect( settings.ECON_LAUNCH_TABLE[interactive.target_app]) except: response = HttpResponse( 'Error: no application ' + interactive.target_app, 404) if response.status_code != 302: return response try: try: interactives = request.session['interactives'] except: interactives = {} sjson = {} sjson["user_id"] = interactive.user_id sjson["resource_id"] = interactive.resource_id sjson["context_id"] = interactive.context_id sjson["target_app"] = interactive.target_app sjson["launchParam"] = json.loads(interactive.launchParam) sjson["started"] = str(interactive.started) #return HttpResponse("naveen" + json.dumps(sjson), status=401) interactives[interactive.target_app] = sjson #return HttpResponse("naveen22" + json.dumps(sjson), status=401) except: interactives = {} interactives[interactive.target_app] = interactive request.session['interactives'] = interactives return response
def grade_problem_and_report(request, session_id, problem_guid): try: session = SessionData.objects.get(session_id=session_id) launch_data = json.loads(session.launch_data) except SessionData.DoesNotExist: response = CorsHttpResponse( '{"status":"error", "details":"no matching session_id for %s"}' % session_id, 404) return response except ValueError: response = CorsHttpResponse( '{"status":"error", "details":"launch_data is not valid JSON"}', 400) return response k_identifier_val = launch_data['custom_target_' + launch_data['custom_currentquestion']] if (k_identifier_val == 'cpi_inflation' or k_identifier_val == 'monetary_policy' or k_identifier_val == 'opp_cost' or k_identifier_val == 'unemp' or k_identifier_val == 'demand_supply' or k_identifier_val == 'gdp' or k_identifier_val == 'elasticity' or k_identifier_val == 'production_possibilities_frontier' or k_identifier_val == 'gains_from_trade' or k_identifier_val.find('qualsims') != -1 or k_identifier_val.find('econ_blair') != -1): try: student_data = json.loads(request.body) except ValueError: raise ValueError("student_data is not valid JSON") answers = student_data['answers'] duration = int(student_data['duration']) nAttempts = int(student_data['nAttempts']) result = student_data if problem_guid == 'usefromsession': problem_guid = launch_data['custom_target_' + launch_data['custom_currentquestion']] if session.launch_mode == 'do': score = float(student_data['score']) pnum = int(student_data['problemNumber']) try: kresp = TPIUtils.submit_outcome(launch_data, problemNumber=pnum, problem_guid=problem_guid, score=score, duration=duration, submissionCount=nAttempts + 1) except Exception as e: return CorsHttpResponse(str(e), 400) return CorsHttpResponse( session.launch_mode + "-----------" + str(kresp) + "------------" + str(result), 200) else: try: problem = ProblemDefinition.objects.get(problem_guid=problem_guid) except SessionData.DoesNotExist: response = CorsHttpResponse( '{"status":"error", "details":"no matching problem_guid for %s"}' % problem_guid, 404) return response try: student_data = json.loads(request.body) except ValueError: raise ValueError("student_data is not valid JSON") answers = student_data['answers'] duration = int(student_data['duration']) nAttempts = int(student_data['nAttempts']) try: result = problem.grade_response(answers) except Exception as e: return CorsHttpResponse(str(e), 400) if session.launch_mode == 'do': try: pnum, points = session.problem_assignment_info(problem_guid) except TypeError: return CorsHttpResponse( 'Points not found for problem guid ' + problem_guid, 400) score = float(result['score']) * points TPIUtils.submit_outcome(launch_data, problemNumber=pnum, problem_guid=problem_guid, score=score, duration=duration, submissionCount=nAttempts + 1) # TODO: test if submission was successful return CorsHttpResponse(json.dumps(result), 200)