Path: blob/master/Week 9/Programming Assignment - 8/ex8/lib/submitWithConfiguration.m
625 views
function submitWithConfiguration(conf)1addpath('./lib/jsonlab');23parts = parts(conf);45fprintf('== Submitting solutions | %s...\n', conf.itemName);67tokenFile = 'token.mat';8if exist(tokenFile, 'file')9load(tokenFile);10[email token] = promptToken(email, token, tokenFile);11else12[email token] = promptToken('', '', tokenFile);13end1415if isempty(token)16fprintf('!! Submission Cancelled\n');17return18end1920try21response = submitParts(conf, email, token, parts);22catch23e = lasterror();24fprintf('\n!! Submission failed: %s\n', e.message);25fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...26e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);27fprintf('\nPlease correct your code and resubmit.\n');28return29end3031if isfield(response, 'errorMessage')32fprintf('!! Submission failed: %s\n', response.errorMessage);33elseif isfield(response, 'errorCode')34fprintf('!! Submission failed: %s\n', response.message);35else36showFeedback(parts, response);37save(tokenFile, 'email', 'token');38end39end4041function [email token] = promptToken(email, existingToken, tokenFile)42if (~isempty(email) && ~isempty(existingToken))43prompt = sprintf( ...44'Use token from last successful submission (%s)? (Y/n): ', ...45email);46reenter = input(prompt, 's');4748if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')49token = existingToken;50return;51else52delete(tokenFile);53end54end55email = input('Login (email address): ', 's');56token = input('Token: ', 's');57end5859function isValid = isValidPartOptionIndex(partOptions, i)60isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));61end6263function response = submitParts(conf, email, token, parts)64body = makePostBody(conf, email, token, parts);65submissionUrl = submissionUrl();6667responseBody = getResponse(submissionUrl, body);68jsonResponse = validateResponse(responseBody);69response = loadjson(jsonResponse);70end7172function body = makePostBody(conf, email, token, parts)73bodyStruct.assignmentSlug = conf.assignmentSlug;74bodyStruct.submitterEmail = email;75bodyStruct.secret = token;76bodyStruct.parts = makePartsStruct(conf, parts);7778opt.Compact = 1;79body = savejson('', bodyStruct, opt);80end8182function partsStruct = makePartsStruct(conf, parts)83for part = parts84partId = part{:}.id;85fieldName = makeValidFieldName(partId);86outputStruct.output = conf.output(partId);87partsStruct.(fieldName) = outputStruct;88end89end9091function [parts] = parts(conf)92parts = {};93for partArray = conf.partArrays94part.id = partArray{:}{1};95part.sourceFiles = partArray{:}{2};96part.name = partArray{:}{3};97parts{end + 1} = part;98end99end100101function showFeedback(parts, response)102fprintf('== \n');103fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');104fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');105for part = parts106score = '';107partFeedback = '';108partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));109partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));110score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);111fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);112end113evaluation = response.evaluation;114totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);115fprintf('== --------------------------------\n');116fprintf('== %43s | %9s | %-s\n', '', totalScore, '');117fprintf('== \n');118end119120% use urlread or curl to send submit results to the grader and get a response121function response = getResponse(url, body)122% try using urlread() and a secure connection123params = {'jsonBody', body};124[response, success] = urlread(url, 'post', params);125126if (success == 0)127% urlread didn't work, try curl & the peer certificate patch128if ispc129% testing note: use 'jsonBody =' for a test case130json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);131else132% it's linux/OS X, so use the other form133json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);134end135% get the response body for the peer certificate patch method136[code, response] = system(json_command);137% test the success code138if (code ~= 0)139fprintf('[error] submission with curl() was not successful\n');140end141end142end143144% validate the grader's response145function response = validateResponse(resp)146% test if the response is json or an HTML page147isJson = length(resp) > 0 && resp(1) == '{';148isHtml = findstr(lower(resp), '<html');149150if (isJson)151response = resp;152elseif (isHtml)153% the response is html, so it's probably an error message154printHTMLContents(resp);155error('Grader response is an HTML message');156else157error('Grader sent no response');158end159end160161% parse a HTML response and print it's contents162function printHTMLContents(response)163strippedResponse = regexprep(response, '<[^>]+>', ' ');164strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');165fprintf(strippedResponse);166end167168169170171%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%172%173% Service configuration174%175%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%176function submissionUrl = submissionUrl()177submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';178end179180181