Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/Coursera-Machine-Learning
Path: blob/master/Week 9/Programming Assignment - 8/ex8/lib/submitWithConfiguration.m
625 views
1
function submitWithConfiguration(conf)
2
addpath('./lib/jsonlab');
3
4
parts = parts(conf);
5
6
fprintf('== Submitting solutions | %s...\n', conf.itemName);
7
8
tokenFile = 'token.mat';
9
if exist(tokenFile, 'file')
10
load(tokenFile);
11
[email token] = promptToken(email, token, tokenFile);
12
else
13
[email token] = promptToken('', '', tokenFile);
14
end
15
16
if isempty(token)
17
fprintf('!! Submission Cancelled\n');
18
return
19
end
20
21
try
22
response = submitParts(conf, email, token, parts);
23
catch
24
e = lasterror();
25
fprintf('\n!! Submission failed: %s\n', e.message);
26
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
27
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
28
fprintf('\nPlease correct your code and resubmit.\n');
29
return
30
end
31
32
if isfield(response, 'errorMessage')
33
fprintf('!! Submission failed: %s\n', response.errorMessage);
34
elseif isfield(response, 'errorCode')
35
fprintf('!! Submission failed: %s\n', response.message);
36
else
37
showFeedback(parts, response);
38
save(tokenFile, 'email', 'token');
39
end
40
end
41
42
function [email token] = promptToken(email, existingToken, tokenFile)
43
if (~isempty(email) && ~isempty(existingToken))
44
prompt = sprintf( ...
45
'Use token from last successful submission (%s)? (Y/n): ', ...
46
email);
47
reenter = input(prompt, 's');
48
49
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
50
token = existingToken;
51
return;
52
else
53
delete(tokenFile);
54
end
55
end
56
email = input('Login (email address): ', 's');
57
token = input('Token: ', 's');
58
end
59
60
function isValid = isValidPartOptionIndex(partOptions, i)
61
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
62
end
63
64
function response = submitParts(conf, email, token, parts)
65
body = makePostBody(conf, email, token, parts);
66
submissionUrl = submissionUrl();
67
68
responseBody = getResponse(submissionUrl, body);
69
jsonResponse = validateResponse(responseBody);
70
response = loadjson(jsonResponse);
71
end
72
73
function body = makePostBody(conf, email, token, parts)
74
bodyStruct.assignmentSlug = conf.assignmentSlug;
75
bodyStruct.submitterEmail = email;
76
bodyStruct.secret = token;
77
bodyStruct.parts = makePartsStruct(conf, parts);
78
79
opt.Compact = 1;
80
body = savejson('', bodyStruct, opt);
81
end
82
83
function partsStruct = makePartsStruct(conf, parts)
84
for part = parts
85
partId = part{:}.id;
86
fieldName = makeValidFieldName(partId);
87
outputStruct.output = conf.output(partId);
88
partsStruct.(fieldName) = outputStruct;
89
end
90
end
91
92
function [parts] = parts(conf)
93
parts = {};
94
for partArray = conf.partArrays
95
part.id = partArray{:}{1};
96
part.sourceFiles = partArray{:}{2};
97
part.name = partArray{:}{3};
98
parts{end + 1} = part;
99
end
100
end
101
102
function showFeedback(parts, response)
103
fprintf('== \n');
104
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
105
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
106
for part = parts
107
score = '';
108
partFeedback = '';
109
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
110
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
111
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
112
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
113
end
114
evaluation = response.evaluation;
115
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
116
fprintf('== --------------------------------\n');
117
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
118
fprintf('== \n');
119
end
120
121
% use urlread or curl to send submit results to the grader and get a response
122
function response = getResponse(url, body)
123
% try using urlread() and a secure connection
124
params = {'jsonBody', body};
125
[response, success] = urlread(url, 'post', params);
126
127
if (success == 0)
128
% urlread didn't work, try curl & the peer certificate patch
129
if ispc
130
% testing note: use 'jsonBody =' for a test case
131
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
132
else
133
% it's linux/OS X, so use the other form
134
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
135
end
136
% get the response body for the peer certificate patch method
137
[code, response] = system(json_command);
138
% test the success code
139
if (code ~= 0)
140
fprintf('[error] submission with curl() was not successful\n');
141
end
142
end
143
end
144
145
% validate the grader's response
146
function response = validateResponse(resp)
147
% test if the response is json or an HTML page
148
isJson = length(resp) > 0 && resp(1) == '{';
149
isHtml = findstr(lower(resp), '<html');
150
151
if (isJson)
152
response = resp;
153
elseif (isHtml)
154
% the response is html, so it's probably an error message
155
printHTMLContents(resp);
156
error('Grader response is an HTML message');
157
else
158
error('Grader sent no response');
159
end
160
end
161
162
% parse a HTML response and print it's contents
163
function printHTMLContents(response)
164
strippedResponse = regexprep(response, '<[^>]+>', ' ');
165
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
166
fprintf(strippedResponse);
167
end
168
169
170
171
172
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
173
%
174
% Service configuration
175
%
176
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
177
function submissionUrl = submissionUrl()
178
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
179
end
180
181