Skip to content

Commit

Permalink
document the code
Browse files Browse the repository at this point in the history
  • Loading branch information
keweizhan committed May 3, 2024
1 parent 27e902f commit e8fdc26
Show file tree
Hide file tree
Showing 9 changed files with 184 additions and 101 deletions.
45 changes: 23 additions & 22 deletions app/assets/javascripts/dag.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
// Main function to build a graph based on a Directed Acyclic Graph (DAG) representation and a mapping from node values to labels.
function buildGraph(dag, nodeValueToLabel) {
const graph = {};
const inDegree = {};
const graph = {}; // Object to hold the adjacency list representation of the graph.
const inDegree = {}; // Object to hold the in-degree count for each node.

// initialize graph and in-degree
// Initialize graph and in-degree for each node based on the nodeValueToLabel mapping.
for (const nodeLabel in nodeValueToLabel) {
graph[nodeLabel] = [];
inDegree[nodeLabel] = 0;
}

// parse the DAG and build the graph
// Parse the DAG string, build the graph and calculate in-degrees.
const lines = dag.split('\n');
for (const line of lines) {
const parts = line.split(':').map(part => part.trim());
Expand All @@ -17,8 +18,8 @@ function buildGraph(dag, nodeValueToLabel) {
const dependencies = parts[1].split(' ').filter(label => label !== '');
for (const dependency of dependencies) {
if (dependency !== '-1' && nodeValueToLabel[nodeLabel] !== undefined && nodeValueToLabel[dependency] !== undefined) {
graph[nodeLabel].push(dependency); // add dependency to the graph
inDegree[dependency]++; // increment in-degree of the dependency
graph[nodeLabel].push(dependency); // Add dependency to the node's adjacency list.
inDegree[dependency]++; // Increment in-degree count for the dependency.
}
}
}
Expand All @@ -29,20 +30,21 @@ function buildGraph(dag, nodeValueToLabel) {
return { graph, inDegree };
}


// Processes the solution by validating the sequence of nodes against the graph's dependencies.
function processSolution(solution, graph, inDegree, nodeValueToLabel) {
console.log("processSolution:", solution);
console.log("processnodeValueToLabel:", nodeValueToLabel);
const visited = new Set();
const visited = new Set(); // Set to track visited nodes.

// Process each node in the solution, ensuring all dependencies are met.
for (const nodeText of solution) {
const nodeLabel = Object.keys(nodeValueToLabel).find(
(label) => nodeValueToLabel[label] === nodeText
label => nodeValueToLabel[label] === nodeText
);

if (nodeLabel === undefined) {
console.log("Skipping node not found in nodeValueToLabel:", nodeText);
continue; // jump to the next node
continue; // Skip if node is not found in mapping.
}

console.log('Current label:', nodeLabel);
Expand All @@ -51,28 +53,26 @@ function processSolution(solution, graph, inDegree, nodeValueToLabel) {

visited.add(nodeLabel);

// check if the node has dependencies
// Check if all dependencies of the current node have been visited.
for (const dependencyLabel of graph[nodeLabel]) {
if (!visited.has(dependencyLabel)) {
console.error("Dependency not satisfied:", nodeText, "depends on", nodeValueToLabel[dependencyLabel]);
return false;
return false; // Dependency check failed.
}
}
}

// check if all nodes were visited
// Ensure all nodes were visited.
if (visited.size !== Object.keys(nodeValueToLabel).length) {
console.error("Not all nodes in nodeValueToLabel were visited.");
return false;
}

console.log('Visited nodes:', Array.from(visited));
return true;
return true; // All checks passed.
}




// High-level function to process the DAG and the solution together.
function processDAG(dag, solution, nodeValueToLabel) {
console.log("DAG:", dag);
console.log("Node value to label mapping:", nodeValueToLabel);
Expand All @@ -81,17 +81,18 @@ function processDAG(dag, solution, nodeValueToLabel) {
return result;
}

// Extracts and maps the solution to the corresponding node labels.
function extractCode(solution, nodeValueToLabel) {
const code = [];
const newNodeValueToLabel = {};
for (const nodeText of solution) {
const nodeLabel = Object.keys(nodeValueToLabel).find(
(key) => nodeValueToLabel[key] === nodeText
key => nodeValueToLabel[key] === nodeText
);
if (nodeLabel !== undefined) {
code.push(nodeText);
newNodeValueToLabel[nodeLabel] = nodeText;
code.push(nodeText); // Collect the node text for the final code array.
newNodeValueToLabel[nodeLabel] = nodeText; // Map labels to node texts.
}
}
return { code, newNodeValueToLabel };
}
return { code, newNodeValueToLabel }; // Return the processed code and updated mapping.
}
56 changes: 30 additions & 26 deletions app/assets/javascripts/peml_code.js
Original file line number Diff line number Diff line change
@@ -1,60 +1,64 @@
const url = "https://skynet.cs.vt.edu/peml-live/api/parse";

// 获取 PEML 数据
// Fetch the PEML data from a local file.
fetch('/data/s7.peml')
.then(response => {
// Convert the response to text format.
return response.text();
})
.then(pemlText => {
// Construct the payload to send in the POST request.
const payload = {
"peml": pemlText,
"output_format": "json",
"render_to_html": "true"
"peml": pemlText, // The PEML data as text.
"output_format": "json", // Specify the output format as JSON.
"render_to_html": "true" // Request HTML rendering.
};

// 发送 POST 请求进行解析
// Send a POST request to the server to parse the PEML text.
$.post(url, payload, function(data, status) {
console.log('Post status:', status);
console.log('Post data:', data);
console.log('Post status:', status); // Log the status of the POST request.
console.log('Post data:', data); // Log the data received from the POST request.

// 检查服务器响应数据是否包含所需字段
// Check if the server's response contains the necessary fields.
if (data && data.title && data.instructions && data.assets && data.assets.code && data.assets.code.starter && data.assets.code.starter.files && data.assets.code.starter.files[0] && data.assets.code.starter.files[0].content) {
// 获取你需要的字段
var title = data.title.split(" -- ")[0];
var instructions = data.instructions;
var initialArray = data.assets.code.starter.files[0].content.map(item => item.code.split('\\n'));
// Extract the required fields from the response.
var title = data.title.split(" -- ")[0]; // Get the title and clean it.
var instructions = data.instructions; // Get the instructions directly.
var initialArray = data.assets.code.starter.files[0].content.map(item => item.code.split('\\n')); // Process the initial array of code.

// 在这里使用你获取的字段
document.getElementById("title").innerHTML = title;
document.getElementById("instructions").innerHTML = instructions;
// Use the extracted fields in your application.
document.getElementById("title").innerHTML = title; // Display the title.
document.getElementById("instructions").innerHTML = instructions; // Display the instructions.

var parson = new ParsonsWidget();
parson.init(initialArray);
parson.shuffleLines();
var parson = new ParsonsWidget(); // Create a new ParsonsWidget instance.
parson.init(initialArray); // Initialize the widget with the initial array.
parson.shuffleLines(); // Shuffle the lines initially.

// Add an event listener for creating a new instance of the shuffled lines.
$("#newInstanceLink").click(function(event) {
event.preventDefault();
parson.shuffleLines();
});

// Add an event listener for providing feedback.
$("#feedbackLink").click(function(event) {
event.preventDefault();
var fb = parson.getFeedback();
$("#feedback").html(fb.feedback);
$("#feedback").html(fb.feedback); // Display the feedback.
if (fb.success) {
score = 50;
score = 50; // Set score on success.
} else {
score = 0;
score = 0; // Reset score on failure.
}
updateScore(score);
updateScore(score); // Update the score display.
});

function updateScore(score) {
// 更新分数的代码
// Implement the logic to update the score in the UI or backend.
}
} else {
console.error('服务器响应数据不完整或格式不正确');
// 在这里处理服务器响应数据不完整或格式不正确的情况
console.error('Incomplete or incorrect server response data.');
// Handle cases where server response data is incomplete or incorrect.
}
});
});
});
10 changes: 3 additions & 7 deletions app/assets/javascripts/simple_code.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ $(document).ready(function(){
Sk.canvas = "studentCanvas";
$.getJSON('/data/simple_code.json', function(response) {
data = response;
// get the specific exercise data
var externalIdElement = document.getElementById("exercise-data");
var externalId = externalIdElement.getAttribute("data-external-id");
var initial = data[index]['initial'];
Expand All @@ -15,14 +16,9 @@ $(document).ready(function(){
document.getElementById("instructions").innerHTML = data[index].instructions;
config.sortableId = 'sortable';
config.trashId = 'sortableTrash';
console.log(data[index]['parsonsConfig']
['turtleModelCode']);
console.log(externalId)
// 如果config中有turtleModelCode,就把grader改成TurtleGrader
// if there is a turtle model code, use the turtle grader
if (data[index]['parsonsConfig']['turtleModelCode']) {
config.grader = ParsonsWidget._graders.TurtleGrader;
console.log("有乌龟")

} else {
config.grader = ParsonsWidget._graders.LanguageTranslationGrader;
}
Expand Down Expand Up @@ -81,4 +77,4 @@ $(document).ready(function(){
}
});
}
});
});
1 change: 1 addition & 0 deletions app/assets/javascripts/simple_pseudocode.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// This file is used to create a Parsons problem for the simple pseudocode exercise
var initial = 'IF $$toggle::a::b$$ $$toggle::<::>::<>$$ b THEN\n min := a\nELSE\n min := b\nENDIF';
var parson;
$(document).ready(function(){
Expand Down
Loading

0 comments on commit e8fdc26

Please sign in to comment.