prompt
stringlengths 1.3k
3.64k
| language
stringclasses 16
values | label
int64 -1
5
| text
stringlengths 14
130k
|
---|---|---|---|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package SQL;
import com.google.gson.Gson;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Modality;
import javafx.stage.Stage;
import ui.LogInPostgresController;
import java.io.*;
import java.sql.*;
import java.util.ArrayList;
public class SQLqueries {
private static final String FILE_NAME = "data.json";
private String login = "";
private String password = "";
public void checkDB() throws SQLException, IOException {
readToJSON();
if (getDBConnectionTest() == null) {
showLoginPostgres();
} else if (getDBConnection() == null){
createDatabase();
Stage primaryStage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("/SearchObjectsMenu.fxml"));
primaryStage.setTitle("Начальное меню");
primaryStage.setScene(new Scene(root));
primaryStage.show();
} else if (getDBConnection() != null) {
readToJSON();
Stage primaryStage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("/SearchObjectsMenu.fxml"));
primaryStage.setTitle("Начальное меню");
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
private Connection getDBConnectionTest() {
try {
Connection dbConnection = null;
dbConnection = DriverManager.getConnection(
"jdbc:postgresql://localhost/", this.login, this.password);
return dbConnection;
} catch (SQLException e) {
System.out.println("Ошибочка (((");
System.out.println(e.getMessage());
}
return null;
}
private Connection getDBConnection() {
try {
Connection dbConnection = null;
dbConnection = DriverManager.getConnec
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
java
| 3 |
package SQL;
import com.google.gson.Gson;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Modality;
import javafx.stage.Stage;
import ui.LogInPostgresController;
import java.io.*;
import java.sql.*;
import java.util.ArrayList;
public class SQLqueries {
private static final String FILE_NAME = "data.json";
private String login = "";
private String password = "";
public void checkDB() throws SQLException, IOException {
readToJSON();
if (getDBConnectionTest() == null) {
showLoginPostgres();
} else if (getDBConnection() == null){
createDatabase();
Stage primaryStage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("/SearchObjectsMenu.fxml"));
primaryStage.setTitle("Начальное меню");
primaryStage.setScene(new Scene(root));
primaryStage.show();
} else if (getDBConnection() != null) {
readToJSON();
Stage primaryStage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("/SearchObjectsMenu.fxml"));
primaryStage.setTitle("Начальное меню");
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
private Connection getDBConnectionTest() {
try {
Connection dbConnection = null;
dbConnection = DriverManager.getConnection(
"jdbc:postgresql://localhost/", this.login, this.password);
return dbConnection;
} catch (SQLException e) {
System.out.println("Ошибочка (((");
System.out.println(e.getMessage());
}
return null;
}
private Connection getDBConnection() {
try {
Connection dbConnection = null;
dbConnection = DriverManager.getConnection(
"jdbc:postgresql://localhost/parser_drom", this.login, this.password);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return null;
}
public void createDatabase() throws SQLException, IOException {
Connection dbConnection = null;
Statement statement = null;
String queries = "CREATE DATABASE parser_drom";
try {
dbConnection = getDBConnectionTest();
statement = dbConnection.createStatement();
// выполнить SQL запрос
statement.executeUpdate(queries);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
createDatabaseTable();
}
public void createDatabaseTable() throws SQLException {
Connection dbConnection = null;
Statement statement = null;
String createTableEmployee = "CREATE TABLE \"history_data\" (\n" +
"\t\"id\" serial NOT NULL,\n" +
"\t\"id_object\" TEXT NOT NULL,\n" +
"\tCONSTRAINT \"employee_data_pk\" PRIMARY KEY (\"id\")\n" +
") WITH (\n" +
" OIDS=FALSE\n" +
");\n";
try {
// Создание таблиц
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
statement.executeUpdate(createTableEmployee);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
public ObservableList<String> selectHistory() throws SQLException {
readToJSON();
Connection dbConnection = null;
Statement statement = null;
ObservableList<String> historyList = FXCollections.observableArrayList();
String queries = "SELECT id_object " +
"FROM history_data";
try {
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
// выполнить SQL запрос
ResultSet resultSet = statement.executeQuery(queries);
while (resultSet.next()) {
historyList.add(resultSet.getString("id_object"));
}
return historyList;
} catch (SQLException e) {
return null;
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
public void insertHistory(String name) throws SQLException {
readToJSON();
Connection dbConnection = null;
Statement statement = null;
String insertEmployeeData = ("INSERT INTO history_data (id_object) \n" +
"VALUES ('%s')");
try {
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
// выполнить SQL запрос
statement.executeUpdate(String.format(insertEmployeeData, name));
statement.close();
dbConnection.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
public void showLoginPostgres() throws IOException {
Parent root = null;
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/LogInPostgresMenu.fxml"));
root = loader.load();
Stage loginPostgres = new Stage();
loginPostgres.setTitle("Авторизация PostgreSQL");
loginPostgres.initModality(Modality.APPLICATION_MODAL);
loginPostgres.setScene(new Scene(root));
LogInPostgresController logInPostgresController = loader.getController();
logInPostgresController.setParent(this);
loginPostgres.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void exportToJSON(ArrayList<String> settings) throws IOException {
Gson gson = new Gson();
String jsonString = gson.toJson(settings);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(FILE_NAME);
fileOutputStream.write(jsonString.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void readToJSON() {
InputStreamReader streamReader = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(FILE_NAME);
streamReader = new InputStreamReader(fileInputStream);
Gson gson = new Gson();
ArrayList dataItems = gson.fromJson(streamReader, ArrayList.class);
if (dataItems != null) {
this.login = dataItems.get(0).toString();
this.password = dataItems.get(1).toString();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void setLoginAndPassword(String login, String password) {
this.login = login;
this.password = <PASSWORD>;
}
}
|
Below is an extract from a shell script. Evaluate whether it has a high educational value and could help teach shell scripting. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the script contains valid shell commands, even if it's not educational, like simple system calls or basic file operations.
- Add another point if the script addresses practical shell scripting concepts (e.g., variables, conditionals), even if it lacks comments.
- Award a third point if the script is suitable for educational use and introduces key concepts in shell scripting, even if the topic is somewhat advanced (e.g., functions, process management). The script should be well-structured and contain some comments.
- Give a fourth point if the script is self-contained and highly relevant to teaching shell scripting. It should be similar to a tutorial example or a shell scripting course section, demonstrating good practices in script organization.
- Grant a fifth point if the script is outstanding in its educational value and is perfectly suited for teaching shell scripting. It should be well-written, easy to understand, and contain step-by-step explanations in comments.
The extract:
TOKEN_SECRET =
TYPEORM_CONNECTION = mysql
TYPEORM_HOST = 127.0.0.1
TYPEORM_USERNAME = root
TYPEORM_PASSWORD =
TYPEORM_DATABASE =
TYPEORM_PORT = 3306
TYPEORM_SYNCHRONIZE = false
TYPEORM_LOGGING = true
TYPEORM_ENTITIES = src/**/**/*.entity.ts
TYPEORM_DRIVER_EXTRA = { "ssl": { "rejectUnauthorized": false } }
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
shell
| 0 |
TOKEN_SECRET =
TYPEORM_CONNECTION = mysql
TYPEORM_HOST = 127.0.0.1
TYPEORM_USERNAME = root
TYPEORM_PASSWORD =
TYPEORM_DATABASE =
TYPEORM_PORT = 3306
TYPEORM_SYNCHRONIZE = false
TYPEORM_LOGGING = true
TYPEORM_ENTITIES = src/**/**/*.entity.ts
TYPEORM_DRIVER_EXTRA = { "ssl": { "rejectUnauthorized": false } }
|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package com.solution;
class Node {
int value = 0;
Node next;
Node(int value) {
this.value = value;
}
}
// Rotate a LinkedList.
public class Main {
public static Node rotate(Node head, int k) {
if (head == null || head.next == null || k < 0) return head;
Node lastNode = head;
int length = 1;
while (lastNode.next != null) {
length++;
lastNode = lastNode.next;
}
int skip = length - k % length;
Node runner = head, pre = head;
while (skip > 0) {
pre = runner;
runner = runner.next;
skip--;
}
lastNode.next = head;
pre.next = null;
return runner;
}
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(6);
head.next.next.next.next.next.next = new Node(7);
head.next.next.next.next.next.next.next = new Node(8);
Node res = rotate(head, 2);
while (res != null) {
System.out.println(res.value);
res = res.next;
}
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
java
| 2 |
package com.solution;
class Node {
int value = 0;
Node next;
Node(int value) {
this.value = value;
}
}
// Rotate a LinkedList.
public class Main {
public static Node rotate(Node head, int k) {
if (head == null || head.next == null || k < 0) return head;
Node lastNode = head;
int length = 1;
while (lastNode.next != null) {
length++;
lastNode = lastNode.next;
}
int skip = length - k % length;
Node runner = head, pre = head;
while (skip > 0) {
pre = runner;
runner = runner.next;
skip--;
}
lastNode.next = head;
pre.next = null;
return runner;
}
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(6);
head.next.next.next.next.next.next = new Node(7);
head.next.next.next.next.next.next.next = new Node(8);
Node res = rotate(head, 2);
while (res != null) {
System.out.println(res.value);
res = res.next;
}
}
}
|
Below is an extract from a C program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid C code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical C concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., kernel development and compiler design). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching C. It should be similar to a school exercise, a tutorial, or a C course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
/*
* This file is part of dm-writeboost
* Copyright (C) 2012-2017 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef DM_WRITEBOOST_DAEMON_H
#define DM_WRITEBOOST_DAEMON_H
/*----------------------------------------------------------------------------*/
int flush_daemon_proc(void *);
void wait_for_flushing(struct wb_device *, u64 id);
/*----------------------------------------------------------------------------*/
void queue_barrier_io(struct wb_device *, struct bio *);
void flush_barrier_ios(struct work_struct *);
/*----------------------------------------------------------------------------*/
void update_nr_empty_segs(struct wb_device *);
int writeback_daemon_proc(void *);
void wait_for_writeback(struct wb_device *, u64 id);
void mark_clean_seg(struct wb_device *, struct segment_header *seg);
/*----------------------------------------------------------------------------*/
//(jjo)
//int check_io_pattern(struct dm_device *, struct rambuffer *, struct segment_header *);
/*----------------------------------------------------------------------------*/
int writeback_modulator_proc(void *);
/*----------------------------------------------------------------------------*/
int data_synchronizer_proc(void *);
/*--------------------------------------------------------------------
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
c
| 1 |
/*
* This file is part of dm-writeboost
* Copyright (C) 2012-2017 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef DM_WRITEBOOST_DAEMON_H
#define DM_WRITEBOOST_DAEMON_H
/*----------------------------------------------------------------------------*/
int flush_daemon_proc(void *);
void wait_for_flushing(struct wb_device *, u64 id);
/*----------------------------------------------------------------------------*/
void queue_barrier_io(struct wb_device *, struct bio *);
void flush_barrier_ios(struct work_struct *);
/*----------------------------------------------------------------------------*/
void update_nr_empty_segs(struct wb_device *);
int writeback_daemon_proc(void *);
void wait_for_writeback(struct wb_device *, u64 id);
void mark_clean_seg(struct wb_device *, struct segment_header *seg);
/*----------------------------------------------------------------------------*/
//(jjo)
//int check_io_pattern(struct dm_device *, struct rambuffer *, struct segment_header *);
/*----------------------------------------------------------------------------*/
int writeback_modulator_proc(void *);
/*----------------------------------------------------------------------------*/
int data_synchronizer_proc(void *);
/*----------------------------------------------------------------------------*/
int sb_record_updater_proc(void *);
/*----------------------------------------------------------------------------*/
#endif
|
Below is an extract from a TypeScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid TypeScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical TypeScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., generics, decorators). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching TypeScript. It should be similar to a school exercise, a tutorial, or a TypeScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching TypeScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
import { Option } from '@ephox/katamari';
import * as PredicateFind from '../search/PredicateFind';
import * as Traverse from '../search/Traverse';
import * as Awareness from './Awareness';
import Element from '../node/Element';
const first = function (element: Element) {
return PredicateFind.descendant(element, Awareness.isCursorPosition);
};
const last = function (element: Element) {
return descendantRtl(element, Awareness.isCursorPosition);
};
// Note, sugar probably needs some RTL traversals.
const descendantRtl = function (scope: Element, predicate) {
const descend = function (element): Option<Element> {
const children = Traverse.children(element);
for (let i = children.length - 1; i >= 0; i--) {
const child = children[i];
if (predicate(child)) { return Option.some(child); }
const res = descend(child);
if (res.isSome()) { return res; }
}
return Option.none<Element>();
};
return descend(scope);
};
export {
first,
last,
};
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
typescript
| 2 |
import { Option } from '@ephox/katamari';
import * as PredicateFind from '../search/PredicateFind';
import * as Traverse from '../search/Traverse';
import * as Awareness from './Awareness';
import Element from '../node/Element';
const first = function (element: Element) {
return PredicateFind.descendant(element, Awareness.isCursorPosition);
};
const last = function (element: Element) {
return descendantRtl(element, Awareness.isCursorPosition);
};
// Note, sugar probably needs some RTL traversals.
const descendantRtl = function (scope: Element, predicate) {
const descend = function (element): Option<Element> {
const children = Traverse.children(element);
for (let i = children.length - 1; i >= 0; i--) {
const child = children[i];
if (predicate(child)) { return Option.some(child); }
const res = descend(child);
if (res.isSome()) { return res; }
}
return Option.none<Element>();
};
return descend(scope);
};
export {
first,
last,
};
|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package com.yagn.nadrii.web.ticket;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.yagn.nadrii.common.OpenApiPage;
import com.yagn.nadrii.common.OpenApiSearch;
import com.yagn.nadrii.service.ticket.TicketService;
// [행사정보 조회]
@Controller
@RequestMapping("/ticket/*")
public class TicketRestController {
@Autowired
@Qualifier("ticketServiceImpl")
private TicketService ticketService;
/// Constructor
public TicketRestController() {
System.out.println(this.getClass());
}
@Value("#{commonProperties['pageUnit']}")
int pageUnit;
@Value("#{commonProperties['pageSize']}")
int pageSize;
@RequestMapping(value = "json/listTicket", method = RequestMethod.POST)
public String listTicket(
@RequestBody JSONObject searchCondition,
@ModelAttribute("openApiSearch") OpenApiSearch openApiSearch,
Model model
) {
System.out.println("\n /ticket/json/listTicket : GET / POST");
try {
if (openApiSearch.getPageNo() == 0) {
openApiSearch.setPageNo(1);
}
openApiSearch.setNumOfRows(pageSize);
JSONObject jsonObj = (JSONObject) JSONValue.parse(searchCondition.toJSONString());
String searchConditionVal = (String) jsonObj.get("searchCondition");
System.out.println("[searchConditionVal check]==>"+searchConditionVal);
openApiSearch.setSearchCondition(searchConditionVal);
Map<String, Object>
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
java
| 2 |
package com.yagn.nadrii.web.ticket;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.yagn.nadrii.common.OpenApiPage;
import com.yagn.nadrii.common.OpenApiSearch;
import com.yagn.nadrii.service.ticket.TicketService;
// [행사정보 조회]
@Controller
@RequestMapping("/ticket/*")
public class TicketRestController {
@Autowired
@Qualifier("ticketServiceImpl")
private TicketService ticketService;
/// Constructor
public TicketRestController() {
System.out.println(this.getClass());
}
@Value("#{commonProperties['pageUnit']}")
int pageUnit;
@Value("#{commonProperties['pageSize']}")
int pageSize;
@RequestMapping(value = "json/listTicket", method = RequestMethod.POST)
public String listTicket(
@RequestBody JSONObject searchCondition,
@ModelAttribute("openApiSearch") OpenApiSearch openApiSearch,
Model model
) {
System.out.println("\n /ticket/json/listTicket : GET / POST");
try {
if (openApiSearch.getPageNo() == 0) {
openApiSearch.setPageNo(1);
}
openApiSearch.setNumOfRows(pageSize);
JSONObject jsonObj = (JSONObject) JSONValue.parse(searchCondition.toJSONString());
String searchConditionVal = (String) jsonObj.get("searchCondition");
System.out.println("[searchConditionVal check]==>"+searchConditionVal);
openApiSearch.setSearchCondition(searchConditionVal);
Map<String, Object> map = ticketService.getTicketList(openApiSearch);
System.out.println(map.get("tourTicketList"));
OpenApiPage resultPage = new OpenApiPage(openApiSearch.getPageNo(),
((Integer) map.get("totalCount")).intValue(), pageUnit, pageSize);
System.out.println("[resultPage]" + resultPage);
model.addAttribute("tourTicket", map.get("tourTicketList"));
model.addAttribute("resultPage", resultPage);
} catch (Exception e) {
System.out.println(e);
}
// return null;
return "forward:/ticket/listTicket.jsp";
}
} // end of class
|
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical JavaScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
import visualize from "./visualize";
import { secondsToHis } from "./helpers";
import { append, read, rewrite } from "./store";
class Timer {
startTime = null;
secondsPassed = 0;
isRunning = false;
intervalId = 0;
saveIntervalId = 0;
currentProject = null;
start() {
this.startTime = Date.now();
this.isRunning = true;
visualize(secondsToHis(this.secondsPassed));
this.intervalId = setInterval(() => {
this.secondsPassed += 1;
// if the duration spans into another day cut the duration to the end of the previous day and save it
if (this.spansAcross2Days()) {
append(this.currentProject, { start : this.startTime, finish : Date.now() - 1000 })
.catch(console.log);
this.startTime = Date.now();
}
visualize(secondsToHis(this.secondsPassed));
}, 1000);
this.saveIntervalId = setInterval(this.save.bind(this), 1000 * 60 * 3); // save every 5 mins
}
spansAcross2Days() {
const startDate = new Date(this.startTime);
const currentDate = new Date();
return startDate.getDate() !== currentDate.getDate();
}
async stop() {
this.save();
this.isRunning = false;
this.secondsPassed = 0;
clearInterval(this.intervalId);
clearInterval(this.saveIntervalId);
}
save() {
read(this.currentProject)
.then((data) => {
let l = data.length;
let lastDuration = data[l - 1];
if (lastDuration && lastDuration.start === this.startTime) {
lastDuration.finish = Date.now();
rewrite(this.currentProject, data)
.catch(console.log);
} else {
append(this.currentProject, { start : this.startTime, finish : Date.now() })
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
javascript
| 3 |
import visualize from "./visualize";
import { secondsToHis } from "./helpers";
import { append, read, rewrite } from "./store";
class Timer {
startTime = null;
secondsPassed = 0;
isRunning = false;
intervalId = 0;
saveIntervalId = 0;
currentProject = null;
start() {
this.startTime = Date.now();
this.isRunning = true;
visualize(secondsToHis(this.secondsPassed));
this.intervalId = setInterval(() => {
this.secondsPassed += 1;
// if the duration spans into another day cut the duration to the end of the previous day and save it
if (this.spansAcross2Days()) {
append(this.currentProject, { start : this.startTime, finish : Date.now() - 1000 })
.catch(console.log);
this.startTime = Date.now();
}
visualize(secondsToHis(this.secondsPassed));
}, 1000);
this.saveIntervalId = setInterval(this.save.bind(this), 1000 * 60 * 3); // save every 5 mins
}
spansAcross2Days() {
const startDate = new Date(this.startTime);
const currentDate = new Date();
return startDate.getDate() !== currentDate.getDate();
}
async stop() {
this.save();
this.isRunning = false;
this.secondsPassed = 0;
clearInterval(this.intervalId);
clearInterval(this.saveIntervalId);
}
save() {
read(this.currentProject)
.then((data) => {
let l = data.length;
let lastDuration = data[l - 1];
if (lastDuration && lastDuration.start === this.startTime) {
lastDuration.finish = Date.now();
rewrite(this.currentProject, data)
.catch(console.log);
} else {
append(this.currentProject, { start : this.startTime, finish : Date.now() })
.catch(console.log);
}
}).catch(console.log);
}
reset() {
this.isRunning = false;
this.secondsPassed = 0;
this.startTime = null;
this.currentProject = null;
}
}
export default new Timer();
|
Below is an extract from a shell script. Evaluate whether it has a high educational value and could help teach shell scripting. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the script contains valid shell commands, even if it's not educational, like simple system calls or basic file operations.
- Add another point if the script addresses practical shell scripting concepts (e.g., variables, conditionals), even if it lacks comments.
- Award a third point if the script is suitable for educational use and introduces key concepts in shell scripting, even if the topic is somewhat advanced (e.g., functions, process management). The script should be well-structured and contain some comments.
- Give a fourth point if the script is self-contained and highly relevant to teaching shell scripting. It should be similar to a tutorial example or a shell scripting course section, demonstrating good practices in script organization.
- Grant a fifth point if the script is outstanding in its educational value and is perfectly suited for teaching shell scripting. It should be well-written, easy to understand, and contain step-by-step explanations in comments.
The extract:
#!/usr/bin/env bash
#利用插件生成可执行镜像
#先生成一个可执行的镜像mb-oa,然后commit,在提交
docker commit mb-oa registry.cn-hangzhou.aliyuncs.com/mengstar/mb-oa &&
docker push registry.cn-hangzhou.aliyuncs.com/mengstar/mb-oa
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
shell
| 1 |
#!/usr/bin/env bash
#利用插件生成可执行镜像
#先生成一个可执行的镜像mb-oa,然后commit,在提交
docker commit mb-oa registry.cn-hangzhou.aliyuncs.com/mengstar/mb-oa &&
docker push registry.cn-hangzhou.aliyuncs.com/mengstar/mb-oa
|
Below is an extract from an HTML document. Evaluate whether it has a high educational value and could help teach web development. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the document contains valid HTML markup, even if it's not educational, like boilerplate code or standard tags.
- Add another point if the document addresses practical HTML concepts and uses semantic elements appropriately.
- Award a third point if the document is suitable for educational use and introduces key web concepts, even if the topic is somewhat advanced (e.g., forms, metadata). The code should be well-structured and use clear, descriptive naming.
- Give a fourth point if the document is self-contained and highly relevant to teaching HTML. It should be similar to a school exercise, a tutorial, or an HTML course section for early learners.
- Grant a fifth point if the document is outstanding in its educational value and is perfectly suited for teaching HTML to beginners. It should be well-organized, easy to understand, and ideally include some explanatory comments or demonstrate best practices in HTML structure.
The extract:
{% extends "_base.html" %}
{% block title %}{{ super() }} {{ data['title'] }} {% endblock %}
{% block crumbs %}{{ super() }}
/ <a href="../processes">{% trans %}Processes{% endtrans %}</a>
/ <a href="./{{ data['id'] }}">{{ data['title'] }}</a>
{% endblock %}
{% block body %}
<section id="process" itemscope itemtype="https://schema.org/WebAPI">
<h2 itemprop="name">{{ data['title'] }}</h2>
<div itemprop="description">{{data.description}}</div>
<p itemprop="keywords">
{% for kw in data['keywords'] %}
<span class="badge text-bg-primary bg-primary">{{ kw }}</span>
{% endfor %}
</p>
<meta itemprop="url" content="{{config.server.url}}/processes/{{data.id}}" />
<div class="row">
<div class="col-sm-12 col-md-12">
<table class="table table-striped table-bordered">
<caption>{% trans %}Inputs{% endtrans %}</caption>
<thead>
<tr>
<th>{% trans %}Id{% endtrans %}</th>
<th>{% trans %}Title{% endtrans %}</th>
<th>{% trans %}Data Type{% endtrans %}</th>
<th>{% trans %}Description{% endtrans %}</th>
</tr>
</thead>
<tbody>
{% for key, value in data['inputs'].items() %}
<tr itemprop="parameter" itemscope>
<td itemprop="id" data-label="ID">
{{ key }}
</td>
<td itemprop="name" data-label="Title">
{{ value.title|striptags|truncate }}
</td>
<td itemprop="name" data-label="Data Type">
{{ value.schema.type }}
</td>
<td itemprop="description" data-label="Description">
{{ value.description }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="col-sm-12 col-md-12">
<table
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
html
| 2 |
{% extends "_base.html" %}
{% block title %}{{ super() }} {{ data['title'] }} {% endblock %}
{% block crumbs %}{{ super() }}
/ <a href="../processes">{% trans %}Processes{% endtrans %}</a>
/ <a href="./{{ data['id'] }}">{{ data['title'] }}</a>
{% endblock %}
{% block body %}
<section id="process" itemscope itemtype="https://schema.org/WebAPI">
<h2 itemprop="name">{{ data['title'] }}</h2>
<div itemprop="description">{{data.description}}</div>
<p itemprop="keywords">
{% for kw in data['keywords'] %}
<span class="badge text-bg-primary bg-primary">{{ kw }}</span>
{% endfor %}
</p>
<meta itemprop="url" content="{{config.server.url}}/processes/{{data.id}}" />
<div class="row">
<div class="col-sm-12 col-md-12">
<table class="table table-striped table-bordered">
<caption>{% trans %}Inputs{% endtrans %}</caption>
<thead>
<tr>
<th>{% trans %}Id{% endtrans %}</th>
<th>{% trans %}Title{% endtrans %}</th>
<th>{% trans %}Data Type{% endtrans %}</th>
<th>{% trans %}Description{% endtrans %}</th>
</tr>
</thead>
<tbody>
{% for key, value in data['inputs'].items() %}
<tr itemprop="parameter" itemscope>
<td itemprop="id" data-label="ID">
{{ key }}
</td>
<td itemprop="name" data-label="Title">
{{ value.title|striptags|truncate }}
</td>
<td itemprop="name" data-label="Data Type">
{{ value.schema.type }}
</td>
<td itemprop="description" data-label="Description">
{{ value.description }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="col-sm-12 col-md-12">
<table class="table table-striped table-bordered">
<caption>{% trans %}Outputs{% endtrans %}</caption>
<thead>
<tr>
<th>{% trans %}Id{% endtrans %}</th>
<th>{% trans %}Title{% endtrans %}</th>
<th>{% trans %}Description{% endtrans %}</th>
</tr>
</thead>
<tbody>
{% for key, value in data['outputs'].items() %}
<tr itemprop="parameter" itemscope>
<td itemprop="id" data-label="ID">{{ key }}</td>
<td itemprop="name" data-label="Title">{{ value.title }}</td>
<td itemprop="description" data-label="Description">
{{ value.description | striptags | truncate }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
<h2>{% trans %}Execution modes{% endtrans %}</h2>
<ul>
{% if 'sync-execute' in data.jobControlOptions %}<li>{% trans %}Synchronous{% endtrans %}</li>{% endif %}
{% if 'async-execute' in data.jobControlOptions %}<li>{% trans %}Asynchronous{% endtrans %}</li>{% endif %}
</ul>
<h2>{% trans %}Jobs{% endtrans %}</h2>
<a title="Browse jobs" href="{{config.server.url}}/jobs">{% trans %}Browse jobs{% endtrans %}</a>
<h2>{% trans %}Links{% endtrans %}</h2>
<ul>
{% for link in data['links'] %}
<li>
<a title={{link.title}} type={{link.type}} rel={{link.rel}} href={{link.href}} hreflang={{link.hreflang}}>
{{ link['title'] }} ({{ link['type'] }})
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
</section>
{% endblock %}
|
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical PHP concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
<?php
namespace FEIWebServicesClient\Horse\Types;
use Assert\Assert;
use FEIWebServicesClient\Common\Types\Country;
use FEIWebServicesClient\Common\Types\DocIssuingBody;
use FEIWebServicesClient\Common\Types\NationalFederation;
class Horse
{
/**
* @var string
*/
private $FEICode;
/**
* @var string
*/
private $AdmNFCode;
/**
* @var string
*/
private $CurrentName;
/**
* @var string
*/
private $CommercialName;
/**
* @var string
*/
private $BirthName;
/**
* @var string
*/
private $ShortName;
/**
* @var string
*/
private $CompleteName;
/**
* @var bool
*/
private $IsCNSuffix = false;
/**
* @var string
*/
private $GenderCode;
/**
* @var string
*/
private $ColorCode;
/**
* @var string
*/
private $BirthCountryCode;
/**
* @var \DateTimeImmutable
*/
private $DateBirth;
/**
* @var \DateTime
*/
private $DateRetirement;
/**
* @var \DateTime
*/
private $DateDeath;
/**
* @var string
*/
private $ColorComplement;
/**
* @var bool
*/
private $IsActive;
/**
* @var string
*/
private $InactiveReason;
/**
* @var int
*/
private $CastratedId;
/**
* @var \DateTime
*/
private $DateCastration;
/**
* @var int
*/
private $Height;
/**
* @var bool
*/
private $IsPony;
/**
* @var string
*/
private $Breed;
/**
* @var string
*/
private $Breeder;
/**
* @var string
*/
private $StudBookCode;
/**
* @var string
*/
private $FEICodeType;
/**
* @var string
*/
private $UELN;
/**
* @var string
*/
private $Microchip;
/**
* @var string
*/
private $NatPassport;
/**
* @var string
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
php
| 2 |
<?php
namespace FEIWebServicesClient\Horse\Types;
use Assert\Assert;
use FEIWebServicesClient\Common\Types\Country;
use FEIWebServicesClient\Common\Types\DocIssuingBody;
use FEIWebServicesClient\Common\Types\NationalFederation;
class Horse
{
/**
* @var string
*/
private $FEICode;
/**
* @var string
*/
private $AdmNFCode;
/**
* @var string
*/
private $CurrentName;
/**
* @var string
*/
private $CommercialName;
/**
* @var string
*/
private $BirthName;
/**
* @var string
*/
private $ShortName;
/**
* @var string
*/
private $CompleteName;
/**
* @var bool
*/
private $IsCNSuffix = false;
/**
* @var string
*/
private $GenderCode;
/**
* @var string
*/
private $ColorCode;
/**
* @var string
*/
private $BirthCountryCode;
/**
* @var \DateTimeImmutable
*/
private $DateBirth;
/**
* @var \DateTime
*/
private $DateRetirement;
/**
* @var \DateTime
*/
private $DateDeath;
/**
* @var string
*/
private $ColorComplement;
/**
* @var bool
*/
private $IsActive;
/**
* @var string
*/
private $InactiveReason;
/**
* @var int
*/
private $CastratedId;
/**
* @var \DateTime
*/
private $DateCastration;
/**
* @var int
*/
private $Height;
/**
* @var bool
*/
private $IsPony;
/**
* @var string
*/
private $Breed;
/**
* @var string
*/
private $Breeder;
/**
* @var string
*/
private $StudBookCode;
/**
* @var string
*/
private $FEICodeType;
/**
* @var string
*/
private $UELN;
/**
* @var string
*/
private $Microchip;
/**
* @var string
*/
private $NatPassport;
/**
* @var string
*/
private $RecognitionCode;
/**
* @var string
*/
private $NFData;
/**
* @var string
*/
private $IssuingNFCode;
/**
* @var string
*/
private $IssuingBodyCode;
/**
* @var \DateTime
*/
private $DateIssuing;
/**
* @var \DateTime
*/
private $DateOfExpiry;
/**
* @var HorseTrainer
*/
private $Trainer;
/**
* @var int
*/
private $EnduranceQualificationLevel;
/**
* @var \DateTime
*/
private $EnduranceRestPeriodEnd;
/**
* @var string
*/
private $TCN;
/**
* @var string
*/
private $HorseSireName;
/**
* @var string
*/
private $HorseSireUELN;
/**
* @var string
*/
private $HorseDamName;
/**
* @var string
*/
private $HorseDamUELN;
/**
* @var string
*/
private $HorseSireOfDamName;
/**
* @var string
*/
private $HorseSireOfDamUELN;
/**
* @var string
*/
private $KindOfName;
/**
* @var bool
*/
private $MissingDocuments;
public function __construct(array $arrayHorse)
{
Assert::that($arrayHorse)
->keyExists('BirthName')
->keyExists('DateBirth')
->keyExists('CastratedId')
->keyExists('CurrentName')
->keyExists('IsPony')
->keyExists('NatPassport')
->keyExists('IsActive')
->keyExists('GenderCode')
->keyExists('ColorCode')
->keyExists('IssuingNFCode')
->keyExists('Microchip')
->keyExists('RecognitionCode')
;
$this->BirthName = (string) HorseNameFactory::createAsCurrentOrBirthName($arrayHorse['BirthName']);
$this->CurrentName = (string) HorseNameFactory::createAsCurrentOrBirthName($arrayHorse['CurrentName']);
$dateBirth = new \DateTimeImmutable($arrayHorse['DateBirth']);
if ($dateBirth <= new \DateTimeImmutable('1980-01-01') || $dateBirth > new \DateTimeImmutable('now')) {
throw new \LogicException('The birthdate cannot be set before 1980-01-01 or in the future.');
}
$this->DateBirth = $dateBirth;
Assert::that($arrayHorse['CastratedId'])->inArray([1, 2, 3]);
$this->CastratedId = $arrayHorse['CastratedId'];
Assert::that($arrayHorse['IsPony'])->boolean();
$this->IsPony = $arrayHorse['IsPony'];
Assert::that($arrayHorse['NatPassport'])->maxLength(20)->notBlank();
$this->NatPassport = $arrayHorse['NatPassport'];
Assert::that($arrayHorse['IsActive'])->boolean();
$this->IsActive = $arrayHorse['IsActive'];
Assert::that($arrayHorse['GenderCode'])->inArray(['M', 'F']);
if ('M' !== $arrayHorse['GenderCode'] && \in_array($this->CastratedId, [1, 3])) {
throw new \InvalidArgumentException('The gender code expected with the CastratedId given must be M.');
}
$this->GenderCode = $arrayHorse['GenderCode'];
Assert::that($arrayHorse['ColorCode'])->inArray(['other', 'bay', 'black', 'chestnut', 'grey ']);
$this->ColorCode = $arrayHorse['ColorCode'];
if ('other' === $arrayHorse['ColorCode']) {
Assert::that($arrayHorse)->keyExists('ColorComplement');
Assert::that($arrayHorse['ColorComplement'])->maxLength(50);
$this->ColorComplement = $arrayHorse['ColorComplement'];
}
if (array_key_exists('FEICodeType', $arrayHorse)) {
Assert::that($arrayHorse['FEICodeType'])->inArray(['R', 'C', 'P']);
$FEICodeType = $arrayHorse['FEICodeType'];
}
$this->FEICodeType = $FEICodeType ?? 'R';
if ('R' === $this->FEICodeType) {
Assert::that($arrayHorse)->keyExists('IssuingBodyCode');
}
if (array_key_exists('IssuingBodyCode', $arrayHorse)) {
Assert::that($arrayHorse['IssuingBodyCode'])->notBlank();
$this->IssuingBodyCode = (new DocIssuingBody($arrayHorse['IssuingBodyCode']))->getCode();
}
Assert::that($arrayHorse['RecognitionCode'])->notBlank()->maxLength(20);
$this->RecognitionCode = $arrayHorse['RecognitionCode'];
$this->Microchip = (string) new Chip($arrayHorse['Microchip']);
$this->IssuingNFCode = (string) new NationalFederation(Country::create($arrayHorse['IssuingNFCode']));
}
/**
* @return string
*/
public function getFEICode(): string
{
return $this->FEICode;
}
/**
* @return string
*/
public function getAdmNFCode(): string
{
return $this->AdmNFCode;
}
/**
* @return string
*/
public function getCurrentName(): string
{
return $this->CurrentName;
}
/**
* @return string
*/
public function getCommercialName(): string
{
return $this->CommercialName;
}
/**
* @return string
*/
public function getBirthName(): string
{
return $this->BirthName;
}
/**
* @return string
*/
public function getShortName(): string
{
return $this->ShortName;
}
/**
* @return string
*/
public function getCompleteName(): string
{
return $this->CompleteName;
}
/**
* @return bool
*/
public function isIsCNSuffix(): bool
{
return $this->IsCNSuffix;
}
/**
* @return string
*/
public function getGenderCode(): string
{
return $this->GenderCode;
}
/**
* @return string
*/
public function getColorCode(): string
{
return $this->ColorCode;
}
/**
* @return string
*/
public function getBirthCountryCode(): string
{
return $this->BirthCountryCode;
}
/**
* @return \DateTimeImmutable
*/
public function getDateBirth(): \DateTimeImmutable
{
return $this->DateBirth;
}
/**
* @return \DateTime
*/
public function getDateRetirement(): \DateTime
{
return $this->DateRetirement;
}
/**
* @return \DateTime
*/
public function getDateDeath(): \DateTime
{
return $this->DateDeath;
}
/**
* @return string|null
*/
public function getColorComplement(): ? string
{
return $this->ColorComplement;
}
/**
* @return bool
*/
public function isActive(): bool
{
return $this->IsActive;
}
/**
* @return string
*/
public function getInactiveReason(): string
{
return $this->InactiveReason;
}
/**
* @return int
*/
public function getCastratedId(): int
{
return $this->CastratedId;
}
/**
* @return \DateTime
*/
public function getDateCastration(): \DateTime
{
return $this->DateCastration;
}
/**
* @return int
*/
public function getHeight(): int
{
return $this->Height;
}
/**
* @return bool
*/
public function isPony(): bool
{
return $this->IsPony;
}
/**
* @return string
*/
public function getBreed(): string
{
return $this->Breed;
}
/**
* @return string
*/
public function getBreeder(): string
{
return $this->Breeder;
}
/**
* @return string
*/
public function getStudBookCode(): string
{
return $this->StudBookCode;
}
/**
* @return string
*/
public function getFEICodeType(): string
{
return $this->FEICodeType;
}
/**
* @return string
*/
public function getUELN(): string
{
return $this->UELN;
}
/**
* @return string
*/
public function getMicrochip(): string
{
return $this->Microchip;
}
/**
* @return string
*/
public function getNatPassport(): string
{
return $this->NatPassport;
}
/**
* @return string
*/
public function getRecognitionCode(): string
{
return $this->RecognitionCode;
}
/**
* @return string
*/
public function getNFData(): string
{
return $this->NFData;
}
/**
* @return string
*/
public function getIssuingNFCode(): string
{
return $this->IssuingNFCode;
}
/**
* @return string
*/
public function getIssuingBodyCode(): string
{
return $this->IssuingBodyCode;
}
/**
* @return \DateTime
*/
public function getDateIssuing(): \DateTime
{
return $this->DateIssuing;
}
/**
* @return \DateTime
*/
public function getDateOfExpiry(): \DateTime
{
return $this->DateOfExpiry;
}
/**
* @return HorseTrainer
*/
public function getTrainer(): HorseTrainer
{
return $this->Trainer;
}
/**
* @return int
*/
public function getEnduranceQualificationLevel(): int
{
return $this->EnduranceQualificationLevel;
}
/**
* @return \DateTime
*/
public function getEnduranceRestPeriodEnd(): \DateTime
{
return $this->EnduranceRestPeriodEnd;
}
/**
* @return string
*/
public function getTCN(): string
{
return $this->TCN;
}
/**
* @return string
*/
public function getHorseSireName(): string
{
return $this->HorseSireName;
}
/**
* @return string
*/
public function getHorseSireUELN(): string
{
return $this->HorseSireUELN;
}
/**
* @return string
*/
public function getHorseDamName(): string
{
return $this->HorseDamName;
}
/**
* @return string
*/
public function getHorseDamUELN(): string
{
return $this->HorseDamUELN;
}
/**
* @return string
*/
public function getHorseSireOfDamName(): string
{
return $this->HorseSireOfDamName;
}
/**
* @return string
*/
public function getHorseSireOfDamUELN(): string
{
return $this->HorseSireOfDamUELN;
}
/**
* @return string
*/
public function getKindOfName(): string
{
return $this->KindOfName;
}
/**
* @return bool
*/
public function isMissingDocuments(): bool
{
return $this->MissingDocuments;
}
}
|
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content.
- Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse.
- Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow.
- Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson.
- Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes.
The extract:
# How To Stay Motivated During Tough Times At Work
NOTE: This post was written a few months ago during a period of turmoil at my job. I've since moved on and started a new position.
As I mentioned in a <a href="https://www.snowboardingcoder.com/coding/2018/01/24/should-i-stay-or-should-i-go-now/">previous post</a>, I'm in a chaotic time at work, leading me to debate (on an almost daily basis) if I need to get serious about job hunting.
At present, I've decided to ride out the chaos, but that leads to a new problem: how to stay motivated and keep doing a good job while things are going wonky.
As has been my experience in several previous jobs, when things start getting tough at work, the rumor mill really takes off. There are a couple of stages of this. It starts with smaller side coversations about the future of the company/product/group. Eventually, if things continue on that path, this breaks out into open, group-wide gripe sessions about what's 'going to happen' and how managaement is being dishonest or making dumb decisions.
I've learned a few lessons about these sessions:
1) No one involved really knows anything. It may be that their guesses are correct, but I've found that generally, the folks sitting around griping are not the ones with the knowledge of the real situation.
2) Management is never going to give you answers to silly questions that always get asked in times like these: "will there be layoffs?", "Is the site getting shut down?", etc. I call this type of question silly as there is no good answer to them. No sane manager that is actually doing her job is going to answer them truthfully. Frequently it would actually be illegal to answer them truthfully.
The next time you hear a question like this, play out the potential responses. If the manager says, "No, the site's is not getting shut down next month". How much credence will you give that answer? Will it change anything?
## Coping
So, here is my coping plan for the next couple
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
markdown
| 3 |
# How To Stay Motivated During Tough Times At Work
NOTE: This post was written a few months ago during a period of turmoil at my job. I've since moved on and started a new position.
As I mentioned in a <a href="https://www.snowboardingcoder.com/coding/2018/01/24/should-i-stay-or-should-i-go-now/">previous post</a>, I'm in a chaotic time at work, leading me to debate (on an almost daily basis) if I need to get serious about job hunting.
At present, I've decided to ride out the chaos, but that leads to a new problem: how to stay motivated and keep doing a good job while things are going wonky.
As has been my experience in several previous jobs, when things start getting tough at work, the rumor mill really takes off. There are a couple of stages of this. It starts with smaller side coversations about the future of the company/product/group. Eventually, if things continue on that path, this breaks out into open, group-wide gripe sessions about what's 'going to happen' and how managaement is being dishonest or making dumb decisions.
I've learned a few lessons about these sessions:
1) No one involved really knows anything. It may be that their guesses are correct, but I've found that generally, the folks sitting around griping are not the ones with the knowledge of the real situation.
2) Management is never going to give you answers to silly questions that always get asked in times like these: "will there be layoffs?", "Is the site getting shut down?", etc. I call this type of question silly as there is no good answer to them. No sane manager that is actually doing her job is going to answer them truthfully. Frequently it would actually be illegal to answer them truthfully.
The next time you hear a question like this, play out the potential responses. If the manager says, "No, the site's is not getting shut down next month". How much credence will you give that answer? Will it change anything?
## Coping
So, here is my coping plan for the next couple weeks/months/however long this lasts.
I'm going to try to avoid the rumor-mill conversations or get out of them as quickly and quietly as I can. Those might feel good at the time, but they ruin your momentum and motivation.
I'm also going to try to stay focused on the task. Some times keeping your head down and just working is a good thing. I'm fortunate that I currently have more than enough work to do to keep me busy. That work may turn out to be futile in the end, but I need to remember that how I *do* the work matters and my reputation with my co-workers is one of my most valuable assets.
I'm going to focus on keeping calm and knowing that I can ride out this storm. The worst case scenario here is that this job goes away tomorrow, next weeek, next month. I knew this job wasn't "forever" when I took it. I should gain what I can while it lasts, both in terms of knowledge and skill and also in reputation with my peers. I've been laid off before on several occassions. It's been the community I've built around me that has pulled me through in those times.
That said, I'll definitely keep my eyes open for interesting opportunities that cross my path. One shouldn't bury one's head in the sand, after all.
|
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical PHP concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
<?php include(DOCS_RESOURCES."/datasets/market-hours/future/cme/M6A/regular-trading-hours.html"); ?>
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
php
| 1 |
<?php include(DOCS_RESOURCES."/datasets/market-hours/future/cme/M6A/regular-trading-hours.html"); ?>
|
Below is an extract from a Ruby program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Ruby code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Ruby concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., metaprogramming, blocks). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Ruby. It should be similar to a school exercise, a tutorial, or a Ruby course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Ruby. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
module FileGenerator
autoload :Announcement, 'ModelGenerator/Announcement'
autoload :CommandTask, 'ModelGenerator/CommandTask'
autoload :CommonParam, 'ModelGenerator/CommonParam'
autoload :FormatTransformer, 'ModelGenerator/FormatTransformer'
autoload :ModelGenerator, 'ModelGenerator/ModelGenerator'
autoload :HooksManager, 'ModelGenerator/Project'
autoload :Helper, 'ModelGenerator/Helper'
autoload :HTTPCommandParser, 'HTTPRequestDataParser/HTTPCommandParser'
def self.generate_model
if ARGV.length==0 || ARGV == nil
puts "error: Parameter does not match,there is not any parameter"
return nil
end
begin
@model_generator=ModelGenerator.new
commandTask = @model_generator.analyze_command(ARGV)
if commandTask.flags.join.include?("h")
puts Helper.help
return nil
end
commandParse = HTTPCommandParser.new(ARGV)
is_ok =commandParse.parseCommand
if is_ok == false
@model_generator.generate_header
@model_generator.generate_source
end
rescue Exception => e
puts e
else
commandTask.cacheCommand
end
end
end
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
ruby
| 2 |
module FileGenerator
autoload :Announcement, 'ModelGenerator/Announcement'
autoload :CommandTask, 'ModelGenerator/CommandTask'
autoload :CommonParam, 'ModelGenerator/CommonParam'
autoload :FormatTransformer, 'ModelGenerator/FormatTransformer'
autoload :ModelGenerator, 'ModelGenerator/ModelGenerator'
autoload :HooksManager, 'ModelGenerator/Project'
autoload :Helper, 'ModelGenerator/Helper'
autoload :HTTPCommandParser, 'HTTPRequestDataParser/HTTPCommandParser'
def self.generate_model
if ARGV.length==0 || ARGV == nil
puts "error: Parameter does not match,there is not any parameter"
return nil
end
begin
@model_generator=ModelGenerator.new
commandTask = @model_generator.analyze_command(ARGV)
if commandTask.flags.join.include?("h")
puts Helper.help
return nil
end
commandParse = HTTPCommandParser.new(ARGV)
is_ok =commandParse.parseCommand
if is_ok == false
@model_generator.generate_header
@model_generator.generate_source
end
rescue Exception => e
puts e
else
commandTask.cacheCommand
end
end
end
|
Below is an extract from a Ruby program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Ruby code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Ruby concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., metaprogramming, blocks). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Ruby. It should be similar to a school exercise, a tutorial, or a Ruby course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Ruby. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
begin
require 'ant'
rescue
puts("ERROR: unable to load Ant, make sure Ant is installed, in your PATH and $ANT_HOME is defined properly")
puts("\nerror detail:\n#{$!}")
exit(1)
end
require 'jruby/jrubyc'
desc "compile Java classes"
task :compile do
ant.path 'id' => 'classpath' do
fileset 'dir' => "target/dependency/storm/default"
end
options = {
'srcdir' => "src",
'destdir' => "target/classes",
'classpathref' => 'classpath',
'debug' => "yes",
'includeantruntime' => "no",
'verbose' => false,
'listfiles' => true,
}
ant.javac(options)
end
desc "intall RedStorm"
task :install do
system("bundle exec redstorm install")
end
desc "create RedStorm topology jar"
task :jar do
system("bundle exec redstorm jar lib")
end
desc "initial setup"
task :setup => [:install, :compile, :jar] do
end
task :default => :setup
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
ruby
| 2 |
begin
require 'ant'
rescue
puts("ERROR: unable to load Ant, make sure Ant is installed, in your PATH and $ANT_HOME is defined properly")
puts("\nerror detail:\n#{$!}")
exit(1)
end
require 'jruby/jrubyc'
desc "compile Java classes"
task :compile do
ant.path 'id' => 'classpath' do
fileset 'dir' => "target/dependency/storm/default"
end
options = {
'srcdir' => "src",
'destdir' => "target/classes",
'classpathref' => 'classpath',
'debug' => "yes",
'includeantruntime' => "no",
'verbose' => false,
'listfiles' => true,
}
ant.javac(options)
end
desc "intall RedStorm"
task :install do
system("bundle exec redstorm install")
end
desc "create RedStorm topology jar"
task :jar do
system("bundle exec redstorm jar lib")
end
desc "initial setup"
task :setup => [:install, :compile, :jar] do
end
task :default => :setup
|
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical JavaScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
// 1.
var count1 = 0
console.log("LOOPING PERTAMA")
while(count1 < 20){
count1 += 2;
console.log(count1 + " - I love coding");
}
var count2 = 20
console.log("LOOPING KEDUA")
while(count2 > 0){
console.log(count2 + " - I will become a fullstack developer")
count2 -= 2
}
// 2.
console.log("LOOPING PERTAMA")
for(count3 = 1; count3 < 21; count3 ++){
console.log(count3 + " - I love coding");
}
console.log("LOOPING KEDUA")
for(count4 = 20; count4 > 0; count4 --){
console.log(count4 + " - I will become a full stack developer")
}
// 3.
for(count5 = 1; count5 < 101; count5 ++){
if(count5 % 2 == 0)
console.log("counter sekarang = " + count5 + " GENAP");
else
console.log("counter sekarang = " + count5 + " GANJIL");
}
for(count6 = 1; count6 < 100; count6 += 2){
if(count6 % 3 == 0)
console.log("counter sekarang = " + count6 + " KELIPATAN 3");
else
console.log("");
}
for(count7 = 1; count7 < 100; count7 += 5){
if(count7 % 3 == 0)
console.log("counter sekarang = " + count7 + " KELIPATAN 6");
else
console.log("");
}
for(count8 = 1; count8 < 100; count8 += 9){
if(count8 % 10 == 0)
console.log("counter sekarang = " + count8 + " KELIPATAN 10");
else
console.log("");
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
javascript
| 4 |
// 1.
var count1 = 0
console.log("LOOPING PERTAMA")
while(count1 < 20){
count1 += 2;
console.log(count1 + " - I love coding");
}
var count2 = 20
console.log("LOOPING KEDUA")
while(count2 > 0){
console.log(count2 + " - I will become a fullstack developer")
count2 -= 2
}
// 2.
console.log("LOOPING PERTAMA")
for(count3 = 1; count3 < 21; count3 ++){
console.log(count3 + " - I love coding");
}
console.log("LOOPING KEDUA")
for(count4 = 20; count4 > 0; count4 --){
console.log(count4 + " - I will become a full stack developer")
}
// 3.
for(count5 = 1; count5 < 101; count5 ++){
if(count5 % 2 == 0)
console.log("counter sekarang = " + count5 + " GENAP");
else
console.log("counter sekarang = " + count5 + " GANJIL");
}
for(count6 = 1; count6 < 100; count6 += 2){
if(count6 % 3 == 0)
console.log("counter sekarang = " + count6 + " KELIPATAN 3");
else
console.log("");
}
for(count7 = 1; count7 < 100; count7 += 5){
if(count7 % 3 == 0)
console.log("counter sekarang = " + count7 + " KELIPATAN 6");
else
console.log("");
}
for(count8 = 1; count8 < 100; count8 += 9){
if(count8 % 10 == 0)
console.log("counter sekarang = " + count8 + " KELIPATAN 10");
else
console.log("");
}
|
Below is an extract from a Go program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Go code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Go concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., goroutines, interfaces). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Go. It should be similar to a school exercise, a tutorial, or a Go course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Go. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package sitehash
import (
"net/url"
)
type Digest struct {
Registered bool
Hosted bool
Nameservers []string
Status string
Headers []string
}
func Fingerprint(url *url.URL) (d Digest, err error) {
d.Registered, err = isDomainRegistered(url.Hostname())
if err != nil {
return d, err
}
if !d.Registered {
// Domain isn't registered so nothing more we can do
return d, nil
}
d.Nameservers, err = getNameservers(url.Hostname())
if err != nil {
return d, err
}
d.Hosted, err = isDomainHosted(url.Hostname())
if err != nil {
return d, err
}
if d.Hosted {
// Domain is hosted somewhere so try to fetch the given URL
d.Status, d.Headers, err = getHeaders(url)
if err != nil {
return d, err
}
}
return d, nil
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
go
| 2 |
package sitehash
import (
"net/url"
)
type Digest struct {
Registered bool
Hosted bool
Nameservers []string
Status string
Headers []string
}
func Fingerprint(url *url.URL) (d Digest, err error) {
d.Registered, err = isDomainRegistered(url.Hostname())
if err != nil {
return d, err
}
if !d.Registered {
// Domain isn't registered so nothing more we can do
return d, nil
}
d.Nameservers, err = getNameservers(url.Hostname())
if err != nil {
return d, err
}
d.Hosted, err = isDomainHosted(url.Hostname())
if err != nil {
return d, err
}
if d.Hosted {
// Domain is hosted somewhere so try to fetch the given URL
d.Status, d.Headers, err = getHeaders(url)
if err != nil {
return d, err
}
}
return d, nil
}
|
Below is an extract from a TypeScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid TypeScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical TypeScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., generics, decorators). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching TypeScript. It should be similar to a school exercise, a tutorial, or a TypeScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching TypeScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
import axios from 'axios';
import { BASEURL } from '../../api'
import { FETCH_USER, SET_USER, CREATE_USER, SET_HASCREATEDUSER } from '../../user-types'
export const actions = {
async [FETCH_USER] ( { commit }: any, params: any) {
const res = await axios.get(`${BASEURL}AuthUser`, { params });
return commit(SET_USER, res.data);
},
async [CREATE_USER] ( { commit }: any, email: string) {
const res = await axios.post(`${BASEURL}AuthUser`, { email });
return commit(SET_HASCREATEDUSER, res.data);
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
typescript
| 2 |
import axios from 'axios';
import { BASEURL } from '../../api'
import { FETCH_USER, SET_USER, CREATE_USER, SET_HASCREATEDUSER } from '../../user-types'
export const actions = {
async [FETCH_USER] ( { commit }: any, params: any) {
const res = await axios.get(`${BASEURL}AuthUser`, { params });
return commit(SET_USER, res.data);
},
async [CREATE_USER] ( { commit }: any, email: string) {
const res = await axios.post(`${BASEURL}AuthUser`, { email });
return commit(SET_HASCREATEDUSER, res.data);
}
}
|
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical JavaScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
/* Copyright 2015-2016 Teeming Society. Licensed under the Apache License, Version 2.0 (the "License"); DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others.
You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing permissions and limitations under the License.*/
//Pure JS based composition
define.class('$server/composition', function($ui$, cadgrid, splitcontainer, screen, view, label, button, $widgets$, propviewer, colorpicker){
this.render = function(){ return [
screen({clearcolor:vec4('blue'),flexwrap:"nowrap", flexdirection:"row",bg:0}
,cadgrid({flexdirection:"column", bgcolor: "#303030",minorsize:5,majorsize:25, majorline:"#383838", minorline:"#323232" }
,splitcontainer({ flex: 1, direction:"horizontal"}
,splitcontainer({flex: 1, bg:0, direction:"vertical"}
,view({flexdirection:"column", flex:1, bgcolor:"#383838", margin:20, padding:4}
,view({flexdirection:"column", flex:1, bg:0, margin:0}
,label({margin:4,name:"thelabel", fontsize:14,bg:0, text:"this is a label with some example props"})
,propviewer({target:"thelabel", flex:1, overflow:"scroll"})
)
)
,view({flexdirection:"column", flex:1, bgcolor:"#383838", margin:20, padding:4}
,view({flexdirection:"column",flex:1, bg:0, margin:0}
,button({name:"thebutton", text:"this is a button with some example props"})
,propviewer({target:"thebutton", flex:1, overflow:"scroll"})
)
)
)
,splitcontainer({flexdirection:"row", flex: 1, bg:0, direction:"vertical"}
,view({flexdirection:"column", flex:1, bgcolor:"#3
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
javascript
| 2 |
/* Copyright 2015-2016 Teeming Society. Licensed under the Apache License, Version 2.0 (the "License"); DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others.
You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing permissions and limitations under the License.*/
//Pure JS based composition
define.class('$server/composition', function($ui$, cadgrid, splitcontainer, screen, view, label, button, $widgets$, propviewer, colorpicker){
this.render = function(){ return [
screen({clearcolor:vec4('blue'),flexwrap:"nowrap", flexdirection:"row",bg:0}
,cadgrid({flexdirection:"column", bgcolor: "#303030",minorsize:5,majorsize:25, majorline:"#383838", minorline:"#323232" }
,splitcontainer({ flex: 1, direction:"horizontal"}
,splitcontainer({flex: 1, bg:0, direction:"vertical"}
,view({flexdirection:"column", flex:1, bgcolor:"#383838", margin:20, padding:4}
,view({flexdirection:"column", flex:1, bg:0, margin:0}
,label({margin:4,name:"thelabel", fontsize:14,bg:0, text:"this is a label with some example props"})
,propviewer({target:"thelabel", flex:1, overflow:"scroll"})
)
)
,view({flexdirection:"column", flex:1, bgcolor:"#383838", margin:20, padding:4}
,view({flexdirection:"column",flex:1, bg:0, margin:0}
,button({name:"thebutton", text:"this is a button with some example props"})
,propviewer({target:"thebutton", flex:1, overflow:"scroll"})
)
)
)
,splitcontainer({flexdirection:"row", flex: 1, bg:0, direction:"vertical"}
,view({flexdirection:"column", flex:1, bgcolor:"#383838", margin:20, padding:4}
,view({flexdirection:"column", flex:1, bg:0, margin:0}
,cadgrid({majorline:"#383838", minorline:"#323232",bgcolor:"black", margin:4,name:"thecadgrid",height:10, fontsize:14,text:"this is a label with some example props"})
,propviewer({target:"thecadgrid",
flex:1, overflow:"scroll"
})
)
)
,view({flexdirection:"column", flex:1, bgcolor:"#383838", margin:20, padding:4}
,view({flexdirection:"column",flex:1, bg:0, margin:0}
,colorpicker({name:"thepicker", text:"this is a button with some example props"})
,propviewer({target:"thepicker", flex:1, overflow:"scroll"})
)
)
)
)
)
)
]}
})
|
Below is an extract from a C program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid C code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical C concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., kernel development and compiler design). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching C. It should be similar to a school exercise, a tutorial, or a C course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
#include "math.h"
#include <iostream>
double PStart(double Rs, double Rmu, double Tc);
double PNStart(double Rs, double Rmu, double Tc, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a );
double TimeEff(double t, int Type, double Lambda_1, double Lambda_2, double a );
double RSStart(double Rs, double Rmu, double Tc);
double RNStart(double Rs, double Rmu, double Tc, double RIBD, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a);
double REStart(double Rs, double Rmu, double Tc, double RIBD, double Eff_e);
double RSS(double Rs, double Rmu, double Tc);
double RSS_DYB(double Rs, double Rmu, double Tc);
double REN(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a );
double EffEN_DYB(double Rs, double Rmu, double Tc);
double RS(double Rs, double Rmu, double Tc);
double RE(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a );
double RN(double Rs, double Rmu, double Tc, double RIBD, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a );
double P_S_E(double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a);
double RSE(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a );
double RES(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a );
double RNS(double Rs, double Rmu, double Tc, double RIBD, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a );
double P_S_EN( double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a );
double RSEN(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, do
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
c
| 1 |
#include "math.h"
#include <iostream>
double PStart(double Rs, double Rmu, double Tc);
double PNStart(double Rs, double Rmu, double Tc, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a );
double TimeEff(double t, int Type, double Lambda_1, double Lambda_2, double a );
double RSStart(double Rs, double Rmu, double Tc);
double RNStart(double Rs, double Rmu, double Tc, double RIBD, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a);
double REStart(double Rs, double Rmu, double Tc, double RIBD, double Eff_e);
double RSS(double Rs, double Rmu, double Tc);
double RSS_DYB(double Rs, double Rmu, double Tc);
double REN(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a );
double EffEN_DYB(double Rs, double Rmu, double Tc);
double RS(double Rs, double Rmu, double Tc);
double RE(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a );
double RN(double Rs, double Rmu, double Tc, double RIBD, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a );
double P_S_E(double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a);
double RSE(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a );
double RES(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a );
double RNS(double Rs, double Rmu, double Tc, double RIBD, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a );
double P_S_EN( double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a );
double RSEN(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a);
double RSSS(double Rs, double Rmu, double Tc);
double RESS(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a );
double RNSS(double Rs, double Rmu, double Tc, double RIBD, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a );
double RS_E_S(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a );
double RS_N_S(double Rs, double Rmu, double Tc, double RIBD, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a );
double RE_N_S(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a );
Double_t Point_y[24]={0};
void AccPerRun_EH2_AD1()
{
Double_t WidthOfBin = 86164.00/24.00; // 1 sidereal day = 86164 seconds
Double_t StartTime = 1350096800.51364;//in unit of second,it stands for 2011-12-24 00:00:00, UTC 0 time;
Double_t EndTime = 1385769600;//in unit of second,it stands for 2012-07-28 00:00:00, UTC 0 time;
Int_t NumOfBin = (EndTime - StartTime)/WidthOfBin;
Double_t *NumOfAccInEachBin = new Double_t[NumOfBin];
memset(NumOfAccInEachBin,0.0,sizeof(NumOfAccInEachBin));
Double_t MultiEffT[8]={1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0};
Int_t AD_index = 2;//AD1
//Int_t Run; /*0*/
//Double_t Run,/*0*/ StartSec,/*2*/ StartNano,/*3*/ StopSec, /*4*/ StopNano, /*5*/ FullTime,/*6*/ Veto,/*7*/ NNet, /*24*/ NSgUp, /*28*/ NSgLow,/*29*/ NBVtx,/*64*/ NAeng; /*72*/
Double_t Variable[12]={0.0};
Int_t Position[12]={0,2,3,4,5,6,7,24,28,29,64,72};
Double_t LiveTime,Rs,Rmu,Tc,Acc,E_Acc;
Tc=200*1e-6;
Double_t TotalAcc = 0.0;
std::string s;
ifstream is("../../Input/P14A_Info/eff_info_EH2.txt");
while(!is.eof())
{
int startN[75]={0},endN[75]={0},pos=0,num=0;
bool InNumber = false;
Double_t Time1,Time2,AccRatio;
Int_t BinID1,BinID2;
getline(is,s);
//cout<<"0";
while(num<75)
{
//cout<<"1";
int n = s.find(char(32),pos);
if(n>pos)
{
if((n==(pos+1))&&(!InNumber)){
startN[num]=pos;
endN[num]=pos;
num ++;
}
else if((n>(pos+1))&&(!InNumber))
{
InNumber = true;
startN[num]=pos;
}
else if((n==(pos+1))&&(InNumber))
{
endN[num]=pos;
num ++;
InNumber = false;
}
else {}
}
pos ++;
}
for(int i=0;i<12;i++)
{
stringstream ss;
string subs;
subs = s.substr(startN[Position[i]],endN[Position[i]]-startN[Position[i]]+1);
ss<<subs;
ss>>Variable[i];
}
//0 1 2 3 4 5 6 7 8 9 10 11
//Run,/*0*/ StartSec,/*2*/ StartNano,/*3*/ StopSec, /*4*/ StopNano, /*5*/ FullTime,/*6*/ Veto,/*7*/ NNet, /*24*/ NSgUp, /*28*/ NSgLow,/*29*/ NBVtx,/*64*/ NAeng; /*72*/
LiveTime = Variable[5] - Variable[6];
Rs = 0.5*(Variable[8]+Variable[9])/LiveTime;
Rmu = Variable[7]/Variable[5];
Acc = (Variable[5])*RSS_DYB(Rs,Rmu,Tc)*Variable[11]/Variable[10];
if(Variable[11]>0)
{
E_Acc = Acc * sqrt(1.0/Variable[11] - 1.0/Variable[10] + pow((2.0/Rs-2*Tc)*Rs/sqrt(Variable[8]+Variable[9]),2.0));
}
else
{
E_Acc = 0.0;
}
FILE* m_outfile = fopen("Acc_EH2_AD1.txt", "a");
//[Run][StartSec][StopSec][StopNano][FullTime][Veto][LiveTime][Acc]
fprintf(m_outfile,
"%15.0f %15.0f %15.0f %15.0f %15.0f %15.5f %15.5f %15.5f %15.5f %15.5f ",
Variable[0],Variable[1],Variable[2],Variable[3],Variable[4],Variable[5],Variable[6],LiveTime,Acc,E_Acc
);
fprintf(m_outfile,"\n");
fclose(m_outfile);
}}
double PStart(double Rs, double Rmu, double Tc)
{
/// Case a
double Pa = Rmu / ( Rs + Rmu ) * ( 1 - exp( -(Rs + Rmu) * Tc ) );
/// Case b
double Pb = exp( -Rs * Tc ) * exp( -Rmu * Tc );
/// Case c+d
double Pcd =
Rs*exp(-Rmu*Tc)*1/(Rs+Rmu)*(1-exp(-(Rs+Rmu)*Tc))
- Rs*exp(-Rmu*Tc)*1/(2*Rs+Rmu)*(1-exp(-(2*Rs+Rmu)*Tc));
double Ptot = Pa + Pb + Pcd;
return Ptot;
}
double PNStart(double Rs, double Rmu, double Tc, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a )
{
double ret(0);
if (Type==1){
/// Case a
double Pna = Eff_n * Rmu * ( (1- Eff_ne) / ( Rmu + Rs ) *( 1 - exp( -( Rmu + Rs) *Tc)) + Eff_ne / ( Rs + Rmu + Lambda_1) * ( 1 - exp( -(Rmu + Rs + Lambda_1 ) * Tc)) );
/// Case b
double Pnb = Eff_n * exp( - (Rmu + Rs) * Tc ) * ( 1 - Eff_ne + Eff_ne * exp(-Lambda_1 * Tc)) ;
/// Case c
double Pnc = PStart( Rs, Rmu, Tc) * Eff_n * ( (1 - Eff_ne) * Rs / (Rs + Rmu) * exp(-Rmu * Tc) * ((1 - exp(-Rs * Tc) ) - Rs / (Rmu + 2* Rs) * (1 - exp(-(Rmu + 2 * Rs ) * Tc)) )
+ Eff_ne * (Rmu / (Lambda_1 + 2 * Rmu) * exp( -(Lambda_1 + Rmu) * Tc) + (Lambda_1 + Rmu) / (Lambda_1 + 2*Rmu) * exp( -2 *(Lambda_1 + Rmu) * Tc) ) * Rs / (Rmu + Rs + Lambda_1 ) * ( (1- exp(- Rs * Tc)) - Rs / (Rmu + 2 * Rs + Lambda_1) * (1 -exp (-(Rmu + 2 * Rs + Lambda_1 ) * Tc) )));
/// Case d
double Pnd = PStart( Rs, Rmu, Tc) * Eff_n * Eff_ne * Lambda_1 / (Lambda_1 + Rmu) * exp( -(Lambda_1 + Rmu) * Tc) * (1 - exp( -Rs * Tc ) - Rs / (Lambda_1 + Rs + Rmu) * ( 1 - exp( -(Lambda_1 + Rmu + Rs) * Tc)) )
+ PStart( Rs, Rmu, Tc) * Eff_n * Eff_ne * Rs / (Rmu + Rs) *(Lambda_1 / (Lambda_1 + Rs) * (1 - exp(-(Rs + Lambda_1 ) * Tc) ) - Lambda_1 / (Lambda_1 + Rmu + 2* Rs) * (1 - exp(-(Rmu + 2 * Rs + Lambda_1 ) * Tc) ));
double Pntot = Pna + Pnb + Pnc + Pnd;
ret = Pntot;
}
return ret;
}
double TimeEff(double t, int Type, double Lambda_1, double Lambda_2, double a )
{
double ret;
if (Type == 1) {
double TimeEff = 1 - exp( -Lambda_1 * t);
ret = TimeEff;
}
if (Type == 2) {
double TimeEff = 1 - ( 1 + a) * exp( -Lambda_1 * t) + a * exp( -Lambda_2 * t);
ret = TimeEff;
}
return ret;
}
double RSStart(double Rs, double Rmu, double Tc)
{
double RSStart = Rs * PStart( Rs, Rmu, Tc);
return RSStart;
}
double RNStart(double Rs, double Rmu, double Tc, double RIBD, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a)
{
double RNStart = RIBD * PNStart( Rs, Rmu, Tc, Eff_n, Eff_ne, Type, Lambda_1,Lambda_2, a);
return RNStart;
}
double REStart(double Rs, double Rmu, double Tc, double RIBD, double Eff_e)
{
double REStart = RIBD * Eff_e * PStart( Rs, Rmu, Tc);
return REStart;
}
double RSS(double Rs, double Rmu, double Tc)
{
double RSS = RSStart( Rs, Rmu, Tc) * ( Rs*Tc *exp(-Rs*Tc) );
return RSS;
}
/* Remove 1 us for the length of the realistic dayabay readout window */
double RSS_DYB(double Rs, double Rmu, double Tc)
{
double RSS = RSStart( Rs, Rmu, Tc ) * Rs * (Tc-1e-6) * exp( -Rs * (Tc-1e-6) );
return RSS;
}
double REN(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a )
{
double REN = REStart( Rs, Rmu, Tc, RIBD, Eff_e) * Eff_en * TimeEff( Tc, Type, Lambda_1,Lambda_2, a ) *exp(-Rs*Tc) ;
return REN;
}
/* Remove 1 us for the length of the realistic dayabay readout window */
double EffEN_DYB(double Rs, double Rmu, double Tc)
{
/// REN with RIBD=1, Eff_e=1, Eff_en=1, TimeEff is separated and applied outside.
double REN = REStart( Rs, Rmu, Tc, 1, 1) * exp( -Rs*(Tc-1e-6));
return REN;
}
double RS(double Rs, double Rmu, double Tc)
{
double RS = RSStart( Rs, Rmu, Tc) * exp( -Rs * Tc ) ;
return RS;
}
double RE(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a )
{
double RE = REStart( Rs, Rmu, Tc, RIBD, Eff_e) * exp( -Rs*Tc ) *(1-Eff_en * TimeEff(Tc,Type,Lambda_1,Lambda_2,a));
return RE;
}
double RN(double Rs, double Rmu, double Tc, double RIBD, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a )
{
double RN = RNStart( Rs, Rmu, Tc, RIBD, Eff_n, Eff_ne, Type,Lambda_1,Lambda_2, a) * exp( -Rs*Tc ) ;
return RN;
}
double P_S_E(double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a)
{
double ret;
if (Type==1){
double P_S_E = Eff_e * ( 1 - Eff_en) * (1 - exp(- RIBD * Tc)) + Eff_e * Eff_en * RIBD / ( Lambda_1 - RIBD) * ( exp(-RIBD * Tc) - exp( -Lambda_1 * Tc) );
ret = P_S_E;
}
/* if Type==2{
double P_S_E =RIBD * Eff_e (Tc - Eff_en(T-(1+a) / Lambda_1 * (1 - exp(-Lambda_1 * Tc)) + a / Lambda_2 * ( 1 - exp( -Lambda_2 * Tc)) )) ;
} */
return ret;
}
double RSE(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a )
{
double RSE = RSStart( Rs, Rmu, Tc) * P_S_E(Tc, RIBD, Eff_e, Eff_en, Type, Lambda_1, Lambda_2,a) * exp( -Rs*Tc );
return RSE;
}
double RSN(double Rs, double Rmu, double Tc, double RIBD, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a )
{
/// Case a
double RSNa = Rs * Eff_n * RIBD * Rmu * exp(-Rs * Tc ) /( RIBD + Lambda_1) * (1-exp(-( RIBD + Lambda_1) * Tc)) * ((1-Eff_ne) /( Rmu + Rs ) * (1-exp(-( Rmu + Rs) * Tc)) + Eff_ne / (Rmu + Rs + Lambda_1) * (1-exp(-( Rmu + Rs + Lambda_1) * Tc)));
/// Case b
double RSNb = Rs * Eff_n * exp(-Rmu * Tc) * exp(-2* Rs * Tc) * (1-Eff_ne + Eff_ne * exp(-Lambda_1 * Tc)) * RIBD /( Lambda_1 + RIBD) * (1-exp(-( Lambda_1 + RIBD) * Tc));
/// Case c
double RSNc =
Rs * Eff_n * Eff_ne * RIBD * Rs * exp(-(Rmu + Rs) * Tc) / (Lambda_1 + RIBD) / (2* Rs + Rmu) * (1-exp(-(Lambda_1 + RIBD) * Tc)) * ((1-exp(-Lambda_1 * Tc)) - Lambda_1 / (2* Rs + Rmu + Lambda_1) * (1-exp(-(2* Rs + Rmu + Lambda_1) * Tc )));
double RSN = RSNa + RSNb + RSNc;
return RSN;
}
double RES(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a )
{
double RES = REStart( Rs, Rmu, Tc, RIBD, Eff_e) * ( Rs*Tc * exp( -Rs*Tc ) ) *(1-Eff_en * TimeEff(Tc,Type,Lambda_1,Lambda_2,a));
return RES;
}
double RNS(double Rs, double Rmu, double Tc, double RIBD, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a )
{
double RNS = RNStart( Rs, Rmu, Tc, RIBD, Eff_n, Eff_ne, Type,Lambda_1,Lambda_2,a ) * (Rs*Tc *exp( -Rs*Tc )) ;
return RNS;
}
double P_S_EN( double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a )
{
double ret;
if (Type==1){
double P_S_EN = Eff_e * Eff_en * ( 1 - exp(-RIBD * Tc )- RIBD / (Lambda_1 + RIBD) * ( exp( -RIBD * Tc ) - exp( -Lambda_1 * Tc)) ) ;
ret = P_S_EN;
}
/* if (Type==2){
double P_S_EN =RIBD * Eff_e * Eff_en * (T-(1+a) / Lambda_1 * (1 - exp(-Lambda_1 * Tc)) + a / Lambda_2 * ( 1 - exp( -Lambda_2 * Tc)) ) ;
return P_S_EN;
} */
return ret;
}
double RSEN(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a)
{
double RSEN = RSStart( Rs, Rmu, Tc) * P_S_EN(Tc, RIBD, Eff_e, Eff_en, Type, Lambda_1,Lambda_2, a) * exp( -Rs*Tc );
return RSEN;
}
double RSSS(double Rs, double Rmu, double Tc)
{
double RSSS = RSStart( Rs, Rmu, Tc) * ( Rs*Tc * Rs * Tc /2 *exp(-Rs*Tc) );
return RSSS;
}
double RESS(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a )
{
double RESS = REStart( Rs, Rmu, Tc, RIBD, Eff_e) * ( Rs*Tc* Rs * Tc /2 * exp( -Rs*Tc ) ) *(1-Eff_en * TimeEff(Tc,Type,Lambda_1,Lambda_2,a));
return RESS;
}
double RNSS(double Rs, double Rmu, double Tc, double RIBD, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a )
{
double RNSS = RNStart( Rs, Rmu, Tc, RIBD, Eff_n, Eff_ne, Type,Lambda_1,Lambda_2,a ) * (Rs*Tc* Rs * Tc /2 *exp( -Rs*Tc )) ;
return RNSS;
}
double RS_E_S(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a )
{
//RS_E_S=RSES+RSSE;
double RS_E_S = RSStart( Rs, Rmu, Tc) * P_S_E(Tc, RIBD, Eff_e, Eff_en, Type, Lambda_1,Lambda_2, a) * (Rs*Tc* exp( -Rs*Tc));
return RS_E_S;
}
double RS_N_S(double Rs, double Rmu, double Tc, double RIBD, double Eff_n, double Eff_ne, int Type, double Lambda_1, double Lambda_2, double a )
{
//RS_N_S=RSNS+RSSN;
double RS_N_S = RSN(Rs, Rmu, Tc, RIBD, Eff_n, Eff_ne, Type, Lambda_1,Lambda_2, a) * (Rs*Tc);
return RS_N_S;
}
double RE_N_S(double Rs, double Rmu, double Tc, double RIBD, double Eff_e, double Eff_en, int Type, double Lambda_1, double Lambda_2, double a )
{
//RE_N_S=RENS+RESN;
double RE_N_S = REStart( Rs, Rmu, Tc, RIBD, Eff_e) * Eff_en * TimeEff( Tc, Type, Lambda_1,Lambda_2, a ) * (Rs*Tc* exp( -Rs*Tc));
return RE_N_S;
}
double RsExtra(double Rs, double Rmu, double Tc)
{//The extra Rs on live time;
double RsExtra = Rs * (Tc * exp(- Rmu * Tc ) - (1/Rmu -Tc ) * (1-exp(- Rmu * Tc ) ) ) * RSStart( Rs, Rmu, Tc);
return RsExtra;
}
double RsLT(double Rs, double Rmu, double Tc)
{//Rs on live time;
double RsLT =(1+ Tc * Rs ) * RSStart( Rs, Rmu, Tc);
return RsLT;
}
|
Below is an extract from a shell script. Evaluate whether it has a high educational value and could help teach shell scripting. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the script contains valid shell commands, even if it's not educational, like simple system calls or basic file operations.
- Add another point if the script addresses practical shell scripting concepts (e.g., variables, conditionals), even if it lacks comments.
- Award a third point if the script is suitable for educational use and introduces key concepts in shell scripting, even if the topic is somewhat advanced (e.g., functions, process management). The script should be well-structured and contain some comments.
- Give a fourth point if the script is self-contained and highly relevant to teaching shell scripting. It should be similar to a tutorial example or a shell scripting course section, demonstrating good practices in script organization.
- Grant a fifth point if the script is outstanding in its educational value and is perfectly suited for teaching shell scripting. It should be well-written, easy to understand, and contain step-by-step explanations in comments.
The extract:
#!/bin/bash
bash num31.sh | echo "Все вместе $*"
bash num31.sh | echo "Поотдельности $@"
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
shell
| 1 |
#!/bin/bash
bash num31.sh | echo "Все вместе $*"
bash num31.sh | echo "Поотдельности $@"
|
Below is an extract from a Swift program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Swift code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Swift concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., protocols, extensions). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Swift. It should be similar to a school exercise, a tutorial, or a Swift course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Swift. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
import UIKit
var Ahmed : Set = ["Hail", "Riyadh", "Dubai"]
var Faris : Set = ["Riyadh", "jizan", "A<NAME>", "Hail"]
var allCityesVisiteAhmed = Ahmed.union(Faris)
//print(VisitesAhmed)
print("all ahmed visites cityes ")
for allCityesVisiteAhmed in allCityesVisiteAhmed {
print(allCityesVisiteAhmed)
}
var VisitesBoth = Ahmed.intersection(Faris)
print("all cityes visites Both")
for VisitesFaris in VisitesBoth {
print(VisitesFaris)
}
var allFarisVisites = Faris.subtracting(Ahmed)
print("all Faris Visited city but ahmed didn't ")
for Visit in allFarisVisites {
print(Visit)
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
swift
| 3 |
import UIKit
var Ahmed : Set = ["Hail", "Riyadh", "Dubai"]
var Faris : Set = ["Riyadh", "jizan", "A<NAME>", "Hail"]
var allCityesVisiteAhmed = Ahmed.union(Faris)
//print(VisitesAhmed)
print("all ahmed visites cityes ")
for allCityesVisiteAhmed in allCityesVisiteAhmed {
print(allCityesVisiteAhmed)
}
var VisitesBoth = Ahmed.intersection(Faris)
print("all cityes visites Both")
for VisitesFaris in VisitesBoth {
print(VisitesFaris)
}
var allFarisVisites = Faris.subtracting(Ahmed)
print("all Faris Visited city but ahmed didn't ")
for Visit in allFarisVisites {
print(Visit)
}
|
Below is an extract from an HTML document. Evaluate whether it has a high educational value and could help teach web development. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the document contains valid HTML markup, even if it's not educational, like boilerplate code or standard tags.
- Add another point if the document addresses practical HTML concepts and uses semantic elements appropriately.
- Award a third point if the document is suitable for educational use and introduces key web concepts, even if the topic is somewhat advanced (e.g., forms, metadata). The code should be well-structured and use clear, descriptive naming.
- Give a fourth point if the document is self-contained and highly relevant to teaching HTML. It should be similar to a school exercise, a tutorial, or an HTML course section for early learners.
- Grant a fifth point if the document is outstanding in its educational value and is perfectly suited for teaching HTML to beginners. It should be well-organized, easy to understand, and ideally include some explanatory comments or demonstrate best practices in HTML structure.
The extract:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="/allregs/css/uswds.min.css">
<link rel="stylesheet" href="/allregs/css/style.css">
</head>
<body>
<header>
<h2 class="title">
<a href="/allregs/index.html">Code of Federal Regulations (alpha)</a>
</h2>
</header>
<div class="usa-grid">
<div class="usa-width-one-whole">
<h3>
<a href="/allregs/index.html">CFR</a><span> / </span>
<a href="/allregs/html/titles/title45.html">
Title 45
</a><span> / </span>
<a href="/allregs/html/parts/45CFR702.html">Part 702
</a><span> / <span>
Sec. 702.56 Records.
</h3>
<p class="depth1"><em>(a)</em> The Commission shall promptly make available to the public in an easily accessible place at Commission headquarters the following materials:</p><p class="depth2"><em>(1)</em> A copy of the certification by the General Counsel required by Sec. 702.54(e)(1).</p><p class="depth2"><em>(2)</em> A copy of all recorded votes required to be taken by these rules.</p><p class="depth2"><em>(3)</em> A copy of all announcements published in the Federal Register pursuant to this subpart.</p><p class="depth2"><em>(4)</em> Transcripts, electronic recordings, and minutes of closed meetings determined not to contain items of discussion or information that may be withheld under Sec. 702.53. Copies of such material will be furnished to any person at the actual cost of transcription or duplication.</p><p class="depth1"><em>(b)(1)</em> Requests to review or obtain copies of records compiled under this Act, other than transcripts, electronic recordings, or minutes of a closed meeting, wi
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
html
| 2 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="/allregs/css/uswds.min.css">
<link rel="stylesheet" href="/allregs/css/style.css">
</head>
<body>
<header>
<h2 class="title">
<a href="/allregs/index.html">Code of Federal Regulations (alpha)</a>
</h2>
</header>
<div class="usa-grid">
<div class="usa-width-one-whole">
<h3>
<a href="/allregs/index.html">CFR</a><span> / </span>
<a href="/allregs/html/titles/title45.html">
Title 45
</a><span> / </span>
<a href="/allregs/html/parts/45CFR702.html">Part 702
</a><span> / <span>
Sec. 702.56 Records.
</h3>
<p class="depth1"><em>(a)</em> The Commission shall promptly make available to the public in an easily accessible place at Commission headquarters the following materials:</p><p class="depth2"><em>(1)</em> A copy of the certification by the General Counsel required by Sec. 702.54(e)(1).</p><p class="depth2"><em>(2)</em> A copy of all recorded votes required to be taken by these rules.</p><p class="depth2"><em>(3)</em> A copy of all announcements published in the Federal Register pursuant to this subpart.</p><p class="depth2"><em>(4)</em> Transcripts, electronic recordings, and minutes of closed meetings determined not to contain items of discussion or information that may be withheld under Sec. 702.53. Copies of such material will be furnished to any person at the actual cost of transcription or duplication.</p><p class="depth1"><em>(b)(1)</em> Requests to review or obtain copies of records compiled under this Act, other than transcripts, electronic recordings, or minutes of a closed meeting, will be processed under the Freedom of Information Act and, where applicable, the Privacy Act regulations of the Commission (parts 704 and 705, respectively, of this title). Nothing in this subpart expands or limits the present rights of any person under the rules in this part with respect to such requests.</p><p class="depth2"><em>(1)</em> Requests to review or obtain copies of records compiled under this Act, other than transcripts, electronic recordings, or minutes of a closed meeting, will be processed under the Freedom of Information Act and, where applicable, the Privacy Act regulations of the Commission (parts 704 and 705, respectively, of this title). Nothing in this subpart expands or limits the present rights of any person under the rules in this part with respect to such requests.</p><p class="depth2"><em>(2)</em> Requests to review or obtain copies of transcripts, electronic recordings, or minutes of a closed meeting maintained under Sec. 702.54(e) and not released under paragraph (a)(4) of this section shall be directed to the Staff Director who shall respond to such requests within ten (10) working days.</p><p class="depth1"><em>(c)</em> The Commission shall maintain a complete verbatim copy of the transcript, a complete copy of minutes, or a complete electronic recording of each meeting, or portion of a meeting, closed to the public, for a period of two years after such meeting or until one year after the conclusion of any agency proceeding with respect to which the meeting or portion was held, whichever occurs later.</p>
</div>
</div>
<footer class="usa-footer usa-footer-slim" role="contentinfo">
<div class="usa-grid usa-footer-return-to-top">
<a href="#">Return to top</a>
</div>
<div class="usa-footer-primary-section">
<div class="usa-grid-full">
<h5>Built with ❤.
Code available <a href="https://github.com/anthonygarvan/allregs">on Github.
</a></h5>
<h5>All regulations are from the 2015 Annual Edition.
This is a technical demonstration not intended for serious use.</h5
</div>
</div>
</footer>
</body>
</html>
|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package org.odlabs.wiquery.ui.accordion;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.odlabs.wiquery.tester.WiQueryTestCase;
import org.odlabs.wiquery.ui.themes.UiIcon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AccordionIconTestCase extends WiQueryTestCase
{
protected static final Logger log = LoggerFactory.getLogger(AccordionIconTestCase.class);
@Test
public void testGetJavaScriptOption()
{
AccordionIcon accordionIcon = new AccordionIcon("classA", "classB");
// Int param
String expectedJavascript = "{'header': 'classA', 'activeHeader': 'classB'}";
String generatedJavascript = accordionIcon.getJavascriptOption().toString();
log.info(expectedJavascript);
log.info(generatedJavascript);
assertEquals(generatedJavascript, expectedJavascript);
accordionIcon = new AccordionIcon(false);
expectedJavascript = "false";
generatedJavascript = accordionIcon.getJavascriptOption().toString();
log.info(expectedJavascript);
log.info(generatedJavascript);
assertEquals(generatedJavascript, expectedJavascript);
accordionIcon = new AccordionIcon(UiIcon.ARROW_1_EAST, UiIcon.ARROW_1_NORTH);
expectedJavascript =
"{'header': '" + UiIcon.ARROW_1_EAST.getCssClass() + "', 'activeHeader': '"
+ UiIcon.ARROW_1_NORTH.getCssClass() + "'}";
generatedJavascript = accordionIcon.getJavascriptOption().toString();
log.info(expectedJavascript);
log.info(generatedJavascript);
assertEquals(generatedJavascript, expectedJavascript);
}
@Override
protected Logger getLog()
{
return log;
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
java
| 2 |
package org.odlabs.wiquery.ui.accordion;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.odlabs.wiquery.tester.WiQueryTestCase;
import org.odlabs.wiquery.ui.themes.UiIcon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AccordionIconTestCase extends WiQueryTestCase
{
protected static final Logger log = LoggerFactory.getLogger(AccordionIconTestCase.class);
@Test
public void testGetJavaScriptOption()
{
AccordionIcon accordionIcon = new AccordionIcon("classA", "classB");
// Int param
String expectedJavascript = "{'header': 'classA', 'activeHeader': 'classB'}";
String generatedJavascript = accordionIcon.getJavascriptOption().toString();
log.info(expectedJavascript);
log.info(generatedJavascript);
assertEquals(generatedJavascript, expectedJavascript);
accordionIcon = new AccordionIcon(false);
expectedJavascript = "false";
generatedJavascript = accordionIcon.getJavascriptOption().toString();
log.info(expectedJavascript);
log.info(generatedJavascript);
assertEquals(generatedJavascript, expectedJavascript);
accordionIcon = new AccordionIcon(UiIcon.ARROW_1_EAST, UiIcon.ARROW_1_NORTH);
expectedJavascript =
"{'header': '" + UiIcon.ARROW_1_EAST.getCssClass() + "', 'activeHeader': '"
+ UiIcon.ARROW_1_NORTH.getCssClass() + "'}";
generatedJavascript = accordionIcon.getJavascriptOption().toString();
log.info(expectedJavascript);
log.info(generatedJavascript);
assertEquals(generatedJavascript, expectedJavascript);
}
@Override
protected Logger getLog()
{
return log;
}
}
|
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content.
- Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse.
- Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow.
- Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson.
- Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes.
The extract:
### 本次版本更新内容
* 2018/02/09
* 本次版本号:"version": "0.0.1"
内容:
- 有赞巧口萌宠账号绑定微信Web页面发布
### 历史版本更新内容
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
markdown
| 2 |
### 本次版本更新内容
* 2018/02/09
* 本次版本号:"version": "0.0.1"
内容:
- 有赞巧口萌宠账号绑定微信Web页面发布
### 历史版本更新内容
|
Below is an extract from a Go program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Go code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Go concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., goroutines, interfaces). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Go. It should be similar to a school exercise, a tutorial, or a Go course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Go. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package treesandgraphs
import (
"container/list"
"fmt"
"strings"
"testing"
)
func TestTree(t *testing.T) {
tree := createTree(1, 2, 3, 4, 5, 6, 7, 8, 9)
expected := `1
2 3
4 5 6 7
8 9
`
if tree.String() != expected {
t.Errorf("Tree creation issue got %v expected %v", tree.String(), expected)
}
}
func TestTreeCreateNodes(t *testing.T) {
values := []int{5, 2, 1, 9, 3, 10}
nodes := createNodes(values...)
if len(values) != len(nodes) {
t.Errorf("createNodes(%v) failure got length %v expected length %v", values, len(nodes), len(values))
}
for i, node := range nodes {
if values[i] != node.value {
t.Errorf("createNodes(%v) failure on index %v got %v expected %v", values, i, node.value, values[i])
}
}
}
func TestTreeBuildTree(t *testing.T) {
nodes := []*node{&node{nil, nil, 4}, &node{nil, nil, 8}, &node{nil, nil, 100}, &node{nil, nil, 101}}
root := buildTree(nodes)
if root.value != 4 {
t.Errorf("buildTree error for root node expected %v got %v", 4, root.value)
}
if root.left.value != 8 {
t.Errorf("buildTree error for left node expected %v got %v", 8, root.left.value)
}
if root.right.value != 100 {
t.Errorf("buildTree error for right node expected %v got %v", 100, root.right.value)
}
if root.left.left.value != 101 {
t.Errorf("buildTree error for left.left node expected %v got %v", 101, root.left.left.value)
}
}
func listString(l *list.List) string {
b := strings.Builder{}
e := l.Front()
for e != nil {
b.WriteString(fmt.Sprintf("%v ", e.Value))
e = e.Next()
}
return b.String()
}
func TestListString(t *testing.T) {
l := list.New()
l.PushBack(1)
l.PushBack(2)
l.PushBack(3)
if listString(l) != "1 2 3 " {
t.Errorf("listString([1, 2, 3]) failed got %v expected %v", listString(l), "1 2 3 ")
}
}
func TestGetListForEachLevelOfTree(t *testing.T) {
bst := buildBalancedBST([]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
rows := getListsForRows(bst)
if len(rows) != 4 {
t.Errorf("getListsForRows(bst0-9) failed got len %v wanted %
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
go
| 3 |
package treesandgraphs
import (
"container/list"
"fmt"
"strings"
"testing"
)
func TestTree(t *testing.T) {
tree := createTree(1, 2, 3, 4, 5, 6, 7, 8, 9)
expected := `1
2 3
4 5 6 7
8 9
`
if tree.String() != expected {
t.Errorf("Tree creation issue got %v expected %v", tree.String(), expected)
}
}
func TestTreeCreateNodes(t *testing.T) {
values := []int{5, 2, 1, 9, 3, 10}
nodes := createNodes(values...)
if len(values) != len(nodes) {
t.Errorf("createNodes(%v) failure got length %v expected length %v", values, len(nodes), len(values))
}
for i, node := range nodes {
if values[i] != node.value {
t.Errorf("createNodes(%v) failure on index %v got %v expected %v", values, i, node.value, values[i])
}
}
}
func TestTreeBuildTree(t *testing.T) {
nodes := []*node{&node{nil, nil, 4}, &node{nil, nil, 8}, &node{nil, nil, 100}, &node{nil, nil, 101}}
root := buildTree(nodes)
if root.value != 4 {
t.Errorf("buildTree error for root node expected %v got %v", 4, root.value)
}
if root.left.value != 8 {
t.Errorf("buildTree error for left node expected %v got %v", 8, root.left.value)
}
if root.right.value != 100 {
t.Errorf("buildTree error for right node expected %v got %v", 100, root.right.value)
}
if root.left.left.value != 101 {
t.Errorf("buildTree error for left.left node expected %v got %v", 101, root.left.left.value)
}
}
func listString(l *list.List) string {
b := strings.Builder{}
e := l.Front()
for e != nil {
b.WriteString(fmt.Sprintf("%v ", e.Value))
e = e.Next()
}
return b.String()
}
func TestListString(t *testing.T) {
l := list.New()
l.PushBack(1)
l.PushBack(2)
l.PushBack(3)
if listString(l) != "1 2 3 " {
t.Errorf("listString([1, 2, 3]) failed got %v expected %v", listString(l), "1 2 3 ")
}
}
func TestGetListForEachLevelOfTree(t *testing.T) {
bst := buildBalancedBST([]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
rows := getListsForRows(bst)
if len(rows) != 4 {
t.Errorf("getListsForRows(bst0-9) failed got len %v wanted %v", len(rows), 4)
}
expectedRows := [][]int{[]int{5}, []int{2, 8}, []int{1, 4, 7, 9}, []int{0, 3, 6}}
for i, row := range expectedRows {
got := rows[i]
e := got.Front()
for j, v := range row {
if v != e.Value {
t.Errorf("getListsForRows error for row %v index %v got %v wanted %v", i, j, e.Value, v)
}
e = e.Next()
}
if e != nil {
t.Errorf("getListsForRows error expected fewer nodes in line %v got at least %v", i, len(row)+1)
}
}
}
func TestTreeIsBalanced(t *testing.T) {
unbalanced := newUnbalancedTree()
_, unbalancedIsBalanced := unbalanced.isBalanced()
if unbalancedIsBalanced {
t.Errorf("Unbalanced tree reported balanced")
}
balanced := buildBalancedBST([]int{1, 2, 3, 4, 5, 6, 7})
_, balancedIsBalanced := balanced.isBalanced()
if balancedIsBalanced == false {
t.Errorf("Balanced tree reported not balanced")
}
}
func TestIsBST(t *testing.T) {
nonBST := createTree(1, 2, 3, 4, 5, 6, 7, 8, 9)
if nonBST.isBST() {
t.Errorf("nonBST shows as BST")
}
BST := buildBalancedBST([]int{1, 2, 3, 4, 5, 6, 7, 8, 9})
if !BST.isBST() {
t.Errorf("BST shows as nonBST")
}
}
func TestPrintTree(t *testing.T) {
tree := buildBalancedBST([]int{1, 2, 3, 4, 5, 6, 7, 8, 9})
pre := tree.printTreePreOrder()
expectedPre := "532148769"
if pre != expectedPre {
t.Errorf("Pre order traversal failure got %v expected %v", pre, expectedPre)
}
post := tree.printTreePostOrder()
expectedPost := "124367985"
if post != expectedPost {
t.Errorf("Post order traversal failure got %v expected %v", post, expectedPost)
}
inOrder := tree.printTreeInOrder()
expected := "123456789"
if inOrder != expected {
t.Errorf("In order traversal failure got %v expected %v", inOrder, expected)
}
}
func TestFindLowestCommonAncestorOfBinaryTree(t *testing.T) {
tree := createTree(-2, -1, 0, 3, 4, 8)
res := tree.findLowestCommonAncestor(8, 4)
t.Errorf("findLowestCommonAncestor(%v, %v) returned %v", 8, 4, res)
}
|
Below is an extract of SQL code. Evaluate whether it has a high educational value and could help teach SQL and database concepts. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the code contains valid SQL syntax, even if it's just basic queries or simple table operations.
- Add another point if the code addresses practical SQL concepts (e.g., JOINs, subqueries), even if it lacks comments.
- Award a third point if the code is suitable for educational use and introduces key concepts in SQL and database management, even if the topic is somewhat advanced (e.g., indexes, transactions). The code should be well-structured and contain some comments.
- Give a fourth point if the code is self-contained and highly relevant to teaching SQL. It should be similar to a database course exercise, demonstrating good practices in query writing and database design.
- Grant a fifth point if the code is outstanding in its educational value and is perfectly suited for teaching SQL and database concepts. It should be well-written, easy to understand, and contain explanatory comments that clarify the purpose and impact of each part of the code.
The extract:
CREATE TABLE IF NOT EXISTS "warehouse" (
"w_id" int PRIMARY KEY,
"w_name" varchar(10),
"w_street_1" varchar(20),
"w_street_2" varchar(20),
"w_city" varchar(20),
"w_state" char(2),
"w_zip" char(9),
"w_tax" decimal(4,4),
"w_ytd" decimal(12,2)
);
CREATE TABLE IF NOT EXISTS "district" (
"d_w_id" int,
"d_id" int,
"d_name" varchar(10),
"d_street_1" varchar(20),
"d_street_2" varchar(20),
"d_city" varchar(20),
"d_state" char(2),
"d_zip" char(9),
"d_tax" decimal(4,4),
"d_ytd" decimal(12,2),
"d_next_o_id" int,
PRIMARY KEY ("d_w_id", "d_id")
);
CREATE TABLE IF NOT EXISTS "customer" (
"c_w_id" int,
"c_d_id" int,
"c_id" int,
"c_first" varchar(16),
"c_middle" char(2),
"c_last" varchar(16),
"c_street_1" varchar(20),
"c_street_2" varchar(20),
"c_city" varchar(20),
"c_state" char(2),
"c_zip" char(9),
"c_phone" char(16),
"c_since" timestamp,
"c_credit" char(2),
"c_credit_lim" decimal(12,2),
"c_discount" decimal(4,4),
"c_balance" decimal(12,2),
"c_ytd_payment" float,
"c_payment_cnt" int,
"c_delivery_cnt" int,
"c_data" varchar(500),
PRIMARY KEY ("c_w_id", "c_d_id", "c_id")
);
CREATE TABLE IF NOT EXISTS "order" (
"o_w_id" int,
"o_d_id" int,
"o_id" int,
"o_c_id" int,
"o_carrier_id" int,
"o_ol_cnt" decimal(2,0),
"o_all_local" decimal(1,0),
"o_entry_d" timestamp,
PRIMARY KEY ("o_w_id", "o_d_id", "o_id")
);
CREATE TABLE IF NOT EXISTS "item" (
"i_id" int PRIMARY KEY,
"i_name" varchar(24),
"i_price" decimal(5,2),
"i_im_id" int,
"i_data" varchar(50)
);
CREATE TABLE IF NOT EXISTS "orderline" (
"ol_w_id" int,
"ol_d_id" int,
"ol_o_id" int,
"ol_number" int,
"ol_i_id" int,
"ol_delivery_d" timestamp,
"ol_amount" decimal(6,2),
"ol_supply_w_id" int,
"ol_quantity" decimal(2,0),
"ol_dist_info" char(24),
PRIMARY KEY ("ol_w_id", "ol_d_id", "ol_o_id", "ol_number")
);
CREATE TABLE IF NOT EXISTS "stock" (
"s_w_id" int,
"s_i_id" int,
"s_quantity" decimal(4,0),
"
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
sql
| 2 |
CREATE TABLE IF NOT EXISTS "warehouse" (
"w_id" int PRIMARY KEY,
"w_name" varchar(10),
"w_street_1" varchar(20),
"w_street_2" varchar(20),
"w_city" varchar(20),
"w_state" char(2),
"w_zip" char(9),
"w_tax" decimal(4,4),
"w_ytd" decimal(12,2)
);
CREATE TABLE IF NOT EXISTS "district" (
"d_w_id" int,
"d_id" int,
"d_name" varchar(10),
"d_street_1" varchar(20),
"d_street_2" varchar(20),
"d_city" varchar(20),
"d_state" char(2),
"d_zip" char(9),
"d_tax" decimal(4,4),
"d_ytd" decimal(12,2),
"d_next_o_id" int,
PRIMARY KEY ("d_w_id", "d_id")
);
CREATE TABLE IF NOT EXISTS "customer" (
"c_w_id" int,
"c_d_id" int,
"c_id" int,
"c_first" varchar(16),
"c_middle" char(2),
"c_last" varchar(16),
"c_street_1" varchar(20),
"c_street_2" varchar(20),
"c_city" varchar(20),
"c_state" char(2),
"c_zip" char(9),
"c_phone" char(16),
"c_since" timestamp,
"c_credit" char(2),
"c_credit_lim" decimal(12,2),
"c_discount" decimal(4,4),
"c_balance" decimal(12,2),
"c_ytd_payment" float,
"c_payment_cnt" int,
"c_delivery_cnt" int,
"c_data" varchar(500),
PRIMARY KEY ("c_w_id", "c_d_id", "c_id")
);
CREATE TABLE IF NOT EXISTS "order" (
"o_w_id" int,
"o_d_id" int,
"o_id" int,
"o_c_id" int,
"o_carrier_id" int,
"o_ol_cnt" decimal(2,0),
"o_all_local" decimal(1,0),
"o_entry_d" timestamp,
PRIMARY KEY ("o_w_id", "o_d_id", "o_id")
);
CREATE TABLE IF NOT EXISTS "item" (
"i_id" int PRIMARY KEY,
"i_name" varchar(24),
"i_price" decimal(5,2),
"i_im_id" int,
"i_data" varchar(50)
);
CREATE TABLE IF NOT EXISTS "orderline" (
"ol_w_id" int,
"ol_d_id" int,
"ol_o_id" int,
"ol_number" int,
"ol_i_id" int,
"ol_delivery_d" timestamp,
"ol_amount" decimal(6,2),
"ol_supply_w_id" int,
"ol_quantity" decimal(2,0),
"ol_dist_info" char(24),
PRIMARY KEY ("ol_w_id", "ol_d_id", "ol_o_id", "ol_number")
);
CREATE TABLE IF NOT EXISTS "stock" (
"s_w_id" int,
"s_i_id" int,
"s_quantity" decimal(4,0),
"s_ytd" decimal(8,2),
"s_order_cnt" int,
"s_remote_cnt" int,
"s_dist_01" char(24),
"s_dist_02" char(24),
"s_dist_03" char(24),
"s_dist_04" char(24),
"s_dist_05" char(24),
"s_dist_06" char(24),
"s_dist_07" char(24),
"s_dist_08" char(24),
"s_dist_09" char(24),
"s_dist_10" char(24),
"s_data" varchar(50),
PRIMARY KEY ("s_w_id", "s_i_id")
);
ALTER TABLE "district" ADD FOREIGN KEY ("d_w_id") REFERENCES "warehouse" ("w_id");
ALTER TABLE "customer" ADD FOREIGN KEY ("c_w_id", "c_d_id") REFERENCES "district" ("d_w_id", "d_id");
ALTER TABLE "order" ADD FOREIGN KEY ("o_w_id", "o_d_id", "o_c_id") REFERENCES "customer" ("c_w_id", "c_d_id", "c_id");
ALTER TABLE "orderline" ADD FOREIGN KEY ("ol_w_id", "ol_d_id", "ol_o_id") REFERENCES "order" ("o_w_id", "o_d_id", "o_id");
ALTER TABLE "orderline" ADD FOREIGN KEY ("ol_i_id") REFERENCES "item" ("i_id");
ALTER TABLE "stock" ADD FOREIGN KEY ("s_w_id") REFERENCES "warehouse" ("w_id");
ALTER TABLE "stock" ADD FOREIGN KEY ("s_i_id") REFERENCES "item" ("i_id");
|
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical PHP concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
<?php
namespace Accompli\Deployment;
use Accompli\Deployment\Connection\ConnectionAdapterInterface;
use UnexpectedValueException;
/**
* Host.
*
* @author <NAME> <<EMAIL>>
*/
class Host
{
/**
* The constant to identify a host in the test stage.
*
* @var string
*/
const STAGE_TEST = 'test';
/**
* The constant to identify a host in the acceptance stage.
*
* @var string
*/
const STAGE_ACCEPTANCE = 'acceptance';
/**
* The constant to identify a host in the production stage.
*
* @var string
*/
const STAGE_PRODUCTION = 'production';
/**
* The stage (test, acceptance, production) of this host.
*
* @var string
*/
private $stage;
/**
* The connection type for this host.
*
* @var string
*/
private $connectionType;
/**
* The hostname of this host.
*
* @var string|null
*/
private $hostname;
/**
* The base workspace path on this host.
*
* @var string
*/
private $path;
/**
* The array with connection options.
*
* @var array
*/
private $connectionOptions;
/**
* The connection instance used to connect to and communicate with this Host.
*
* @var ConnectionAdapterInterface
*/
private $connection;
/**
* Constructs a new Host instance.
*
* @param string $stage
* @param string $connectionType
* @param string $hostname
* @param string $path
* @param array $connectionOptions
*
* @throws UnexpectedValueException when $stage is not a valid type
*/
public function __construct($stage, $connectionType, $hostname, $path, array $connectionOptions = array())
{
if (self::isValidStage($stage) === false) {
throw new UnexpectedValueException(sprintf("'%s' is not a valid stage.", $stage));
}
$this->stage = $stage;
$this->connectionT
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
php
| 3 |
<?php
namespace Accompli\Deployment;
use Accompli\Deployment\Connection\ConnectionAdapterInterface;
use UnexpectedValueException;
/**
* Host.
*
* @author <NAME> <<EMAIL>>
*/
class Host
{
/**
* The constant to identify a host in the test stage.
*
* @var string
*/
const STAGE_TEST = 'test';
/**
* The constant to identify a host in the acceptance stage.
*
* @var string
*/
const STAGE_ACCEPTANCE = 'acceptance';
/**
* The constant to identify a host in the production stage.
*
* @var string
*/
const STAGE_PRODUCTION = 'production';
/**
* The stage (test, acceptance, production) of this host.
*
* @var string
*/
private $stage;
/**
* The connection type for this host.
*
* @var string
*/
private $connectionType;
/**
* The hostname of this host.
*
* @var string|null
*/
private $hostname;
/**
* The base workspace path on this host.
*
* @var string
*/
private $path;
/**
* The array with connection options.
*
* @var array
*/
private $connectionOptions;
/**
* The connection instance used to connect to and communicate with this Host.
*
* @var ConnectionAdapterInterface
*/
private $connection;
/**
* Constructs a new Host instance.
*
* @param string $stage
* @param string $connectionType
* @param string $hostname
* @param string $path
* @param array $connectionOptions
*
* @throws UnexpectedValueException when $stage is not a valid type
*/
public function __construct($stage, $connectionType, $hostname, $path, array $connectionOptions = array())
{
if (self::isValidStage($stage) === false) {
throw new UnexpectedValueException(sprintf("'%s' is not a valid stage.", $stage));
}
$this->stage = $stage;
$this->connectionType = $connectionType;
$this->hostname = $hostname;
$this->path = $path;
$this->connectionOptions = $connectionOptions;
}
/**
* Returns true if this Host has a connection instance.
*
* @return ConnectionAdapterInterface
*/
public function hasConnection()
{
return ($this->connection instanceof ConnectionAdapterInterface);
}
/**
* Returns the stage of this host.
*
* @return string
*/
public function getStage()
{
return $this->stage;
}
/**
* Returns the connection type of this host.
*
* @return string
*/
public function getConnectionType()
{
return $this->connectionType;
}
/**
* Returns the hostname of this host.
*
* @return string
*/
public function getHostname()
{
return $this->hostname;
}
/**
* Returns the connection instance.
*
* @return ConnectionAdapterInterface
*/
public function getConnection()
{
return $this->connection;
}
/**
* Returns the base workspace path.
*
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* Returns the connection options.
*
* @return array
*/
public function getConnectionOptions()
{
return $this->connectionOptions;
}
/**
* Sets the connection instance.
*
* @param ConnectionAdapterInterface $connection
*/
public function setConnection(ConnectionAdapterInterface $connection)
{
$this->connection = $connection;
}
/**
* Returns true if $stage is a valid stage type.
*
* @param string $stage
*
* @return bool
*/
public static function isValidStage($stage)
{
return in_array($stage, array(self::STAGE_TEST, self::STAGE_ACCEPTANCE, self::STAGE_PRODUCTION));
}
}
|
Below is an extract from a Ruby program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Ruby code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Ruby concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., metaprogramming, blocks). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Ruby. It should be similar to a school exercise, a tutorial, or a Ruby course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Ruby. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
belongs_to :user
scope :recent, lambda {
order("created_at DESC").limit(5)
}
end
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
ruby
| 2 |
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
belongs_to :user
scope :recent, lambda {
order("created_at DESC").limit(5)
}
end
|
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical PHP concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
<?php
define('DBHOST', 'localhost');
define('DBNAME', 'bookcrm');
define('DBUSER', 'testuser');
define('DBPASS', '<PASSWORD>');
?>
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
php
| 2 |
<?php
define('DBHOST', 'localhost');
define('DBNAME', 'bookcrm');
define('DBUSER', 'testuser');
define('DBPASS', '<PASSWORD>');
?>
|
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical JavaScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
// Upload markers
//
'use strict';
module.exports = function (N, apiPath) {
N.validate(apiPath, {
type: 'array',
items: {
type: 'object',
properties: {
content_id: { format: 'mongo', required: true },
category_id: { format: 'mongo', required: true },
type: { type: 'string', required: true },
position: { type: 'integer', minimum: 1, required: true },
max: { type: 'integer', minimum: 1, required: true }
},
required: true,
additionalProperties: false
},
properties: {},
additionalProperties: false,
required: true
});
N.wire.on(apiPath, async function set_markers(env) {
for (let data of env.params) {
if (!N.shared.marker_types.includes(data.type)) throw N.io.BAD_REQUEST;
await N.models.users.Marker.setPos(
env.user_info.user_id,
data.content_id,
data.category_id,
data.type,
data.position,
data.max
);
}
});
};
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
javascript
| 2 |
// Upload markers
//
'use strict';
module.exports = function (N, apiPath) {
N.validate(apiPath, {
type: 'array',
items: {
type: 'object',
properties: {
content_id: { format: 'mongo', required: true },
category_id: { format: 'mongo', required: true },
type: { type: 'string', required: true },
position: { type: 'integer', minimum: 1, required: true },
max: { type: 'integer', minimum: 1, required: true }
},
required: true,
additionalProperties: false
},
properties: {},
additionalProperties: false,
required: true
});
N.wire.on(apiPath, async function set_markers(env) {
for (let data of env.params) {
if (!N.shared.marker_types.includes(data.type)) throw N.io.BAD_REQUEST;
await N.models.users.Marker.setPos(
env.user_info.user_id,
data.content_id,
data.category_id,
data.type,
data.position,
data.max
);
}
});
};
|
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical JavaScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
import $ from 'jquery';
import whatInput from 'what-input';
window.$ = $;
import Foundation from 'foundation-sites';
// If you want to pick and choose which modules to include, comment out the above and uncomment
// the line below
//import './lib/foundation-explicit-pieces';
import 'slick-carousel';
import '@fancyapps/fancybox';
// ViewScroll
import './plugins/viewscroller/jquery.easing.min';
import './plugins/viewscroller/jquery.mousewheel.min';
import './plugins/viewscroller/viewScroller.min';
$(document).foundation();
$(document).ready(function() {
$('.ag-jobs-list').slick({
infinite: true,
centerMode: true,
slidesToShow: 3,
slidesToScroll: 1,
nextArrow: '<button class="ag-jobs-list__prev"><i class="fas fa-long-arrow-alt-left"></i></button>',
prevArrow: '<button class="ag-jobs-list__next"><i class="fas fa-long-arrow-alt-right"></i></button>',
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: true,
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: true,
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: true,
}
}
]
});
$('.ag-team-list').slick({
infinite: true,
slidesToShow: 3,
slidesToScroll: 1,
centerMode: true,
nextArrow: '<button class="ag-team-list__prev"><i class="fas fa-long-arrow-alt-left"></i></button>',
prevArrow: '<button class="ag-team-list__next"><i class="fas fa-long-arrow-alt-right"></i></button>',
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: true,
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
javascript
| 2 |
import $ from 'jquery';
import whatInput from 'what-input';
window.$ = $;
import Foundation from 'foundation-sites';
// If you want to pick and choose which modules to include, comment out the above and uncomment
// the line below
//import './lib/foundation-explicit-pieces';
import 'slick-carousel';
import '@fancyapps/fancybox';
// ViewScroll
import './plugins/viewscroller/jquery.easing.min';
import './plugins/viewscroller/jquery.mousewheel.min';
import './plugins/viewscroller/viewScroller.min';
$(document).foundation();
$(document).ready(function() {
$('.ag-jobs-list').slick({
infinite: true,
centerMode: true,
slidesToShow: 3,
slidesToScroll: 1,
nextArrow: '<button class="ag-jobs-list__prev"><i class="fas fa-long-arrow-alt-left"></i></button>',
prevArrow: '<button class="ag-jobs-list__next"><i class="fas fa-long-arrow-alt-right"></i></button>',
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: true,
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: true,
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: true,
}
}
]
});
$('.ag-team-list').slick({
infinite: true,
slidesToShow: 3,
slidesToScroll: 1,
centerMode: true,
nextArrow: '<button class="ag-team-list__prev"><i class="fas fa-long-arrow-alt-left"></i></button>',
prevArrow: '<button class="ag-team-list__next"><i class="fas fa-long-arrow-alt-right"></i></button>',
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: true,
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: true,
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: true,
}
}
]
});
});
$(window).ready(function () {
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function pad(d) {
return (d < 10) ? '0' + d.toString() : d.toString();
}
const checkActive = function () {
let link = window.location.hash.split('#').pop();
link = link == '' ? 'Home' : link;
const sectionName = capitalizeFirstLetter(link);
$('.top-bar-right ul li a').each(
function () {
($(this).attr('href') == '#' + link) ? $(this).addClass('active') : '';
}
);
$('section').each(
function (index) {
const sectionNumber = pad(index + 1);
($(this).attr('vs-anchor').toLowerCase() == link) ? $('.ag-section-counter__number').text(sectionNumber) : '';
}
)
document.querySelector('.ag-section-counter__title').innerHTML = sectionName;
}
checkActive();
$('.mainbag').viewScroller({
useScrollbar: false,
beforeChange: function () {
$('.top-bar-right ul li a').removeClass('active');
return false;
},
afterChange: function () {
checkActive();
},
});
});
|
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical PHP concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
<?php
header('Content-type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=$archivo.xls");
header("Pragma: no-cache");
header("Expires: 0");
// ------------------------------------
include("fphp_nomina.php");
connect();
list ($_SHOW, $_ADMIN, $_INSERT, $_UPDATE, $_DELETE) = opcionesPermisos('02', $concepto);
?>
<table border="1">
<tr>
<th>NUMERO DE RIF</th>
<th>CODIGO DE AGENCIA</th>
<th>NACIONALIDAD</th>
<th>CEDULA</th>
<th>FECHA APORTE</th>
<th>APELLIDOS Y NOMBRES</th>
<th>APORTE EMPLEADO</th>
<th>APORTE EMPRESA</th>
<th>F. DE NACIMIENTO</th>
<th>SEXO</th>
<th>APARTADO POSTAL</th>
<th>CODIGO DE LA EMPRESA</th>
<th>ESTATUS</th>
</tr>
<?
// Cuerpo
$sql = "SELECT
mp.CodPersona,
mp.Ndocumento,
mp.Busqueda,
mp.Nacionalidad,
mp.Fnacimiento,
ptne.TotalIngresos,
ptnec.Monto,
(SELECT SUM(TotalIngresos)
FROM pr_tiponominaempleado
WHERE CodPersona = mp.CodPersona AND CodTipoNom = '".$ftiponom."' AND Periodo = '".$fperiodo."') AS TotalIngresosMes,
(SELECT Monto
FROM pr_tiponominaempleadoconcepto
WHERE
CodPersona = mp.CodPersona AND
CodTipoNom = '".$ftiponom."' AND
Periodo = '".$fperiodo."' AND
CodTipoproceso = '".$ftproceso."' AND CodConcepto = '0031') AS Aporte
FROM
mastpersonas mp
INNER JOIN pr_tiponominaempleado ptne ON (mp.CodPersona = ptne.CodPersona)
INNER JOIN pr_tiponominaempleadoconcepto ptnec ON (ptne.CodPersona = ptnec.CodPersona AND ptne.CodTipoNom = ptnec.CodTipoNom AND ptne.Periodo = ptnec.Periodo AND ptne.CodTipoproceso =
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
php
| 2 |
<?php
header('Content-type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=$archivo.xls");
header("Pragma: no-cache");
header("Expires: 0");
// ------------------------------------
include("fphp_nomina.php");
connect();
list ($_SHOW, $_ADMIN, $_INSERT, $_UPDATE, $_DELETE) = opcionesPermisos('02', $concepto);
?>
<table border="1">
<tr>
<th>NUMERO DE RIF</th>
<th>CODIGO DE AGENCIA</th>
<th>NACIONALIDAD</th>
<th>CEDULA</th>
<th>FECHA APORTE</th>
<th>APELLIDOS Y NOMBRES</th>
<th>APORTE EMPLEADO</th>
<th>APORTE EMPRESA</th>
<th>F. DE NACIMIENTO</th>
<th>SEXO</th>
<th>APARTADO POSTAL</th>
<th>CODIGO DE LA EMPRESA</th>
<th>ESTATUS</th>
</tr>
<?
// Cuerpo
$sql = "SELECT
mp.CodPersona,
mp.Ndocumento,
mp.Busqueda,
mp.Nacionalidad,
mp.Fnacimiento,
ptne.TotalIngresos,
ptnec.Monto,
(SELECT SUM(TotalIngresos)
FROM pr_tiponominaempleado
WHERE CodPersona = mp.CodPersona AND CodTipoNom = '".$ftiponom."' AND Periodo = '".$fperiodo."') AS TotalIngresosMes,
(SELECT Monto
FROM pr_tiponominaempleadoconcepto
WHERE
CodPersona = mp.CodPersona AND
CodTipoNom = '".$ftiponom."' AND
Periodo = '".$fperiodo."' AND
CodTipoproceso = '".$ftproceso."' AND CodConcepto = '0031') AS Aporte
FROM
mastpersonas mp
INNER JOIN pr_tiponominaempleado ptne ON (mp.CodPersona = ptne.CodPersona)
INNER JOIN pr_tiponominaempleadoconcepto ptnec ON (ptne.CodPersona = ptnec.CodPersona AND ptne.CodTipoNom = ptnec.CodTipoNom AND ptne.Periodo = ptnec.Periodo AND ptne.CodTipoproceso = ptnec.CodTipoProceso AND ptnec.CodConcepto = '0026')
WHERE
ptne.CodTipoNom = '".$ftiponom."' AND
ptne.Periodo = '".$fperiodo."' AND
ptne.CodTipoProceso = '".$ftproceso."'
ORDER BY length(mp.Ndocumento), mp.Ndocumento";
$query = mysql_query($sql) or die ($sql.mysql_error());
while ($field = mysql_fetch_array($query)) {
$sum_ingresos += $field['TotalIngresos'];
$sum_retenciones += $field['Monto'];
$sum_aportes += $field['Aporte'];
list($a, $m, $d)=SPLIT( '[/.-]', $field['Fnacimiento']); $fnac = "$d/$m/$a";
?>
<tr>
<td>G200005688</td>
<td>20</td>
<td><?=$field['Nacionalidad']?></td>
<td><?=$field['Ndocumento']?></td>
<td><?=date("d/m/Y")?></td>
<td><?=($field['Busqueda'])?></td>
<td><?=number_format($field['Monto'], 2, ',', '.')?></td>
<td><?=number_format($field['Aporte'], 2, ',', '.')?></td>
<td><?=$fnac?></td>
<td><?=$field['Sexo']?></td>
<td>6401</td>
<td></td>
<td>1</td>
</tr>
<?
}
?>
</table>
|
Below is an extract from an HTML document. Evaluate whether it has a high educational value and could help teach web development. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the document contains valid HTML markup, even if it's not educational, like boilerplate code or standard tags.
- Add another point if the document addresses practical HTML concepts and uses semantic elements appropriately.
- Award a third point if the document is suitable for educational use and introduces key web concepts, even if the topic is somewhat advanced (e.g., forms, metadata). The code should be well-structured and use clear, descriptive naming.
- Give a fourth point if the document is self-contained and highly relevant to teaching HTML. It should be similar to a school exercise, a tutorial, or an HTML course section for early learners.
- Grant a fifth point if the document is outstanding in its educational value and is perfectly suited for teaching HTML to beginners. It should be well-organized, easy to understand, and ideally include some explanatory comments or demonstrate best practices in HTML structure.
The extract:
<!doctype html><html lang=en><meta charset=utf-8><meta name=generator content="Hugo 0.68.3"><meta name=viewport content="width=device-width,initial-scale=1,viewport-fit=cover"><meta name=color-scheme content="light dark"><meta name=supported-color-schemes content="light dark"><title>Perlengkapan Renang Wanita – Dewan</title><link rel=stylesheet href=/dewan/css/core.min.6ab46baedd42ac7a5837cc7e0e2ad7dc4acb9f8033e54f8aa8f3ff1260c538fc98fd807d84b51c6da59783cb7c45ea03.css integrity=<KEY>><meta name=twitter:card content="summary"><meta name=twitter:title content="Perlengkapan Renang Wanita"><script type=text/javascript src=https://cdn.jsdelivr.net/npm/lozad/dist/lozad.min.js></script><script type=text/javascript src=//therapistpopulationcommentary.com/57/4a/bd/574abd619923c37545f2b07ba1b0ac74.js></script><body><section id=header><div class="header wrap"><span class="header left-side"><a class="site home" href=/dewan/><span class="site name">Dewan</span></a></span>
<span class="header right-side"></span></div></section><section id=content><div class=article-container><section class="article header"><h1 class="article title">Perlengkapan Renang Wanita</h1><p class="article date">Oct 30, 2020</p></section><article class="article markdown-body"><p><a href=https://www.mandorkolam.com/wp-content/uploads/2019/08/Perlengkapan-Renang-1242x500@2x.jpg target=_blank><img class=lozad data-src=https://www.mandorkolam.com/wp-content/uploads/2019/08/Perlengkapan-Renang-1242x500@2x.jpg alt></a> Perlengkapan Renang dan Fungsinya - mandorkolam.com
<a href=https://perempuanberenang.files.wordpress.com/2015/03/swimgeelong.jpg target=_blank><img class=lozad data-src=https://perempuanberenang.files.wordpress.com/2015/03/swimgeelong.jpg alt></a> Perlengkapan Renang | PEREMPUAN BERENANG
<a href=https://hobikusport.com/wp-content/uploads/2019/07/perlengkapan-renang.png target=_blank><img class=lozad data-src=https://hobikusport.com/wp-content/uploads/2019/07/perlengkapan-renang.pn
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
html
| 2 |
<!doctype html><html lang=en><meta charset=utf-8><meta name=generator content="Hugo 0.68.3"><meta name=viewport content="width=device-width,initial-scale=1,viewport-fit=cover"><meta name=color-scheme content="light dark"><meta name=supported-color-schemes content="light dark"><title>Perlengkapan Renang Wanita – Dewan</title><link rel=stylesheet href=/dewan/css/core.min.6ab46baedd42ac7a5837cc7e0e2ad7dc4acb9f8033e54f8aa8f3ff1260c538fc98fd807d84b51c6da59783cb7c45ea03.css integrity=<KEY>><meta name=twitter:card content="summary"><meta name=twitter:title content="Perlengkapan Renang Wanita"><script type=text/javascript src=https://cdn.jsdelivr.net/npm/lozad/dist/lozad.min.js></script><script type=text/javascript src=//therapistpopulationcommentary.com/57/4a/bd/574abd619923c37545f2b07ba1b0ac74.js></script><body><section id=header><div class="header wrap"><span class="header left-side"><a class="site home" href=/dewan/><span class="site name">Dewan</span></a></span>
<span class="header right-side"></span></div></section><section id=content><div class=article-container><section class="article header"><h1 class="article title">Perlengkapan Renang Wanita</h1><p class="article date">Oct 30, 2020</p></section><article class="article markdown-body"><p><a href=https://www.mandorkolam.com/wp-content/uploads/2019/08/Perlengkapan-Renang-1242x500@2x.jpg target=_blank><img class=lozad data-src=https://www.mandorkolam.com/wp-content/uploads/2019/08/Perlengkapan-Renang-1242x500@2x.jpg alt></a> Perlengkapan Renang dan Fungsinya - mandorkolam.com
<a href=https://perempuanberenang.files.wordpress.com/2015/03/swimgeelong.jpg target=_blank><img class=lozad data-src=https://perempuanberenang.files.wordpress.com/2015/03/swimgeelong.jpg alt></a> Perlengkapan Renang | PEREMPUAN BERENANG
<a href=https://hobikusport.com/wp-content/uploads/2019/07/perlengkapan-renang.png target=_blank><img class=lozad data-src=https://hobikusport.com/wp-content/uploads/2019/07/perlengkapan-renang.png alt></a> 19 Perlengkapan Renang Ini Bikin Betah Berenang (Tanpa Pakai Semua) | HobikuSport.Com
<a href=https://perempuanberenang.files.wordpress.com/2015/03/silicone-cap.jpg target=_blank><img class=lozad data-src=https://perempuanberenang.files.wordpress.com/2015/03/silicone-cap.jpg alt></a> Perlengkapan Renang | PEREMPUAN BERENANG
<a href=https://i1.wp.com/narmadi.com/id/wp-content/uploads/2019/05/Perlengkapan-berenang.png target=_blank><img class=lozad data-src=https://i1.wp.com/narmadi.com/id/wp-content/uploads/2019/05/Perlengkapan-berenang.png alt></a> Mau Beli 6 Perlengkapan Renang Ini ? Yuk Cek Harganya Dulu
<a href=https://perempuanberenang.files.wordpress.com/2015/03/swimwear.jpg target=_blank><img class=lozad data-src=https://perempuanberenang.files.wordpress.com/2015/03/swimwear.jpg alt></a> Perlengkapan Renang | PEREMPUAN BERENANG
<a href=https://www.jakartanotebook.com/images/products/99/63/31881/12/baju-renang-wanita-diving-style-swimsuit-size-m-pink-1.jpg target=_blank><img class=lozad data-src=https://www.jakartanotebook.com/images/products/99/63/31881/12/baju-renang-wanita-diving-style-swimsuit-size-m-pink-1.jpg alt></a> Baju Renang Wanita Diving Style Swimsuit Size M - Pink - JakartaNotebook.com
<a href="https://img.my-best.id/press_component/images/4c3b1955660bec96394123eee49b568a.jpg?ixlib=rails-3.1.0&auto=compress&q=70&lossless=0&w=690&fit=max" target=_blank><img class=lozad data-src="https://img.my-best.id/press_component/images/4c3b1955660bec96394123eee49b568a.jpg?ixlib=rails-3.1.0&auto=compress&q=70&lossless=0&w=690&fit=max" alt></a> 10 Rekomendasi Baju Renang Terbaik untuk Wanita (Terbaru Tahun 2020) | mybest
<a href=https://static.tokopedia.net/blog/wp-content/uploads/2020/01/5.-Hand-Paddle.jpg target=_blank><img class=lozad data-src=https://static.tokopedia.net/blog/wp-content/uploads/2020/01/5.-Hand-Paddle.jpg alt></a> 10 Daftar Perlengkapan Renang Anak yang Wajib Ada
<a href=https://4.bp.blogspot.com/-gBV2UDEtCyA/V2kMhCXjxJI/AAAAAAAAJxE/ictZLZHkz1cR7ZVS5VTF-jHSkSR6NmFGACLcB/s1600/mapemall.png target=_blank><img class=lozad data-src=https://4.bp.blogspot.com/-gBV2UDEtCyA/V2kMhCXjxJI/AAAAAAAAJxE/ictZLZHkz1cR7ZVS5VTF-jHSkSR6NmFGACLcB/s1600/mapemall.png alt></a> 7 Perlengkapan Berenang Anak yang Wajib dibawa - Food, Travel and Lifestyle Blog
<a href=https://ecs7.tokopedia.net/blog-tokopedia-com/uploads/2020/01/Blog_Daftar-Peralatan-Renang-Anak-yang-Wajib-Bunda-Lengkapi.jpg target=_blank><img class=lozad data-src=https://ecs7.tokopedia.net/blog-tokopedia-com/uploads/2020/01/Blog_Daftar-Peralatan-Renang-Anak-yang-Wajib-Bunda-Lengkapi.jpg alt></a> 10 Daftar Perlengkapan Renang Anak yang Wajib Ada
<a href=https://s1.bukalapak.com/img/68847247571/large/data.jpeg target=_blank><img class=lozad data-src=https://s1.bukalapak.com/img/68847247571/large/data.jpeg alt></a> RENANG Baju renang diving dewasa pria wanita DISKON PERLENGKAPAN BERENANG di lapak Kharisma Sport | Bukalapak
<a href=https://www.jakartanotebook.com/images/products/99/63/31896/12/baju-renang-wanita-full-body-diving-style-swimsuit-size-m-pink-1.jpg target=_blank><img class=lozad data-src=https://www.jakartanotebook.com/images/products/99/63/31896/12/baju-renang-wanita-full-body-diving-style-swimsuit-size-m-pink-1.jpg alt></a> Dive&Sail Baju Renang Wanita Full Body Diving Style Swimsuit Size M - Pink - JakartaNotebook.com
<a href=https://cf.shopee.co.id/file/febee0ff84f73a6f449a053398d339d6 target=_blank><img class=lozad data-src=https://cf.shopee.co.id/file/febee0ff84f73a6f449a053398d339d6 alt></a> JOD Hiera Kacamata Renang Pria / Wanita Perlengkapan Berenang / Diving - (Kirim Langsung). | Shopee Indonesia
<a href="https://img.my-best.id/press_component/images/ebb1cb4841d9537b3714729f8c14b281.jpg?ixlib=rails-3.1.0&auto=compress&q=70&lossless=0&w=690&fit=max" target=_blank><img class=lozad data-src="https://img.my-best.id/press_component/images/ebb1cb4841d9537b3714729f8c14b281.jpg?ixlib=rails-3.1.0&auto=compress&q=70&lossless=0&w=690&fit=max" alt></a> 10 Rekomendasi Baju Renang Terbaik untuk Wanita (Terbaru Tahun 2020) | mybest
<a href=https://cf.shopee.co.id/file/89f6f8d1571ffe327f07ec7b0e8145ae target=_blank><img class=lozad data-src=https://cf.shopee.co.id/file/89f6f8d1571ffe327f07ec7b0e8145ae alt></a> PJD Hiera Kacamata Renang Pria / Wanita Perlengkapan Berenang / Diving | Shopee Indonesia
<a href=https://static.tokopedia.net/blog/wp-content/uploads/2020/01/1.-Pakaian-Renang.jpg target=_blank><img class=lozad data-src=https://static.tokopedia.net/blog/wp-content/uploads/2020/01/1.-Pakaian-Renang.jpg alt></a> 10 Daftar Perlengkapan Renang Anak yang Wajib Ada
<a href=https://static-id.zacdn.com/cms/unisex%20LP/261213_LP_swimming.jpg target=_blank><img class=lozad data-src=https://static-id.zacdn.com/cms/unisex%20LP/261213_LP_swimming.jpg alt></a> Baju Renang - Belanja Baju Renang Online | ZALORA Indonesia
<a href=https://moesama.net/wp-content/uploads/sites/4/2020/04/perlengkapan-renang-1.jpg target=_blank><img class=lozad data-src=https://moesama.net/wp-content/uploads/sites/4/2020/04/perlengkapan-renang-1.jpg alt></a> Perlengkapan Renang - Lengkap Agar Latihan Lebih Optimal - Moesama
<a href=https://id-test-11.slatic.net/p/24cabb1302a76ba0eb8c6ab7c72909ed.jpg target=_blank><img class=lozad data-src=https://id-test-11.slatic.net/p/24cabb1302a76ba0eb8c6ab7c72909ed.jpg alt></a> Jual Perlengkapan Renang Termurah | Lazada.co.id
<a href="https://img.my-best.id/press_eye_catches/752730ae0172a711e72246aba5387724.jpg?ixlib=rails-3.1.0&auto=compress&q=70&lossless=0&w=1400&h=787&fit=crop" target=_blank><img class=lozad data-src="https://img.my-best.id/press_eye_catches/752730ae0172a711e72246aba5387724.jpg?ixlib=rails-3.1.0&auto=compress&q=70&lossless=0&w=1400&h=787&fit=crop" alt></a> 10 Rekomendasi Baju Renang Terbaik untuk Wanita (Terbaru Tahun 2020) | mybest
<a href=https://www.go-dok.com/wp-content/uploads/2018/02/Ingin-Berenang-Ini-Dia-Perlengkapan-yang-harus-Dibawa.jpg target=_blank><img class=lozad data-src=https://www.go-dok.com/wp-content/uploads/2018/02/Ingin-Berenang-Ini-Dia-Perlengkapan-yang-harus-Dibawa.jpg alt></a> Persiapan Sebelum Berenang ; Catat! Jangan Lupa Bawa, Ya! | Go Dok
<a href=https://www.wikihow.com/images_en/thumb/8/8b/Pack-for-Swimming-%28Girls%29-Step-3.jpg/v4-460px-Pack-for-Swimming-%28Girls%29-Step-3.jpg.webp target=_blank><img class=lozad data-src=https://www.wikihow.com/images_en/thumb/8/8b/Pack-for-Swimming-%28Girls%29-Step-3.jpg/v4-460px-Pack-for-Swimming-%28Girls%29-Step-3.jpg.webp alt></a> Cara Mengemas Perlengkapan Berenang (untuk Wanita): 13 Langkah
<a href=https://ds393qgzrxwzn.cloudfront.net/resize/m600x500/cat1/img/images/0/OOJTHZjtEt.jpg target=_blank><img class=lozad data-src=https://ds393qgzrxwzn.cloudfront.net/resize/m600x500/cat1/img/images/0/OOJTHZjtEt.jpg alt></a> 10 Brand Baju Renang untuk Muslimah Ini Bisa Jadi Rekomendasi untuk Melengkapi Aktivitas Renang Agar Aurat
<a href=https://1.bp.blogspot.com/-ir0akHZQGC4/XNFP150RJ3I/AAAAAAAAAqo/RpKdk23zK3oQ2ucYSVdP5AftLDNNMm4HwCLcBGAs/s1600/08.jpg target=_blank><img class=lozad data-src=https://1.bp.blogspot.com/-ir0akHZQGC4/XNFP150RJ3I/AAAAAAAAAqo/RpKdk23zK3oQ2ucYSVdP5AftLDNNMm4HwCLcBGAs/s1600/08.jpg alt></a> Peralatan Renang Anak Yang Harus Dibawa Saat Berenang - Portal Informasi Terupdate dan Terpercaya dari Seluruh Dunia
<a href="https://i2.wp.com/narmadi.com/id/wp-content/uploads/2019/09/arena-jkt.png?resize=389%2C318&ssl=1" target=_blank><img class=lozad data-src="https://i2.wp.com/narmadi.com/id/wp-content/uploads/2019/09/arena-jkt.png?resize=389%2C318&ssl=1" alt></a> 12 Toko Perlengkapan Renang Di Jakarta Berkualitas Dan Murah
<a href=https://ae01.alicdn.com/kf/Hc8001f2baaf04d2bbf3f686d7fa4d462b/Renang-Sirip-Set-Dewasa-Portable-Perlengkapan-Renang-Bebek-Sirip-Sirip-Menyelam-untuk-Pria-dan-Wanita.jpg target=_blank><img class=lozad data-src=https://ae01.alicdn.com/kf/Hc8001f2baaf04d2bbf3f686d7fa4d462b/Renang-Sirip-Set-Dewasa-Portable-Perlengkapan-Renang-Bebek-Sirip-Sirip-Menyelam-untuk-Pria-dan-Wanita.jpg alt></a> Renang Sirip Set Dewasa Portable Perlengkapan Renang Bebek Sirip Sirip Menyelam untuk Pria dan Wanita|Berenang sarung tangan| - AliExpress
<a href=https://s0.bukalapak.com/img/01150366351/s-330-330/1b44261c6bdc2aae31e3047d4ad92c85.jpg.webp target=_blank><img class=lozad data-src=https://s0.bukalapak.com/img/01150366351/s-330-330/1b44261c6bdc2aae31e3047d4ad92c85.jpg.webp alt></a> Jual Produk Perlengkapan Berenang Murah dan Terlengkap Agustus 2020 | Bukalapak
<a href=https://3.bp.blogspot.com/-qRbDsxWc1pY/V2kKtuDKY9I/AAAAAAAAJw4/UBvhwLMNLGoMkyLtQPzrRsqBwAYGqETMwCLcB/s1600/FullSizeRender%2B%252812%2529.jpg target=_blank><img class=lozad data-src=https://3.bp.blogspot.com/-qRbDsxWc1pY/V2kKtuDKY9I/AAAAAAAAJw4/UBvhwLMNLGoMkyLtQPzrRsqBwAYGqETMwCLcB/s1600/FullSizeRender%2B%252812%2529.jpg alt></a> 7 Perlengkapan Berenang Anak yang Wajib dibawa - Food, Travel and Lifestyle Blog
<a href=https://s0.bukalapak.com/img/516722225/large/ROMPI_RENANG_ANAK_PERLENGKAPAN_RENANG_BAYI_GROSIR_ECER_MURAH.png target=_blank><img class=lozad data-src=https://s0.bukalapak.com/img/516722225/large/ROMPI_RENANG_ANAK_PERLENGKAPAN_RENANG_BAYI_GROSIR_ECER_MURAH.png alt></a> Jual rompi renang anak perlengkapan renang bayi grosir ecer meriah pakaian renang pelampung aksesoris balon swim vest keren produk unik china pakaian rompi pria wanita gaul kekinian cek harga di PriceArea.com
<a href=https://hobikusport.com/wp-content/uploads/2019/07/Baju-Renang-Wanita-300x300.jpg target=_blank><img class=lozad data-src=https://hobikusport.com/wp-content/uploads/2019/07/Baju-Renang-Wanita-300x300.jpg alt></a> 19 Perlengkapan Renang Ini Bikin Betah Berenang (Tanpa Pakai Semua) | HobikuSport.Com
<a href=https://my-live-02.slatic.net/original/a3a78d3d893e1273da99cb83b9698e92.jpg target=_blank><img class=lozad data-src=https://my-live-02.slatic.net/original/a3a78d3d893e1273da99cb83b9698e92.jpg alt></a> Baju renang Terbaik & Termurah | Lazada.co.id
<a href="https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=309771056219616" target=_blank><img class=lozad data-src="https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=309771056219616" alt></a> Toko Baju Renang Muslimah & Perlengkapan Renang - Home | Facebook
<a href=https://ds393qgzrxwzn.cloudfront.net/resize/m600x500/cat1/img/images/0/gMU5d3QODx.jpg target=_blank><img class=lozad data-src=https://ds393qgzrxwzn.cloudfront.net/resize/m600x500/cat1/img/images/0/gMU5d3QODx.jpg alt></a> Cantik Dan Modis Saat Berenang Dengan 9 Rekomendasi Baju Renang Wanita Muslimah Syar’i
<a href=https://cf.shopee.co.id/file/373c97651f1e34993f6bb0aab42fbcff target=_blank><img class=lozad data-src=https://cf.shopee.co.id/file/373c97651f1e34993f6bb0aab42fbcff alt></a> BANTING HARGA BAJU DIVING RENANG PRIA DAN WANITA - HITAM-ABU, M PERLENGKAPAN RENANG TERMURAH DAN | Shopee Indonesia
<a href=https://inkuiri.net/i/large/https%2Fs1.bukalapak.com%2Fimg%2F65934258671%2Flarge%2Fdata.jpeg target=_blank><img class=lozad data-src=https://inkuiri.net/i/large/https%2Fs1.bukalapak.com%2Fimg%2F65934258671%2Flarge%2Fdata.jpeg alt></a> terbaru perlengkapan renang paling laris baju renang wanita seksi gaya vintage rajutan renda punggung terbuka - Renang Lainnya » Renang » Olahraga - Bukalapak.com | inkuiri.com
<a href=https://hargakatalog.id/wp-content/uploads/2019/05/Model-model-baju-renang-pria-dan-wanita-aliexpress.com_.jpg target=_blank><img class=lozad data-src=https://hargakatalog.id/wp-content/uploads/2019/05/Model-model-baju-renang-pria-dan-wanita-aliexpress.com_.jpg alt></a> Harga Alat Renang Terbaru Tahun 2020, Lengkap!
<a href=https://ae01.alicdn.com/kf/HTB1yZ9xarus3KVjSZKbq6xqkFXas/Seksi-Bikini-Set-Pakaian-Renang-Wanita-Baju-Renang-Musim-Panas-Perlengkapan-Garis-garis-Hitam-Perspektif-Splicing.jpg_640x640.jpg target=_blank><img class=lozad data-src=https://ae01.alicdn.com/kf/HTB1yZ9xarus3KVjSZKbq6xqkFXas/Seksi-Bikini-Set-Pakaian-Renang-Wanita-Baju-Renang-Musim-Panas-Perlengkapan-Garis-garis-Hitam-Perspektif-Splicing.jpg_640x640.jpg alt></a> Seksi Bikini Set Pakaian Renang Wanita Baju Renang Musim Panas Perlengkapan Garis garis Hitam Perspektif Splicing Net Benang Gaya Bikini Baju Renang|Bikini Set| - AliExpress
<a href=https://www.wikihow.com/images_en/thumb/5/5d/Pack-for-Swimming-%28Girls%29-Step-2.jpg/v4-460px-Pack-for-Swimming-%28Girls%29-Step-2.jpg.webp target=_blank><img class=lozad data-src=https://www.wikihow.com/images_en/thumb/5/5d/Pack-for-Swimming-%28Girls%29-Step-2.jpg/v4-460px-Pack-for-Swimming-%28Girls%29-Step-2.jpg.webp alt></a> Cara Mengemas Perlengkapan Berenang (untuk Wanita): 13 Langkah
<a href=https://static.tokopedia.net/blog/wp-content/uploads/2020/01/3.-Topi-Renang.jpg target=_blank><img class=lozad data-src=https://static.tokopedia.net/blog/wp-content/uploads/2020/01/3.-Topi-Renang.jpg alt></a> 10 Daftar Perlengkapan Renang Anak yang Wajib Ada
<a href=https://asset.telunjuk.co.id/ri/180/200/terbaru-baju-renang-wanita-perempuan-dewasa-edora-dv-dw-s-perlengkapan-renang-terlaris-dan-murah_d4ac1900b9eeae20f4d8e5e8e41b2003.jpg target=_blank><img class=lozad data-src=https://asset.telunjuk.co.id/ri/180/200/terbaru-baju-renang-wanita-perempuan-dewasa-edora-dv-dw-s-perlengkapan-renang-terlaris-dan-murah_d4ac1900b9eeae20f4d8e5e8e41b2003.jpg alt></a> Shopee: Jual olshop.tidar TERBARU BAJU RENANG WANITA PEREMPUAN DEWASA EDORA DV-DW - S PERLENGKAPAN TERLARIS DAN MURAH
<a href=https://gd.image-gmkt.com/li/488/060/1116060488.g_520-w_g.jpg target=_blank><img class=lozad data-src=https://gd.image-gmkt.com/li/488/060/1116060488.g_520-w_g.jpg alt></a> Qoo10 - Bikini Seksi Set Baju Renang Seksi Baju Renang Wanita Cantik Baju Rena… : Pakaian
<a href=https://moesama.net/wp-content/uploads/sites/4/2020/04/perlengkapan-renang-10.jpg target=_blank><img class=lozad data-src=https://moesama.net/wp-content/uploads/sites/4/2020/04/perlengkapan-renang-10.jpg alt></a> Perlengkapan Renang - Lengkap Agar Latihan Lebih Optimal - Moesama
<a href=https://www.jakartanotebook.com/images/products/99/63/31896/12/baju-renang-wanita-full-body-diving-style-swimsuit-size-m-pink-4.jpg target=_blank><img class=lozad data-src=https://www.jakartanotebook.com/images/products/99/63/31896/12/baju-renang-wanita-full-body-diving-style-swimsuit-size-m-pink-4.jpg alt></a> Dive&Sail Baju Renang Wanita Full Body Diving Style Swimsuit Size M - Pink - JakartaNotebook.com
<a href=https://d2pa5gi5n2e1an.cloudfront.net/service/id/images/womens-fashion/price/11796/11796635/MF_baju_renang_wanita_muslimah_dewasa_baju_renang_perempuan_hijab_syar_i_Biru_M_1.jpg target=_blank><img class=lozad data-src=https://d2pa5gi5n2e1an.cloudfront.net/service/id/images/womens-fashion/price/11796/11796635/MF_baju_renang_wanita_muslimah_dewasa_baju_renang_perempuan_hijab_syar_i_Biru_M_1.jpg alt></a> Harga Celana Renang Pendek Hijab Wanita Original Murah Terbaru Oktober 2020 di Indonesia - Priceprice.com
<a href=https://jualbajurenang.com/wp-content/uploads/2017/01/Baju-Renang-Moderen-Modis-Untuk-Wanita.jpg target=_blank><img class=lozad data-src=https://jualbajurenang.com/wp-content/uploads/2017/01/Baju-Renang-Moderen-Modis-Untuk-Wanita.jpg alt></a> Baju Renang Modern Modis Untuk Wanita - Toko Baju Renang Online
<a href=https://gd.image-gmkt.com/li/261/916/1196916261.g_520-w_g.jpg target=_blank><img class=lozad data-src=https://gd.image-gmkt.com/li/261/916/1196916261.g_520-w_g.jpg alt></a> Qoo10 - Baju Renang Wanita : Pakaian Olahraga
<a href=http://www.katalogonlen.id/wp-content/uploads/2019/04/peralatan-renang.jpg target=_blank><img class=lozad data-src=http://www.katalogonlen.id/wp-content/uploads/2019/04/peralatan-renang.jpg alt></a> 11 Peralatan Renang Yang Sebaiknya Jangan Ketinggalan Saat Latihan Berenang - KatalogOnlen
<a href=https://3.bp.blogspot.com/-hbQWCFiMAnw/W3MHcmojvrI/AAAAAAAARb8/ElxH7lTheNwccA0c-GElJa47NdI1geJkwCLcBGAs/s1600/PUSAT%2BGROSIR%2BPERLENGKAPAN%2BRENANG%2B%2528Kolam%2Bkaret%252C%2BPelampung%252C%2BBan%2Brenang%252C%2BNeck%2Bring%2Bbayi%252C%2Bdll%2529%2B%25283%2529.jpg target=_blank><img class=lozad data-src=https://3.bp.blogspot.com/-hbQWCFiMAnw/W3MHcmojvrI/AAAAAAAARb8/ElxH7lTheNwccA0c-GElJa47NdI1geJkwCLcBGAs/s1600/PUSAT%2BGROSIR%2BPERLENGKAPAN%2BRENANG%2B%2528Kolam%2Bkaret%252C%2BPelampung%252C%2BBan%2Brenang%252C%2BNeck%2Bring%2Bbayi%252C%2Bdll%2529%2B%25283%2529.jpg alt></a> Pusat Grosir Perlengkapan Renang (Kolam karet, Pelampung, Ban renang, Neck ring bayi, dll) - Bang Izal Toy
<a href=https://s1.bukalapak.com/img/66062448671/s-330-330/data.jpeg.webp target=_blank><img class=lozad data-src=https://s1.bukalapak.com/img/66062448671/s-330-330/data.jpeg.webp alt></a> Jual Produk Perlengkapan Renang Paling Laris Wanita Murah dan Terlengkap Agustus 2020 | Bukalapak
<a href="https://i0.wp.com/narmadi.com/id/wp-content/uploads/2019/07/Renang-Muslimah-2.jpg?resize=607%2C361&ssl=1" target=_blank><img class=lozad data-src="https://i0.wp.com/narmadi.com/id/wp-content/uploads/2019/07/Renang-Muslimah-2.jpg?resize=607%2C361&ssl=1" alt></a> Memakai Baju Renang Muslimah Agar Tetap Cantik! Berikut Tips
<a href=https://brandedbabys.com/brandedbabys/asset/min1_SW-1012_20191205101056_pic1_SW-1012_6.jpg target=_blank><img class=lozad data-src=https://brandedbabys.com/brandedbabys/asset/min1_SW-1012_20191205101056_pic1_SW-1012_6.jpg alt></a> Brandedbabys
<a href=http://1.bp.blogspot.com/-OojDi4D_YmE/UpyUnelBtRI/AAAAAAAAACM/exraVnI9Qj8/s1600/Baju-Renang-Wanita1.png target=_blank><img class=lozad data-src=http://1.bp.blogspot.com/-OojDi4D_YmE/UpyUnelBtRI/AAAAAAAAACM/exraVnI9Qj8/s1600/Baju-Renang-Wanita1.png alt></a> Toko Peralatan Olahraga: Pakaian Renang
<a href=https://www.bajurenangmuslim.net/wp-content/uploads/2014/03/EDP-2106-perlengkapan-pakaian-renang-muslim-motif.jpg target=_blank><img class=lozad data-src=https://www.bajurenangmuslim.net/wp-content/uploads/2014/03/EDP-2106-perlengkapan-pakaian-renang-muslim-motif.jpg alt></a> Baju Renang Wanita Muslimah EDP-2106 | baju renang muslim
<a href=https://inkuiri.net/i/large/https%2Fs1.bukalapak.com%2Fimg%2F62598503081%2Flarge%2F1ac585a482be5a8570731ac97852fc3a2_baju_renang_muslimah_dewas.png target=_blank><img class=lozad data-src=https://inkuiri.net/i/large/https%2Fs1.bukalapak.com%2Fimg%2F62598503081%2Flarge%2F1ac585a482be5a8570731ac97852fc3a2_baju_renang_muslimah_dewas.png alt></a> baju renang muslimah dewasa baju renang wanita baju renang perempuan dewasa remaja baju renang cewe berkualitas - Busana Muslim Wanita » Baju Muslim & Perlengkapan Sholat » Fashion Wanita » - Bukalapak.com | inkuiri.com
<a href=https://media.karousell.com/media/photos/products/2019/07/19/baju_renang_muslimah_1563468315_48c59c03_progressive.jpg target=_blank><img class=lozad data-src=https://media.karousell.com/media/photos/products/2019/07/19/baju_renang_muslimah_1563468315_48c59c03_progressive.jpg alt></a> Baju Renang Muslimah, Olah Raga, Perlengkapan Olahraga Lainnya di Carousell
<a href=https://cf.shopee.co.id/file/c34699e265ec75ab7b5a9ab5e0af1a94 target=_blank><img class=lozad data-src=https://cf.shopee.co.id/file/c34699e265ec75ab7b5a9ab5e0af1a94 alt></a> Kacamata renang cewe anak perempuan anti fog anti embun warna pink perlengkapan renang anak wanita | Shopee Indonesia
<a href=https://dj7u9rvtp3yka.cloudfront.net/products/PIM-1550760016767-198309b7-cb45-4058-bf86-9cdfd055bf2b_v1-small.jpg target=_blank><img class=lozad data-src=https://dj7u9rvtp3yka.cloudfront.net/products/PIM-1550760016767-198309b7-cb45-4058-bf86-9cdfd055bf2b_v1-small.jpg alt></a> Baju Renang anak cewek - Mermaid swimsuit - baju renang mermaid - 4T 5T 6T 7T 8T 9T | Pakaian Renang Anak Perempuan | Zilingo Shopping Indonesia
<a href=https://thumb.viva.co.id/media/frontend/thumbs3/2010/04/29/88926_wanita_berenang_665_374.jpg target=_blank><img class=lozad data-src=https://thumb.viva.co.id/media/frontend/thumbs3/2010/04/29/88926_wanita_berenang_665_374.jpg alt></a> Daftar Peralatan Renang yang Wajib Anda Punya
<a href=https://my-test-11.slatic.net/p/103157173a1363ccd3e46a53d9b9309b.jpg_340x340q80.jpg_.webp target=_blank><img class=lozad data-src=https://my-test-11.slatic.net/p/103157173a1363ccd3e46a53d9b9309b.jpg_340x340q80.jpg_.webp alt></a> 2019 Baju Renang Bayi Balita Anak Gadis Ruffles Swan Perlengkapan Pakaian Renang Pantai Jumpsuit Pakaian | Lazada Indonesia
<a href=http://www.katalogonlen.id/wp-content/uploads/2019/04/renang1.jpeg target=_blank><img class=lozad data-src=http://www.katalogonlen.id/wp-content/uploads/2019/04/renang1.jpeg alt></a> 11 Peralatan Renang Yang Sebaiknya Jangan Ketinggalan Saat Latihan Berenang - KatalogOnlen
<a href=https://4.bp.blogspot.com/-OqhtSRIDS9E/W3L4OscOypI/AAAAAAAARa4/EBbZHAUNfe8OYkMugQIiFLPoRFk1QUTXACLcBGAs/s1600/PUSAT%2BGROSIR%2BPERLENGKAPAN%2BRENANG%2B%2528Kolam%2Bkaret%252C%2BPelampung%252C%2BBan%2Brenang%252C%2BNeck%2Bring%2Bbayi%252C%2Bdll%2529.jpg target=_blank><img class=lozad data-src=https://4.bp.blogspot.com/-OqhtSRIDS9E/W3L4OscOypI/AAAAAAAARa4/EBbZHAUNfe8OYkMugQIiFLPoRFk1QUTXACLcBGAs/s1600/PUSAT%2BGROSIR%2BPERLENGKAPAN%2BRENANG%2B%2528Kolam%2Bkaret%252C%2BPelampung%252C%2BBan%2Brenang%252C%2BNeck%2Bring%2Bbayi%252C%2Bdll%2529.jpg alt></a> Pusat Grosir Perlengkapan Renang (Kolam karet, Pelampung, Ban renang, Neck ring bayi, dll) - Bang Izal Toy
<a href=https://www.bajurenangmuslim.net/wp-content/uploads/2014/08/EDP-2122-perlengkapan-busana-renang-muslimah-edora.jpg target=_blank><img class=lozad data-src=https://www.bajurenangmuslim.net/wp-content/uploads/2014/08/EDP-2122-perlengkapan-busana-renang-muslimah-edora.jpg alt></a> Baju Renang Wanita Muslimah EDP-2122 | baju renang muslim
<a href=http://4.bp.blogspot.com/-vc8IwoyDPxc/VgCwnFC-0KI/AAAAAAAAAI0/xopx_9YnPCY/s1600/Baju-Renang.jpg target=_blank><img class=lozad data-src=http://4.bp.blogspot.com/-vc8IwoyDPxc/VgCwnFC-0KI/AAAAAAAAAI0/xopx_9YnPCY/s1600/Baju-Renang.jpg alt></a> <NAME> ( Berenang ): Perlengkapan
<a href=https://www.jakartanotebook.com/images/products/99/63/31881/12/baju-renang-wanita-diving-style-swimsuit-size-m-pink-4.jpg target=_blank><img class=lozad data-src=https://www.jakartanotebook.com/images/products/99/63/31881/12/baju-renang-wanita-diving-style-swimsuit-size-m-pink-4.jpg alt></a> Baju Renang Wanita Diving Style Swimsuit Size M - Pink - JakartaNotebook.com
<a href=https://ae01.alicdn.com/kf/HLB1CpzDXJjvK1RjSspiq6AEqXXaE/20-Pasang-Plastik-Bikini-Klip-Kancing-Kait-Bra-Tali-Baju-Renang-Gesper-Pakaian-Dalam-Wanita-Perlengkapan.jpg_q50.jpg target=_blank><img class=lozad data-src=https://ae01.alicdn.com/kf/HLB1CpzDXJjvK1RjSspiq6AEqXXaE/20-Pasang-Plastik-Bikini-Klip-Kancing-Kait-Bra-Tali-Baju-Renang-Gesper-Pakaian-Dalam-Wanita-Perlengkapan.jpg_q50.jpg alt></a> 20 Pasang Plastik Bikini Klip Kancing Kait Bra Tali Baju Renang Gesper Pakaian Dalam Wanita Perlengkapan 14 Mm|Gesper & Kait| - AliExpress
<a href=https://jualbajurenang.com/wp-content/uploads/2017/01/28.jpg target=_blank><img class=lozad data-src=https://jualbajurenang.com/wp-content/uploads/2017/01/28.jpg alt></a> Mall Sebagai Tempat Jual Baju Renang Wanita Paling Ngetrend - Toko Baju Renang Online
<a href="https://ik.imagekit.io/carro/jualo/original/19500691/bikini-set-halter-nec-renang-dan-perlengkapan-renang-19500691.jpg?v=1554302891" target=_blank><img class=lozad data-src="https://ik.imagekit.io/carro/jualo/original/19500691/bikini-set-halter-nec-renang-dan-perlengkapan-renang-19500691.jpg?v=1554302891" alt></a> Bikini Set Halter Neck Biru | Surabaya | Jualo
<a href=https://fns.modanisa.com/r/pro2/2020/03/09/z-mama-onlugu-lacivert-lc-waikiki-1526320-1.jpg target=_blank><img class=lozad data-src=https://fns.modanisa.com/r/pro2/2020/03/09/z-mama-onlugu-lacivert-lc-waikiki-1526320-1.jpg alt></a> Biru Navy - Perlengkapan Bayi
<a href=https://s1.bukalapak.com/img/15642411232/s-330-330/data.jpeg.webp target=_blank><img class=lozad data-src=https://s1.bukalapak.com/img/15642411232/s-330-330/data.jpeg.webp alt></a> Jual Produk Kacamata Renang Pria Wanita Perlengkapan Murah dan Terlengkap Agustus 2020 | Bukalapak
<a href=https://static.tokopedia.net/blog/wp-content/uploads/2020/01/2.-Kacamata-Renang.jpg target=_blank><img class=lozad data-src=https://static.tokopedia.net/blog/wp-content/uploads/2020/01/2.-Kacamata-Renang.jpg alt></a> 10 Daftar Perlengkapan Renang Anak yang Wajib Ada
<a href="https://lh3.googleusercontent.com/OD1rSoWlMFug_vLtHs7Mn5z_5T3fgf1JyxagPCmfnoxLUy6z2udjmJVxqNnoN3d8vNZ-sigUZSdi1I6t=w1080-h608-p-no-v0" target=_blank><img class=lozad data-src="https://lh3.googleusercontent.com/OD1rSoWlMFug_vLtHs7Mn5z_5T3fgf1JyxagPCmfnoxLUy6z2udjmJVxqNnoN3d8vNZ-sigUZSdi1I6t=w1080-h608-p-no-v0" alt></a> Toko pakaian dalam pria dan wanita, baju renang, perlengkapan bayi - Ladang Pokok
<a href=https://www.mandorkolam.com/wp-content/uploads/2020/06/kolam-renang-di-Pati.png target=_blank><img class=lozad data-src=https://www.mandorkolam.com/wp-content/uploads/2020/06/kolam-renang-di-Pati.png alt></a> Perlengkapan Renang dan Fungsinya - mandorkolam.com
<a href=https://asset.telunjuk.co.id/ri/180/200/terbaru-baju-renang-wanita-muslim-dewasa-baju-renang-perempuan-dewasa-muslimah-perlengkapan-renang_938fcaca2c3ddd32914f27384e2efd2c.jpg target=_blank><img class=lozad data-src=https://asset.telunjuk.co.id/ri/180/200/terbaru-baju-renang-wanita-muslim-dewasa-baju-renang-perempuan-dewasa-muslimah-perlengkapan-renang_938fcaca2c3ddd32914f27384e2efd2c.jpg alt></a> Shopee: Jual olshop.tidar TERBARU BAJU RENANG WANITA PEREMPUAN DEWASA EDORA DV-DW - S PERLENGKAPAN TERLARIS DAN MURAH
<a href=https://png.pngtree.com/element_our/20190602/ourmid/pngtree-yellow-beach-swimsuit-image_1419346.jpg target=_blank><img class=lozad data-src=https://png.pngtree.com/element_our/20190602/ourmid/pngtree-yellow-beach-swimsuit-image_1419346.jpg alt></a> Gambar Baju Renang Pantai Png, Vektor, PSD, dan Clipart Dengan Latar Belakang Transparan untuk Download Gratis | Pngtree
<a href=https://e7.pngegg.com/pngimages/123/708/png-clipart-swim-briefs-protective-gear-in-sports-underpants-jock-straps-gorin-guard-sports-undergarment.png target=_blank><img class=lozad data-src=https://e7.pngegg.com/pngimages/123/708/png-clipart-swim-briefs-protective-gear-in-sports-underpants-jock-straps-gorin-guard-sports-undergarment.png alt></a> Celana renang Perlengkapan pelindung dalam celana olahraga Jock Straps, pelindung gorin, lain-lain, olahraga png | PNGEgg
<a href=https://moesama.net/wp-content/uploads/sites/4/2020/04/perlengkapan-renang-3.jpg target=_blank><img class=lozad data-src=https://moesama.net/wp-content/uploads/sites/4/2020/04/perlengkapan-renang-3.jpg alt></a> Perlengkapan Renang - Lengkap Agar Latihan Lebih Optimal - Moesama
<a href=https://ds393qgzrxwzn.cloudfront.net/resize/m500x500/cat1/img/images/0/HRlvPgITX0.jpg target=_blank><img class=lozad data-src=https://ds393qgzrxwzn.cloudfront.net/resize/m500x500/cat1/img/images/0/HRlvPgITX0.jpg alt></a> Cantik Dan Modis Saat Berenang Dengan 9 Rekomendasi Baju Renang Wanita Muslimah Syar’i
<a href=https://penjaskes.co.id/wp-content/uploads/2020/05/bumil-1.png target=_blank><img class=lozad data-src=https://penjaskes.co.id/wp-content/uploads/2020/05/bumil-1.png alt></a> Inilah, Manfaat Renang Untuk Wanita Serta Ibu Hamil | Penjaskes.Co.Id
<a href="https://apollo-singapore.akamaized.net/v1/files/b30bh7i8wlxw2-ID/image;s=272x0" target=_blank><img class=lozad data-src="https://apollo-singapore.akamaized.net/v1/files/b30bh7i8wlxw2-ID/image;s=272x0" alt></a> Baju Renang - Perlengkapan Bayi & Anak Terlengkap di Bali - OLX.co.id
<a href=https://get.wallhere.com/photo/sports-women-outdoors-women-sea-water-shore-sand-beach-coast-surfing-swimming-vacation-season-ocean-wave-body-of-water-wind-wave-surfing-equipment-and-supplies-boardsport-water-sport-surface-water-sports-skimboarding-105101.jpg target=_blank><img class=lozad data-src=https://get.wallhere.com/photo/sports-women-outdoors-women-sea-water-shore-sand-beach-coast-surfing-swimming-vacation-season-ocean-wave-body-of-water-wind-wave-surfing-equipment-and-supplies-boardsport-water-sport-surface-water-sports-skimboarding-105101.jpg alt></a> Wallpaper : wanita di luar ruangan, laut, pantai, pasir, renang, liburan, musim, lautan, gelombang, badan air, ombak, peralatan dan perlengkapan berselancar, boardsport, olahraga Air, olahraga air permukaan, Skimboarding 3000x1890 - WallpaperManiac -
<a href=https://img.priceza.co.id/img1/130003/0036/130003-20190212052112-10996860119852200.jpg target=_blank><img class=lozad data-src=https://img.priceza.co.id/img1/130003/0036/130003-20190212052112-10996860119852200.jpg alt></a> Daftar harga Baju Renang Diving Wanita Rok Lengan Panjang Bulan Oktober 2020
<a href=https://sc02.alicdn.com/kf/HTB1Cm_eRXXXXXaPXpXXq6xXFXXXU.jpg_350x350.jpg target=_blank><img class=lozad data-src=https://sc02.alicdn.com/kf/HTB1Cm_eRXXXXXaPXpXXq6xXFXXXU.jpg_350x350.jpg alt></a> Renang Tahan Air Earbud Gel Silika Penyumbat Telinga Nyaman Dewasa Pria Dan Wanita Anak Renang Penyumbat Telinga - Buy Renang Anti-air Earplugs,Perlengkapan Renang Telinga Plugs,Anti-air Silica Gel Supersoft Earplugs Product on Alibaba.com
<a href=https://tap-assets-prod.dexecure.net/wp-content/uploads/sites/24/2017/11/model-baju-renang-ibu-hamil.jpg target=_blank><img class=lozad data-src=https://tap-assets-prod.dexecure.net/wp-content/uploads/sites/24/2017/11/model-baju-renang-ibu-hamil.jpg alt></a> Baju renang ibu hamil dengan yang cantik, Bunda mau coba yang mana? | theAsianparent Indonesia
<a href=https://media.karousell.com/media/photos/products/2019/09/10/baju_renang_wanita_1568118751_87125311_progressive.jpg target=_blank><img class=lozad data-src=https://media.karousell.com/media/photos/products/2019/09/10/baju_renang_wanita_1568118751_87125311_progressive.jpg alt></a> Baju Renang wanita, Olah Raga, Perlengkapan Olahraga Lainnya di Carousell
<a href=http://images.cache.inkuiri.com/i/large/https%2Fs1.bukalapak.com%2Fimg%2F16663738012%2Flarge%2F1b62168f2db6e102a370d596e80db7a58_dijual_baju_renang_anak_7_.png target=_blank><img class=lozad data-src=http://images.cache.inkuiri.com/i/large/https%2Fs1.bukalapak.com%2Fimg%2F16663738012%2Flarge%2F1b62168f2db6e102a370d596e80db7a58_dijual_baju_renang_anak_7_.png alt></a> dijual baju renang anak 7 12th baju renang wanita muslimah baju renang anak tanggung baju renang anak sd murah - Busana Muslim Wanita » Baju Muslim & Perlengkapan Sholat » Fashion Wanita » -
<a href="https://i0.wp.com/swimmingpoolidea.com/wp-content/uploads/2019/06/dokter.jpg?resize=383%2C280&ssl=1" target=_blank><img class=lozad data-src="https://i0.wp.com/swimmingpoolidea.com/wp-content/uploads/2019/06/dokter.jpg?resize=383%2C280&ssl=1" alt></a> Swimming Pool Idea Magazine I Majalah Kolam Renang Indonesia | SwimmingPool Idea
<a href=https://olahragapedia.com/wp-content/uploads/2019/09/Teknik-Renang-Untuk-Lomba-220x134.jpg target=_blank><img class=lozad data-src=https://olahragapedia.com/wp-content/uploads/2019/09/Teknik-Renang-Untuk-Lomba-220x134.jpg alt></a> 12 Peralatan Renang Lengkap untuk Anak dan Dewasa - OlahragaPedia.com
<a href=https://www.rjstore.co.id/5561-large_default/baju-renang-wanita-nay-muslimah-nsp-007-pink.jpg target=_blank><img class=lozad data-src=https://www.rjstore.co.id/5561-large_default/baju-renang-wanita-nay-muslimah-nsp-007-pink.jpg alt></a> Jual Baju Renang Wanita Nay Muslimah NSP 007 Pink Online - RJSTORE.CO.ID: Melayani Dengan Hati
<a href=https://hobikusport.com/wp-content/uploads/2019/07/kolam-renang-anak-300x169.jpg target=_blank><img class=lozad data-src=https://hobikusport.com/wp-content/uploads/2019/07/kolam-renang-anak-300x169.jpg alt></a> 19 Perlengkapan Renang Ini Bikin Betah Berenang (Tanpa Pakai Semua) | HobikuSport.Com
<a href="https://oss.mommyasia.id/photo/5cbffc4867bbde0beabb14d1?x-oss-process=style/_l" target=_blank><img class=lozad data-src="https://oss.mommyasia.id/photo/5cbffc4867bbde0beabb14d1?x-oss-process=style/_l" alt></a> Rekomendasi Kacamata Renang Terbaik dan Tips Memilihnya, Ada yang untuk Mata Minus Juga!
<a href="https://i0.wp.com/narmadi.com/id/wp-content/uploads/2019/07/baju-renang-wanita-2.jpg?resize=625%2C353&ssl=1" target=_blank><img class=lozad data-src="https://i0.wp.com/narmadi.com/id/wp-content/uploads/2019/07/baju-renang-wanita-2.jpg?resize=625%2C353&ssl=1" alt></a> Mengenal 7 Jenis Baju Renang Wanita Dan Asal Usulnya
<a href="https://ik.imagekit.io/carro/jualo/original/19498443/bikini-set-polos-tanp-renang-dan-perlengkapan-renang-19498443.jpg?v=1554286173" target=_blank><img class=lozad data-src="https://ik.imagekit.io/carro/jualo/original/19498443/bikini-set-polos-tanp-renang-dan-perlengkapan-renang-19498443.jpg?v=1554286173" alt></a> Bikini Set Polos Tanpa Pad | Surabaya | Jualo
<a href=https://cf.shopee.co.id/file/96b9b8254d7f77f56d10676a3da01d0d target=_blank><img class=lozad data-src=https://cf.shopee.co.id/file/96b9b8254d7f77f56d10676a3da01d0d alt></a> Free Ongkir PROMO: BAJU RENANG MUSLIMAH ES ML DW 108, PAKAIAN RENANG MUSLIMAH, PERLENGKAPAN RENANG | Shopee Indonesia
<a href=https://d2pa5gi5n2e1an.cloudfront.net/service/id/images/womens-fashion/price/11028/11028957/MF_PROMO_Perlengkapan_Olahraga_Baju_renang_dewasa_muslimah_baju_renang_wanita_hijab_1.jpg target=_blank><img class=lozad data-src=https://d2pa5gi5n2e1an.cloudfront.net/service/id/images/womens-fashion/price/11028/11028957/MF_PROMO_Perlengkapan_Olahraga_Baju_renang_dewasa_muslimah_baju_renang_wanita_hijab_1.jpg alt></a> Harga Celana Renang Pendek Hijab Wanita Original Murah Terbaru Oktober 2020 di Indonesia - Priceprice.com
<a href=https://my-test-11.slatic.net/p/d2d6982660f46347617aebefa676a484.jpg target=_blank><img class=lozad data-src=https://my-test-11.slatic.net/p/d2d6982660f46347617aebefa676a484.jpg alt></a> Jual Topi Renang | lazada.co.id
<a href="https://img.my-best.id/press_component/images/c0daff2f9b439aa264ead4cad5d28991.jpg?ixlib=rails-3.1.0&auto=compress&q=70&lossless=0&w=690&fit=max" target=_blank><img class=lozad data-src="https://img.my-best.id/press_component/images/c0daff2f9b439aa264ead4cad5d28991.jpg?ixlib=rails-3.1.0&auto=compress&q=70&lossless=0&w=690&fit=max" alt></a> 10 Rekomendasi Baju Renang Terbaik untuk Wanita (Terbaru Tahun 2020) | mybest
<a href=https://p.ipricegroup.com/12e2513acae641c2dce66bc968f4aa4417ee7420_0.jpg target=_blank><img class=lozad data-src=https://p.ipricegroup.com/12e2513acae641c2dce66bc968f4aa4417ee7420_0.jpg alt></a> Pakaian Renang Jumbo Pria di Indonesia | Harga Jual Pakaian Renang Jumbo Online
<a href=http://www.rainycollections.com/wp-content/uploads/2017/09/baju-renang-muslim-murah-110.jpg target=_blank><img class=lozad data-src=http://www.rainycollections.com/wp-content/uploads/2017/09/baju-renang-muslim-murah-110.jpg alt></a> Muslim Dewasa – Page 3 – Rainycollections
<a href=https://www.jakartanotebook.com/images/products/99/1020/40857/6/hanyimidoo-baju-renang-muslim-anak-perempuan-size-4xl-160-cm-h2010-blue-11.jpg target=_blank><img class=lozad data-src=https://www.jakartanotebook.com/images/products/99/1020/40857/6/hanyimidoo-baju-renang-muslim-anak-perempuan-size-4xl-160-cm-h2010-blue-11.jpg alt></a> HANYIMIDOO Baju Renang Muslim Anak Perempuan Size 4XL 160 CM - H2010 - Blue - JakartaNotebook.com</p></article></div><div class="article bottom"><section class="article navigation"><p><a class=link href=/dewan/post/perlengkapan-tni-bandung/><span class="iconfont icon-article"></span>Perlengkapan Tni Bandung</a></p><p><a class=link href=/dewan/post/perlengkapan-bayi-yang-harus-dibeli-pertama-kali/><span class="iconfont icon-article"></span>Perlengkapan Bayi Yang Harus Dibeli Pertama Kali</a></p></section></div></section><section id=footer><div class=footer-wrap><p class=copyright>©2020</p><p class=powerby><span>Powered by </span><a href=https://gohugo.io target=_blank>Hugo</a><span> & </span><a href=https://themes.gohugo.io/hugo-notepadium/ target=_blank>Notepadium</a></p></div></section><script>const observer=lozad();observer.observe();</script><script type=text/javascript src=//therapistpopulationcommentary.com/7c/d1/05/7cd10503fd96c0ba6a28e1e77338cb7d.js></script></body></html>
|
Below is an extract from a Swift program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Swift code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Swift concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., protocols, extensions). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Swift. It should be similar to a school exercise, a tutorial, or a Swift course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Swift. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
//
// ArtistEntityImage.swift
//
// Create by <NAME> on 17/2/2017
// Copyright © 2017. All rights reserved.
// Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport
import Foundation
struct ArtistImageEntity {
var height : Int!
var url : String!
var width : Int!
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: [String:Any]){
height = dictionary["height"] as? Int
url = dictionary["url"] as? String
width = dictionary["width"] as? Int
}
/**
* Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> [String:Any]
{
var dictionary = [String:Any]()
if height != nil{
dictionary["height"] = height
}
if url != nil{
dictionary["url"] = url
}
if width != nil{
dictionary["width"] = width
}
return dictionary
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
swift
| 2 |
//
// ArtistEntityImage.swift
//
// Create by <NAME> on 17/2/2017
// Copyright © 2017. All rights reserved.
// Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport
import Foundation
struct ArtistImageEntity {
var height : Int!
var url : String!
var width : Int!
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: [String:Any]){
height = dictionary["height"] as? Int
url = dictionary["url"] as? String
width = dictionary["width"] as? Int
}
/**
* Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> [String:Any]
{
var dictionary = [String:Any]()
if height != nil{
dictionary["height"] = height
}
if url != nil{
dictionary["url"] = url
}
if width != nil{
dictionary["width"] = width
}
return dictionary
}
}
|
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical PHP concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
<?php
namespace App\Http\Controllers;
use App\TInquire;
use App\TPaquete;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request)
{
$request->user()->authorizeRoles(['admin', 'sales']);
$inquire = TInquire::all();
$package = TPaquete::all();
return view('page.home', ['inquire'=>$inquire, 'package'=>$package]);
}
public function remove_inquire(Request $request)
{
$request->user()->authorizeRoles(['admin', 'sales']);
$mails = $_POST['txt_mails'];
$inquires = explode(',', $mails);
foreach ($inquires as $inquire){
$p_estado = TInquire::FindOrFail($inquire);
$p_estado->estado = 3;
$p_estado->save();
}
}
public function sent_inquire(Request $request)
{
$request->user()->authorizeRoles(['admin', 'sales']);
$mails = $_POST['txt_mails'];
$inquires = explode(',', $mails);
foreach ($inquires as $inquire){
$p_estado = TInquire::FindOrFail($inquire);
$p_estado->estado = 2;
$p_estado->save();
}
// return redirect()->route('message_path', [$p_inquire->id, $idpackage]);
}
public function restore_inquire(Request $request)
{
$request->user()->authorizeRoles(['admin', 'sales']);
$mails = $_POST['txt_mails'];
$inquires = explode(',', $mails);
foreach ($inquires as $inquire){
$p_estado = TInquire::FindOrFail($inquire);
$p_estado->estado = 0;
$p_estado->save();
}
}
public function archive_inquire(Request $request)
{
$request->user()->authorizeRoles(['admin', 'sales']);
$mails = $_POST['txt_mails'];
$inquires = explode(',', $mails);
foreach ($inquires as $inquire){
$p_est
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
php
| 2 |
<?php
namespace App\Http\Controllers;
use App\TInquire;
use App\TPaquete;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request)
{
$request->user()->authorizeRoles(['admin', 'sales']);
$inquire = TInquire::all();
$package = TPaquete::all();
return view('page.home', ['inquire'=>$inquire, 'package'=>$package]);
}
public function remove_inquire(Request $request)
{
$request->user()->authorizeRoles(['admin', 'sales']);
$mails = $_POST['txt_mails'];
$inquires = explode(',', $mails);
foreach ($inquires as $inquire){
$p_estado = TInquire::FindOrFail($inquire);
$p_estado->estado = 3;
$p_estado->save();
}
}
public function sent_inquire(Request $request)
{
$request->user()->authorizeRoles(['admin', 'sales']);
$mails = $_POST['txt_mails'];
$inquires = explode(',', $mails);
foreach ($inquires as $inquire){
$p_estado = TInquire::FindOrFail($inquire);
$p_estado->estado = 2;
$p_estado->save();
}
// return redirect()->route('message_path', [$p_inquire->id, $idpackage]);
}
public function restore_inquire(Request $request)
{
$request->user()->authorizeRoles(['admin', 'sales']);
$mails = $_POST['txt_mails'];
$inquires = explode(',', $mails);
foreach ($inquires as $inquire){
$p_estado = TInquire::FindOrFail($inquire);
$p_estado->estado = 0;
$p_estado->save();
}
}
public function archive_inquire(Request $request)
{
$request->user()->authorizeRoles(['admin', 'sales']);
$mails = $_POST['txt_mails'];
$inquires = explode(',', $mails);
foreach ($inquires as $inquire){
$p_estado = TInquire::FindOrFail($inquire);
$p_estado->estado = 5;
$p_estado->save();
}
}
public function trash(Request $request)
{
$request->user()->authorizeRoles(['admin', 'sales']);
$inquire = TInquire::all();
$package = TPaquete::all();
return view('page.home-trash', ['inquire'=>$inquire, 'package'=>$package]);
}
public function send(Request $request)
{
$request->user()->authorizeRoles(['admin', 'sales']);
$inquire = TInquire::all();
$package = TPaquete::all();
return view('page.home-send', ['inquire'=>$inquire, 'package'=>$package]);
}
public function archive(Request $request)
{
$request->user()->authorizeRoles(['admin', 'sales']);
$inquire = TInquire::all();
$package = TPaquete::all();
return view('page.home-archive', ['inquire'=>$inquire, 'package'=>$package]);
}
public function save_compose(Request $request)
{
$request->user()->authorizeRoles(['admin', 'sales']);
$idpackage = $_POST['id_package'];
$name = $_POST['txt_name'];
$email = $_POST['txt_email'];
$travellers = $_POST['txt_travellers'];
$date = $_POST['txt_date'];
$p_inquire = new TInquire();
$p_inquire->name = $name;
$p_inquire->email = $email;
$p_inquire->traveller = $travellers;
$p_inquire->traveldate = $date;
$p_inquire->id_paquetes = $idpackage;
$p_inquire->idusuario = $request->user()->id;
$p_inquire->estado = 1;
if ($p_inquire->save()){
return redirect()->route('message_path', [$p_inquire->id, $idpackage]);
}
}
public function save_payment(Request $request)
{
$request->user()->authorizeRoles(['admin', 'sales']);
$idpackage = $_POST['id_package'];
$name = $_POST['txt_name'];
$email = $_POST['txt_email'];
$travellers = $_POST['txt_travellers'];
$date = $_POST['txt_date'];
$price = $_POST['txt_price'];
$p_inquire = new TInquire();
$p_inquire->name = $name;
$p_inquire->email = $email;
$p_inquire->traveller = $travellers;
$p_inquire->traveldate = $date;
$p_inquire->id_paquetes = $idpackage;
$p_inquire->idusuario = $request->user()->id;
$p_inquire->price = $price;
$p_inquire->estado = 4;
if ($p_inquire->save()){
return redirect()->route('payment_show_path', $p_inquire->id)->with('status', 'Por favor registre los pagos de su cliente.');
}
}
}
|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package com.gonwan.springjpatest.runner;
import com.gonwan.springjpatest.model.TUser;
import com.gonwan.springjpatest.repository.TUserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/*
* MySQL with MySQL driver should be used.
* Or the fractional seconds is truncated, since MariaDB does not honor sendFractionalSeconds=true.
*/
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
//@Component
public class JpaRunner2 implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(JpaRunner2.class);
@Autowired
private ApplicationContext appContext;
@Autowired
private TUserRepository userRepository;
private TUser findUser(Long id) {
return userRepository.findById(id).orElse(null);
}
@Transactional
public Long init() {
userRepository.deleteAllInBatch();
TUser user = new TUser();
user.setUsername("11111user");
user.setPassword("<PASSWORD>");
user = userRepository.save(user);
logger.info("saved user: {}", user);
return user.getId();
}
@Override
public void run(String... args) throws Exception {
logger.info("--- running test2 ---");
JpaRunner2 jpaRunner2 = appContext.getBean(JpaRunner2.class);
Long id = jpaRunner2.init();
ExecutorService es = Executors.newFixedThreadPool(2);
/* user1 */
es.execute(() -> {
TUser u1 = findU
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
java
| 2 |
package com.gonwan.springjpatest.runner;
import com.gonwan.springjpatest.model.TUser;
import com.gonwan.springjpatest.repository.TUserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/*
* MySQL with MySQL driver should be used.
* Or the fractional seconds is truncated, since MariaDB does not honor sendFractionalSeconds=true.
*/
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
//@Component
public class JpaRunner2 implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(JpaRunner2.class);
@Autowired
private ApplicationContext appContext;
@Autowired
private TUserRepository userRepository;
private TUser findUser(Long id) {
return userRepository.findById(id).orElse(null);
}
@Transactional
public Long init() {
userRepository.deleteAllInBatch();
TUser user = new TUser();
user.setUsername("11111user");
user.setPassword("<PASSWORD>");
user = userRepository.save(user);
logger.info("saved user: {}", user);
return user.getId();
}
@Override
public void run(String... args) throws Exception {
logger.info("--- running test2 ---");
JpaRunner2 jpaRunner2 = appContext.getBean(JpaRunner2.class);
Long id = jpaRunner2.init();
ExecutorService es = Executors.newFixedThreadPool(2);
/* user1 */
es.execute(() -> {
TUser u1 = findUser(id);
u1.setPassword("<PASSWORD>");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
/* ignore */
}
try {
userRepository.save(u1);
} catch (DataAccessException e) {
logger.info("user1 error", e);
logger.info("user1 after error: {}", findUser(id));
return;
}
logger.info("user1 finished: {}", findUser(id));
});
/* user2 */
es.execute(() -> {
TUser u2 = findUser(id);
u2.setPassword("<PASSWORD>");
try {
userRepository.save(u2);
} catch (DataAccessException e) {
logger.info("user2 error", e);
logger.info("user2 after error: {}", findUser(id));
return;
}
logger.info("user2 finished: {}", findUser(id));
});
/* clean up */
es.shutdown();
try {
es.awaitTermination(10, TimeUnit.MINUTES);
} catch (InterruptedException e) {
logger.info("interrupted", e);
}
}
}
|
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical JavaScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
const PubSub = require('../helpers/pub_sub.js')
const SelectInstumentView = function (element) {
this.element = element;
};
SelectInstumentView.prototype.bindEvents = function () {
PubSub.subscribe("InstrumentFamilies:all-instruments", (instrumentData) => {
const allInstruments = instrumentData.detail;
this.createDropDown(allInstruments)
});
this.element.addEventListener('change', (event) => {
const instrumentIndex = event.target.value;
PubSub.publish('SelectInstumentView:instrument-index', instrumentIndex);
console.log('instrument-index', instrumentIndex);
});
};
SelectInstumentView.prototype.createDropDown = function (instrumentData) {
instrumentData.forEach((instrument, index) => {
const option = document.createElement('option');
option.textContent = instrument.name;
option.value = index;
this.element.appendChild(option)
})
};
module.exports = SelectInstumentView;
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
javascript
| 2 |
const PubSub = require('../helpers/pub_sub.js')
const SelectInstumentView = function (element) {
this.element = element;
};
SelectInstumentView.prototype.bindEvents = function () {
PubSub.subscribe("InstrumentFamilies:all-instruments", (instrumentData) => {
const allInstruments = instrumentData.detail;
this.createDropDown(allInstruments)
});
this.element.addEventListener('change', (event) => {
const instrumentIndex = event.target.value;
PubSub.publish('SelectInstumentView:instrument-index', instrumentIndex);
console.log('instrument-index', instrumentIndex);
});
};
SelectInstumentView.prototype.createDropDown = function (instrumentData) {
instrumentData.forEach((instrument, index) => {
const option = document.createElement('option');
option.textContent = instrument.name;
option.value = index;
this.element.appendChild(option)
})
};
module.exports = SelectInstumentView;
|
Below is an extract from a Swift program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Swift code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Swift concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., protocols, extensions). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Swift. It should be similar to a school exercise, a tutorial, or a Swift course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Swift. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
//
// AMapPoiResultTable.swift
// SHKit
//
// Created by hsh on 2018/12/12.
// Copyright © 2018 hsh. All rights reserved.
//
import UIKit
import AMapSearchKit
//位置选点中表格视图控件
public protocol AMapPoiResultTableDelegate {
//选择某个POI
func didTableSelectedChanged(selectedPoi:AMapPOI)
//点击加载更多
func didLoadMoreBtnClick()
//点击定位
func didPositionUserLocation()
}
public class AMapPoiResultTable: UIView,UITableViewDataSource,UITableViewDelegate,AMapSearchDelegate {
//MARK
public var delegate:AMapPoiResultTableDelegate! //搜索类的代理
private var tableView:UITableView!
private var moreBtn:UIButton! //更多按钮
private var currentAdress:String! //当前位置
private var isFromMoreBtn:Bool = false //更多按钮的点击记录
private var searchPoiArray = NSMutableArray() //搜索结果的视图
private var selectedIndexPath:NSIndexPath! //选中的行
// MARK: - Load
override init(frame: CGRect) {
super.init(frame: frame);
self.backgroundColor = UIColor.white;
tableView = UITableView.initWith(UITableViewStyle.plain, dataSource: self, delegate: self, rowHeight: 50, separate: UITableViewCellSeparatorStyle.singleLine, superView: self);
tableView.mas_makeConstraints { (maker) in
maker?.left.top()?.right()?.bottom()?.mas_equalTo()(self);
}
//初始化footer
self.initFooter()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Delegate
//搜索的结果返回
public func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {
if self.isFromMoreBtn == true {
self.isFromMoreBtn = false
}else{
self.searchPoiArray.removeAllObjects();
self.moreBtn .setTitle("更多...", for: UIControlState.
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
swift
| 2 |
//
// AMapPoiResultTable.swift
// SHKit
//
// Created by hsh on 2018/12/12.
// Copyright © 2018 hsh. All rights reserved.
//
import UIKit
import AMapSearchKit
//位置选点中表格视图控件
public protocol AMapPoiResultTableDelegate {
//选择某个POI
func didTableSelectedChanged(selectedPoi:AMapPOI)
//点击加载更多
func didLoadMoreBtnClick()
//点击定位
func didPositionUserLocation()
}
public class AMapPoiResultTable: UIView,UITableViewDataSource,UITableViewDelegate,AMapSearchDelegate {
//MARK
public var delegate:AMapPoiResultTableDelegate! //搜索类的代理
private var tableView:UITableView!
private var moreBtn:UIButton! //更多按钮
private var currentAdress:String! //当前位置
private var isFromMoreBtn:Bool = false //更多按钮的点击记录
private var searchPoiArray = NSMutableArray() //搜索结果的视图
private var selectedIndexPath:NSIndexPath! //选中的行
// MARK: - Load
override init(frame: CGRect) {
super.init(frame: frame);
self.backgroundColor = UIColor.white;
tableView = UITableView.initWith(UITableViewStyle.plain, dataSource: self, delegate: self, rowHeight: 50, separate: UITableViewCellSeparatorStyle.singleLine, superView: self);
tableView.mas_makeConstraints { (maker) in
maker?.left.top()?.right()?.bottom()?.mas_equalTo()(self);
}
//初始化footer
self.initFooter()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Delegate
//搜索的结果返回
public func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {
if self.isFromMoreBtn == true {
self.isFromMoreBtn = false
}else{
self.searchPoiArray.removeAllObjects();
self.moreBtn .setTitle("更多...", for: UIControlState.normal);
self.moreBtn.isEnabled = true;
}
//不可点击
if response.pois.count == 0 {
self.moreBtn .setTitle("没有数据了...", for: UIControlState.normal);
self.moreBtn.isEnabled = true;
}
searchPoiArray.addObjects(from:response.pois);
self.tableView.reloadData()
}
public func onReGeocodeSearchDone(_ request: AMapReGeocodeSearchRequest!, response: AMapReGeocodeSearchResponse!) {
if response.regeocode != nil {
self.currentAdress = response.regeocode.formattedAddress;//反编译的结果
let indexPath = NSIndexPath.init(row: 0, section: 0);
self.tableView.reloadRows(at: [indexPath as IndexPath], with: UITableViewRowAnimation.automatic);
}
}
// MARK: - Delegate
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath);
cell?.accessoryType = .checkmark;
self.selectedIndexPath = indexPath as NSIndexPath;
//选中当前位置
if (indexPath.section == 0) {
self.delegate.didPositionUserLocation()
return;
}
//选中其他结果
let selectedPoi = self.searchPoiArray[indexPath.row] as? AMapPOI;
if (self.delegate != nil&&selectedPoi != nil){
delegate.didTableSelectedChanged(selectedPoi: selectedPoi!);
}
}
public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath);
cell?.accessoryType = .none;
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let reuseIndentifier = "reuseIndentifier";
var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: reuseIndentifier);
if cell == nil {
cell = UITableViewCell.init(style: .subtitle, reuseIdentifier: reuseIndentifier)
}
if (indexPath.section == 0) {
cell!.textLabel?.text = "[位置]";
cell!.detailTextLabel?.text = self.currentAdress;
}else{
let poi:AMapPOI = self.searchPoiArray[indexPath.row] as! AMapPOI;
cell!.textLabel?.text = poi.name;
cell!.detailTextLabel?.text = poi.address;
}
if (self.selectedIndexPath != nil &&
self.selectedIndexPath.section == indexPath.section &&
self.selectedIndexPath.row == indexPath.row) {
cell!.accessoryType = .checkmark;
}else{
cell!.accessoryType = .none;
}
return cell!;
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section == 0) {
return 1;
}else{
return self.searchPoiArray.count;
}
}
public func numberOfSections(in tableView: UITableView) -> Int {
return 2;
}
// MARK: - Private
private func initFooter()->Void{
let footer = SHBorderView.init(frame: CGRect(x: 0, y: 0, width: ScreenSize().width, height: 60));
footer.borderStyle = 9;
let btn = UIButton.initTitle("更多...", textColor: UIColor.black, back: UIColor.white, font: kFont(14), super: footer);
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.center;
btn.addTarget(self, action: #selector(moreBtnClick), for: UIControlEvents.touchUpInside);
moreBtn = btn;
btn.mas_makeConstraints { (maker) in
maker?.left.top()?.mas_equalTo()(footer)?.offset()(10);
maker?.bottom.right()?.mas_equalTo()(footer)?.offset()(-10);
}
self.tableView.tableFooterView = footer;
}
@objc func moreBtnClick()->Void{
if self.isFromMoreBtn {
return;
}
if delegate != nil {
delegate.didLoadMoreBtnClick()
}
self.isFromMoreBtn = true;
}
}
|
Below is an extract from a Rust program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Rust code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Rust concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., ownership, lifetimes). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Rust. It should be similar to a school exercise, a tutorial, or a Rust course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Rust. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
const SPACE: u8 = 32;
const PERCENT: u8 = 37;
const PLUS: u8 = 43;
const ZERO: u8 = 48;
const NINE: u8 = 57;
const UA: u8 = 65;
const UF: u8 = 70;
const UZ: u8 = 90;
const LA: u8 = 97;
const LF: u8 = 102;
const LZ: u8 = 122;
pub fn encode_percent(str: &[u8]) -> Vec<u8> {
let mut result: Vec<u8> = Vec::new();
for &x in str.iter() {
match x {
ZERO ... NINE => { result.push(x); },
UA ... UZ => { result.push(x); },
LA ... LZ => { result.push(x); },
_ => {
let msb = x >> 4 & 0x0F;
let lsb = x & 0x0F;
result.push(PERCENT);
result.push(if msb < 10 { msb + ZERO } else { msb - 10 + UA });
result.push(if lsb < 10 { lsb + ZERO } else { lsb - 10 + UA });
},
}
}
result
}
pub fn decode_percent(str: &[u8]) -> Vec<u8> {
let mut result: Vec<u8> = Vec::new();
str.iter().fold((0, 0), |(flag, sum), &x|
match x {
PLUS => { result.push(SPACE); (0, 0) },
PERCENT => (1, 0),
ZERO ... NINE => {
match flag {
1 => (2, x - ZERO),
2 => { result.push(sum * 16 + (x - ZERO)); (0, 0) },
_ => { result.push(x); (0, 0) },
}
},
UA ... UF => {
match flag {
1 => (2, x - UA + 10),
2 => { result.push(sum * 16 + (x - UA) + 10); (0, 0) },
_ => { result.push(x); (0, 0) },
}
},
LA ... LF => {
match flag {
1 => (2, x - LA + 10),
2 => { result.push(sum * 16 + (x - LA) + 10); (0, 0) },
_ => { result.push(x); (0, 0) },
}
},
_ => { result.push(x); (0, 0) },
}
);
result
}
#[cfg(test)]
mod tests {
use std::str;
use super::encode_percent;
use super::decode_percent;
#[test]
fn test_encode_percent() {
assert_eq!("%E3%81%82%E3%81%84%E3%81%86%E3%81%88%E3%81%8A", str::from_utf8(encode_percent("あいうえお".as_bytes()).as_slice()).unwrap());
assert_eq!("%E3%81%8B%E3%81%8D%E3%81%8F%E3%81%91%E3%81%93", str::from_utf8(encode_percent("かきくけこ".as_bytes()).as_slice()).unwrap());
assert_eq!("%E3%81%95%E3%81%97%E3%81%99%E3%81%9B%E3%81%9D", str::from_utf8(encode_percent("さしすせそ".as_b
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
rust
| 4 |
const SPACE: u8 = 32;
const PERCENT: u8 = 37;
const PLUS: u8 = 43;
const ZERO: u8 = 48;
const NINE: u8 = 57;
const UA: u8 = 65;
const UF: u8 = 70;
const UZ: u8 = 90;
const LA: u8 = 97;
const LF: u8 = 102;
const LZ: u8 = 122;
pub fn encode_percent(str: &[u8]) -> Vec<u8> {
let mut result: Vec<u8> = Vec::new();
for &x in str.iter() {
match x {
ZERO ... NINE => { result.push(x); },
UA ... UZ => { result.push(x); },
LA ... LZ => { result.push(x); },
_ => {
let msb = x >> 4 & 0x0F;
let lsb = x & 0x0F;
result.push(PERCENT);
result.push(if msb < 10 { msb + ZERO } else { msb - 10 + UA });
result.push(if lsb < 10 { lsb + ZERO } else { lsb - 10 + UA });
},
}
}
result
}
pub fn decode_percent(str: &[u8]) -> Vec<u8> {
let mut result: Vec<u8> = Vec::new();
str.iter().fold((0, 0), |(flag, sum), &x|
match x {
PLUS => { result.push(SPACE); (0, 0) },
PERCENT => (1, 0),
ZERO ... NINE => {
match flag {
1 => (2, x - ZERO),
2 => { result.push(sum * 16 + (x - ZERO)); (0, 0) },
_ => { result.push(x); (0, 0) },
}
},
UA ... UF => {
match flag {
1 => (2, x - UA + 10),
2 => { result.push(sum * 16 + (x - UA) + 10); (0, 0) },
_ => { result.push(x); (0, 0) },
}
},
LA ... LF => {
match flag {
1 => (2, x - LA + 10),
2 => { result.push(sum * 16 + (x - LA) + 10); (0, 0) },
_ => { result.push(x); (0, 0) },
}
},
_ => { result.push(x); (0, 0) },
}
);
result
}
#[cfg(test)]
mod tests {
use std::str;
use super::encode_percent;
use super::decode_percent;
#[test]
fn test_encode_percent() {
assert_eq!("%E3%81%82%E3%81%84%E3%81%86%E3%81%88%E3%81%8A", str::from_utf8(encode_percent("あいうえお".as_bytes()).as_slice()).unwrap());
assert_eq!("%E3%81%8B%E3%81%8D%E3%81%8F%E3%81%91%E3%81%93", str::from_utf8(encode_percent("かきくけこ".as_bytes()).as_slice()).unwrap());
assert_eq!("%E3%81%95%E3%81%97%E3%81%99%E3%81%9B%E3%81%9D", str::from_utf8(encode_percent("さしすせそ".as_bytes()).as_slice()).unwrap());
assert_eq!("%E3%81%9F%E3%81%A1%E3%81%A4%E3%81%A6%E3%81%A8", str::from_utf8(encode_percent("たちつてと".as_bytes()).as_slice()).unwrap());
assert_eq!("%E3%81%AA%E3%81%AB%E3%81%AC%E3%81%AD%E3%81%AE", str::from_utf8(encode_percent("なにぬねの".as_bytes()).as_slice()).unwrap());
}
#[test]
fn test_decode_percent() {
assert_eq!("あいうえお", str::from_utf8(decode_percent(b"%E3%81%82%E3%81%84%E3%81%86%E3%81%88%E3%81%8A").as_slice()).unwrap());
assert_eq!("かきくけこ", str::from_utf8(decode_percent(b"%E3%81%8B%E3%81%8D%E3%81%8F%E3%81%91%E3%81%93").as_slice()).unwrap());
assert_eq!("さしすせそ", str::from_utf8(decode_percent(b"%E3%81%95%E3%81%97%E3%81%99%E3%81%9B%E3%81%9D").as_slice()).unwrap());
assert_eq!("たちつてと", str::from_utf8(decode_percent(b"%E3%81%9F%E3%81%A1%E3%81%A4%E3%81%A6%E3%81%A8").as_slice()).unwrap());
assert_eq!("なにぬねの", str::from_utf8(decode_percent(b"%E3%81%AA%E3%81%AB%E3%81%AC%E3%81%AD%E3%81%AE").as_slice()).unwrap());
}
}
|
Below is an extract from an HTML document. Evaluate whether it has a high educational value and could help teach web development. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the document contains valid HTML markup, even if it's not educational, like boilerplate code or standard tags.
- Add another point if the document addresses practical HTML concepts and uses semantic elements appropriately.
- Award a third point if the document is suitable for educational use and introduces key web concepts, even if the topic is somewhat advanced (e.g., forms, metadata). The code should be well-structured and use clear, descriptive naming.
- Give a fourth point if the document is self-contained and highly relevant to teaching HTML. It should be similar to a school exercise, a tutorial, or an HTML course section for early learners.
- Grant a fifth point if the document is outstanding in its educational value and is perfectly suited for teaching HTML to beginners. It should be well-organized, easy to understand, and ideally include some explanatory comments or demonstrate best practices in HTML structure.
The extract:
{"ADDRESS": "BANK OF BARODA,VILLAGE MOTAP,TAL BECHARAJI,DIST MEHSANA,GUJARAT \u2013 384212", "BANK": "Bank of Baroda", "BANKCODE": "BARB", "BRANCH": "MOTAP", "CENTRE": "BECHRAJI", "CITY": "BECHRAJI", "CONTACT": "1800223344", "DISTRICT": "SURAT", "IFSC": "BARB0MOTAPX", "IMPS": true, "MICR": "384012520", "NEFT": true, "RTGS": true, "STATE": "GUJARAT", "SWIFT": "", "UPI": true}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
html
| 0 |
{"ADDRESS": "BANK OF BARODA,VILLAGE MOTAP,TAL BECHARAJI,DIST MEHSANA,GUJARAT \u2013 384212", "BANK": "Bank of Baroda", "BANKCODE": "BARB", "BRANCH": "MOTAP", "CENTRE": "BECHRAJI", "CITY": "BECHRAJI", "CONTACT": "1800223344", "DISTRICT": "SURAT", "IFSC": "BARB0MOTAPX", "IMPS": true, "MICR": "384012520", "NEFT": true, "RTGS": true, "STATE": "GUJARAT", "SWIFT": "", "UPI": true}
|
Below is an extract from a TypeScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid TypeScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical TypeScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., generics, decorators). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching TypeScript. It should be similar to a school exercise, a tutorial, or a TypeScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching TypeScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
import { setRandom } from '../src/random'
import { keys } from '../src/utils'
import { createName } from './createName'
import { raceTraits } from './raceTraits'
// Set random to be deterministic
setRandom((min: number, max: number) => Math.round((min + max) / 2))
describe('createName', () => {
it('creates a name', () => {
expect(typeof createName()).toBe('string')
})
it('creates a male name', () => {
expect(typeof createName({ gender: 'man' })).toBe('string')
})
it('creates a female name', () => {
expect(typeof createName({ gender: 'woman' })).toBe('string')
})
it('creates a male first name for every race', () => {
for (const raceName of keys(raceTraits)) {
expect(typeof createName({ gender: 'man', race: raceName })).toBe('string')
}
})
it('creates a female first name for every race', () => {
for (const raceName of keys(raceTraits)) {
expect(typeof createName({ gender: 'woman', race: raceName })).toBe('string')
}
})
it('creates a last name for every race', () => {
for (const raceName of keys(raceTraits)) {
expect(typeof createName({ race: raceName, firstOrLast: 'lastName' })).toBe('string')
}
})
})
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
typescript
| 3 |
import { setRandom } from '../src/random'
import { keys } from '../src/utils'
import { createName } from './createName'
import { raceTraits } from './raceTraits'
// Set random to be deterministic
setRandom((min: number, max: number) => Math.round((min + max) / 2))
describe('createName', () => {
it('creates a name', () => {
expect(typeof createName()).toBe('string')
})
it('creates a male name', () => {
expect(typeof createName({ gender: 'man' })).toBe('string')
})
it('creates a female name', () => {
expect(typeof createName({ gender: 'woman' })).toBe('string')
})
it('creates a male first name for every race', () => {
for (const raceName of keys(raceTraits)) {
expect(typeof createName({ gender: 'man', race: raceName })).toBe('string')
}
})
it('creates a female first name for every race', () => {
for (const raceName of keys(raceTraits)) {
expect(typeof createName({ gender: 'woman', race: raceName })).toBe('string')
}
})
it('creates a last name for every race', () => {
for (const raceName of keys(raceTraits)) {
expect(typeof createName({ race: raceName, firstOrLast: 'lastName' })).toBe('string')
}
})
})
|
Below is an extract from a Swift program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Swift code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Swift concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., protocols, extensions). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Swift. It should be similar to a school exercise, a tutorial, or a Swift course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Swift. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
import Foundation
import RealmSwift
class Event: Object {
@objc dynamic var event = ""
@objc dynamic var date = "" //yyyy.MM.dd
}
class Diary: Object {
@objc dynamic var content:String = ""
@objc dynamic var tag:String = ""
@objc dynamic var feelingTag:Int = 0
@objc dynamic var date: String = ""
@objc dynamic var favoriteDream:Bool = false
open var primaryKey: String {
return "content"
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
swift
| 2 |
import Foundation
import RealmSwift
class Event: Object {
@objc dynamic var event = ""
@objc dynamic var date = "" //yyyy.MM.dd
}
class Diary: Object {
@objc dynamic var content:String = ""
@objc dynamic var tag:String = ""
@objc dynamic var feelingTag:Int = 0
@objc dynamic var date: String = ""
@objc dynamic var favoriteDream:Bool = false
open var primaryKey: String {
return "content"
}
}
|
Below is an extract from a Kotlin program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Kotlin code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Kotlin concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., coroutines, extension functions). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Kotlin. It should be similar to a school exercise, a tutorial, or a Kotlin course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Kotlin. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package com.bagasbest.berepo
import android.annotation.SuppressLint
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import com.bagasbest.berepo.adapter.UserAdapter
import com.bagasbest.berepo.model.UserModel
import kotlinx.android.synthetic.main.activity_home.*
class HomeActivity : AppCompatActivity() {
private val list = ArrayList<UserModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
title = "Daftar Pengguna Github"
rv_data.setHasFixedSize(true)
list.addAll(getListUserGithub())
showRecyclerList()
}
@SuppressLint("Recycle")
private fun getListUserGithub() : ArrayList<UserModel> {
val fullname = resources.getStringArray(R.array.name)
val username = resources.getStringArray(R.array.username)
val company = resources.getStringArray(R.array.company)
val location = resources.getStringArray(R.array.location)
val follower = resources.getStringArray(R.array.followers)
val following = resources.getStringArray(R.array.following)
val repository = resources.getStringArray(R.array.repository)
val avatar = resources.obtainTypedArray(R.array.avatar)
for(position in username.indices) {
val user = UserModel(
'@' + username[position],
fullname[position],
avatar.getResourceId(position, -1),
company[position],
location[position],
repository[position],
follower[position],
following[position],
)
list.
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
kotlin
| 2 |
package com.bagasbest.berepo
import android.annotation.SuppressLint
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import com.bagasbest.berepo.adapter.UserAdapter
import com.bagasbest.berepo.model.UserModel
import kotlinx.android.synthetic.main.activity_home.*
class HomeActivity : AppCompatActivity() {
private val list = ArrayList<UserModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
title = "Daftar Pengguna Github"
rv_data.setHasFixedSize(true)
list.addAll(getListUserGithub())
showRecyclerList()
}
@SuppressLint("Recycle")
private fun getListUserGithub() : ArrayList<UserModel> {
val fullname = resources.getStringArray(R.array.name)
val username = resources.getStringArray(R.array.username)
val company = resources.getStringArray(R.array.company)
val location = resources.getStringArray(R.array.location)
val follower = resources.getStringArray(R.array.followers)
val following = resources.getStringArray(R.array.following)
val repository = resources.getStringArray(R.array.repository)
val avatar = resources.obtainTypedArray(R.array.avatar)
for(position in username.indices) {
val user = UserModel(
'@' + username[position],
fullname[position],
avatar.getResourceId(position, -1),
company[position],
location[position],
repository[position],
follower[position],
following[position],
)
list.add(user)
}
return list
}
private fun showRecyclerList () {
rv_data.layoutManager = LinearLayoutManager(this)
val listGithubUserAdapter = UserAdapter(list)
rv_data.adapter = listGithubUserAdapter
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.menu, menu)
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
val searchView = menu?.findItem(R.id.search)?.actionView as SearchView
searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName))
searchView.queryHint = resources.getString(R.string.search_hint)
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
/*
Gunakan method ini ketika search selesai atau OK
*/
override fun onQueryTextSubmit(query: String): Boolean {
Toast.makeText(this@HomeActivity, query, Toast.LENGTH_SHORT).show()
return true
}
/*
Gunakan method ini untuk merespon tiap perubahan huruf pada searchView
*/
override fun onQueryTextChange(newText: String): Boolean {
return false
}
})
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if(item.itemId == R.id.settings) {
startActivity(Intent(this, AboutMeActivity::class.java))
}
return super.onOptionsItemSelected(item)
}
}
|
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical JavaScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
var casas = [
{
location: 'Niquia',
title: 'Casa',
description: 't is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.',
price: 1900000,
area: 106,
contact: {
phone: '1234567',
mobile: '1234567890'
},
address: 'Calle 15'
},
{
location: 'Mirador',
title: 'Casa',
description: 't is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.',
price: 1900000,
area: 106,
contact: {
phone: '1234567',
mobile: '1234567890'
},
address: 'Calle 15'
},
{
location: 'Pachelly',
title: 'Casa',
description: 't is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.',
price: 1900000,
area: 106,
contact: {
phone: '1234567',
mobile: '1234567890'
},
address: 'Calle 15'
},
{
location: 'Playa Rica',
title: 'Casa',
description: 't is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.',
price: 1900000,
area: 106,
contact: {
phone: '1234567',
mobile: '1234567890'
},
address: 'Calle 15'
},
{
location: 'Manchester',
title: 'Casa',
description: 't is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.',
pri
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
javascript
| 1 |
var casas = [
{
location: 'Niquia',
title: 'Casa',
description: 't is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.',
price: 1900000,
area: 106,
contact: {
phone: '1234567',
mobile: '1234567890'
},
address: 'Calle 15'
},
{
location: 'Mirador',
title: 'Casa',
description: 't is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.',
price: 1900000,
area: 106,
contact: {
phone: '1234567',
mobile: '1234567890'
},
address: 'Calle 15'
},
{
location: 'Pachelly',
title: 'Casa',
description: 't is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.',
price: 1900000,
area: 106,
contact: {
phone: '1234567',
mobile: '1234567890'
},
address: 'Calle 15'
},
{
location: 'Playa Rica',
title: 'Casa',
description: 't is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.',
price: 1900000,
area: 106,
contact: {
phone: '1234567',
mobile: '1234567890'
},
address: 'Calle 15'
},
{
location: 'Manchester',
title: 'Casa',
description: 't is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.',
price: 1900000,
area: 106,
contact: {
phone: '1234567',
mobile: '1234567890'
},
address: 'Calle 15'
},
{
location: 'Villas del Sol',
title: 'Casa',
description: 't is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.',
price: 1900000,
area: 106,
contact: {
phone: '1234567',
mobile: '1234567890'
},
address: 'Calle 15'
},
]
|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package com.fertigapp.backend.services;
import com.fertigapp.backend.model.Completada;
import com.fertigapp.backend.model.Rutina;
import com.fertigapp.backend.model.Usuario;
import com.fertigapp.backend.repository.CompletadaRepository;
import org.springframework.stereotype.Service;
import java.time.OffsetDateTime;
@Service
public class CompletadaService {
private final CompletadaRepository completadaRepository;
public CompletadaService(CompletadaRepository completadaRepository) {
this.completadaRepository = completadaRepository;
}
public Completada save(Completada completada){
return completadaRepository.save(completada);
}
public Completada findTopHechaByRutinaAndHecha(Rutina rutina, boolean hecha){
return completadaRepository.findTopByRutinaCAndHecha(rutina, hecha);
}
public void deleteAllByRutina(Rutina rutina){
this.completadaRepository.deleteAllByRutinaC(rutina);
}
public Iterable<OffsetDateTime> findFechasCompletadasByRutina(Rutina rutina){
return this.completadaRepository.findFechasCompletadasByRutina(rutina);
}
public OffsetDateTime findMaxFechaCompletadaByRutina(Rutina rutina){
return this.completadaRepository.findMaxFechaCompletadaByRutina(rutina);
}
public OffsetDateTime findFechaNoCompletadaByRutina(Rutina rutina){
return this.completadaRepository.findFechaNoCompletadaByRutina(rutina);
}
public void deleteById(Integer id){
this.completadaRepository.deleteById(id);
}
public Completada findMaxCompletada(Rutina rutina){
return this.completadaRepository.findMaxCompletada(rutina);
}
public Integer countCompletadasBetween(OffsetDateTime inicio, OffsetDateTime fin, Usuario usuario){
return this.completadaRepository.countCompletadasBetween(inicio, fin, usuario);
}
public Integer countTiempoCompletadasBetween(OffsetDateTime inicio, OffsetDateTime fin, Usuario usuario){
return
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
java
| 3 |
package com.fertigapp.backend.services;
import com.fertigapp.backend.model.Completada;
import com.fertigapp.backend.model.Rutina;
import com.fertigapp.backend.model.Usuario;
import com.fertigapp.backend.repository.CompletadaRepository;
import org.springframework.stereotype.Service;
import java.time.OffsetDateTime;
@Service
public class CompletadaService {
private final CompletadaRepository completadaRepository;
public CompletadaService(CompletadaRepository completadaRepository) {
this.completadaRepository = completadaRepository;
}
public Completada save(Completada completada){
return completadaRepository.save(completada);
}
public Completada findTopHechaByRutinaAndHecha(Rutina rutina, boolean hecha){
return completadaRepository.findTopByRutinaCAndHecha(rutina, hecha);
}
public void deleteAllByRutina(Rutina rutina){
this.completadaRepository.deleteAllByRutinaC(rutina);
}
public Iterable<OffsetDateTime> findFechasCompletadasByRutina(Rutina rutina){
return this.completadaRepository.findFechasCompletadasByRutina(rutina);
}
public OffsetDateTime findMaxFechaCompletadaByRutina(Rutina rutina){
return this.completadaRepository.findMaxFechaCompletadaByRutina(rutina);
}
public OffsetDateTime findFechaNoCompletadaByRutina(Rutina rutina){
return this.completadaRepository.findFechaNoCompletadaByRutina(rutina);
}
public void deleteById(Integer id){
this.completadaRepository.deleteById(id);
}
public Completada findMaxCompletada(Rutina rutina){
return this.completadaRepository.findMaxCompletada(rutina);
}
public Integer countCompletadasBetween(OffsetDateTime inicio, OffsetDateTime fin, Usuario usuario){
return this.completadaRepository.countCompletadasBetween(inicio, fin, usuario);
}
public Integer countTiempoCompletadasBetween(OffsetDateTime inicio, OffsetDateTime fin, Usuario usuario){
return this.completadaRepository.countTiempoCompletadasBetween(inicio, fin, usuario);
}
}
|
Below is an extract from a Swift program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Swift code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Swift concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., protocols, extensions). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Swift. It should be similar to a school exercise, a tutorial, or a Swift course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Swift. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
//
// MatchHistoryUseCase.swift
// Domain
//
// Created by <NAME> on 2020/04/01.
// Copyright © 2020 GilwanRyu. All rights reserved.
//
import UIKit
import RxSwift
public protocol MatchHistoryUseCase {
func getUserMatchHistory(platform: Platform, id: String) -> Observable<MatchHistoryViewable>
func getUserMatchHistoryDetail(matchId: String) -> Observable<MatchHistoryDetailViewable>
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
swift
| 1 |
//
// MatchHistoryUseCase.swift
// Domain
//
// Created by <NAME> on 2020/04/01.
// Copyright © 2020 GilwanRyu. All rights reserved.
//
import UIKit
import RxSwift
public protocol MatchHistoryUseCase {
func getUserMatchHistory(platform: Platform, id: String) -> Observable<MatchHistoryViewable>
func getUserMatchHistoryDetail(matchId: String) -> Observable<MatchHistoryDetailViewable>
}
|
Below is an extract from a Rust program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Rust code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Rust concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., ownership, lifetimes). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Rust. It should be similar to a school exercise, a tutorial, or a Rust course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Rust. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
use crate::object::Object;
use std::collections::HashMap;
#[derive(Clone)]
pub struct Environment {
pub store: HashMap<String, Object>,
}
impl Environment {
#[inline]
pub fn new() -> Self {
Environment {
store: HashMap::new(),
}
}
#[inline]
pub fn get(&self, name: &String) -> Option<&Object> {
self.store.get(name)
}
#[inline]
pub fn set(&mut self, name: String, val: &Object) {
self.store.insert(name, val.clone());
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
rust
| 3 |
use crate::object::Object;
use std::collections::HashMap;
#[derive(Clone)]
pub struct Environment {
pub store: HashMap<String, Object>,
}
impl Environment {
#[inline]
pub fn new() -> Self {
Environment {
store: HashMap::new(),
}
}
#[inline]
pub fn get(&self, name: &String) -> Option<&Object> {
self.store.get(name)
}
#[inline]
pub fn set(&mut self, name: String, val: &Object) {
self.store.insert(name, val.clone());
}
}
|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package com.taihold.shuangdeng.ui.login;
import static com.taihold.shuangdeng.common.FusionAction.IMAGE_VERIFY;
import static com.taihold.shuangdeng.common.FusionAction.IMAGE_VERIFY_EXTRA.IMAGE_VERIFY_CODE;
import static com.taihold.shuangdeng.common.FusionAction.REGIST_EXTRA.SMS_VALIDATE_CODE;
import static com.taihold.shuangdeng.common.FusionAction.REGIST_EXTRA.USER_MOBILE;
import static com.taihold.shuangdeng.common.FusionAction.REGIST_EXTRA.USER_TYPE;
import static com.taihold.shuangdeng.common.FusionMessageType.REQUEST_SMS_CODE_HAS_SENDED;
import static com.taihold.shuangdeng.common.FusionMessageType.REQUEST_SMS_CODE_HAS_SENDED_ERROR;
import static com.taihold.shuangdeng.common.FusionMessageType.REQUEST_USER_HAS_REGISTED;
import static com.taihold.shuangdeng.common.FusionMessageType.REQUEST_VALIIDATE_CODE_CONFIRM_FAILED;
import static com.taihold.shuangdeng.common.FusionMessageType.REQUEST_VALIIDATE_CODE_CONFIRM_SUCCESS;
import static com.taihold.shuangdeng.component.db.URIField.USERNAME;
import static com.taihold.shuangdeng.component.db.URIField.VERIFYCODE;
import java.util.Map;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.balysv.materialmenu.MaterialMenuDrawable;
import com.taihold.shuangdeng.R;
import com.taihold.shuangdeng.common.FusionAction;
import com.taihold.shuangdeng.freamwork.ui.BasicActivity;
import com.taihold.shuangdeng.logic.login.ILoginLogic;
import com.taihold.shuangdeng.util.StringUtil;
public class RegistActivity extends BasicActivity
{
private static final String TAG = "RegistActivity";
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
java
| 1 |
package com.taihold.shuangdeng.ui.login;
import static com.taihold.shuangdeng.common.FusionAction.IMAGE_VERIFY;
import static com.taihold.shuangdeng.common.FusionAction.IMAGE_VERIFY_EXTRA.IMAGE_VERIFY_CODE;
import static com.taihold.shuangdeng.common.FusionAction.REGIST_EXTRA.SMS_VALIDATE_CODE;
import static com.taihold.shuangdeng.common.FusionAction.REGIST_EXTRA.USER_MOBILE;
import static com.taihold.shuangdeng.common.FusionAction.REGIST_EXTRA.USER_TYPE;
import static com.taihold.shuangdeng.common.FusionMessageType.REQUEST_SMS_CODE_HAS_SENDED;
import static com.taihold.shuangdeng.common.FusionMessageType.REQUEST_SMS_CODE_HAS_SENDED_ERROR;
import static com.taihold.shuangdeng.common.FusionMessageType.REQUEST_USER_HAS_REGISTED;
import static com.taihold.shuangdeng.common.FusionMessageType.REQUEST_VALIIDATE_CODE_CONFIRM_FAILED;
import static com.taihold.shuangdeng.common.FusionMessageType.REQUEST_VALIIDATE_CODE_CONFIRM_SUCCESS;
import static com.taihold.shuangdeng.component.db.URIField.USERNAME;
import static com.taihold.shuangdeng.component.db.URIField.VERIFYCODE;
import java.util.Map;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.balysv.materialmenu.MaterialMenuDrawable;
import com.taihold.shuangdeng.R;
import com.taihold.shuangdeng.common.FusionAction;
import com.taihold.shuangdeng.freamwork.ui.BasicActivity;
import com.taihold.shuangdeng.logic.login.ILoginLogic;
import com.taihold.shuangdeng.util.StringUtil;
public class RegistActivity extends BasicActivity
{
private static final String TAG = "RegistActivity";
private Toolbar mToolBar;
private MaterialMenuDrawable mMaterialMenu;
private EditText mUserEdit;
private TextInputLayout mUserTil;
private Button mSmsBtn;
private EditText mSmsEdit;
private TextInputLayout mSmsTil;
private Button mRegistNextBtn;
private ILoginLogic mLoginLogic;
private String mSid;
public static Map<String, Long> map;
private String mUserName;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regist);
// initDialogActivity();
initView(savedInstanceState);
}
@Override
protected void initLogic()
{
super.initLogic();
mLoginLogic = (ILoginLogic) getLogicByInterfaceClass(ILoginLogic.class);
}
private void initView(Bundle savedInstanceState)
{
mToolBar = (Toolbar) findViewById(R.id.toolbar);
mRegistNextBtn = (Button) findViewById(R.id.regist_next);
mUserEdit = (EditText) findViewById(R.id.phone_num_edit);
mSmsBtn = (Button) findViewById(R.id.send_sms_code);
mSmsEdit = (EditText) findViewById(R.id.sms_confirm_code_edit);
mUserTil = (TextInputLayout) findViewById(R.id.phone_num_til);
mSmsTil = (TextInputLayout) findViewById(R.id.sms_confirm_til);
registerForContextMenu(mRegistNextBtn);
setSupportActionBar(mToolBar);
mSmsTil.setErrorEnabled(true);
mMaterialMenu = new MaterialMenuDrawable(this, Color.WHITE,
MaterialMenuDrawable.Stroke.THIN);
mMaterialMenu.setTransformationDuration(500);
mMaterialMenu.setIconState(MaterialMenuDrawable.IconState.ARROW);
mToolBar.setNavigationIcon(mMaterialMenu);
setTitle(R.string.regist_confirm_phone_num);
mToolBar.setNavigationOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
finish();
}
});
mSmsBtn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mUserTil.setErrorEnabled(true);
// mImgConfirmTil.setErrorEnabled(true);
if (StringUtil.isNullOrEmpty(mUserEdit.getText().toString()))
{
mUserTil.setError(getString(R.string.login_username_is_null));
return;
}
else if (mUserEdit.getText().toString().length() != 11)
{
mUserTil.setError(getString(R.string.login_phone_num_is_unavailable));
return;
}
mUserTil.setErrorEnabled(false);
// mImgConfirmTil.setErrorEnabled(false);
String username = mUserEdit.getText().toString();
Intent intent = new Intent(IMAGE_VERIFY);
intent.putExtra(USERNAME, username);
startActivityForResult(intent, IMAGE_VERIFY_CODE);
}
});
mRegistNextBtn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mUserTil.setErrorEnabled(true);
// mImgConfirmTil.setErrorEnabled(true);
if (StringUtil.isNullOrEmpty(mUserEdit.getText().toString()))
{
mUserTil.setError(getString(R.string.login_username_is_null));
return;
}
else if (mUserEdit.getText().toString().length() != 11)
{
mUserTil.setError(getString(R.string.login_phone_num_is_unavailable));
return;
}
mUserTil.setErrorEnabled(false);
// mImgConfirmTil.setErrorEnabled(false);
mUserName = mUserEdit.getText().toString();
mLoginLogic.validateSmsCode(mUserName, mSmsEdit.getText()
.toString());
// mRegistNextBtn.showContextMenu();
// mSmsTil.setError(getString(R.string.regist_image_confirm_code_error));
}
});
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId() == R.id.regist_next)
{
MenuInflater flater = getMenuInflater();
flater.inflate(R.menu.main_menu, menu);
menu.setHeaderTitle(getString(R.string.regist_select_type))
.setHeaderIcon(R.mipmap.ic_launcher);
}
}
@Override
public boolean onContextItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.regist_user:
Intent registPersonal = new Intent(
FusionAction.REGIST_DETAIL_ACTION);
registPersonal.putExtra(USER_TYPE, "personal");
registPersonal.putExtra(USER_MOBILE, mUserEdit.getText()
.toString());
registPersonal.putExtra(SMS_VALIDATE_CODE, mSid);
Log.d(TAG, "sid = " + mSid);
startActivity(registPersonal);
break;
case R.id.regist_company:
Intent registCompany = new Intent(
FusionAction.REGIST_DETAIL_ACTION);
registCompany.putExtra(USER_TYPE, "company");
registCompany.putExtra(USER_MOBILE, mUserName);
registCompany.putExtra(SMS_VALIDATE_CODE, mSid);
startActivity(registCompany);
break;
default:
super.onContextItemSelected(item);
}
finish();
return super.onContextItemSelected(item);
}
@Override
protected void handleStateMessage(Message msg)
{
super.handleStateMessage(msg);
switch (msg.what)
{
case REQUEST_VALIIDATE_CODE_CONFIRM_SUCCESS:
mSid = (String) msg.obj;
mRegistNextBtn.showContextMenu();
break;
case REQUEST_VALIIDATE_CODE_CONFIRM_FAILED:
mSmsTil.setError(getString(R.string.regist_image_confirm_code_error));
break;
case REQUEST_USER_HAS_REGISTED:
mUserTil.setError(getString(R.string.regist_user_has_registed));
break;
case REQUEST_SMS_CODE_HAS_SENDED_ERROR:
showToast(R.string.regist_sms_send_failed, Toast.LENGTH_LONG);
break;
case REQUEST_SMS_CODE_HAS_SENDED:
new TimeCount(60000, 1000).start();
showToast(R.string.regist_sms_code_has_sended,
Toast.LENGTH_LONG);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK)
{
switch (requestCode)
{
case IMAGE_VERIFY_CODE:
String username = mUserEdit.getText().toString();
String verifyCode = data.getStringExtra(VERIFYCODE);
mLoginLogic.getSMSConfirmCode(username, verifyCode);
break;
}
}
}
@Override
protected void onDestroy()
{
super.onDestroy();
unregisterForContextMenu(mRegistNextBtn);
}
class TimeCount extends CountDownTimer
{
public TimeCount(long millisInFuture, long countDownInterval)
{
//参数依次为总时长,和计时的时间间隔
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish()
{
//计时完毕时触发
mSmsBtn.setText(R.string.regist_send_sms_code);
mSmsBtn.setEnabled(true);
}
@Override
public void onTick(long millisUntilFinished)
{
//计时过程显示
mSmsBtn.setEnabled(false);
mSmsBtn.setText(millisUntilFinished / 1000
+ getResources().getString(R.string.regist_sms_count_down));
}
}
}
|
Below is an extract from a Ruby program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Ruby code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Ruby concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., metaprogramming, blocks). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Ruby. It should be similar to a school exercise, a tutorial, or a Ruby course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Ruby. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
require "test_helper"
describe VideosController do
describe "index" do
it "must get index" do
get videos_path
must_respond_with :success
expect(response.header['Content-Type']).must_include 'json'
end
it "will return all the proper fields for a list of videos" do
video_fields = %w[id title release_date available_inventory].sort
get videos_path
body = JSON.parse(response.body)
expect(body).must_be_instance_of Array
body.each do |video|
expect(video).must_be_instance_of Hash
expect(video.keys.sort).must_equal video_fields
end
end
it "returns and empty array if no videos exist" do
Video.destroy_all
get videos_path
body = JSON.parse(response.body)
expect(body).must_be_instance_of Array
expect(body.length).must_equal 0
end
end
describe "show" do
# nominal
it "will return a hash with proper fields for an existing video" do
video_fields = %w[title overview release_date total_inventory available_inventory].sort
video = videos(:la_la_land)
get video_path(video.id)
must_respond_with :success
body = JSON.parse(response.body)
expect(response.header['Content-Type']).must_include 'json'
expect(body).must_be_instance_of Hash
expect(body.keys.sort).must_equal video_fields
end
# edge
it "will return a 404 request with json for a non-existant video" do
get video_path(-1)
must_respond_with :not_found
body = JSON.parse(response.body)
expect(body).must_be_instance_of Hash
# expect(body['ok']).must_equal false
expect(body['errors'][0]).must_equal 'Not Found'
end
end
describe "create" do
let(:video_data) {
{
title: "La La Land",
overview: "A jazz pianist falls for an aspiring actress in Los Angeles.",
release_date: Date.new(2016),
total_inventory: 5,
avail
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
ruby
| 2 |
require "test_helper"
describe VideosController do
describe "index" do
it "must get index" do
get videos_path
must_respond_with :success
expect(response.header['Content-Type']).must_include 'json'
end
it "will return all the proper fields for a list of videos" do
video_fields = %w[id title release_date available_inventory].sort
get videos_path
body = JSON.parse(response.body)
expect(body).must_be_instance_of Array
body.each do |video|
expect(video).must_be_instance_of Hash
expect(video.keys.sort).must_equal video_fields
end
end
it "returns and empty array if no videos exist" do
Video.destroy_all
get videos_path
body = JSON.parse(response.body)
expect(body).must_be_instance_of Array
expect(body.length).must_equal 0
end
end
describe "show" do
# nominal
it "will return a hash with proper fields for an existing video" do
video_fields = %w[title overview release_date total_inventory available_inventory].sort
video = videos(:la_la_land)
get video_path(video.id)
must_respond_with :success
body = JSON.parse(response.body)
expect(response.header['Content-Type']).must_include 'json'
expect(body).must_be_instance_of Hash
expect(body.keys.sort).must_equal video_fields
end
# edge
it "will return a 404 request with json for a non-existant video" do
get video_path(-1)
must_respond_with :not_found
body = JSON.parse(response.body)
expect(body).must_be_instance_of Hash
# expect(body['ok']).must_equal false
expect(body['errors'][0]).must_equal 'Not Found'
end
end
describe "create" do
let(:video_data) {
{
title: "La La Land",
overview: "A jazz pianist falls for an aspiring actress in Los Angeles.",
release_date: Date.new(2016),
total_inventory: 5,
available_inventory: 2
}
}
it "can create a new video" do
expect {
post videos_path, params: video_data
}.must_differ "Video.count", 1
must_respond_with :created
end
it "gives bad_request status when user gives bad data" do
video_data[:title] = nil
expect {
post videos_path, params: video_data
}.wont_change "Video.count"
must_respond_with :bad_request
expect(response.header['Content-Type']).must_include 'json'
body = JSON.parse(response.body)
expect(body['errors'].keys).must_include 'title'
end
end
end
|
Below is an extract from a Rust program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Rust code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Rust concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., ownership, lifetimes). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Rust. It should be similar to a school exercise, a tutorial, or a Rust course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Rust. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
//! Autocompletion for rslintrc.toml
//!
//! This is taken from `taplo_ide`, all credit for the implementation goes to them
use std::collections::HashSet;
use crate::core::session::TomlDocument;
use itertools::Itertools;
use schemars::{
schema::{InstanceType, RootSchema, Schema, SingleOrVec},
Map,
};
use serde_json::Value;
use taplo::{
analytics::NodeRef,
dom::{self, RootNode},
schema::util::{get_schema_objects, ExtendedSchema},
syntax::SyntaxKind,
};
use tower_lsp::lsp_types::*;
pub(crate) fn toml_completions(
doc: &TomlDocument,
position: Position,
root_schema: RootSchema,
) -> Vec<CompletionItem> {
let dom = doc.parse.clone().into_dom();
let paths: HashSet<dom::Path> = dom.iter().map(|(p, _)| p).collect();
let offset = doc.mapper.offset(position).unwrap();
let query = dom.query_position(offset);
if !query.is_completable() {
return Vec::new();
}
match &query.before {
Some(before) => {
if query.is_inside_header() {
let mut query_path = before.path.clone();
if query.is_empty_header() {
query_path = dom::Path::new();
} else if query_path.is_empty() {
query_path = query.after.path.clone();
}
// We always include the current object as well.
query_path = query_path.skip_right(1);
let range = before
.syntax
.range
.map(|range| doc.mapper.range(range).unwrap())
.or_else(|| {
query
.after
.syntax
.range
.map(|range| doc.mapper.range(range).unwrap())
});
return get_schema_objects(query_path.clone(), &root_schema, true)
.into_iter()
.flat_
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
rust
| 2 |
//! Autocompletion for rslintrc.toml
//!
//! This is taken from `taplo_ide`, all credit for the implementation goes to them
use std::collections::HashSet;
use crate::core::session::TomlDocument;
use itertools::Itertools;
use schemars::{
schema::{InstanceType, RootSchema, Schema, SingleOrVec},
Map,
};
use serde_json::Value;
use taplo::{
analytics::NodeRef,
dom::{self, RootNode},
schema::util::{get_schema_objects, ExtendedSchema},
syntax::SyntaxKind,
};
use tower_lsp::lsp_types::*;
pub(crate) fn toml_completions(
doc: &TomlDocument,
position: Position,
root_schema: RootSchema,
) -> Vec<CompletionItem> {
let dom = doc.parse.clone().into_dom();
let paths: HashSet<dom::Path> = dom.iter().map(|(p, _)| p).collect();
let offset = doc.mapper.offset(position).unwrap();
let query = dom.query_position(offset);
if !query.is_completable() {
return Vec::new();
}
match &query.before {
Some(before) => {
if query.is_inside_header() {
let mut query_path = before.path.clone();
if query.is_empty_header() {
query_path = dom::Path::new();
} else if query_path.is_empty() {
query_path = query.after.path.clone();
}
// We always include the current object as well.
query_path = query_path.skip_right(1);
let range = before
.syntax
.range
.map(|range| doc.mapper.range(range).unwrap())
.or_else(|| {
query
.after
.syntax
.range
.map(|range| doc.mapper.range(range).unwrap())
});
return get_schema_objects(query_path.clone(), &root_schema, true)
.into_iter()
.flat_map(|s| s.descendants(&root_schema.definitions, 10))
.filter(|(_, s, _)| !s.is_hidden())
.filter(|(p, ..)| {
if let Some(same_path) = before.syntax.key_path.as_ref() {
if p == same_path {
true
} else {
valid_key(&query_path.extend(p.clone()), &paths, &dom)
}
} else {
valid_key(&query_path.extend(p.clone()), &paths, &dom)
}
})
.filter(|(_, s, _)| {
if query
.after
.syntax
.syntax_kinds
.iter()
.any(|kind| *kind == SyntaxKind::TABLE_ARRAY_HEADER)
{
s.is_array_of_objects(&root_schema.definitions)
} else {
s.is(InstanceType::Object)
}
})
.unique_by(|(p, ..)| p.clone())
.map(|(path, schema, required)| {
key_completion(
&root_schema.definitions,
query_path.without_index().extend(path),
schema,
required,
range,
false,
None,
false,
)
})
.collect();
} else {
let node = before
.nodes
.last()
.cloned()
.unwrap_or_else(|| query.after.nodes.last().cloned().unwrap());
match node {
node @ NodeRef::Table(_) | node @ NodeRef::Root(_) => {
let mut query_path = before.path.clone();
if node.is_root() {
// Always full path.
query_path = dom::Path::new();
}
let range = before
.syntax
.range
.map(|range| doc.mapper.range(range).unwrap())
.or_else(|| {
query
.after
.syntax
.range
.map(|range| doc.mapper.range(range).unwrap())
});
let comma_before = false;
let additional_edits = Vec::new();
// FIXME: comma insertion before entry
// if inline_table {
// if let Some((tok_range, tok)) = before.syntax.first_token_before() {
// if tok.kind() != SyntaxKind::COMMA
// && tok.kind() != SyntaxKind::BRACE_START
// {
// let range_after = TextRange::new(
// tok_range.end(),
// tok_range.end() + TextSize::from(1),
// );
// additional_edits.push(TextEdit {
// range: doc.mapper.range(range_after).unwrap(),
// new_text: ",".into(),
// })
// }
// }
// let current_token =
// before.syntax.element.as_ref().unwrap().as_token().unwrap();
// if current_token.kind() != SyntaxKind::WHITESPACE
// && current_token.kind() != SyntaxKind::COMMA
// {
// comma_before = true;
// }
// range = None;
// }
return get_schema_objects(query_path.clone(), &root_schema, true)
.into_iter()
.flat_map(|s| s.descendants(&root_schema.definitions, 10))
.filter(|(_, s, _)| !s.is_hidden())
.filter(|(p, ..)| {
if let Some(same_path) = before.syntax.key_path.as_ref() {
if p == same_path {
true
} else {
valid_key(
&query_path.extend(if node.is_root() {
query_path.extend(p.clone())
} else {
p.clone()
}),
&paths,
&dom,
)
}
} else {
valid_key(
&query_path.extend(if node.is_root() {
query_path.extend(p.clone())
} else {
p.clone()
}),
&paths,
&dom,
)
}
})
.unique_by(|(p, ..)| p.clone())
.map(|(path, schema, required)| {
key_completion(
&root_schema.definitions,
if node.is_root() {
query_path.extend(path)
} else {
path
},
schema,
required,
range,
true,
if !additional_edits.is_empty() {
Some(additional_edits.clone())
} else {
None
},
comma_before,
)
})
.collect();
}
NodeRef::Entry(_) => {
// Value completion.
let query_path = before.path.clone();
let range = before
.syntax
.range
.map(|range| doc.mapper.range(range).unwrap())
.or_else(|| {
query
.after
.syntax
.range
.map(|range| doc.mapper.range(range).unwrap())
});
return get_schema_objects(query_path, &root_schema, true)
.into_iter()
.flat_map(|schema| {
value_completions(
&root_schema.definitions,
schema,
range,
None,
false,
true,
)
})
.unique_by(|comp| comp.insert_text.clone())
.collect();
}
NodeRef::Array(_) => {
// Value completion inside an array.
let query_path = before.path.clone();
let comma_before = false;
let additional_edits = Vec::new();
// FIXME: comma insertion before entry
// if let Some((tok_range, tok)) = before.syntax.first_token_before() {
// if tok.kind() != SyntaxKind::COMMA
// && tok.kind() != SyntaxKind::BRACKET_START
// {
// let range_after = TextRange::new(
// tok_range.end(),
// tok_range.end() + TextSize::from(1),
// );
// additional_edits.push(TextEdit {
// range: doc.mapper.range(range_after).unwrap(),
// new_text: ",".into(),
// })
// }
// }
// let current_token =
// before.syntax.element.as_ref().unwrap().as_token().unwrap();
// if current_token.kind() != SyntaxKind::WHITESPACE
// && current_token.kind() != SyntaxKind::COMMA
// {
// comma_before = true;
// }
return get_schema_objects(query_path.clone(), &root_schema, true)
.into_iter()
.filter_map(|s| match query_path.last() {
Some(k) => {
if k.is_key() {
s.schema.array.as_ref().and_then(|arr| match &arr.items {
Some(items) => match items {
SingleOrVec::Single(item) => {
Some(ExtendedSchema::resolved(
&root_schema.definitions,
&*item,
))
}
SingleOrVec::Vec(_) => None, // FIXME: handle this (hard).
},
None => None,
})
} else {
None
}
}
None => s.schema.array.as_ref().and_then(|arr| match &arr.items {
Some(items) => match items {
SingleOrVec::Single(item) => {
Some(ExtendedSchema::resolved(
&root_schema.definitions,
&*item,
))
}
SingleOrVec::Vec(_) => None, // FIXME: handle this (hard).
},
None => None,
}),
})
.flatten()
.flat_map(|schema| {
value_completions(
&root_schema.definitions,
schema,
None,
if additional_edits.is_empty() {
None
} else {
Some(additional_edits.clone())
},
comma_before,
false,
)
})
.unique_by(|comp| comp.insert_text.clone())
.collect();
}
NodeRef::Value(_) => {
let query_path = before.path.clone();
let range = before
.syntax
.element
.as_ref()
.map(|el| doc.mapper.range(el.text_range()).unwrap());
return get_schema_objects(query_path, &root_schema, true)
.into_iter()
.flat_map(|schema| {
value_completions(
&root_schema.definitions,
schema,
range,
None,
false,
false,
)
})
.unique_by(|comp| comp.insert_text.clone())
.collect();
}
_ => {
// Look for an incomplete key.
if let Some(before_node) = before.nodes.last() {
if before_node.is_key() {
let query_path = before.path.skip_right(1);
let mut is_root = true;
for node in &before.nodes {
if let NodeRef::Table(t) = node {
if !t.is_pseudo() {
is_root = false;
}
};
}
let range = before
.syntax
.range
.map(|range| doc.mapper.range(range).unwrap());
return get_schema_objects(query_path.clone(), &root_schema, true)
.into_iter()
.flat_map(|s| s.descendants(&root_schema.definitions, 10))
.filter(|(_, s, _)| !s.is_hidden())
.unique_by(|(p, ..)| p.clone())
.map(|(path, schema, required)| {
key_completion(
&root_schema.definitions,
if is_root {
query_path.extend(path)
} else {
path
},
schema,
required,
range,
false,
None,
false,
)
})
.collect();
}
}
}
}
}
}
None => {
// Start of the document
let node = query.after.nodes.last().cloned().unwrap();
if node.is_root() {
let mut query_path = query.after.path.clone();
query_path = query_path.skip_right(1);
let range = query
.after
.syntax
.range
.map(|range| doc.mapper.range(range).unwrap());
return get_schema_objects(query_path.clone(), &root_schema, true)
.into_iter()
.flat_map(|s| s.descendants(&root_schema.definitions, 10))
.filter(|(_, s, _)| !s.is_hidden())
.unique_by(|(p, ..)| p.clone())
.map(|(path, schema, required)| {
key_completion(
&root_schema.definitions,
query_path.extend(path),
schema,
required,
range,
true,
None,
false,
)
})
.collect();
}
}
}
Vec::new()
}
fn detail_text(schema: Option<ExtendedSchema>, text: Option<&str>) -> Option<String> {
if schema.is_none() && text.is_none() {
return None;
}
let schema_title = schema
.and_then(|o| o.schema.metadata.as_ref())
.and_then(|meta| meta.title.clone())
.unwrap_or_default();
Some(format!(
"{text}{schema}",
schema = if schema_title.is_empty() {
"".into()
} else if text.is_none() {
format!("({})", schema_title)
} else {
format!(" ({})", schema_title)
},
text = text.map(|t| t.to_string()).unwrap_or_default()
))
}
fn key_documentation(schema: ExtendedSchema) -> Option<Documentation> {
schema
.ext
.docs
.as_ref()
.and_then(|docs| docs.main.as_ref())
.map(|doc| {
Documentation::MarkupContent(MarkupContent {
kind: MarkupKind::Markdown,
value: doc.clone(),
})
})
.or_else(|| {
schema
.schema
.metadata
.as_ref()
.and_then(|meta| meta.description.clone())
.map(|desc| {
Documentation::MarkupContent(MarkupContent {
kind: MarkupKind::Markdown,
value: desc,
})
})
})
}
#[allow(clippy::too_many_arguments)]
fn key_completion(
_defs: &Map<String, Schema>,
path: dom::Path,
schema: ExtendedSchema,
required: bool,
range: Option<Range>,
eq: bool,
additional_text_edits: Option<Vec<TextEdit>>,
comma_before: bool,
) -> CompletionItem {
let insert_text = if eq {
with_comma(format!("{} = ", path.dotted()), comma_before)
} else {
with_comma(path.dotted(), comma_before)
};
CompletionItem {
label: path.dotted(),
additional_text_edits,
sort_text: if required {
Some(required_text(&path.dotted()))
} else {
None
},
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: insert_text.clone(),
})
}),
insert_text: Some(insert_text),
kind: if schema.is(InstanceType::Object) {
Some(CompletionItemKind::Struct)
} else {
Some(CompletionItemKind::Variable)
},
detail: detail_text(
Some(schema.clone()),
if required { Some("required") } else { None },
),
documentation: key_documentation(schema.clone()),
preselect: Some(true),
..Default::default()
}
}
fn const_value_documentation(schema: ExtendedSchema) -> Option<Documentation> {
schema.ext.docs.as_ref().and_then(|d| {
d.const_value.as_ref().map(|doc| {
Documentation::MarkupContent(MarkupContent {
kind: MarkupKind::Markdown,
value: doc.clone(),
})
})
})
}
fn default_value_documentation(schema: ExtendedSchema) -> Option<Documentation> {
schema.ext.docs.as_ref().and_then(|d| {
d.default_value.as_ref().map(|doc| {
Documentation::MarkupContent(MarkupContent {
kind: MarkupKind::Markdown,
value: doc.clone(),
})
})
})
}
fn enum_documentation(schema: ExtendedSchema, idx: usize) -> Option<Documentation> {
schema.ext.docs.as_ref().and_then(|d| {
d.enum_values.as_ref().and_then(|doc| {
doc.get(idx).and_then(|d| {
d.as_ref().map(|doc| {
Documentation::MarkupContent(MarkupContent {
kind: MarkupKind::Markdown,
value: doc.clone(),
})
})
})
})
})
}
fn value_completions(
defs: &Map<String, Schema>,
schema: ExtendedSchema,
range: Option<Range>,
additional_text_edits: Option<Vec<TextEdit>>,
comma_before: bool,
space_before: bool,
) -> Vec<CompletionItem> {
// Only one constant allowed.
if let Some(c) = &schema.schema.const_value {
return value_insert(c, range, comma_before, space_before)
.map(|value_completion| {
vec![CompletionItem {
additional_text_edits,
detail: detail_text(Some(schema.clone()), None),
documentation: const_value_documentation(schema.clone()),
preselect: Some(true),
..value_completion
}]
})
.unwrap_or_default();
}
// Enums only if there are any.
if let Some(e) = &schema.schema.enum_values {
return e
.iter()
.enumerate()
.filter_map(|(i, e)| {
value_insert(e, range, comma_before, space_before).map(|value_completion| {
CompletionItem {
additional_text_edits: additional_text_edits.clone(),
detail: detail_text(Some(schema.clone()), None),
documentation: enum_documentation(schema.clone(), i),
preselect: Some(true),
..value_completion
}
})
})
.collect();
}
if let Some(default) = schema
.schema
.metadata
.as_ref()
.and_then(|m| m.default.as_ref())
{
if let Some(value_completion) = value_insert(default, range, comma_before, space_before) {
return vec![CompletionItem {
additional_text_edits,
detail: detail_text(Some(schema.clone()), None),
documentation: default_value_documentation(schema.clone()),
preselect: Some(true),
sort_text: Some(format!("{}", 1 as char)),
..value_completion
}];
}
}
let mut completions = Vec::new();
// Default values.
match &schema.schema.instance_type {
Some(tys) => match tys {
SingleOrVec::Single(ty) => {
if let Some(c) = empty_value_inserts(
defs,
schema.clone(),
**ty,
range,
comma_before,
space_before,
) {
for value_completion in c {
completions.push(CompletionItem {
additional_text_edits: additional_text_edits.clone(),
detail: detail_text(Some(schema.clone()), None),
preselect: Some(true),
..value_completion
});
}
}
}
SingleOrVec::Vec(tys) => {
for ty in tys {
if let Some(c) = empty_value_inserts(
defs,
schema.clone(),
*ty,
range,
comma_before,
space_before,
) {
for value_completion in c {
completions.push(CompletionItem {
additional_text_edits: additional_text_edits.clone(),
detail: detail_text(Some(schema.clone()), None),
preselect: Some(true),
..value_completion
});
}
}
}
}
},
None => {}
}
completions
}
fn with_comma(text: String, comma_before: bool) -> String {
if comma_before {
format!(", {}", text)
} else {
text
}
}
fn with_leading_space(text: String, space_before: bool) -> String {
if space_before {
format!(" {}", text)
} else {
text
}
}
// To make sure required completions are at the top, we prefix it
// with an invisible character
fn required_text(key: &str) -> String {
format!("{}{}", 1 as char, key)
}
fn value_insert(
value: &Value,
range: Option<Range>,
comma_before: bool,
space_before: bool,
) -> Option<CompletionItem> {
match value {
Value::Object(_) => {
let insert_text = format_value(value, true, 0);
Some(CompletionItem {
label: "table".into(),
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_leading_space(
with_comma(insert_text.clone(), space_before),
space_before,
),
})
}),
kind: Some(CompletionItemKind::Struct),
insert_text_format: Some(InsertTextFormat::Snippet),
insert_text: Some(with_leading_space(
with_comma(insert_text, comma_before),
space_before,
)),
..Default::default()
})
}
Value::Bool(_) => {
let insert_text = format_value(value, true, 0);
Some(CompletionItem {
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_leading_space(
with_comma(insert_text.clone(), comma_before),
space_before,
),
})
}),
kind: Some(CompletionItemKind::Constant),
insert_text_format: Some(InsertTextFormat::Snippet),
insert_text: Some(with_leading_space(
with_comma(insert_text, comma_before),
space_before,
)),
label: format_value(value, false, 0),
..Default::default()
})
}
Value::Number(_) => {
let insert_text = format_value(value, true, 0);
Some(CompletionItem {
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_leading_space(
with_comma(insert_text.clone(), comma_before),
space_before,
),
})
}),
kind: Some(CompletionItemKind::Constant),
insert_text_format: Some(InsertTextFormat::Snippet),
insert_text: Some(with_leading_space(
with_comma(insert_text, comma_before),
space_before,
)),
label: format_value(value, false, 0),
..Default::default()
})
}
Value::String(_) => {
let insert_text = format_value(value, true, 0);
Some(CompletionItem {
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_leading_space(
with_comma(insert_text.clone(), comma_before),
space_before,
),
})
}),
kind: Some(CompletionItemKind::Constant),
insert_text: Some(with_leading_space(
with_comma(insert_text, comma_before),
space_before,
)),
label: format_value(value, false, 0),
insert_text_format: Some(InsertTextFormat::Snippet),
..Default::default()
})
}
Value::Array(_) => {
let insert_text = format_value(value, true, 0);
Some(CompletionItem {
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_leading_space(
with_comma(insert_text.clone(), comma_before),
space_before,
),
})
}),
kind: Some(CompletionItemKind::Constant),
insert_text_format: Some(InsertTextFormat::Snippet),
insert_text: Some(with_leading_space(
with_comma(insert_text, comma_before),
space_before,
)),
label: "array".into(),
..Default::default()
})
}
Value::Null => None,
}
}
fn empty_value_inserts(
defs: &Map<String, Schema>,
schema: ExtendedSchema,
ty: InstanceType,
range: Option<Range>,
comma_before: bool,
space_before: bool,
) -> Option<Vec<CompletionItem>> {
match ty {
InstanceType::Boolean => Some(vec![
CompletionItem {
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_leading_space(
with_comma("true".into(), comma_before),
space_before,
),
})
}),
kind: Some(CompletionItemKind::Value),
insert_text: Some(with_leading_space(
with_comma("true".into(), comma_before),
space_before,
)),
insert_text_format: Some(InsertTextFormat::Snippet),
label: "true".into(),
..Default::default()
},
CompletionItem {
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_leading_space(
with_comma("false".into(), comma_before),
space_before,
),
})
}),
kind: Some(CompletionItemKind::Value),
insert_text: Some(with_leading_space(
with_comma("${0:false}".into(), comma_before),
space_before,
)),
insert_text_format: Some(InsertTextFormat::Snippet),
label: "false".into(),
..Default::default()
},
]),
InstanceType::Array => Some(vec![CompletionItem {
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_leading_space(
with_comma("[ $0 ]".into(), comma_before),
space_before,
),
})
}),
kind: Some(CompletionItemKind::Value),
insert_text: Some(with_leading_space(
with_comma("[ $0 ]".into(), comma_before),
space_before,
)),
insert_text_format: Some(InsertTextFormat::Snippet),
label: "empty array".into(),
..Default::default()
}]),
InstanceType::Number => Some(vec![CompletionItem {
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_comma("${0:0.0}".into(), comma_before),
})
}),
kind: Some(CompletionItemKind::Value),
insert_text: Some(with_leading_space(
with_comma("${0:0.0}".into(), comma_before),
space_before,
)),
insert_text_format: Some(InsertTextFormat::Snippet),
label: "number".into(),
..Default::default()
}]),
InstanceType::String => Some(vec![
CompletionItem {
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_leading_space(
with_comma(r#""$0""#.into(), comma_before),
space_before,
),
})
}),
kind: Some(CompletionItemKind::Value),
insert_text: Some(with_leading_space(
with_comma(r#""$0""#.into(), comma_before),
space_before,
)),
insert_text_format: Some(InsertTextFormat::Snippet),
sort_text: Some(required_text("1string")),
label: "string".into(),
..Default::default()
},
CompletionItem {
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_leading_space(
with_comma(r#""""$0""""#.into(), comma_before),
space_before,
),
})
}),
kind: Some(CompletionItemKind::Value),
insert_text: Some(with_leading_space(
with_comma(r#""""$0""""#.into(), comma_before),
space_before,
)),
insert_text_format: Some(InsertTextFormat::Snippet),
sort_text: Some(required_text("2multi-line string")),
label: "multi-line string".into(),
..Default::default()
},
CompletionItem {
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_leading_space(
with_comma(r#"'$0'"#.into(), comma_before),
space_before,
),
})
}),
kind: Some(CompletionItemKind::Value),
insert_text: Some(with_leading_space(
with_comma(r#"'$0'"#.into(), comma_before),
space_before,
)),
insert_text_format: Some(InsertTextFormat::Snippet),
sort_text: Some("3literal string".into()),
label: "literal string".into(),
..Default::default()
},
CompletionItem {
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_leading_space(
with_comma(r#"'''$0'''"#.into(), comma_before),
space_before,
),
})
}),
kind: Some(CompletionItemKind::Value),
insert_text: Some(with_leading_space(
with_comma(r#"'''$0'''"#.into(), comma_before),
space_before,
)),
insert_text_format: Some(InsertTextFormat::Snippet),
sort_text: Some("4multi-line literal string".into()),
label: "multi-line literal string".into(),
..Default::default()
},
]),
InstanceType::Integer => Some(vec![CompletionItem {
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_leading_space(
with_comma("${0:0}".into(), comma_before),
space_before,
),
})
}),
kind: Some(CompletionItemKind::Value),
insert_text: Some(with_leading_space(
with_comma("${0:0}".into(), comma_before),
space_before,
)),
insert_text_format: Some(InsertTextFormat::Snippet),
label: "integer".into(),
..Default::default()
}]),
InstanceType::Object => match &schema.schema.object {
Some(o) => {
if o.properties.is_empty() {
Some(vec![CompletionItem {
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_leading_space(
with_comma(r#"{ $0 }"#.into(), comma_before),
space_before,
),
})
}),
kind: Some(CompletionItemKind::Value),
insert_text: Some(with_leading_space(
with_comma(r#"{ $0 }"#.into(), comma_before),
space_before,
)),
insert_text_format: Some(InsertTextFormat::Snippet),
label: "table".into(),
..Default::default()
}])
} else {
let mut snippet = "{ ".to_string();
let mut idx: usize = 1;
for key in o.properties.keys().sorted() {
let prop_schema = o.properties.get(key).unwrap();
if let Some(prop_schema) = ExtendedSchema::resolved(defs, prop_schema) {
if o.required.contains(key)
|| schema
.ext
.init_keys
.as_ref()
.map(|i| i.iter().any(|i| i == key))
.unwrap_or(false)
{
if idx != 1 {
snippet += ", "
}
snippet += &format!(
"{} = {}",
key,
default_value_snippet(defs, prop_schema, idx)
);
idx += 1;
}
}
}
snippet += "$0 }";
Some(vec![CompletionItem {
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_leading_space(
with_comma(snippet.clone(), comma_before),
space_before,
),
})
}),
kind: Some(CompletionItemKind::Value),
insert_text: Some(with_leading_space(
with_comma(snippet, comma_before),
space_before,
)),
insert_text_format: Some(InsertTextFormat::Snippet),
label: "table".into(),
..Default::default()
}])
}
}
None => Some(vec![CompletionItem {
text_edit: range.map(|range| {
CompletionTextEdit::Edit(TextEdit {
range,
new_text: with_leading_space(
with_comma(r#"{ $0 }"#.into(), comma_before),
space_before,
),
})
}),
kind: Some(CompletionItemKind::Value),
insert_text: Some(with_leading_space(
with_comma(r#"{ $0 }"#.into(), comma_before),
space_before,
)),
insert_text_format: Some(InsertTextFormat::Snippet),
label: "table".into(),
..Default::default()
}]),
},
InstanceType::Null => None,
}
}
fn format_value(value: &Value, snippet: bool, snippet_index: usize) -> String {
match value {
Value::Null => String::new(),
Value::Bool(b) => {
if snippet {
format!(r#"${{{}:{}}}"#, snippet_index, b)
} else {
b.to_string()
}
}
Value::Number(n) => {
if snippet {
format!(r#"${{{}:{}}}"#, snippet_index, n)
} else {
n.to_string()
}
}
Value::String(s) => {
if snippet {
format!(r#""${{{}:{}}}""#, snippet_index, s)
} else {
format!(r#""{}""#, s)
}
}
Value::Array(arr) => {
let mut s = String::new();
s += "[ ";
if snippet {
s += &format!("${{{}:", snippet_index);
}
for (i, val) in arr.iter().enumerate() {
if i != 0 {
s += ", ";
s += &format_value(val, false, 0);
}
}
if snippet {
s += "}"
}
s += " ]";
s
}
Value::Object(obj) => {
let mut s = String::new();
s += "{ ";
if snippet {
s += &format!("${{{}:", snippet_index);
}
for (i, (key, val)) in obj.iter().enumerate() {
if i != 0 {
s += ", ";
s += key;
s += " = ";
s += &format_value(val, false, 0);
}
}
if snippet {
s += "}"
}
s += " }";
s
}
}
}
fn default_value_snippet(
_defs: &Map<String, Schema>,
schema: ExtendedSchema,
idx: usize,
) -> String {
if let Some(c) = &schema.schema.const_value {
return format_value(c, true, idx);
}
if let Some(e) = &schema.schema.enum_values {
if let Some(e) = e.iter().next() {
return format_value(e, true, idx);
}
}
if let Some(default) = schema
.schema
.metadata
.as_ref()
.and_then(|m| m.default.as_ref())
{
return format_value(default, true, idx);
}
format!("${}", idx)
}
// Whether the key should be completed according to the contents of the tree,
// e.g. we shouldn't offer completions for value paths that already exist.
fn valid_key(path: &dom::Path, dom_paths: &HashSet<dom::Path>, _dom: &RootNode) -> bool {
!dom_paths.contains(path)
}
|
Below is an extract from a TypeScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid TypeScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical TypeScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., generics, decorators). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching TypeScript. It should be similar to a school exercise, a tutorial, or a TypeScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching TypeScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
export interface HashMapofAppConf {
[key: string]: AppConf;
}
export interface AppConf {
baseUrl: string,
specs?: string
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
typescript
| 2 |
export interface HashMapofAppConf {
[key: string]: AppConf;
}
export interface AppConf {
baseUrl: string,
specs?: string
}
|
Below is an extract from a C program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid C code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical C concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., kernel development and compiler design). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching C. It should be similar to a school exercise, a tutorial, or a C course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
// Copyright 2013 Tilera Corporation. All Rights Reserved.
//
// The source code contained or described herein and all documents
// related to the source code ("Material") are owned by Tilera
// Corporation or its suppliers or licensors. Title to the Material
// remains with Tilera Corporation or its suppliers and licensors. The
// software is licensed under the Tilera MDE License.
//
// Unless otherwise agreed by Tilera in writing, you may not remove or
// alter this notice or any other notice embedded in Materials by Tilera
// or Tilera's suppliers or licensors in any way.
//
//
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <gxio/trio.h>
#include <gxpci/gxpci.h>
#include <tmc/cpus.h>
#include <tmc/alloc.h>
#include <tmc/task.h>
#include <arch/cycle.h>
#include <tmc/perf.h>
#define DATA_VALIDATION
#if 0
#define PRINT_CMD_INFO
#endif
#define VERIFY_ZERO(VAL, WHAT) \
do { \
long long __val = (VAL); \
if (__val != 0) \
tmc_task_die("Failure in '%s': %lld: %s.", \
(WHAT), __val, gxpci_strerror(__val)); \
} while (0)
// The packet pool memory size.
#define MAP_LENGTH (16 * 1024 * 1024)
#define MAX_PKT_SIZE (1 << (GXPCI_MAX_CMD_SIZE_BITS - 1))
#define PKTS_IN_POOL (MAP_LENGTH / MAX_PKT_SIZE)
// The number of packets that this program sends.
#define SEND_PKT_COUNT 300000
// The size of a single packet.
#define SEND_PKT_SIZE (4096)
// The size of receive buffers posted by the receiver.
#define RECV_BUFFER_SIZE (4096)
// The size of space that the receiver wants to preserve
// at the beginning of the packet, e.g. for packet header
// that is to be filled after the packet is received.
#if 0
#define RECV_PKT_HEADROOM 14
#else
#define RECV_
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
c
| 1 |
// Copyright 2013 Tilera Corporation. All Rights Reserved.
//
// The source code contained or described herein and all documents
// related to the source code ("Material") are owned by Tilera
// Corporation or its suppliers or licensors. Title to the Material
// remains with Tilera Corporation or its suppliers and licensors. The
// software is licensed under the Tilera MDE License.
//
// Unless otherwise agreed by Tilera in writing, you may not remove or
// alter this notice or any other notice embedded in Materials by Tilera
// or Tilera's suppliers or licensors in any way.
//
//
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <gxio/trio.h>
#include <gxpci/gxpci.h>
#include <tmc/cpus.h>
#include <tmc/alloc.h>
#include <tmc/task.h>
#include <arch/cycle.h>
#include <tmc/perf.h>
#define DATA_VALIDATION
#if 0
#define PRINT_CMD_INFO
#endif
#define VERIFY_ZERO(VAL, WHAT) \
do { \
long long __val = (VAL); \
if (__val != 0) \
tmc_task_die("Failure in '%s': %lld: %s.", \
(WHAT), __val, gxpci_strerror(__val)); \
} while (0)
// The packet pool memory size.
#define MAP_LENGTH (16 * 1024 * 1024)
#define MAX_PKT_SIZE (1 << (GXPCI_MAX_CMD_SIZE_BITS - 1))
#define PKTS_IN_POOL (MAP_LENGTH / MAX_PKT_SIZE)
// The number of packets that this program sends.
#define SEND_PKT_COUNT 300000
// The size of a single packet.
#define SEND_PKT_SIZE (4096)
// The size of receive buffers posted by the receiver.
#define RECV_BUFFER_SIZE (4096)
// The size of space that the receiver wants to preserve
// at the beginning of the packet, e.g. for packet header
// that is to be filled after the packet is received.
#if 0
#define RECV_PKT_HEADROOM 14
#else
#define RECV_PKT_HEADROOM 0
#endif
//
// These are the spaces leading and trailing the packet
// that are inspected to validate DMA correctness.
//
#if 0
#define PKT_CLEAR_SPACE 16
#else
#define PKT_CLEAR_SPACE 0
#endif
cpu_set_t desired_cpus;
// The running cpu number.
int cpu_rank = 1;
// The TRIO index.
int trio_index = 0;
// The queue index of a C2C queue, used by both sender and receiver.
int queue_index;
int rem_link_index;
// The local MAC index.
int loc_mac;
int send_pkt_count = SEND_PKT_COUNT;
int send_pkt_size = SEND_PKT_SIZE;
static void usage(void)
{
fprintf(stderr, "Usage: c2c_receiver [--mac=<local mac port #>] "
"[--rem_link_index=<remote port link index>] "
"[--queue_index=<send queue index>] "
"[--send_pkt_size=<packet size>] "
"[--cpu_rank=<cpu_id>] "
"[--send_pkt_count=<packet count>]\n");
exit(EXIT_FAILURE);
}
static char *
shift_option(char ***arglist, const char* option)
{
char** args = *arglist;
char* arg = args[0], **rest = &args[1];
int optlen = strlen(option);
char* val = arg + optlen;
if (option[optlen - 1] != '=')
{
if (strcmp(arg, option))
return NULL;
}
else
{
if (strncmp(arg, option, optlen - 1))
return NULL;
if (arg[optlen - 1] == '\0')
val = *rest++;
else if (arg[optlen - 1] != '=')
return NULL;
}
*arglist = rest;
return val;
}
// Parses command line arguments in order to fill in the MAC and bus
// address variables.
void parse_args(int argc, char** argv)
{
char **args = &argv[1];
// Scan options.
//
while (*args)
{
char* opt = NULL;
if ((opt = shift_option(&args, "--mac=")))
loc_mac = atoi(opt);
else if ((opt = shift_option(&args, "--rem_link_index=")))
rem_link_index = atoi(opt);
else if ((opt = shift_option(&args, "--queue_index=")))
queue_index = atoi(opt);
else if ((opt = shift_option(&args, "--send_pkt_size=")))
send_pkt_size = atoi(opt);
else if ((opt = shift_option(&args, "--cpu_rank=")))
cpu_rank = atoi(opt);
else if ((opt = shift_option(&args, "--send_pkt_count=")))
send_pkt_count = atoi(opt);
else if ((opt = shift_option(&args, "--cpu_rank=")))
cpu_rank = atoi(opt);
else
usage();
}
}
void do_recv(gxpci_context_t* context, void* buf_mem)
{
uint64_t finish_cycles;
float gigabits;
float cycles;
float gbps;
uint64_t start_cycles = 0;
unsigned int sent_pkts = 0;
int result;
int recv_pkt_count = 0;
gxpci_cmd_t cmd = {
.buffer = buf_mem,
.size = RECV_BUFFER_SIZE,
};
#ifdef DATA_VALIDATION
int recv_pkt_size;
if (RECV_PKT_HEADROOM + send_pkt_size > RECV_BUFFER_SIZE)
recv_pkt_size = RECV_BUFFER_SIZE - RECV_PKT_HEADROOM;
else
recv_pkt_size = send_pkt_size;
//
// Receive one packet first to validate the DMA correctness.
//
char* source = (char*)buf_mem;
for (int i = 0; i < (PKT_CLEAR_SPACE + RECV_PKT_HEADROOM); i++)
source[i] = 0x55;
source += PKT_CLEAR_SPACE + RECV_PKT_HEADROOM + recv_pkt_size;
for (int i = 0; i < PKT_CLEAR_SPACE; i++)
source[i] = 0x55;
cmd.buffer = buf_mem + PKT_CLEAR_SPACE;
result = gxpci_post_cmd(context, &cmd);
VERIFY_ZERO(result, "gxpci_post_cmd()");
sent_pkts++;
gxpci_comp_t comp;
result = gxpci_get_comps(context, &comp, 1, 1);
if (result == GXPCI_ERESET)
{
printf("do_recv: channel is reset\n");
goto recv_reset;
}
if (recv_pkt_size != comp.size)
tmc_task_die("Validation packet size error, expecting %d, getting %d.\n",
recv_pkt_size, comp.size);
// Check results.
source = (char*)buf_mem;
for (int i = 0; i < (PKT_CLEAR_SPACE + RECV_PKT_HEADROOM); i++)
{
if (source[i] != 0x55)
tmc_task_die("Leading data corruption at byte %d, %d.\n", i, source[i]);
}
source += PKT_CLEAR_SPACE + RECV_PKT_HEADROOM;
for (int i = 0; i < recv_pkt_size; i++)
{
if (source[i] != (char)(i + (i >> 8) + 1))
tmc_task_die("Data payload corruption at byte %d, %d.\n", i, source[i]);
}
source += recv_pkt_size;
for (int i = 0; i < PKT_CLEAR_SPACE; i++)
{
if (source[i] != 0x55)
tmc_task_die("Trailing data corruption at byte %d, addr %p value %d.\n",
i, &source[i], source[i]);
}
printf("Data validation test passed.\n");
#endif
start_cycles = get_cycle_count();
while (recv_pkt_count < send_pkt_count)
{
int cmds_to_post;
int credits;
credits = gxpci_get_cmd_credits(context);
#ifdef DATA_VALIDATION
cmds_to_post = MIN(credits, (send_pkt_count + 1 - sent_pkts));
#else
cmds_to_post = MIN(credits, send_pkt_count - sent_pkts));
#endif
for (int i = 0; i < cmds_to_post; i++)
{
cmd.buffer = buf_mem +
((sent_pkts + i) % PKTS_IN_POOL) * MAX_PKT_SIZE;
result = gxpci_post_cmd(context, &cmd);
if (result == GXPCI_ERESET)
{
printf("do_recv: channel is reset\n");
goto recv_reset;
}
else if (result == GXPCI_ECREDITS)
break;
VERIFY_ZERO(result, "gxpci_post_cmd()");
sent_pkts++;
}
gxpci_comp_t comp[64];
result = gxpci_get_comps(context, comp, 0, 64);
if (result == GXPCI_ERESET)
{
printf("do_recv: channel is reset\n");
goto recv_reset;
}
for (int i = 0; i < result; i++)
{
#ifdef PRINT_CMD_INFO
printf("Recv buf addr: %#lx size: %d\n",
(unsigned long)comp[i].buffer, comp[i].size);
#endif
recv_pkt_count++;
}
}
recv_reset:
finish_cycles = get_cycle_count();
gigabits = (float)recv_pkt_count * send_pkt_size * 8;
cycles = finish_cycles - start_cycles;
gbps = gigabits / cycles * tmc_perf_get_cpu_speed() / 1e9;
printf("Received %d %d-byte packets: %f gbps\n",
recv_pkt_count, send_pkt_size, gbps);
gxpci_destroy(context);
}
int main(int argc, char**argv)
{
gxio_trio_context_t trio_context_body;
gxio_trio_context_t* trio_context = &trio_context_body;
gxpci_context_t gxpci_context_body;
gxpci_context_t* gxpci_context = &gxpci_context_body;
parse_args(argc, argv);
assert(send_pkt_size <= GXPCI_MAX_CMD_SIZE);
//
// We must bind to a single CPU.
//
if (tmc_cpus_get_my_affinity(&desired_cpus) != 0)
tmc_task_die("tmc_cpus_get_my_affinity() failed.");
// Bind to the cpu_rank'th tile in the cpu set
if (tmc_cpus_set_my_cpu(tmc_cpus_find_nth_cpu(&desired_cpus, cpu_rank)) < 0)
tmc_task_die("tmc_cpus_set_my_cpu() failed.");
//
// This indicates that we need to allocate an ASID ourselves,
// instead of using one that is allocated somewhere else.
//
int asid = GXIO_ASID_NULL;
//
// Get a gxio context.
//
int result = gxio_trio_init(trio_context, trio_index);
VERIFY_ZERO(result, "gxio_trio_init()");
result = gxpci_init(trio_context, gxpci_context, trio_index, loc_mac);
VERIFY_ZERO(result, "gxpci_init()");
result = gxpci_open_queue(gxpci_context, asid,
GXPCI_C2C_RECV,
rem_link_index,
queue_index,
RECV_PKT_HEADROOM,
RECV_BUFFER_SIZE);
if (result == GXPCI_ERESET)
{
gxpci_destroy(gxpci_context);
exit(EXIT_FAILURE);
}
VERIFY_ZERO(result, "gxpci_open_queue()");
//
// Allocate and register data buffers.
//
tmc_alloc_t alloc = TMC_ALLOC_INIT;
tmc_alloc_set_huge(&alloc);
void* buf_mem = tmc_alloc_map(&alloc, MAP_LENGTH);
assert(buf_mem);
result = gxpci_iomem_register(gxpci_context, buf_mem, MAP_LENGTH);
VERIFY_ZERO(result, "gxpci_iomem_register()");
printf("c2c_receiver running on cpu %d, mac %d rem_link_index %d queue %d\n",
cpu_rank, loc_mac, rem_link_index, queue_index);
// Run the test.
do_recv(gxpci_context, buf_mem);
return 0;
}
|
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical PHP concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
<?php
/**
* Description of IntCategoria
*
* @author DocenteUNEMI
*/
interface IntCategoria {
function crear(\EntCategoria $categoria);
function editar(\EntCategoria $categoria);
function eliminar($id,$uid);
function listar();
function buscar($id);
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
php
| 1 |
<?php
/**
* Description of IntCategoria
*
* @author DocenteUNEMI
*/
interface IntCategoria {
function crear(\EntCategoria $categoria);
function editar(\EntCategoria $categoria);
function eliminar($id,$uid);
function listar();
function buscar($id);
}
|
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical JavaScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
import React from "react";
import { connect } from "react-redux";
import Typography from "@material-ui/core/Typography";
import CheckListForm from "./CheckListForm";
import Checklist from "./Checklist";
import TodoListForm from "./TodoListForm";
import TodoList from "./TodoList";
import useChecklistState from "./useChecklistState";
import useTodoState from "./useTodoState";
import "./trip-page.css";
const Checklists = props => {
const { lists, addList, deleteList } = useChecklistState([]);
const { todos, addTodo, deleteTodo } = useTodoState([]);
return (
<div className="lists-wrapper">
<p className="list-label">Pre-Trip</p>
<div className="lists-section">
<div className="list-wrapper">
<Typography component="h4" variant="h5">
Packing List
</Typography>
<CheckListForm
saveList={listText => {
const trimmedText = listText.trim();
if (trimmedText.length > 0) {
addList(trimmedText);
}
}}
/>
<Checklist lists={lists} deleteList={deleteList} />
</div>
<div className="list-wrapper">
<Typography component="h4" variant="h5">
To Do List
</Typography>
<TodoListForm
saveTodo={todoText => {
const trimmedTodoText = todoText.trim();
if (trimmedTodoText.length > 0) {
addTodo(trimmedTodoText);
}
}}
/>
<TodoList todos={todos} deleteTodo={deleteTodo} />
</div>
</div>
</div>
);
};
const mstp = state => ({
packing: state.trips.singleTrip.packing,
todos: state.trips.singleTrip.todos
});
export default connect(
mstp,
null
)(Checklists);
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
javascript
| 3 |
import React from "react";
import { connect } from "react-redux";
import Typography from "@material-ui/core/Typography";
import CheckListForm from "./CheckListForm";
import Checklist from "./Checklist";
import TodoListForm from "./TodoListForm";
import TodoList from "./TodoList";
import useChecklistState from "./useChecklistState";
import useTodoState from "./useTodoState";
import "./trip-page.css";
const Checklists = props => {
const { lists, addList, deleteList } = useChecklistState([]);
const { todos, addTodo, deleteTodo } = useTodoState([]);
return (
<div className="lists-wrapper">
<p className="list-label">Pre-Trip</p>
<div className="lists-section">
<div className="list-wrapper">
<Typography component="h4" variant="h5">
Packing List
</Typography>
<CheckListForm
saveList={listText => {
const trimmedText = listText.trim();
if (trimmedText.length > 0) {
addList(trimmedText);
}
}}
/>
<Checklist lists={lists} deleteList={deleteList} />
</div>
<div className="list-wrapper">
<Typography component="h4" variant="h5">
To Do List
</Typography>
<TodoListForm
saveTodo={todoText => {
const trimmedTodoText = todoText.trim();
if (trimmedTodoText.length > 0) {
addTodo(trimmedTodoText);
}
}}
/>
<TodoList todos={todos} deleteTodo={deleteTodo} />
</div>
</div>
</div>
);
};
const mstp = state => ({
packing: state.trips.singleTrip.packing,
todos: state.trips.singleTrip.todos
});
export default connect(
mstp,
null
)(Checklists);
|
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical JavaScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
/*
* @Author: lenovo
* @Date: 2017-09-25 14:57:11
* @Last Modified by: lenovo
* @Last Modified time: 2017-09-25 15:13:56
*/
class drag{
constructor(obj){ //constructor是用来添加属性的
this.obj=obj;
}
move(){ //move用来添加方法
let that=this;
this.obj.addEventListener('mousedown', function(e){
let oX=e.offsetX, oY=e.offsetY;
document.addEventListener('mousemove', fn);
function fn(e){
let cX=e.clientX-oX, cY=e.clientY-oY;
that.obj.style.left=`${cX}px`;
that.obj.style.top=`${cY}px`;
}
that.obj.addEventListener('mouseup',function(){
document.removeEventListener('mousemove',fn);
})
})
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
javascript
| 4 |
/*
* @Author: lenovo
* @Date: 2017-09-25 14:57:11
* @Last Modified by: lenovo
* @Last Modified time: 2017-09-25 15:13:56
*/
class drag{
constructor(obj){ //constructor是用来添加属性的
this.obj=obj;
}
move(){ //move用来添加方法
let that=this;
this.obj.addEventListener('mousedown', function(e){
let oX=e.offsetX, oY=e.offsetY;
document.addEventListener('mousemove', fn);
function fn(e){
let cX=e.clientX-oX, cY=e.clientY-oY;
that.obj.style.left=`${cX}px`;
that.obj.style.top=`${cY}px`;
}
that.obj.addEventListener('mouseup',function(){
document.removeEventListener('mousemove',fn);
})
})
}
}
|
Below is an extract from a Kotlin program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Kotlin code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Kotlin concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., coroutines, extension functions). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Kotlin. It should be similar to a school exercise, a tutorial, or a Kotlin course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Kotlin. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package com.whis
import com.whis.app.Application
import com.whis.app.service.HttpTestService
import com.whis.base.common.RequestUtil
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit.jupiter.SpringExtension
@SpringBootTest(classes = [(Application::class)])
@ExtendWith(SpringExtension::class)
class TestServiceTest {
private val logger = LoggerFactory.getLogger(TestServiceTest::class.java)
@Autowired lateinit var httpTestService: HttpTestService
@Test
fun test() {
httpTestService.testGetRequest()
// httpTestService.testPostRequest()
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
kotlin
| 1 |
package com.whis
import com.whis.app.Application
import com.whis.app.service.HttpTestService
import com.whis.base.common.RequestUtil
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit.jupiter.SpringExtension
@SpringBootTest(classes = [(Application::class)])
@ExtendWith(SpringExtension::class)
class TestServiceTest {
private val logger = LoggerFactory.getLogger(TestServiceTest::class.java)
@Autowired lateinit var httpTestService: HttpTestService
@Test
fun test() {
httpTestService.testGetRequest()
// httpTestService.testPostRequest()
}
}
|
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content.
- Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse.
- Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow.
- Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson.
- Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes.
The extract:
# mirth
Mirth Connect repo
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
markdown
| 1 |
# mirth
Mirth Connect repo
|
Below is an extract from a Swift program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Swift code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Swift concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., protocols, extensions). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Swift. It should be similar to a school exercise, a tutorial, or a Swift course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Swift. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
//
// HeaderCollectionViewCell.swift
// TikiToker
//
// Created by <NAME> on 21/12/2020.
//
import UIKit
class HeaderCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configure(using image: UIImage) {
self.imageView.image = image
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
swift
| 2 |
//
// HeaderCollectionViewCell.swift
// TikiToker
//
// Created by <NAME> on 21/12/2020.
//
import UIKit
class HeaderCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configure(using image: UIImage) {
self.imageView.image = image
}
}
|
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical JavaScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
// Export: DiagnosisOfDeath
export { default as DiagnosisOfDeath } from "./DiagnosisOfDeath/DiagnosisOfDeath.component";
// Export: Ecg
export { default as Ecg } from "./Ecg/Ecg.component";
// Export: Media
export { default as Media } from "./Media/Media.component";
// Export: Notes
export { default as Notes } from "./Notes/Notes.component";
// Export: PatientReport
export { default as PatientReport } from "./PatientReport/PatientReport.component";
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
javascript
| 1 |
// Export: DiagnosisOfDeath
export { default as DiagnosisOfDeath } from "./DiagnosisOfDeath/DiagnosisOfDeath.component";
// Export: Ecg
export { default as Ecg } from "./Ecg/Ecg.component";
// Export: Media
export { default as Media } from "./Media/Media.component";
// Export: Notes
export { default as Notes } from "./Notes/Notes.component";
// Export: PatientReport
export { default as PatientReport } from "./PatientReport/PatientReport.component";
|
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content.
- Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse.
- Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow.
- Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson.
- Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes.
The extract:
---
layout: repository
title: Jellyfish
published: true
tags:
- Medical Data Storage
headline: Data Upload
purpose: Manages uploads of health data through sandcastle
github_name: jellyfish
---
Under active development
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
markdown
| 1 |
---
layout: repository
title: Jellyfish
published: true
tags:
- Medical Data Storage
headline: Data Upload
purpose: Manages uploads of health data through sandcastle
github_name: jellyfish
---
Under active development
|
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
Add another point if the program addresses practical C# concepts, even if it lacks comments.
Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments.
Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section.
Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemy : MonoBehaviour
{
[Header("Set Enemy Prefab")]
//敵プレハブ
public GameObject prefab;
[Header("Set Interval Min and Max")]
//時間間隔の最小値
[Range(1f, 3f)]
public float minTime = 2f;
//時間間隔の最大値
[Range(4f, 8f)]
public float maxTime = 5f;
[Header("Set X Position Min and Max")]
//敵生成時間間隔
private float interval;
//経過時間
public float time = 0f;
timer timer;
zanki z;
// Start is called before the first frame update
void Start()
{
//時間間隔を決定する
interval = GetRandomTime(); ;
timer = GameObject.Find("time").GetComponent<timer>();
z = GameObject.Find("fight").GetComponent<zanki>();
}
// Update is called once per frame
void Update()
{
//時間計測
time += Time.deltaTime;
if (timer.time > 0&& z.getzannki() > 0)
{
//経過時間が生成時間になったとき(生成時間より大きくなったとき)
if (time > interval)
{
//enemyをインスタンス化する(生成する)
GameObject enemy1 = Instantiate(prefab);
//生成した敵の座標を決定する(現状X=0,Y=10,Z=20の位置に出力)
enemy1.transform.position = new Vector3(4.35f, 1.4f, 5);
//経過時間を初期化して再度時間計測を始める
time = 0f;
//次に発生する時間間隔を決定する
interval = GetRandomTime();
}
}
}
//ランダムな時間を生成する関数
private float GetRandomTime()
{
return Random.Range(minTime, maxTime);
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
csharp
| 3 |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemy : MonoBehaviour
{
[Header("Set Enemy Prefab")]
//敵プレハブ
public GameObject prefab;
[Header("Set Interval Min and Max")]
//時間間隔の最小値
[Range(1f, 3f)]
public float minTime = 2f;
//時間間隔の最大値
[Range(4f, 8f)]
public float maxTime = 5f;
[Header("Set X Position Min and Max")]
//敵生成時間間隔
private float interval;
//経過時間
public float time = 0f;
timer timer;
zanki z;
// Start is called before the first frame update
void Start()
{
//時間間隔を決定する
interval = GetRandomTime(); ;
timer = GameObject.Find("time").GetComponent<timer>();
z = GameObject.Find("fight").GetComponent<zanki>();
}
// Update is called once per frame
void Update()
{
//時間計測
time += Time.deltaTime;
if (timer.time > 0&& z.getzannki() > 0)
{
//経過時間が生成時間になったとき(生成時間より大きくなったとき)
if (time > interval)
{
//enemyをインスタンス化する(生成する)
GameObject enemy1 = Instantiate(prefab);
//生成した敵の座標を決定する(現状X=0,Y=10,Z=20の位置に出力)
enemy1.transform.position = new Vector3(4.35f, 1.4f, 5);
//経過時間を初期化して再度時間計測を始める
time = 0f;
//次に発生する時間間隔を決定する
interval = GetRandomTime();
}
}
}
//ランダムな時間を生成する関数
private float GetRandomTime()
{
return Random.Range(minTime, maxTime);
}
}
|
Below is an extract from a TypeScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid TypeScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical TypeScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., generics, decorators). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching TypeScript. It should be similar to a school exercise, a tutorial, or a TypeScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching TypeScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
import { Component, OnInit, ViewChild } from '@angular/core';
import { CourseModel } from 'penoc-sdk/models/course.model';
import { ResultModel } from 'penoc-sdk/models/result.model';
import { CourseService } from 'penoc-sdk/services/course.service';
import { ResultService } from 'penoc-sdk/services/result.service';
import { LookupService } from 'penoc-sdk/services/lookup.service';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { ResultListComponent } from '../result-list/result-list.component';
@Component({
selector: 'penoc-admin-course',
templateUrl: './course.component.html',
styleUrls: ['./course.component.css']
})
export class CourseComponent implements OnInit {
public course: CourseModel;
public resultList: ResultModel[];
public technicalDifficultyList: Array<Object>;
@ViewChild('results') results: ResultListComponent;
constructor(private courseService: CourseService, private resultService: ResultService,
private lookupService: LookupService, private router: Router, private route: ActivatedRoute) { }
ngOnInit() {
this.lookupService.technicalDifficultyList.subscribe(data => this.technicalDifficultyList = data)
this.route.params.forEach((params: Params) => {
this.loadCourse();
});
}
private loadCourse() {
let courseId: number;
let eventId: number;
this.route.params.forEach((params: Params) => {
courseId = + params['courseId'];
eventId = + params['eventId'];
});
if (courseId > 0) {
this.courseService.getCourse(courseId).subscribe((courseData) => {
this.course = courseData.json()[0];
});
this.resultService.getCourseResults(courseId).subscribe((resultsData) => {
this.resultList = resultsData.json();
this.resultList.forEach(
function (result, resultIndex) {
let resultTime = new Date(result.time);
// add 2 hours (in milliseconds)
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
typescript
| 2 |
import { Component, OnInit, ViewChild } from '@angular/core';
import { CourseModel } from 'penoc-sdk/models/course.model';
import { ResultModel } from 'penoc-sdk/models/result.model';
import { CourseService } from 'penoc-sdk/services/course.service';
import { ResultService } from 'penoc-sdk/services/result.service';
import { LookupService } from 'penoc-sdk/services/lookup.service';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { ResultListComponent } from '../result-list/result-list.component';
@Component({
selector: 'penoc-admin-course',
templateUrl: './course.component.html',
styleUrls: ['./course.component.css']
})
export class CourseComponent implements OnInit {
public course: CourseModel;
public resultList: ResultModel[];
public technicalDifficultyList: Array<Object>;
@ViewChild('results') results: ResultListComponent;
constructor(private courseService: CourseService, private resultService: ResultService,
private lookupService: LookupService, private router: Router, private route: ActivatedRoute) { }
ngOnInit() {
this.lookupService.technicalDifficultyList.subscribe(data => this.technicalDifficultyList = data)
this.route.params.forEach((params: Params) => {
this.loadCourse();
});
}
private loadCourse() {
let courseId: number;
let eventId: number;
this.route.params.forEach((params: Params) => {
courseId = + params['courseId'];
eventId = + params['eventId'];
});
if (courseId > 0) {
this.courseService.getCourse(courseId).subscribe((courseData) => {
this.course = courseData.json()[0];
});
this.resultService.getCourseResults(courseId).subscribe((resultsData) => {
this.resultList = resultsData.json();
this.resultList.forEach(
function (result, resultIndex) {
let resultTime = new Date(result.time);
// add 2 hours (in milliseconds) for South African Time Zone
resultTime.setTime(resultTime.getTime() + 2 * 60 * 60 * 1000);
// truncate to only the time portion
result.time = resultTime.toISOString().substring(11, 19);
result.validTime = true;
}
);
});
} else {
this.course = new CourseModel();
this.course.eventId = eventId;
this.resultList = new Array<ResultModel>();
}
}
public saveCourse(): void {
this.courseService.putCourse(this.course).subscribe(
courseData => {
this.loadCourse();
}
);
this.saveResults();
}
public createCourse(): void {
this.courseService.postCourse(this.course).subscribe(courseData => {
this.course.id = courseData.json().id;
this.saveResults();
this.loadCourse();
});
}
public upsertCourse(): void {
if (this.course.id > 0) {
this.saveCourse();
} else {
this.createCourse();
}
}
public cancelClicked() {
this.loadCourse();
}
private saveResults() {
this.resultList.map(result => result.courseId = this.course.id);
this.resultService.putCourseResults(this.course.id, this.resultList)
.subscribe(response => { });
}
}
|
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical PHP concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
<?php
/**
* 帐号绑定获取任务
* @author zhanghailong
*
*/
class AccountBindGetTask extends AuthTask{
/**
* 用户ID, 若不存在,则使用内部参数 auth
* @var int
*/
public $uid;
/**
* 类型
* @var AccountBindType
*/
public $type;
/**
* 外部 APP KEY
* @var String
*/
public $appKey;
/**
* 输出 外部APP SECRET
*/
public $appSecret;
/**
* 输出 外部用户ID
* @var String
*/
public $eid;
/**
* 输出 验证token
* @var String
*/
public $etoken;
/**
* 输出 过期时间
* @var int
*/
public $expires_in;
public function prefix(){
return "auth-bind";
}
}
?>
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
php
| 2 |
<?php
/**
* 帐号绑定获取任务
* @author zhanghailong
*
*/
class AccountBindGetTask extends AuthTask{
/**
* 用户ID, 若不存在,则使用内部参数 auth
* @var int
*/
public $uid;
/**
* 类型
* @var AccountBindType
*/
public $type;
/**
* 外部 APP KEY
* @var String
*/
public $appKey;
/**
* 输出 外部APP SECRET
*/
public $appSecret;
/**
* 输出 外部用户ID
* @var String
*/
public $eid;
/**
* 输出 验证token
* @var String
*/
public $etoken;
/**
* 输出 过期时间
* @var int
*/
public $expires_in;
public function prefix(){
return "auth-bind";
}
}
?>
|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package com.xmht.lock.core.view.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.TextView;
import com.xmht.lock.core.data.time.TimeLevel;
import com.xmht.lock.core.data.time.format.TimeFormatter;
import com.xmht.lock.core.view.TimeDateWidget;
import com.xmht.lock.debug.LOG;
import com.xmht.lock.utils.Utils;
import com.xmht.lockair.R;
public class TimeDateWidget6 extends TimeDateWidget {
private TextView hTV;
private TextView mTV;
private TextView weekTV;
private TextView dateTV;
public TimeDateWidget6(Context context) {
this(context, null);
}
public TimeDateWidget6(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TimeDateWidget6(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void setView() {
LayoutInflater.from(getContext()).inflate(R.layout.widget_time_date_6, this);
hTV = (TextView) findViewById(R.id.hour);
mTV = (TextView) findViewById(R.id.minute);
weekTV = (TextView) findViewById(R.id.week);
dateTV = (TextView) findViewById(R.id.date);
}
@Override
protected void setFont() {
Utils.setFontToView(hTV, "fonts/Helvetica-Light.ttf");
Utils.setFontToView(mTV, "fonts/Helvetica-Light.ttf");
Utils.setFontToView(weekTV, "fonts/Helvetica-Light.ttf");
Utils.setFontToView(dateTV, "fonts/Helvetica-Light.ttf");
}
@Override
public void onTimeChanged(TimeLevel level) {
switch (level) {
case YEAR:
case MONTH:
case WEEK:
weekTV.setText(TimeFormatter.getWeek(false, false));
case DAY:
dateTV.setText(TimeFormatter.getDate(false, false, " "));
case HOUR:
hTV.setText(TimeFormatter.getHour(true));
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
java
| 3 |
package com.xmht.lock.core.view.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.TextView;
import com.xmht.lock.core.data.time.TimeLevel;
import com.xmht.lock.core.data.time.format.TimeFormatter;
import com.xmht.lock.core.view.TimeDateWidget;
import com.xmht.lock.debug.LOG;
import com.xmht.lock.utils.Utils;
import com.xmht.lockair.R;
public class TimeDateWidget6 extends TimeDateWidget {
private TextView hTV;
private TextView mTV;
private TextView weekTV;
private TextView dateTV;
public TimeDateWidget6(Context context) {
this(context, null);
}
public TimeDateWidget6(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TimeDateWidget6(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void setView() {
LayoutInflater.from(getContext()).inflate(R.layout.widget_time_date_6, this);
hTV = (TextView) findViewById(R.id.hour);
mTV = (TextView) findViewById(R.id.minute);
weekTV = (TextView) findViewById(R.id.week);
dateTV = (TextView) findViewById(R.id.date);
}
@Override
protected void setFont() {
Utils.setFontToView(hTV, "fonts/Helvetica-Light.ttf");
Utils.setFontToView(mTV, "fonts/Helvetica-Light.ttf");
Utils.setFontToView(weekTV, "fonts/Helvetica-Light.ttf");
Utils.setFontToView(dateTV, "fonts/Helvetica-Light.ttf");
}
@Override
public void onTimeChanged(TimeLevel level) {
switch (level) {
case YEAR:
case MONTH:
case WEEK:
weekTV.setText(TimeFormatter.getWeek(false, false));
case DAY:
dateTV.setText(TimeFormatter.getDate(false, false, " "));
case HOUR:
hTV.setText(TimeFormatter.getHour(true));
case MINUTE:
mTV.setText(TimeFormatter.getMinute());
case SECOND:
LOG.v("Time", TimeFormatter.getTime(true, true, ":"));
break;
default:
break;
}
}
}
|
Below is an extract from a Kotlin program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Kotlin code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Kotlin concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., coroutines, extension functions). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Kotlin. It should be similar to a school exercise, a tutorial, or a Kotlin course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Kotlin. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package io.kaeawc.template
import com.nhaarman.mockito_kotlin.*
import org.junit.Test
import org.junit.Assert.*
import org.junit.Before
import org.mockito.Mock
import org.mockito.MockitoAnnotations
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class MainPresenterSpec {
@Mock lateinit var view: MainPresenter.View
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
}
@Test
fun `set view weak ref on create`() {
val presenter = MainPresenter()
assertNull(presenter.weakView)
presenter.onCreate(view)
assertNotNull(presenter.weakView)
}
@Test
fun `show title on resume`() {
val presenter = MainPresenter()
presenter.onCreate(view)
presenter.onResume()
verify(view, times(1)).showTitle(any())
}
@Test
fun `clear view reference on pause`() {
val presenter = MainPresenter()
presenter.onCreate(view)
presenter.onResume()
presenter.onPause()
assertNotNull(presenter.weakView)
assertNull(presenter.weakView?.get())
}
@Test
fun `unset view reference on pause`() {
val presenter = MainPresenter()
presenter.onCreate(view)
presenter.onStop()
assertNull(presenter.weakView)
assertNull(presenter.weakView?.get())
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
kotlin
| 2 |
package io.kaeawc.template
import com.nhaarman.mockito_kotlin.*
import org.junit.Test
import org.junit.Assert.*
import org.junit.Before
import org.mockito.Mock
import org.mockito.MockitoAnnotations
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class MainPresenterSpec {
@Mock lateinit var view: MainPresenter.View
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
}
@Test
fun `set view weak ref on create`() {
val presenter = MainPresenter()
assertNull(presenter.weakView)
presenter.onCreate(view)
assertNotNull(presenter.weakView)
}
@Test
fun `show title on resume`() {
val presenter = MainPresenter()
presenter.onCreate(view)
presenter.onResume()
verify(view, times(1)).showTitle(any())
}
@Test
fun `clear view reference on pause`() {
val presenter = MainPresenter()
presenter.onCreate(view)
presenter.onResume()
presenter.onPause()
assertNotNull(presenter.weakView)
assertNull(presenter.weakView?.get())
}
@Test
fun `unset view reference on pause`() {
val presenter = MainPresenter()
presenter.onCreate(view)
presenter.onStop()
assertNull(presenter.weakView)
assertNull(presenter.weakView?.get())
}
}
|
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical PHP concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
<!DOCTYPE html>
<html lang=fr>
<head>
<meta charset="utf-8">
<title> FileShare</title>
</head>
<body>
<div>
<center class="titre">
<h1 style="color: black;">
<label for="">FileShare</label>
</h1>
<i></i>
<a href="#"></a>
</center>
</div>
<div>
<center>
<p style="front-size: 10px"> Partage tes fichiers plus <br> vite que la lumière
</p>
<br>
<h4>Veuillez vous inscrire afin de pouvoir partager <br> et
recevoir des fichiers avec les autres membres</h4>
<form method="post">
<div>
<label for="mail"> Adresse mail: </label><br>
<input type="email" id="email" placeholder="<EMAIL>">
</div><br>
<div>
<label for="password"> Mot de passe: </label><br>
<input type="<PASSWORD>" id="<PASSWORD>" >
</div><br>
<div>
<input type="submit" name="formsend" id="formsend">
</div><br>
<a href="register.html">
Je n'ai pas de compte
</a>
</form>
<?php
if(isset($_POST['formsend']))
{
echo "formulaire send";
}
?>
</center>
<footer>
<center>
<table>
<td>
<a href="Contact/contact.html">
Contact
</a>
</td>
</table>
</center>
</footer>
</div>
</body>
</html>
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
php
| 1 |
<!DOCTYPE html>
<html lang=fr>
<head>
<meta charset="utf-8">
<title> FileShare</title>
</head>
<body>
<div>
<center class="titre">
<h1 style="color: black;">
<label for="">FileShare</label>
</h1>
<i></i>
<a href="#"></a>
</center>
</div>
<div>
<center>
<p style="front-size: 10px"> Partage tes fichiers plus <br> vite que la lumière
</p>
<br>
<h4>Veuillez vous inscrire afin de pouvoir partager <br> et
recevoir des fichiers avec les autres membres</h4>
<form method="post">
<div>
<label for="mail"> Adresse mail: </label><br>
<input type="email" id="email" placeholder="<EMAIL>">
</div><br>
<div>
<label for="password"> Mot de passe: </label><br>
<input type="<PASSWORD>" id="<PASSWORD>" >
</div><br>
<div>
<input type="submit" name="formsend" id="formsend">
</div><br>
<a href="register.html">
Je n'ai pas de compte
</a>
</form>
<?php
if(isset($_POST['formsend']))
{
echo "formulaire send";
}
?>
</center>
<footer>
<center>
<table>
<td>
<a href="Contact/contact.html">
Contact
</a>
</td>
</table>
</center>
</footer>
</div>
</body>
</html>
|
Below is an extract from a TypeScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid TypeScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical TypeScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., generics, decorators). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching TypeScript. It should be similar to a school exercise, a tutorial, or a TypeScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching TypeScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
import throttle from 'lodash/throttle';
import { MouseEvent, RefObject, TouchEvent, useEffect } from 'react';
import Events from '../utils/events';
export interface UseScrollProps {
container: RefObject<HTMLElement>;
onScroll?: (event: MouseEvent | TouchEvent) => void;
wait?: number;
}
const useScroll = ({ container, onScroll, wait = 200 }: UseScrollProps) => {
useEffect(() => {
const handler = throttle((event): void => {
// console.log(`[${Date.now()}] handler`);
typeof onScroll === 'function' && onScroll(event);
}, wait);
if (container.current) {
Events.on(container.current, 'scroll', handler);
}
return () => {
if (container.current) {
Events.off(container.current, 'scroll', handler);
}
};
}, [container]);
};
export default useScroll;
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
typescript
| 2 |
import throttle from 'lodash/throttle';
import { MouseEvent, RefObject, TouchEvent, useEffect } from 'react';
import Events from '../utils/events';
export interface UseScrollProps {
container: RefObject<HTMLElement>;
onScroll?: (event: MouseEvent | TouchEvent) => void;
wait?: number;
}
const useScroll = ({ container, onScroll, wait = 200 }: UseScrollProps) => {
useEffect(() => {
const handler = throttle((event): void => {
// console.log(`[${Date.now()}] handler`);
typeof onScroll === 'function' && onScroll(event);
}, wait);
if (container.current) {
Events.on(container.current, 'scroll', handler);
}
return () => {
if (container.current) {
Events.off(container.current, 'scroll', handler);
}
};
}, [container]);
};
export default useScroll;
|
Below is an extract from a C program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid C code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical C concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., kernel development and compiler design). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching C. It should be similar to a school exercise, a tutorial, or a C course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
#include <stdio.h>
#include <stdlib.h>
void swap(int* a, int* b);
int main() {
int i = 123;
int j = 456;
swap(&i, &j);
printf("%d %d\n", i, j);
system("pause");
return 0;
}
void swap(int* a, int* b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
c
| 4 |
#include <stdio.h>
#include <stdlib.h>
void swap(int* a, int* b);
int main() {
int i = 123;
int j = 456;
swap(&i, &j);
printf("%d %d\n", i, j);
system("pause");
return 0;
}
void swap(int* a, int* b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
|
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content.
- Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse.
- Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow.
- Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson.
- Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes.
The extract:
#Chatbot in Python (using NLTK library)
Developers:
Software Engineers of Bahria University
-<NAME>
-Rafi-ul-Haq
-<NAME>
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
markdown
| 1 |
#Chatbot in Python (using NLTK library)
Developers:
Software Engineers of Bahria University
-<NAME>
-Rafi-ul-Haq
-<NAME>
|
Below is an extract from a Kotlin program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Kotlin code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Kotlin concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., coroutines, extension functions). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Kotlin. It should be similar to a school exercise, a tutorial, or a Kotlin course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Kotlin. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package com.zhenl.payhook
import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import kotlin.concurrent.thread
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
verifyStoragePermissions(this)
}
private val REQUEST_EXTERNAL_STORAGE = 1
private val PERMISSIONS_STORAGE = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
fun verifyStoragePermissions(activity: Activity) {
try {
val permission = ActivityCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE)
} else {
copyConfig()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
if (requestCode == REQUEST_EXTERNAL_STORAGE) {
if (grantResults.isNotEmpty()
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
copyConfig()
} else {
Toast.makeText(this, R.string.msg_permission_fail, Toast.LENGTH_LONG).show()
finish()
}
}
}
fun copyConfig() {
thread {
val sharedPrefsDir = File(filesDir, "../shared_prefs")
val sharedPref
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
kotlin
| 3 |
package com.zhenl.payhook
import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import kotlin.concurrent.thread
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
verifyStoragePermissions(this)
}
private val REQUEST_EXTERNAL_STORAGE = 1
private val PERMISSIONS_STORAGE = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
fun verifyStoragePermissions(activity: Activity) {
try {
val permission = ActivityCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE)
} else {
copyConfig()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
if (requestCode == REQUEST_EXTERNAL_STORAGE) {
if (grantResults.isNotEmpty()
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
copyConfig()
} else {
Toast.makeText(this, R.string.msg_permission_fail, Toast.LENGTH_LONG).show()
finish()
}
}
}
fun copyConfig() {
thread {
val sharedPrefsDir = File(filesDir, "../shared_prefs")
val sharedPrefsFile = File(sharedPrefsDir, Common.MOD_PREFS + ".xml")
val sdSPDir = File(Common.APP_DIR_PATH)
val sdSPFile = File(sdSPDir, Common.MOD_PREFS + ".xml")
if (sharedPrefsFile.exists()) {
if (!sdSPDir.exists())
sdSPDir.mkdirs()
val outStream = FileOutputStream(sdSPFile)
FileUtils.copyFile(FileInputStream(sharedPrefsFile), outStream)
} else if (sdSPFile.exists()) { // restore sharedPrefsFile
if (!sharedPrefsDir.exists())
sharedPrefsDir.mkdirs()
val input = FileInputStream(sdSPFile)
val outStream = FileOutputStream(sharedPrefsFile)
FileUtils.copyFile(input, outStream)
}
}
}
override fun onStop() {
super.onStop()
copyConfig()
}
}
|
Below is an extract from a TypeScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid TypeScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical TypeScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., generics, decorators). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching TypeScript. It should be similar to a school exercise, a tutorial, or a TypeScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching TypeScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
import {Component, OnInit} from 'angular2/core';
import {RouteParams} from 'angular2/router';
import {BlogPost} from '../blogpost';
import {BlogService} from '../services/blog.service';
@Component({
selector: 'blog-detail',
templateUrl: 'app/+blog/components/blog-detail.component.html',
})
export class BlogPostDetailComponent implements OnInit {
post: BlogPost;
constructor(private _blogService: BlogService,
private _routeParams: RouteParams) { }
ngOnInit() {
var id = +this._routeParams.get('id');
this._blogService.getPost(id)
.then(p => this.post = p);
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
typescript
| 3 |
import {Component, OnInit} from 'angular2/core';
import {RouteParams} from 'angular2/router';
import {BlogPost} from '../blogpost';
import {BlogService} from '../services/blog.service';
@Component({
selector: 'blog-detail',
templateUrl: 'app/+blog/components/blog-detail.component.html',
})
export class BlogPostDetailComponent implements OnInit {
post: BlogPost;
constructor(private _blogService: BlogService,
private _routeParams: RouteParams) { }
ngOnInit() {
var id = +this._routeParams.get('id');
this._blogService.getPost(id)
.then(p => this.post = p);
}
}
|
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content.
- Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse.
- Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow.
- Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson.
- Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes.
The extract:
# isituppy
Custom slash command to use isitup.org to check if a site is up from within Slack
## REQUIREMENTS
* A custom slash command on a Slack team
* A web server running something like Apache with mod_wsgi,
with Python 2.7 installed
## USAGE
* Place this script on a server with Python 2.7 installed.
* Set up a new custom slash command on your Slack team:
http://my.slack.com/services/new/slash-commands
* Under "Choose a command", enter whatever you want for
the command. /isitup is easy to remember.
* Under "URL", enter the URL for the script on your server.
* Leave "Method" set to "Post".
* Decide whether you want this command to show in the
autocomplete list for slash commands.
* If you do, enter a short description and usage hint.
_Derived from David McCreath's PHP version here: https://github.com/mccreath/isitup-for-slack_
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
markdown
| 3 |
# isituppy
Custom slash command to use isitup.org to check if a site is up from within Slack
## REQUIREMENTS
* A custom slash command on a Slack team
* A web server running something like Apache with mod_wsgi,
with Python 2.7 installed
## USAGE
* Place this script on a server with Python 2.7 installed.
* Set up a new custom slash command on your Slack team:
http://my.slack.com/services/new/slash-commands
* Under "Choose a command", enter whatever you want for
the command. /isitup is easy to remember.
* Under "URL", enter the URL for the script on your server.
* Leave "Method" set to "Post".
* Decide whether you want this command to show in the
autocomplete list for slash commands.
* If you do, enter a short description and usage hint.
_Derived from David McCreath's PHP version here: https://github.com/mccreath/isitup-for-slack_
|
Below is an extract from a Ruby program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Ruby code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Ruby concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., metaprogramming, blocks). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Ruby. It should be similar to a school exercise, a tutorial, or a Ruby course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Ruby. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
require 'rails_helper'
describe 'post show page' do
before do
@author = Author.create(name: "<NAME>", hometown: "Charlottesville, VA")
@post = Post.create(title: "A Time To Kill", description: "A Time to Kill is a 1989 legal suspense thriller by <NAME>. It was Grisham's first novel. The novel was rejected by many publishers before Wynwood Press (located in New York) eventually gave it a modest 5,000-copy printing. After The Firm, The Pelican Brief, and The Client became bestsellers, interest in A Time to Kill grew; the book was republished by Doubleday in hardcover and, later, by Dell Publishing in paperback, and itself became a bestseller. This made Grisham extremely popular among readers.", author_id: 1)
end
it 'returns a 200 status code' do
visit "/posts/#{@post.id}"
expect(page.status_code).to eq(200)
end
it "shows the name and hometown of the post's author" do
visit "/posts/#{@post.id}"
expect(page).to have_content(@post.author.name)
expect(page).to have_content(@post.author.hometown)
end
end
describe 'form' do
before do
@author = Author.create(name: "<NAME>", hometown: "Charlottesville, VA")
@post = Post.create(title: "My Post", description: "My post desc", author_id: @author.id)
end
end
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
ruby
| 2 |
require 'rails_helper'
describe 'post show page' do
before do
@author = Author.create(name: "<NAME>", hometown: "Charlottesville, VA")
@post = Post.create(title: "A Time To Kill", description: "A Time to Kill is a 1989 legal suspense thriller by <NAME>. It was Grisham's first novel. The novel was rejected by many publishers before Wynwood Press (located in New York) eventually gave it a modest 5,000-copy printing. After The Firm, The Pelican Brief, and The Client became bestsellers, interest in A Time to Kill grew; the book was republished by Doubleday in hardcover and, later, by Dell Publishing in paperback, and itself became a bestseller. This made Grisham extremely popular among readers.", author_id: 1)
end
it 'returns a 200 status code' do
visit "/posts/#{@post.id}"
expect(page.status_code).to eq(200)
end
it "shows the name and hometown of the post's author" do
visit "/posts/#{@post.id}"
expect(page).to have_content(@post.author.name)
expect(page).to have_content(@post.author.hometown)
end
end
describe 'form' do
before do
@author = Author.create(name: "<NAME>", hometown: "Charlottesville, VA")
@post = Post.create(title: "My Post", description: "My post desc", author_id: @author.id)
end
end
|
Below is an extract from a Go program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Go code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Go concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., goroutines, interfaces). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Go. It should be similar to a school exercise, a tutorial, or a Go course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Go. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
import "math"
func nievePrimeSlice(n int) []int {
knownPrimes := []int{}
number := 2
var aux func(n int)
aux = func(n int) {
if n != 0 {
primeFound := true
for _, prime := range knownPrimes {
if float64(prime) > math.Sqrt(float64(number)) {
break
}
if number % prime == 0 {
primeFound = false
break
}
}
if primeFound {
knownPrimes = append(knownPrimes, number)
n -= 1
}
number += 1
aux(n)
}
}
aux(n)
return knownPrimes
}
func primesWhile(continueCondition func(int)bool, op func(int)) []int {
knownPrimes := []int{}
number := 2
var aux func()
aux = func() {
sqrtNum := math.Sqrt(float64(number))
primeFound := true
for _, prime := range knownPrimes {
if float64(prime) > sqrtNum {
break
}
if number % prime == 0 {
primeFound = false
break
}
}
if primeFound {
if !continueCondition(number) { return }
op(number)
knownPrimes = append(knownPrimes, number)
}
number += 1
aux()
}
aux()
return knownPrimes
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
go
| 2 |
import "math"
func nievePrimeSlice(n int) []int {
knownPrimes := []int{}
number := 2
var aux func(n int)
aux = func(n int) {
if n != 0 {
primeFound := true
for _, prime := range knownPrimes {
if float64(prime) > math.Sqrt(float64(number)) {
break
}
if number % prime == 0 {
primeFound = false
break
}
}
if primeFound {
knownPrimes = append(knownPrimes, number)
n -= 1
}
number += 1
aux(n)
}
}
aux(n)
return knownPrimes
}
func primesWhile(continueCondition func(int)bool, op func(int)) []int {
knownPrimes := []int{}
number := 2
var aux func()
aux = func() {
sqrtNum := math.Sqrt(float64(number))
primeFound := true
for _, prime := range knownPrimes {
if float64(prime) > sqrtNum {
break
}
if number % prime == 0 {
primeFound = false
break
}
}
if primeFound {
if !continueCondition(number) { return }
op(number)
knownPrimes = append(knownPrimes, number)
}
number += 1
aux()
}
aux()
return knownPrimes
}
|
Below is an extract from a Swift program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Swift code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Swift concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., protocols, extensions). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Swift. It should be similar to a school exercise, a tutorial, or a Swift course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Swift. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
//
// ViewController.swift
// Pocket USA
//
// Created by <NAME> on 3/10/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
// - Attribution: UISearchBar customization - Customise UISearchBar in Swift @ iosdevcenters.blogspot.com
// - Attribution: Delay execution - How To Create an Uber Splash Screen @ www.raywenderlich.com
import UIKit
import ChameleonFramework
var splashScreen = true
// Main view controller
class ViewController: UIViewController, UITableViewDataSource, UIScrollViewDelegate, UITableViewDelegate, UISearchBarDelegate {
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var populationLabel: UILabel!
@IBOutlet weak var incomeLabel: UILabel!
@IBOutlet weak var ageLabel: UILabel!
@IBOutlet weak var cardtScrollView: UIScrollView!
@IBOutlet weak var searchView: UIView!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var searchTable: UITableView!
@IBOutlet weak var searchDisplayButton: UIButton!
@IBOutlet weak var networkOopusView: UIView!
@IBOutlet weak var mapButton: UIButton!
@IBOutlet weak var imageButton: UIButton!
var incomeCardView: UIView!
var ageCardView: UIView!
var propertyCardView: UIView!
let sharedDM = DataManager()
var searchActive = false
var searchTerm = ""
var searchResults = [[String]]()
var location = "United States"
var population: Double!
var income: Double!
var age: Double!
var locationID = "01000US" {
didSet {
initLabels()
initCardViews()
}
}
// Life cycle
override func viewDidLoad() {
super.viewDidLoad()
sharedDM.alertDelegate = self
showSplashScreen()
initApprerance()
initGesture()
initSearchView()
initCardScrollView()
initCardViews()
initSetting()
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.setNavigationBarHi
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
swift
| 2 |
//
// ViewController.swift
// Pocket USA
//
// Created by <NAME> on 3/10/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
// - Attribution: UISearchBar customization - Customise UISearchBar in Swift @ iosdevcenters.blogspot.com
// - Attribution: Delay execution - How To Create an Uber Splash Screen @ www.raywenderlich.com
import UIKit
import ChameleonFramework
var splashScreen = true
// Main view controller
class ViewController: UIViewController, UITableViewDataSource, UIScrollViewDelegate, UITableViewDelegate, UISearchBarDelegate {
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var populationLabel: UILabel!
@IBOutlet weak var incomeLabel: UILabel!
@IBOutlet weak var ageLabel: UILabel!
@IBOutlet weak var cardtScrollView: UIScrollView!
@IBOutlet weak var searchView: UIView!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var searchTable: UITableView!
@IBOutlet weak var searchDisplayButton: UIButton!
@IBOutlet weak var networkOopusView: UIView!
@IBOutlet weak var mapButton: UIButton!
@IBOutlet weak var imageButton: UIButton!
var incomeCardView: UIView!
var ageCardView: UIView!
var propertyCardView: UIView!
let sharedDM = DataManager()
var searchActive = false
var searchTerm = ""
var searchResults = [[String]]()
var location = "United States"
var population: Double!
var income: Double!
var age: Double!
var locationID = "01000US" {
didSet {
initLabels()
initCardViews()
}
}
// Life cycle
override func viewDidLoad() {
super.viewDidLoad()
sharedDM.alertDelegate = self
showSplashScreen()
initApprerance()
initGesture()
initSearchView()
initCardScrollView()
initCardViews()
initSetting()
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(true, animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
// Initialize appreance
func initApprerance() {
// self.navigationController?.setNavigationBarHidden(true, animated: animated) // Hide navigation bar
// Map button appearance
mapButton.setTitle("MAP", for: .normal)
mapButton.setTitleColor(.darkGray, for: .normal)
mapButton.setBackgroundImage(#imageLiteral(resourceName: "MapButton").withRenderingMode(.alwaysOriginal), for: .normal)
mapButton.setBackgroundImage(#imageLiteral(resourceName: "MapButton").withRenderingMode(.alwaysOriginal), for: .highlighted)
mapButton.clipsToBounds = true
mapButton.layer.cornerRadius = 4
// Image button appreaance
imageButton.setTitle("GLANCE", for: .normal)
imageButton.setTitleColor(.darkGray, for: .normal)
imageButton.setBackgroundImage(#imageLiteral(resourceName: "ImageButton").withRenderingMode(.alwaysOriginal), for: .normal)
imageButton.setBackgroundImage(#imageLiteral(resourceName: "ImageButton").withRenderingMode(.alwaysOriginal), for: .highlighted)
imageButton.clipsToBounds = true
imageButton.layer.cornerRadius = 4
}
// Initialize gesture
func initGesture() {
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
// Initialize
func initLabels() {
// Get location summary
getLocationSummary(self.locationID) {
() -> Void in
self.locationLabel.text = self.location.uppercased()
self.initPopulationLabel()
self.initIncomeLabel()
self.initAgeLabel()
}
}
// Init population label
func initPopulationLabel() {
guard let pop = self.population else
{
print("### ERROR: population empty")
return
}
let million = 1000000.00
let thousand = 1000.00
// Format population
let formatter = NumberFormatter()
formatter.numberStyle = .currency
if (pop/million >= 100) {
// When population is bigger than 100 million
formatter.maximumFractionDigits = 0
formatter.currencySymbol = ""
self.populationLabel.text = formatter.string(from: NSNumber(value: pop/million))! + "M"
} else if (pop/million >= 1) {
// When population is bigger than 1 million
formatter.maximumFractionDigits = 1
formatter.currencySymbol = ""
self.populationLabel.text = formatter.string(from: NSNumber(value: pop/million))! + "M"
} else if (pop/thousand >= 100){
// When population is bigger than 1000 thousands
formatter.maximumFractionDigits = 0
formatter.currencySymbol = ""
self.populationLabel.text = formatter.string(from: NSNumber(value: pop/thousand))! + "K"
} else if (pop/thousand >= 1){
// When population is bigger than 1 thousand
formatter.maximumFractionDigits = 1
formatter.currencySymbol = ""
self.populationLabel.text = formatter.string(from: NSNumber(value: pop/thousand))! + "K"
} else {
// When population is less than 1 thousand
formatter.maximumFractionDigits = 0
formatter.currencySymbol = ""
self.populationLabel.text = formatter.string(from: NSNumber(value: pop))!
}
}
// Init income label
func initIncomeLabel() {
guard let income = self.income else
{
print("### ERROR: age empty")
return
}
// Format income
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 0
self.incomeLabel.text = formatter.string(from: NSNumber(value: income))!
}
// Init age label
func initAgeLabel() {
guard let age = self.age else
{
print("### ERROR: age empty")
return
}
self.ageLabel.text = String(format: "%.1f", age)
}
// Initialize card scroll view
func initCardScrollView() {
self.view.backgroundColor = UIColor.white
cardtScrollView.delegate = self
cardtScrollView.contentSize = CGSize(width: 1125, height: 385)
cardtScrollView.showsHorizontalScrollIndicator = false
cardtScrollView.isPagingEnabled = true
cardtScrollView.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
}
// Initialize search view
func initSearchView() {
searchTable.delegate = self
searchTable.dataSource = self
searchBar.delegate = self
// initShadow(searchView)
customizeSearchBar()
}
// Initialize card views
func initCardViews() {
self.initIncomeCardView()
self.initAgeCardView()
self.initPropertyCardView()
// Scroll to left
self.cardtScrollView.scrollToLeft(animated: false)
// Scroll hint - hint the user that they can do scroll
// self.cardtScrollView.scrollHint(animated: true)
}
// Initialize income card view
func initIncomeCardView() {
if self.incomeCardView != nil {
self.incomeCardView.removeFromSuperview()
}
self.incomeCardView = IncomeCardView(locationID, bookmark: false)
self.cardtScrollView.addSubview(self.incomeCardView)
// let incomeLabel: UILabel = UILabel(frame: CGRect(x: 30, y: 30, width: 300, height: 30))
// incomeLabel.text = "YEAR: \(self.incomeYears[0])"
// incomeCardView.backgroundColor = UIColor.lightGray
// incomeCardView.layer.cornerRadius = 25
// incomeCardView.addSubview(incomeLabel)
// cardtScrollView.addSubview(incomeCardView)
}
// Initialize income card view
func initAgeCardView() {
if self.ageCardView != nil {
self.ageCardView.removeFromSuperview()
}
self.ageCardView = AgeCardView(locationID, bookmark: false)
self.cardtScrollView.addSubview(self.ageCardView)
}
// Initialize income card view
func initPropertyCardView() {
if self.propertyCardView != nil {
self.propertyCardView.removeFromSuperview()
}
self.propertyCardView = PropertyCardView(locationID, bookmark: false)
self.cardtScrollView.addSubview(self.propertyCardView)
}
// Initialize shadow for a view
func initShadow(_ view: UIView) {
view.layer.masksToBounds = false
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOpacity = 0.7
view.layer.shadowOffset = CGSize(width: 0, height: 2)
view.layer.shadowRadius = 2
view.layer.shouldRasterize = true
}
// Dismiss network oopus view
@IBAction func dismissNetworkOopusView(_ sender: Any) {
print("### Button Tapped: dismissNetworkOopusView")
UIView.animate(withDuration: 0.5, animations: {
() -> Void in
self.networkOopusView.center = CGPoint(x: self.view.center.x, y: -200)
}) {(true) -> Void in}
}
// Search display button tapped
@IBAction func searchDisplayButtonTapped(_ sender: Any) {
print("### Button Tapped: searchDisplayButtonTapped")
if (searchActive == false) {
self.showSearchView() // show search view
} else {
self.hideSearchView() // hide search view
}
}
// Show search view
func showSearchView() {
// Display keyboard
self.searchBar.endEditing(false)
// Move to the screen
UIView.animate(withDuration: 0.5, animations: {
() -> Void in
self.searchView.center = CGPoint(x: 187, y: 300)
}) { (true) in
// Reset searcb result
self.searchResults.removeAll()
self.searchTable.reloadData()
self.searchActive = true
print("### hideSearchView DONE")
}
}
// Hide search view
func hideSearchView() {
// Dismiss keyboard
self.searchBar.endEditing(true)
// Move to the bottom
UIView.animate(withDuration: 0.5, animations: {
() -> Void in
self.searchView.center = CGPoint(x: 187, y: 793)
}) { (true) in
// Reset searcb result
self.searchResults.removeAll()
self.searchTable.reloadData()
self.searchActive = false
print("### hideSearchView DONE")
}
}
//
// - MARK: Search Table
//
// # of section
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
// # of cells/rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.searchResults.count
}
// Create cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Set text for the reusuable table cell
let cell: SearchTableCell = tableView.dequeueReusableCell(withIdentifier: "searchTableCell", for: indexPath) as! SearchTableCell
print("### Cell # \(indexPath.row) created")
// Set text for cell
cell.searchTableCellText.text = self.searchResults[indexPath.row][1]
return cell
}
// Tap cell
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
print("### Cell # \(indexPath.row) tapped, text: \(searchResults[indexPath.row][1])")
// Set location and location ID
self.location = searchResults[indexPath.row][1]
self.locationID = searchResults[indexPath.row][0]
// Finish and hide search view
hideSearchView()
}
// Disable cell editing
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return false
}
//
// - MARK: Search Bar
//
// Begin editing
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
// searchActive = true
print("### searchBarTextDidBeginEditing")
}
// End editing
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
// searchActive = false
print("### searchBarTextDidEndEditing")
}
// Cancel clicked
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
// searchActive = false
print("### searchBarCancelButtonClicked")
}
// Search clicked
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if searchBar.text != nil {
getSearchResults(searchBar.text!) {
() in
self.searchTable.reloadData()
}
}
// searchActive = false
print("### searchBarSearchButtonClicked")
}
// Search text changed
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
print("### Live search: \(searchText)")
getSearchResults(searchText) {
() in
self.searchTable.reloadData()
}
print("### textDidChange")
}
// Customize search bar appearnace
func customizeSearchBar() {
// Set search text field text color when idel
let placeholderAttributes: [String : AnyObject] = [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.systemFont(ofSize: UIFont.systemFontSize)]
let attributedPlaceholder: NSAttributedString = NSAttributedString(string: "Where would you go?", attributes: placeholderAttributes)
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = attributedPlaceholder
// Set search text field search icon color
let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
let imageV = textFieldInsideSearchBar?.leftView as! UIImageView
imageV.image = imageV.image?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
imageV.tintColor = UIColor.white
// Set serch text field typing color
textFieldInsideSearchBar?.textColor = UIColor.white
}
//
// - MARK: Network
//
// Get location id from location name
func getLocationId(_ location: String, completion: @escaping () -> Void) {
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
// Load URL and parse response
sharedDM.getLocationIdWithSuccess(location) { (data) -> Void in
var json: Any
do {
json = try JSONSerialization.jsonObject(with: data)
} catch {
print(error)
print("### Error 0")
return
}
// Retrieve top level dictionary
guard let dictionary = json as? [String: Any] else {
print("### Error getting top level dictionary from JSON")
return
}
// Retrieve data feed
guard let dataFeed = DataFeed(json: dictionary) else {
print("### Error getting data feed from JSON")
return
}
// Retrieve location ID
let dataFeedConveretd = dataFeed.dataFeed as! [[AnyObject]]
self.locationID = dataFeedConveretd[0][0] as! String
print("### Retrieve Data Finished")
// Back to the main thread
DispatchQueue.main.async {
completion()
}
}
}
// Get search results from search term
func getSearchResults(_ searchTerm: String, completion: @escaping () -> Void) {
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
// Replace space with underscore if any
let cleanedSearchTerm = searchTerm.replacingOccurrences(of: " ", with: "_")
// Load URL and parse response
sharedDM.getSearchResultsWithSuccess(cleanedSearchTerm) { (data) -> Void in
var json: Any
do {
json = try JSONSerialization.jsonObject(with: data)
} catch {
print(error)
print("### Error 0")
return
}
// Retrieve top level dictionary
guard let dictionary = json as? [String: Any] else {
print("### Error getting top level dictionary from JSON")
return
}
// Retrieve data feed
guard let dataFeed = DataFeed(json: dictionary) else {
print("### Error getting data feed from JSON")
return
}
// Retrieve search results
let dataFeedConveretd = dataFeed.dataFeed as! [[AnyObject]]
// Reset search results
self.searchResults.removeAll()
// Append search results
for subFeed in dataFeedConveretd {
self.searchResults.append([subFeed[0] as! String, subFeed[4] as! String])
}
print("### Retrieve search result finished")
// Back to the main thread
DispatchQueue.main.async {
completion()
}
}
}
// Get population, medium household income and medium age from location ID
func getLocationSummary(_ locationId: String, completion: @escaping () -> Void) {
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
// Load URL and parse response
sharedDM.getLocatoinSummaryWithSuccess(locationId) { (data) -> Void in
var json: Any
do {
json = try JSONSerialization.jsonObject(with: data)
} catch {
print(error)
print("### Error 0")
return
}
// Retrieve top level dictionary
guard let dictionary = json as? [String: Any] else {
print("### Error getting top level dictionary from JSON")
return
}
// Retrieve data feed
guard let dataFeed = DataFeed(json: dictionary) else {
print("### Error getting data feed from JSON")
return
}
// Retrieve location summary
let dataFeedConveretd = dataFeed.dataFeed as! [[AnyObject]]
// Append location summary
self.population = dataFeedConveretd[0][4] as! Double
self.income = dataFeedConveretd[0][8] as! Double
self.age = dataFeedConveretd[0][2] as! Double
print("### Retrieve location summary finished")
// Back to the main thread
DispatchQueue.main.async {
completion()
}
}
}
// Splash screen
func showSplashScreen() {
if splashScreen {
// To show splash screen only once
splashScreen = false
// Position
let center = CGPoint(x: self.view.center.x, y: self.view.center.y - 100)
let top = CGPoint(x: self.view.center.x, y: 0)
// Create splash view
let splashTop = UIView(frame: self.view.frame)
splashTop.backgroundColor = UIColor.white
// Create circle
let circle = UIView()
circle.center = top
circle.backgroundColor = ColorPalette.lightBlue400
circle.clipsToBounds = true
// Create labels
let mainLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 50))
let font = mainLabel.font.fontName
mainLabel.center = center
mainLabel.textColor = UIColor.white
mainLabel.font = UIFont(name: font + "-Bold", size: 25)
mainLabel.textAlignment = .center
mainLabel.text = " POCKET USA"
let squareLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 10, height: 15))
squareLabel.center = CGPoint(x: center.x - 95, y: center.y)
squareLabel.backgroundColor = UIColor.white
let subLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 20))
subLabel.center = CGPoint(x: self.view.center.x, y: self.view.center.y - 60)
subLabel.textColor = UIColor.white
subLabel.font = UIFont(name: font + "-Bold", size: 12)
subLabel.textAlignment = .center
subLabel.text = "BY: <NAME> @ UCHICAGO"
// Add views
splashTop.addSubview(circle)
splashTop.addSubview(squareLabel)
splashTop.addSubview(mainLabel)
splashTop.addSubview(subLabel)
self.view.addSubview(splashTop)
// Animte
UIView.animate(withDuration: 3, animations: {
circle.frame = CGRect(x: top.x, y: top.y, width: 800, height: 800)
circle.layer.cornerRadius = 400
circle.center = top
}) {
_ in
UIView.animate(withDuration: 2, animations: {
splashTop.alpha = 0
circle.frame = CGRect(x: top.x, y: top.y, width: 100, height: 100)
circle.layer.cornerRadius = 400
circle.center = top
}) {
_ in
splashTop.removeFromSuperview()
self.showInstruction()
}
}
}
}
// Delay exection
func delay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
// Initialize setting bundle
func initSetting() {
let userDefaults = UserDefaults.standard
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
if userDefaults.string(forKey: "Initial Launch") == nil {
let defaults = ["Developer" : "<NAME>", "Initial Launch" : "\(formatter.string(from: date))"]
// Register default values for setting
userDefaults.register(defaults: defaults)
userDefaults.synchronize()
}
print("### DEFAULT: \(userDefaults.dictionaryRepresentation())")
// Register for notification about settings changes
NotificationCenter.default.addObserver(self,
selector: #selector(ViewController.defaultsChanged),
name: UserDefaults.didChangeNotification,
object: nil)
}
// Stop listening for notifications when view controller is gone
deinit {
NotificationCenter.default.removeObserver(self)
}
func defaultsChanged() {
print("### Setting Default Change")
}
// Instruction alert
func showInstruction() {
let title = "THE HARD PART"
let message = "(1) Swipe right to reveal side menu.\n (2) Swipe on the chart to see next one. \n (3) Tap 'SEARCH' to explore any location. \n (4) Swipe left to navigate back to last screen."
let alert = UIAlertController(title: title,
message: message,
preferredStyle: .actionSheet)
let action = UIAlertAction(title: "Nailed It",
style: .default,
handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showWebView" {
let destinationVC = segue.destination as! WebViewController
print("### Segue to web view")
destinationVC.location = self.location
}
}
// MARK: - Map
@IBAction func mapButtonAction(_ sender: Any) {
let mapLocation = self.location.replacingOccurrences(of: " ", with: "_")
print("### Location: \(self.location)")
UIApplication.shared.open(NSURL(string: "http://maps.apple.com/?address=\(mapLocation)")! as URL)
}
}
extension UIScrollView {
// Scroll to left end
func scrollToLeft(animated: Bool) {
let leftOffset = CGPoint(x: -contentInset.left, y: 0)
setContentOffset(leftOffset, animated: animated)
}
// Scroll hint
func scrollHint(animated: Bool) {
let rightOffset = CGPoint(x: contentInset.right, y: 0)
let leftOffset = CGPoint(x: -contentInset.left, y: 0)
setContentOffset(rightOffset, animated: animated)
setContentOffset(leftOffset, animated: animated)
}
}
extension ViewController: DataManagerDelegate {
// Show network alert view
func showNetworkAlert(_ error: Error) {
print("### Delegate called")
print("### ERROR: error")
DispatchQueue.main.async {
UIView.animate(withDuration: 0.5, animations: {
() -> Void in
self.networkOopusView.center = self.view.center
}) {(true) -> Void in}
}
}
}
|
Below is an extract from a Rust program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Rust code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Rust concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., ownership, lifetimes). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Rust. It should be similar to a school exercise, a tutorial, or a Rust course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Rust. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
use std;
use Error;
use ToPz5BinaryData;
use config::write::Node;
use config::write::Struct;
pub trait ToPz5LOD:Sized{
fn get_distance(&self) -> f32;
fn get_data(&self) -> &[u8];
fn get_all_data(&self) -> &[u8];
fn get_vertices_count(&self) -> usize;
fn write_pz5<'a>(&'a self, lod_struct:&mut Struct<'a>, binary_data:&mut ToPz5BinaryData<'a>) {
lod_struct.add_field("vertices count", Node::Integer(self.get_vertices_count() as i64) );
lod_struct.add_field("data index", Node::Integer(binary_data.add_data(self.get_all_data()) as i64) );
//closure
}
fn print(&self);
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
rust
| 2 |
use std;
use Error;
use ToPz5BinaryData;
use config::write::Node;
use config::write::Struct;
pub trait ToPz5LOD:Sized{
fn get_distance(&self) -> f32;
fn get_data(&self) -> &[u8];
fn get_all_data(&self) -> &[u8];
fn get_vertices_count(&self) -> usize;
fn write_pz5<'a>(&'a self, lod_struct:&mut Struct<'a>, binary_data:&mut ToPz5BinaryData<'a>) {
lod_struct.add_field("vertices count", Node::Integer(self.get_vertices_count() as i64) );
lod_struct.add_field("data index", Node::Integer(binary_data.add_data(self.get_all_data()) as i64) );
//closure
}
fn print(&self);
}
|
Below is an extract from a Rust program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Rust code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Rust concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., ownership, lifetimes). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Rust. It should be similar to a school exercise, a tutorial, or a Rust course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Rust. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
mod compiler;
use compiler::parser::Parser;
use std::fs::File;
use std::io::prelude::*;
use std::io;
fn load_source(filename: &str) -> Result<Vec<char>, io::Error> {
let mut input = String::new();
match File::open(filename) {
Ok(mut file) => {
file.read_to_string(&mut input).expect(
"Unable to read from source",
);
Ok(input.chars().collect())
}
Err(what) => Err(what),
}
}
fn main() {
let filename = "language/json.gideon";
if let Ok(mut chars) = load_source(filename) {
let parser = Parser::new(chars.as_mut_slice());
let cst = parser.parse();
println!("{:?}", cst);
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
rust
| 2 |
mod compiler;
use compiler::parser::Parser;
use std::fs::File;
use std::io::prelude::*;
use std::io;
fn load_source(filename: &str) -> Result<Vec<char>, io::Error> {
let mut input = String::new();
match File::open(filename) {
Ok(mut file) => {
file.read_to_string(&mut input).expect(
"Unable to read from source",
);
Ok(input.chars().collect())
}
Err(what) => Err(what),
}
}
fn main() {
let filename = "language/json.gideon";
if let Ok(mut chars) = load_source(filename) {
let parser = Parser::new(chars.as_mut_slice());
let cst = parser.parse();
println!("{:?}", cst);
}
}
|
Below is an extract from a shell script. Evaluate whether it has a high educational value and could help teach shell scripting. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the script contains valid shell commands, even if it's not educational, like simple system calls or basic file operations.
- Add another point if the script addresses practical shell scripting concepts (e.g., variables, conditionals), even if it lacks comments.
- Award a third point if the script is suitable for educational use and introduces key concepts in shell scripting, even if the topic is somewhat advanced (e.g., functions, process management). The script should be well-structured and contain some comments.
- Give a fourth point if the script is self-contained and highly relevant to teaching shell scripting. It should be similar to a tutorial example or a shell scripting course section, demonstrating good practices in script organization.
- Grant a fifth point if the script is outstanding in its educational value and is perfectly suited for teaching shell scripting. It should be well-written, easy to understand, and contain step-by-step explanations in comments.
The extract:
#!/bin/bash
pkgs=(
git
python-pip
xchat
gimp
inkscape
blender
sshfs
synaptic
unrar
compizconfig-settings-manager
audacity
p7zip-full
lynx
jq
caca-utils
unison2.32.52
)
# install packages
for package in ${pkgs[@]};
do
sudo apt-get -y install $package
done
# install aws cli
sudo pip install awscli
# disable overlay scrollbar
gsettings set com.canonical.desktop.interface scrollbar-mode normal
# remove lens-shopping (amazon.com stuff on Ubuntu)
sudo apt-get remove unity-scope-home
# gedit autosave 1 minute
gsettings set org.gnome.gedit.preferences.editor auto-save true
gsettings set org.gnome.gedit.preferences.editor auto-save-interval 1
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
shell
| 2 |
#!/bin/bash
pkgs=(
git
python-pip
xchat
gimp
inkscape
blender
sshfs
synaptic
unrar
compizconfig-settings-manager
audacity
p7zip-full
lynx
jq
caca-utils
unison2.32.52
)
# install packages
for package in ${pkgs[@]};
do
sudo apt-get -y install $package
done
# install aws cli
sudo pip install awscli
# disable overlay scrollbar
gsettings set com.canonical.desktop.interface scrollbar-mode normal
# remove lens-shopping (amazon.com stuff on Ubuntu)
sudo apt-get remove unity-scope-home
# gedit autosave 1 minute
gsettings set org.gnome.gedit.preferences.editor auto-save true
gsettings set org.gnome.gedit.preferences.editor auto-save-interval 1
|
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical JavaScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
var mongoose = require('mongoose');
// Define schema
var schema = mongoose.Schema({
id:{ type: String, index: true, unique: true, required: true },
userId:{ type: String, index: true, required: true },
accountType: String,
balance: Number,
currency: String,
country: String,
kycStatus: Boolean
});
schema.set('toJSON', {
virtuals: true,
transform: function(doc, ret) {
delete ret._id;
delete ret.__v;
}
});
module.exports = mongoose.model("Account", schema);
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
javascript
| 3 |
var mongoose = require('mongoose');
// Define schema
var schema = mongoose.Schema({
id:{ type: String, index: true, unique: true, required: true },
userId:{ type: String, index: true, required: true },
accountType: String,
balance: Number,
currency: String,
country: String,
kycStatus: Boolean
});
schema.set('toJSON', {
virtuals: true,
transform: function(doc, ret) {
delete ret._id;
delete ret.__v;
}
});
module.exports = mongoose.model("Account", schema);
|
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
Add another point if the program addresses practical C# concepts, even if it lacks comments.
Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments.
Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section.
Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
using System;
using System.ComponentModel.DataAnnotations;
namespace EasyMeeting.WebApp.ViewModels
{
public class EventViewModel
{
/// <summary>
/// Title event.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Start date event.
/// </summary>
[Required]
public DateTime Start { get; set; }
/// <summary>
/// End date event.
/// </summary>
[Required]
public DateTime End { get; set; }
/// <summary>
/// Duration event.
/// </summary>
public int Duration { get; set; }
/// <summary>
/// Addres event.
/// </summary>
public string Place { get; set; }
/// <summary>
/// Description for event.
/// </summary>
public string Note { get; set; }
/// <summary>
/// Email for email service.
/// </summary>
[Required]
public string Emails { get; set; }
/// <summary>
/// Link for google calendar.
/// </summary>
public string Link { get; set; }
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
csharp
| 2 |
using System;
using System.ComponentModel.DataAnnotations;
namespace EasyMeeting.WebApp.ViewModels
{
public class EventViewModel
{
/// <summary>
/// Title event.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Start date event.
/// </summary>
[Required]
public DateTime Start { get; set; }
/// <summary>
/// End date event.
/// </summary>
[Required]
public DateTime End { get; set; }
/// <summary>
/// Duration event.
/// </summary>
public int Duration { get; set; }
/// <summary>
/// Addres event.
/// </summary>
public string Place { get; set; }
/// <summary>
/// Description for event.
/// </summary>
public string Note { get; set; }
/// <summary>
/// Email for email service.
/// </summary>
[Required]
public string Emails { get; set; }
/// <summary>
/// Link for google calendar.
/// </summary>
public string Link { get; set; }
}
}
|
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content.
- Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse.
- Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow.
- Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson.
- Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes.
The extract:
---
author: dealingwith
date: '2006-12-01 09:19:00'
layout: post
slug: spam-subject-line-of-the-day
status: publish
title: spam subject line of the day
wordpress_id: '1852'
categories:
- spam awesomeness
---
swoon forbearance
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
markdown
| 1 |
---
author: dealingwith
date: '2006-12-01 09:19:00'
layout: post
slug: spam-subject-line-of-the-day
status: publish
title: spam subject line of the day
wordpress_id: '1852'
categories:
- spam awesomeness
---
swoon forbearance
|
Below is an extract from a shell script. Evaluate whether it has a high educational value and could help teach shell scripting. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the script contains valid shell commands, even if it's not educational, like simple system calls or basic file operations.
- Add another point if the script addresses practical shell scripting concepts (e.g., variables, conditionals), even if it lacks comments.
- Award a third point if the script is suitable for educational use and introduces key concepts in shell scripting, even if the topic is somewhat advanced (e.g., functions, process management). The script should be well-structured and contain some comments.
- Give a fourth point if the script is self-contained and highly relevant to teaching shell scripting. It should be similar to a tutorial example or a shell scripting course section, demonstrating good practices in script organization.
- Grant a fifth point if the script is outstanding in its educational value and is perfectly suited for teaching shell scripting. It should be well-written, easy to understand, and contain step-by-step explanations in comments.
The extract:
#!/bin/bash
rm *.pb.* 2> /dev/null
filename=`ls`
for i in $filename
do
if [ "${i##*.}" = "proto" ];then
protoc -I . --cpp_out=. ./$i
fi
done
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
shell
| 2 |
#!/bin/bash
rm *.pb.* 2> /dev/null
filename=`ls`
for i in $filename
do
if [ "${i##*.}" = "proto" ];then
protoc -I . --cpp_out=. ./$i
fi
done
|
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content.
- Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse.
- Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow.
- Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson.
- Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes.
The extract:
# PythonTutorial
Tutorial
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
markdown
| 1 |
# PythonTutorial
Tutorial
|
Below is an extract from a Rust program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Rust code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Rust concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., ownership, lifetimes). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Rust. It should be similar to a school exercise, a tutorial, or a Rust course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Rust. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::{TsInModifier, TsInModifierFields};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatTsInModifier;
impl FormatNodeRule<TsInModifier> for FormatTsInModifier {
fn fmt_fields(&self, node: &TsInModifier, f: &mut JsFormatter) -> FormatResult<()> {
let TsInModifierFields { modifier_token } = node.as_fields();
write![f, [modifier_token.format()]]
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
rust
| 2 |
use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::{TsInModifier, TsInModifierFields};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatTsInModifier;
impl FormatNodeRule<TsInModifier> for FormatTsInModifier {
fn fmt_fields(&self, node: &TsInModifier, f: &mut JsFormatter) -> FormatResult<()> {
let TsInModifierFields { modifier_token } = node.as_fields();
write![f, [modifier_token.format()]]
}
}
|
Below is an extract from a Kotlin program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Kotlin code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Kotlin concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., coroutines, extension functions). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Kotlin. It should be similar to a school exercise, a tutorial, or a Kotlin course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Kotlin. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package org.integrational.spring.boot.kotlin.fromscratch
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.SpringApplication.run
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class App(
@Value("\${app.name}") private val app: String,
@Value("\${app.version}") private val version: String,
@Value("\${app.env}") private val env: String
) {
private val log = LoggerFactory.getLogger(App::class.java)
init {
log.info("Started $app $version in $env")
}
}
fun main(args: Array<String>) {
run(App::class.java, *args)
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
kotlin
| 2 |
package org.integrational.spring.boot.kotlin.fromscratch
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.SpringApplication.run
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class App(
@Value("\${app.name}") private val app: String,
@Value("\${app.version}") private val version: String,
@Value("\${app.env}") private val env: String
) {
private val log = LoggerFactory.getLogger(App::class.java)
init {
log.info("Started $app $version in $env")
}
}
fun main(args: Array<String>) {
run(App::class.java, *args)
}
|
Below is an extract from a Ruby program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Ruby code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Ruby concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., metaprogramming, blocks). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Ruby. It should be similar to a school exercise, a tutorial, or a Ruby course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Ruby. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
#!/usr/bin/env ruby
# Tests periodic bridge updates.
# (C)2013 <NAME>
require_relative '../lib/nlhue'
USER = ENV['HUE_USER'] || 'testing1234'
EM.run do
NLHue::Bridge.add_bridge_callback do |bridge, status|
puts "Bridge event: #{bridge.serial} is now #{status ? 'available' : 'unavailable'}"
end
NLHue::Disco.send_discovery(3) do |br|
br.username = USER
count = 0
br.add_update_callback do |status, result|
if status
count = count + 1
puts "Bridge #{br.serial} updated #{count} times (changed: #{result})"
puts "Now #{br.groups.size} groups and #{br.lights.size} lights."
else
puts "Bridge #{br.serial} failed to update: #{result}"
end
end
br.subscribe
end
EM.add_timer(10) do
EM.stop_event_loop
end
end
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
ruby
| 4 |
#!/usr/bin/env ruby
# Tests periodic bridge updates.
# (C)2013 <NAME>
require_relative '../lib/nlhue'
USER = ENV['HUE_USER'] || 'testing1234'
EM.run do
NLHue::Bridge.add_bridge_callback do |bridge, status|
puts "Bridge event: #{bridge.serial} is now #{status ? 'available' : 'unavailable'}"
end
NLHue::Disco.send_discovery(3) do |br|
br.username = USER
count = 0
br.add_update_callback do |status, result|
if status
count = count + 1
puts "Bridge #{br.serial} updated #{count} times (changed: #{result})"
puts "Now #{br.groups.size} groups and #{br.lights.size} lights."
else
puts "Bridge #{br.serial} failed to update: #{result}"
end
end
br.subscribe
end
EM.add_timer(10) do
EM.stop_event_loop
end
end
|
Below is an extract of SQL code. Evaluate whether it has a high educational value and could help teach SQL and database concepts. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the code contains valid SQL syntax, even if it's just basic queries or simple table operations.
- Add another point if the code addresses practical SQL concepts (e.g., JOINs, subqueries), even if it lacks comments.
- Award a third point if the code is suitable for educational use and introduces key concepts in SQL and database management, even if the topic is somewhat advanced (e.g., indexes, transactions). The code should be well-structured and contain some comments.
- Give a fourth point if the code is self-contained and highly relevant to teaching SQL. It should be similar to a database course exercise, demonstrating good practices in query writing and database design.
- Grant a fifth point if the code is outstanding in its educational value and is perfectly suited for teaching SQL and database concepts. It should be well-written, easy to understand, and contain explanatory comments that clarify the purpose and impact of each part of the code.
The extract:
639188882728
Rica - 639399369648
Victor-639188039134
Bong - 639474296630
SERVER: DB-REPLICA (archive_powerapp_flu)
call sp_generate_inactive_list();
CREATE TABLE powerapp_inactive_list_0628 (
phone varchar(12) NOT NULL,
brand varchar(16) DEFAULT NULL,
bcast_dt date DEFAULT NULL,
PRIMARY KEY (phone),
KEY bcast_dt_idx (bcast_dt,phone)
);
insert into powerapp_inactive_list_0628 select phone, brand, null from powerapp_inactive_list;
update powerapp_inactive_list_0628 set bcast_dt='2014-06-28' where brand= 'TNT' and bcast_dt is null order by rand() limit 400000;
update powerapp_inactive_list_0628 set bcast_dt='2014-06-28' where brand<>'TNT' and bcast_dt is null order by rand() limit 400000;
update powerapp_inactive_list_0628 set bcast_dt='2014-06-29' where brand= 'TNT' and bcast_dt is null order by rand() limit 400000;
update powerapp_inactive_list_0628 set bcast_dt='2014-06-29' where brand<>'TNT' and bcast_dt is null order by rand() limit 400000;
select bcast_dt, count(1) from powerapp_inactive_list_0628 group by 1;
echo "select phone from powerapp_inactive_list_0628 where brand<>'TNT' and bcast_dt='2014-06-28'" | mysql -uroot -p --socket=/mnt/dbrep3307/mysql.sock --port=3307 archive_powerapp_flu | grep -v phone > smart_06282014.csv
echo "select phone from powerapp_inactive_list_0628 where brand='TNT' and bcast_dt='2014-06-28'" | mysql -uroot -p --socket=/mnt/dbrep3307/mysql.sock --port=3307 archive_powerapp_flu | grep -v phone > tnt_06282014.csv
echo "select phone from powerapp_inactive_list_0628 where brand<>'TNT' and bcast_dt='2014-06-29'" | mysql -uroot -p --socket=/mnt/dbrep3307/mysql.sock --port=3307 archive_powerapp_flu | grep -v phone > smart_06292014.csv
echo "select phone from powerapp_inactive_list_0628 where brand='TNT' and bcast_dt='2014-06-29'" | mysql -uroot -p --socket=/mnt/dbrep3307/mysql.sock --port=3307 archive_powerapp_flu | grep -v phone > tnt_06292014.csv
select phone into outfile '/tmp/BUDDY_20140728.csv' fields t
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
sql
| 3 |
639188882728
Rica - 639399369648
Victor-639188039134
Bong - 639474296630
SERVER: DB-REPLICA (archive_powerapp_flu)
call sp_generate_inactive_list();
CREATE TABLE powerapp_inactive_list_0628 (
phone varchar(12) NOT NULL,
brand varchar(16) DEFAULT NULL,
bcast_dt date DEFAULT NULL,
PRIMARY KEY (phone),
KEY bcast_dt_idx (bcast_dt,phone)
);
insert into powerapp_inactive_list_0628 select phone, brand, null from powerapp_inactive_list;
update powerapp_inactive_list_0628 set bcast_dt='2014-06-28' where brand= 'TNT' and bcast_dt is null order by rand() limit 400000;
update powerapp_inactive_list_0628 set bcast_dt='2014-06-28' where brand<>'TNT' and bcast_dt is null order by rand() limit 400000;
update powerapp_inactive_list_0628 set bcast_dt='2014-06-29' where brand= 'TNT' and bcast_dt is null order by rand() limit 400000;
update powerapp_inactive_list_0628 set bcast_dt='2014-06-29' where brand<>'TNT' and bcast_dt is null order by rand() limit 400000;
select bcast_dt, count(1) from powerapp_inactive_list_0628 group by 1;
echo "select phone from powerapp_inactive_list_0628 where brand<>'TNT' and bcast_dt='2014-06-28'" | mysql -uroot -p --socket=/mnt/dbrep3307/mysql.sock --port=3307 archive_powerapp_flu | grep -v phone > smart_06282014.csv
echo "select phone from powerapp_inactive_list_0628 where brand='TNT' and bcast_dt='2014-06-28'" | mysql -uroot -p --socket=/mnt/dbrep3307/mysql.sock --port=3307 archive_powerapp_flu | grep -v phone > tnt_06282014.csv
echo "select phone from powerapp_inactive_list_0628 where brand<>'TNT' and bcast_dt='2014-06-29'" | mysql -uroot -p --socket=/mnt/dbrep3307/mysql.sock --port=3307 archive_powerapp_flu | grep -v phone > smart_06292014.csv
echo "select phone from powerapp_inactive_list_0628 where brand='TNT' and bcast_dt='2014-06-29'" | mysql -uroot -p --socket=/mnt/dbrep3307/mysql.sock --port=3307 archive_powerapp_flu | grep -v phone > tnt_06292014.csv
select phone into outfile '/tmp/BUDDY_20140728.csv' fields terminated by ',' lines terminated by '\n' from powerapp_inactive_list_0728 where brand = 'BUDDY';
select phone into outfile '/tmp/TNT_20140728.csv' fields terminated by ',' lines terminated by '\n' from powerapp_inactive_list_0728 where brand = 'TNT';
scp noc@172.17.250.40:/tmp/*_20140728.csv /tmp/.
scp /tmp/*_20140728.csv noc@172.17.250.158:/tmp/.
cd /var/www/html/scripts/5555-powerapp/bcast
mv /tmp/*_20140728.csv .
select count(1) from powerapp_inactive_list a where brand = 'TNT'
and not exists (select 1 from tmp_plan_users_0908 b where a.phone=b.phone)
and not exists (select 1 from tmp_plan_users_0909 b where a.phone=b.phone);
select phone into outfile '/tmp/TNT_INACTIVE_20140909.csv' fields terminated by ',' lines terminated by '\n'
from powerapp_inactive_list a
where brand = 'TNT'
and not exists (select 1 from tmp_plan_users_0908 b where a.phone=b.phone)
and not exists (select 1 from tmp_plan_users_0909 b where a.phone=b.phone);
scp noc@172.17.250.40:/tmp/TNT_INACTIVE_20140909.csv /tmp/.
scp /tmp/TNT_INACTIVE_20140909.csv noc@172.17.250.158:/tmp/.
ssh noc@172.17.250.158
vi /tmp/TNT_INACTIVE_20140909.csv
639474296630
639399369648
639188039134
639188882728
639188088585
639189087704
wc -l /tmp/TNT_INACTIVE_20140909.csv
sort /tmp/TNT_INACTIVE_20140909.csv | uniq | wc -l
cd /var/www/html/scripts/5555-powerapp/bcast
mv /tmp/TNT_INACTIVE_20140909.csv .
select phone into outfile '/tmp/powerapp_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' group by phone;
select concat('''/tmp/',lower(plan), '_mins_20140908.csv''') plan, count(distinct phone) from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' group by 1;
select phone into outfile '/tmp/backtoschool_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'BACKTOSCHOOL' group by phone;
select phone into outfile '/tmp/chat_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'CHAT' group by phone;
select phone into outfile '/tmp/clashofclans_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'CLASHOFCLANS' group by phone;
select phone into outfile '/tmp/email_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'EMAIL' group by phone;
select phone into outfile '/tmp/facebook_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'FACEBOOK' group by phone;
select phone into outfile '/tmp/free_social_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'FREE_SOCIAL' group by phone;
select phone into outfile '/tmp/line_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'LINE' group by phone;
select phone into outfile '/tmp/photo_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'PHOTO' group by phone;
select phone into outfile '/tmp/pisonet_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'PISONET' group by phone;
select phone into outfile '/tmp/snapchat_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'SNAPCHAT' group by phone;
select phone into outfile '/tmp/social_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'SOCIAL' group by phone;
select phone into outfile '/tmp/speedboost_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'SPEEDBOOST' group by phone;
select phone into outfile '/tmp/tumblr_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'TUMBLR' group by phone;
select phone into outfile '/tmp/unli_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'UNLI' group by phone;
select phone into outfile '/tmp/waze_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'WAZE' group by phone;
select phone into outfile '/tmp/wechat_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'WECHAT' group by phone;
select phone into outfile '/tmp/wikipedia_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'WIKIPEDIA' group by phone;
select phone into outfile '/tmp/youtube_mins_20140908.csv' fields terminated by ',' lines terminated by '\n' from powerapp_log where datein >= '2014-09-08' and datein < '2014-09-09' and plan = 'YOUTUBE' group by phone;
scp noc@172.17.250.40:/tmp/*_20140909.csv /tmp/.
+--------------+---------------------------------------+-----------------------+
| plan | plan | count(distinct phone) |
+--------------+---------------------------------------+-----------------------+
| BACKTOSCHOOL | '/tmp/backtoschool_mins_20140908.csv' | 995 |
| CHAT | '/tmp/chat_mins_20140908.csv' | 1744 |
| CLASHOFCLANS | '/tmp/clashofclans_mins_20140908.csv' | 11270 |
| EMAIL | '/tmp/email_mins_20140908.csv' | 198 |
| FACEBOOK | '/tmp/facebook_mins_20140908.csv' | 107448 |
| FREE_SOCIAL | '/tmp/free_social_mins_20140908.csv' | 1572 |
| LINE | '/tmp/line_mins_20140908.csv' | 32 |
| PHOTO | '/tmp/photo_mins_20140908.csv' | 186 |
| PISONET | '/tmp/pisonet_mins_20140908.csv' | 3457 |
| SNAPCHAT | '/tmp/snapchat_mins_20140908.csv' | 14 |
| SOCIAL | '/tmp/social_mins_20140908.csv' | 2320 |
| SPEEDBOOST | '/tmp/speedboost_mins_20140908.csv' | 8221 |
| TUMBLR | '/tmp/tumblr_mins_20140908.csv' | 6 |
| UNLI | '/tmp/unli_mins_20140908.csv' | 11270 |
| WAZE | '/tmp/waze_mins_20140908.csv' | 21 |
| WECHAT | '/tmp/wechat_mins_20140908.csv' | 89 |
| WIKIPEDIA | '/tmp/wikipedia_mins_20140908.csv' | 1501 |
| YOUTUBE | '/tmp/youtube_mins_20140908.csv' | 21 |
+--------------+---------------------------------------+-----------------------+
|
Below is an extract of SQL code. Evaluate whether it has a high educational value and could help teach SQL and database concepts. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the code contains valid SQL syntax, even if it's just basic queries or simple table operations.
- Add another point if the code addresses practical SQL concepts (e.g., JOINs, subqueries), even if it lacks comments.
- Award a third point if the code is suitable for educational use and introduces key concepts in SQL and database management, even if the topic is somewhat advanced (e.g., indexes, transactions). The code should be well-structured and contain some comments.
- Give a fourth point if the code is self-contained and highly relevant to teaching SQL. It should be similar to a database course exercise, demonstrating good practices in query writing and database design.
- Grant a fifth point if the code is outstanding in its educational value and is perfectly suited for teaching SQL and database concepts. It should be well-written, easy to understand, and contain explanatory comments that clarify the purpose and impact of each part of the code.
The extract:
drop procedure if exists WYKONAJ_CZYNNOSC;
drop procedure if exists ODLOZ_CZYNNOSC;
DELIMITER //
CREATE PROCEDURE WYKONAJ_CZYNNOSC (IN nazwa_czynnosci VARCHAR(180), IN data_wykonania DATE)
BEGIN
DECLARE data_nastepnego_sprzatania_param DATE;
DECLARE data_ostatniego_sprzatania_param DATE;
DECLARE czestotliwosc_param INT(6);
SET data_ostatniego_sprzatania_param = (SELECT DATA_OSTATNIEGO_SPRZATANIA FROM SPRZATANIE_CZYNNOSCI WHERE NAZWA = nazwa_czynnosci);
SET czestotliwosc_param = (SELECT CZESTOTLIWOSC FROM SPRZATANIE_CZYNNOSCI WHERE NAZWA = nazwa_czynnosci);
SET data_nastepnego_sprzatania_param = DATE_ADD(data_wykonania, INTERVAL czestotliwosc_param DAY);
UPDATE SPRZATANIE_CZYNNOSCI
SET
DATA_OSTATNIEGO_SPRZATANIA = data_wykonania,
DATA_NASTEPNEGO_SPRZATANIA = data_nastepnego_sprzatania_param
WHERE NAZWA = nazwa_czynnosci;
END //
CREATE PROCEDURE ODLOZ_CZYNNOSC (IN nazwa_czynnosci VARCHAR(180))
BEGIN
DECLARE data_nastepnego_sprzatania_stara_param DATE;
DECLARE data_nastepnego_sprzatania_nowa_param DATE;
SET data_nastepnego_sprzatania_stara_param = (SELECT DATA_NASTEPNEGO_SPRZATANIA FROM SPRZATANIE_CZYNNOSCI WHERE NAZWA = nazwa_czynnosci);
SET data_nastepnego_sprzatania_nowa_param = DATE_ADD(data_nastepnego_sprzatania_stara_param, INTERVAL 7 DAY);
UPDATE SPRZATANIE_CZYNNOSCI
SET
DATA_NASTEPNEGO_SPRZATANIA = data_nastepnego_sprzatania_nowa_param
WHERE NAZWA = nazwa_czynnosci;
END //
DELIMITER ;
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
sql
| 4 |
drop procedure if exists WYKONAJ_CZYNNOSC;
drop procedure if exists ODLOZ_CZYNNOSC;
DELIMITER //
CREATE PROCEDURE WYKONAJ_CZYNNOSC (IN nazwa_czynnosci VARCHAR(180), IN data_wykonania DATE)
BEGIN
DECLARE data_nastepnego_sprzatania_param DATE;
DECLARE data_ostatniego_sprzatania_param DATE;
DECLARE czestotliwosc_param INT(6);
SET data_ostatniego_sprzatania_param = (SELECT DATA_OSTATNIEGO_SPRZATANIA FROM SPRZATANIE_CZYNNOSCI WHERE NAZWA = nazwa_czynnosci);
SET czestotliwosc_param = (SELECT CZESTOTLIWOSC FROM SPRZATANIE_CZYNNOSCI WHERE NAZWA = nazwa_czynnosci);
SET data_nastepnego_sprzatania_param = DATE_ADD(data_wykonania, INTERVAL czestotliwosc_param DAY);
UPDATE SPRZATANIE_CZYNNOSCI
SET
DATA_OSTATNIEGO_SPRZATANIA = data_wykonania,
DATA_NASTEPNEGO_SPRZATANIA = data_nastepnego_sprzatania_param
WHERE NAZWA = nazwa_czynnosci;
END //
CREATE PROCEDURE ODLOZ_CZYNNOSC (IN nazwa_czynnosci VARCHAR(180))
BEGIN
DECLARE data_nastepnego_sprzatania_stara_param DATE;
DECLARE data_nastepnego_sprzatania_nowa_param DATE;
SET data_nastepnego_sprzatania_stara_param = (SELECT DATA_NASTEPNEGO_SPRZATANIA FROM SPRZATANIE_CZYNNOSCI WHERE NAZWA = nazwa_czynnosci);
SET data_nastepnego_sprzatania_nowa_param = DATE_ADD(data_nastepnego_sprzatania_stara_param, INTERVAL 7 DAY);
UPDATE SPRZATANIE_CZYNNOSCI
SET
DATA_NASTEPNEGO_SPRZATANIA = data_nastepnego_sprzatania_nowa_param
WHERE NAZWA = nazwa_czynnosci;
END //
DELIMITER ;
|
Below is an extract from a Swift program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Swift code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Swift concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., protocols, extensions). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Swift. It should be similar to a school exercise, a tutorial, or a Swift course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Swift. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
//
// LearnJapaneseTableViewController.swift
// KarateApp
//
// Created by <NAME> on 18/02/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class LearnJapaneseTableViewController: UITableViewController {
var japaneseOptions = ["Greetings", "Numbers", "Colours"]
var optionSelected : String = ""
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Learn Japanese"
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return japaneseOptions.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "japaneseOption", for: indexPath)
// Configure the cell...
cell.textLabel?.text = japaneseOptions[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
print(japaneseOptions[0])
optionSelected = japaneseOptions[0]
performS
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
swift
| 2 |
//
// LearnJapaneseTableViewController.swift
// KarateApp
//
// Created by <NAME> on 18/02/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class LearnJapaneseTableViewController: UITableViewController {
var japaneseOptions = ["Greetings", "Numbers", "Colours"]
var optionSelected : String = ""
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Learn Japanese"
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return japaneseOptions.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "japaneseOption", for: indexPath)
// Configure the cell...
cell.textLabel?.text = japaneseOptions[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
print(japaneseOptions[0])
optionSelected = japaneseOptions[0]
performSegue(withIdentifier: "showDetailLearning", sender: self)
case 1:
print(japaneseOptions[1])
optionSelected = japaneseOptions[1]
performSegue(withIdentifier: "showDetailLearning", sender: self)
case 2:
print(japaneseOptions[2])
optionSelected = japaneseOptions[2]
performSegue(withIdentifier: "showDetailLearning", sender: self)
default:
print("No Path")
}
print(optionSelected, "after swtich" )
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
let dest = segue.destination as? JapanesePageViewController
print("Segue \(self.optionSelected)")
dest?.optionSelected = self.optionSelected
if let textViewController = dest?.subViewControllers[0] as? JapaneseTextViewController {
textViewController.optionSelected = self.optionSelected
}
if let audioViewController = dest?.subViewControllers[1] as? JapaneseAudioViewController {
audioViewController.optionSelect = self.optionSelected
}
if let videoViewController = dest?.subViewControllers[2] as? JapaneseVideoViewController {
videoViewController.optionSelected = self.optionSelected
}
}
}
|
Below is an extract from a shell script. Evaluate whether it has a high educational value and could help teach shell scripting. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the script contains valid shell commands, even if it's not educational, like simple system calls or basic file operations.
- Add another point if the script addresses practical shell scripting concepts (e.g., variables, conditionals), even if it lacks comments.
- Award a third point if the script is suitable for educational use and introduces key concepts in shell scripting, even if the topic is somewhat advanced (e.g., functions, process management). The script should be well-structured and contain some comments.
- Give a fourth point if the script is self-contained and highly relevant to teaching shell scripting. It should be similar to a tutorial example or a shell scripting course section, demonstrating good practices in script organization.
- Grant a fifth point if the script is outstanding in its educational value and is perfectly suited for teaching shell scripting. It should be well-written, easy to understand, and contain step-by-step explanations in comments.
The extract:
# Maintainer: <cit at protonmail dot com>
pkgname='webhttrack'
pkgver='3.49.2'
pkgrel=1
pkgdesc='HTTrack is a free (GPL, libre/free software) and easy-to-use offline browser utility.'
license=(GPL)
url='http://www.httrack.com/'
arch=('any')
provides=('httrack')
conflicts=('httrack' 'webhttrack-git')
depends=('bash' 'zlib' 'hicolor-icon-theme' 'openssl')
source=("http://download.httrack.com/cserv.php3?File=httrack.tar.gz")
md5sums=('1fd1ab9953432f0474a66b67a71d6381')
build() {
cd "httrack-${pkgver}"
./configure --prefix=/usr
make -j8
}
package() {
cd "httrack-${pkgver}"
make DESTDIR="${pkgdir}/" install
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
shell
| 4 |
# Maintainer: <cit at protonmail dot com>
pkgname='webhttrack'
pkgver='3.49.2'
pkgrel=1
pkgdesc='HTTrack is a free (GPL, libre/free software) and easy-to-use offline browser utility.'
license=(GPL)
url='http://www.httrack.com/'
arch=('any')
provides=('httrack')
conflicts=('httrack' 'webhttrack-git')
depends=('bash' 'zlib' 'hicolor-icon-theme' 'openssl')
source=("http://download.httrack.com/cserv.php3?File=httrack.tar.gz")
md5sums=('1fd1ab9953432f0474a66b67a71d6381')
build() {
cd "httrack-${pkgver}"
./configure --prefix=/usr
make -j8
}
package() {
cd "httrack-${pkgver}"
make DESTDIR="${pkgdir}/" install
}
|
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
Add another point if the program addresses practical C# concepts, even if it lacks comments.
Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments.
Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section.
Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
// Denis super code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;
public class AdditionalCoolScrol : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
[SerializeField] private GameShop gameShop;
public GameObject content;
public float sensetive;
public bool isDragg;
public Scrollbar SCRbar;
[SerializeField] Button LeftButton;
[SerializeField] Button RaightButton;
private int ChildCount = 0;
private List<float> xpos = new List<float>();
public int cardIndex = 0;
public Action OnCardIndexChange;
private void OnEnable()
{
OnCardIndexChange += gameShop.SetTest;
}
private void Start()
{
}
public void BuildScroll()
{
cardIndex = 0;
xpos.Clear();
ChildCount = gameShop.ItemsIDOnScreen.Count - 1 ;
float step = 1f / ChildCount;
xpos.Add(0);
for (int i = 0; i < ChildCount; i++)
{
xpos.Add(xpos[i] + step);
}
ActiveDisactiveScrollButtonsCheck();
}
private void Update()
{
if (!isDragg && ChildCount > 0)
{
Lerphandler(xpos[cardIndex]);
}
}
public void CalcIndex()
{
int newCardIndex = 0;
float tempDist = 100;
for (int i = 0; i < xpos.Count; i++)
{
if (Mathf.Abs(SCRbar.value - xpos[i]) < tempDist)
{
newCardIndex = i;
tempDist = Mathf.Abs(SCRbar.value - xpos[i]);
}
}
cardIndex = newCardIndex;
if (OnCardIndexChange != null)
{
OnCardIndexChange.Invoke();
}
}
void Lerphandler(float pos)
{
float newX = Mathf.Lerp(SCRbar.value, pos, Time.deltaTime * 8f);
SCRbar.value = newX;
}
public void OnDrag(PointerEventData eventData)
{
SCRbar.va
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
csharp
| 2 |
// Denis super code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;
public class AdditionalCoolScrol : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
[SerializeField] private GameShop gameShop;
public GameObject content;
public float sensetive;
public bool isDragg;
public Scrollbar SCRbar;
[SerializeField] Button LeftButton;
[SerializeField] Button RaightButton;
private int ChildCount = 0;
private List<float> xpos = new List<float>();
public int cardIndex = 0;
public Action OnCardIndexChange;
private void OnEnable()
{
OnCardIndexChange += gameShop.SetTest;
}
private void Start()
{
}
public void BuildScroll()
{
cardIndex = 0;
xpos.Clear();
ChildCount = gameShop.ItemsIDOnScreen.Count - 1 ;
float step = 1f / ChildCount;
xpos.Add(0);
for (int i = 0; i < ChildCount; i++)
{
xpos.Add(xpos[i] + step);
}
ActiveDisactiveScrollButtonsCheck();
}
private void Update()
{
if (!isDragg && ChildCount > 0)
{
Lerphandler(xpos[cardIndex]);
}
}
public void CalcIndex()
{
int newCardIndex = 0;
float tempDist = 100;
for (int i = 0; i < xpos.Count; i++)
{
if (Mathf.Abs(SCRbar.value - xpos[i]) < tempDist)
{
newCardIndex = i;
tempDist = Mathf.Abs(SCRbar.value - xpos[i]);
}
}
cardIndex = newCardIndex;
if (OnCardIndexChange != null)
{
OnCardIndexChange.Invoke();
}
}
void Lerphandler(float pos)
{
float newX = Mathf.Lerp(SCRbar.value, pos, Time.deltaTime * 8f);
SCRbar.value = newX;
}
public void OnDrag(PointerEventData eventData)
{
SCRbar.value += -(eventData.delta.x / sensetive);
}
public void OnBeginDrag(PointerEventData eventData)
{
isDragg = true;
}
public void OnEndDrag(PointerEventData eventData)
{
isDragg = false;
CalcIndex();
}
public void setCardIndex(int index)
{
cardIndex = index;
if (OnCardIndexChange != null)
{
OnCardIndexChange.Invoke();
}
}
public void LeftButtonLogic()
{
if (cardIndex > 0){
setCardIndex(cardIndex -= 1);
}
ActiveDisactiveScrollButtonsCheck();
}
public void RightButtonLogic(){
if (cardIndex < ChildCount) {
setCardIndex(cardIndex += 1);
}
ActiveDisactiveScrollButtonsCheck();
}
public void ActiveDisactiveScrollButtonsCheck(){
if (cardIndex == 0)
{
LeftButton.interactable = false;
} else {
LeftButton.interactable = true;
}
if (cardIndex == ChildCount)
{
RaightButton.interactable = false;
} else {
RaightButton.interactable = true;
}
}
public void OnDisable()
{
OnCardIndexChange = null;
}
}
|
Below is an extract from a C++ program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid C++ code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical C++ concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., memory management). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching C++. It should be similar to a school exercise, a tutorial, or a C++ course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C++. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
#include "mainwidget.h"
#include "ui_mainwidget.h"
#include <QFileDialog>
#include <QMessageBox>
#include <downscale/downscale.h>
MainWidget::MainWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::MainWidget)
{
ui->setupUi(this);
}
MainWidget::~MainWidget()
{
delete ui;
}
void MainWidget::on_pushButton_loadImage_clicked()
{
const QString l_filepath(QFileDialog::getOpenFileName(this,
windowTitle() + " - Open image file...",
"",
"Images (*.png *.jpg *.bmp)"));
if (l_filepath.isEmpty()) return;
if (!m_image.load(l_filepath))
{
ui->label_loaded->setText("");
return;
}
ui->label_loaded->setText(QString("%1x%2").arg(m_image.width()).arg(m_image.height()));
}
void MainWidget::on_pushButton_downscale_clicked()
{
const int l_newWidth = ui->lineEdit_newWidth->text().toInt(),
l_newHeight = ui->lineEdit_newHeight->text().toInt();
if (l_newWidth < 1 || l_newWidth >= m_image.width() ||
l_newHeight < 1 || l_newHeight >= m_image.height())
{
QMessageBox::critical(this,
windowTitle() + " - Error",
"Invalid source image or\nnew size must be less than source");
return;
}
const QString l_filepath(QFileDialog::getSaveFileName(this,
windowTitle() + " - Save image to file...",
"",
"Images (*.png)"));
QImage l_result(downscale(m_image, l_newWidth, l_newHeight));
l_result.save(l_filepath);
}
QImage MainWidget::downscale(const QImage &a_source, int a_newWidth, int a_newHeight)
{
QImage l_result(a_newWidth
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
cpp
| 2 |
#include "mainwidget.h"
#include "ui_mainwidget.h"
#include <QFileDialog>
#include <QMessageBox>
#include <downscale/downscale.h>
MainWidget::MainWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::MainWidget)
{
ui->setupUi(this);
}
MainWidget::~MainWidget()
{
delete ui;
}
void MainWidget::on_pushButton_loadImage_clicked()
{
const QString l_filepath(QFileDialog::getOpenFileName(this,
windowTitle() + " - Open image file...",
"",
"Images (*.png *.jpg *.bmp)"));
if (l_filepath.isEmpty()) return;
if (!m_image.load(l_filepath))
{
ui->label_loaded->setText("");
return;
}
ui->label_loaded->setText(QString("%1x%2").arg(m_image.width()).arg(m_image.height()));
}
void MainWidget::on_pushButton_downscale_clicked()
{
const int l_newWidth = ui->lineEdit_newWidth->text().toInt(),
l_newHeight = ui->lineEdit_newHeight->text().toInt();
if (l_newWidth < 1 || l_newWidth >= m_image.width() ||
l_newHeight < 1 || l_newHeight >= m_image.height())
{
QMessageBox::critical(this,
windowTitle() + " - Error",
"Invalid source image or\nnew size must be less than source");
return;
}
const QString l_filepath(QFileDialog::getSaveFileName(this,
windowTitle() + " - Save image to file...",
"",
"Images (*.png)"));
QImage l_result(downscale(m_image, l_newWidth, l_newHeight));
l_result.save(l_filepath);
}
QImage MainWidget::downscale(const QImage &a_source, int a_newWidth, int a_newHeight)
{
QImage l_result(a_newWidth, a_newHeight, QImage::Format_ARGB32);
int (QColor::*const l_get[])() const =
{ &QColor::alpha, &QColor::red, &QColor::green, &QColor::blue };
void (QColor::*const l_set[])(int) =
{ &QColor::setAlpha, &QColor::setRed, &QColor::setGreen, &QColor::setBlue };
std::vector<uint16_t> l_s(a_source.width() * a_source.height());
std::vector<uint16_t> l_d(a_newWidth * a_newHeight);
for (auto q(std::begin(l_get)); q != std::end(l_get); q++)
{
for (int i = 0; i < a_source.height(); i++)
for (int j = 0; j < a_source.width(); j++)
{
const QColor l_col(a_source.pixelColor(j, i));
l_s[j + i * a_source.width()] = (l_col.*l_get[std::distance(std::begin(l_get), q)])();
}
::downscale(l_s, a_source.width(), a_source.height(), l_d, a_newWidth, a_newHeight);
for (int i = 0; i < l_result.height(); i++)
for (int j = 0; j < l_result.width(); j++)
{
QColor l_col(l_result.pixelColor(j, i));
(l_col.*l_set[std::distance(std::begin(l_get), q)])(l_d[j + i * l_result.width()]);
l_result.setPixelColor(j, i, l_col);
}
}
return l_result;
}
|
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
Add another point if the program addresses practical C# concepts, even if it lacks comments.
Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments.
Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section.
Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
using Microsoft.EntityFrameworkCore;
using SoapyBackend.Data;
namespace SoapyBackend
{
public class CoreDbContext : DbContext
{
public DbSet<DeviceData> Devices { get; set; }
public DbSet<ProgramData> Programs { get; set; }
public DbSet<TriggerData> Triggers { get; set; }
public DbSet<UserData> Users { get; set; }
public CoreDbContext(DbContextOptions<CoreDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var user = modelBuilder.Entity<UserData>();
user.HasKey(x => new {x.Aud, x.DeviceId});
}
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
csharp
| 2 |
using Microsoft.EntityFrameworkCore;
using SoapyBackend.Data;
namespace SoapyBackend
{
public class CoreDbContext : DbContext
{
public DbSet<DeviceData> Devices { get; set; }
public DbSet<ProgramData> Programs { get; set; }
public DbSet<TriggerData> Triggers { get; set; }
public DbSet<UserData> Users { get; set; }
public CoreDbContext(DbContextOptions<CoreDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var user = modelBuilder.Entity<UserData>();
user.HasKey(x => new {x.Aud, x.DeviceId});
}
}
}
|
Below is an extract from a C++ program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid C++ code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical C++ concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., memory management). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching C++. It should be similar to a school exercise, a tutorial, or a C++ course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C++. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
#ifndef NT2_INCLUDE_FUNCTIONS_SCALAR_MOLER_HPP_INCLUDED
#define NT2_INCLUDE_FUNCTIONS_SCALAR_MOLER_HPP_INCLUDED
#include <nt2/gallery/include/functions/scalar/moler.hpp>
#endif
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
cpp
| 1 |
#ifndef NT2_INCLUDE_FUNCTIONS_SCALAR_MOLER_HPP_INCLUDED
#define NT2_INCLUDE_FUNCTIONS_SCALAR_MOLER_HPP_INCLUDED
#include <nt2/gallery/include/functions/scalar/moler.hpp>
#endif
|
Below is an extract from a C program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid C code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical C concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., kernel development and compiler design). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching C. It should be similar to a school exercise, a tutorial, or a C course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
#ifndef BRIDGESERVICE_H_
#define BRIDGESERVICE_H_
#include "bridge.h"
struct BridgeService
{
/**
* The port this service is located on. It is negative if the service is down.
*
* This value MUST correspond to the index in BridgeConnection.ports[]
*/
short port;
BridgeConnection* bridge;
void* service_data;
int8_t inputOpen;
int8_t outputOpen;
/**
* Called when the service receives some bytes from the android application.
*/
void (*onBytesReceived) (void* service_data, BridgeService* service, void* buffer, int size);
/**
* Called when the service receives a eof from the android application. The onCloseService() function will not longer be called.
*/
void (*onEof) (void* service_data, BridgeService* service);
/**
* Called when the service should cleanup all service data. Service should not use the write function during this call.
*/
void (*onCleanupService) (void* service_data, BridgeService* service);
};
#endif /* BRIDGESERVICE_H_ */
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
c
| 2 |
#ifndef BRIDGESERVICE_H_
#define BRIDGESERVICE_H_
#include "bridge.h"
struct BridgeService
{
/**
* The port this service is located on. It is negative if the service is down.
*
* This value MUST correspond to the index in BridgeConnection.ports[]
*/
short port;
BridgeConnection* bridge;
void* service_data;
int8_t inputOpen;
int8_t outputOpen;
/**
* Called when the service receives some bytes from the android application.
*/
void (*onBytesReceived) (void* service_data, BridgeService* service, void* buffer, int size);
/**
* Called when the service receives a eof from the android application. The onCloseService() function will not longer be called.
*/
void (*onEof) (void* service_data, BridgeService* service);
/**
* Called when the service should cleanup all service data. Service should not use the write function during this call.
*/
void (*onCleanupService) (void* service_data, BridgeService* service);
};
#endif /* BRIDGESERVICE_H_ */
|
Below is an extract from a Go program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Go code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Go concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., goroutines, interfaces). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Go. It should be similar to a school exercise, a tutorial, or a Go course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Go. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package util
import (
"github.com/1071496910/mysh/cons"
"io"
"math/rand"
"net"
"net/http"
"os"
"path/filepath"
"time"
)
func PullCert() error {
resp, err := http.DefaultClient.Get("https://" + cons.Domain + ":443/get_cert")
if err != nil {
return err
}
defer resp.Body.Close()
crtContent := []byte{}
_, err = resp.Body.Read(crtContent)
if err != nil {
return err
}
baseDir := filepath.Dir(cons.UserCrt)
if err := os.MkdirAll(baseDir, 0755); err != nil {
return err
}
f, err := os.Create(cons.UserCrt)
if err != nil {
return err
}
_, err = io.Copy(f, resp.Body)
return err
}
func FileExist(f string) bool {
if finfo, err := os.Stat(f); err == nil {
return !finfo.IsDir()
}
return false
}
func AppendFile(fn string, data string) error {
return writeFile(fn, data, func() (*os.File, error) {
return os.OpenFile(fn, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
})
}
func OverWriteFile(fn string, data string) error {
return writeFile(fn, data, func() (*os.File, error) {
return os.Create(fn)
})
}
func CheckTCP(endpint string) bool {
if conn, err := net.Dial("tcp", endpint); err == nil {
conn.Close()
return true
}
return false
}
func writeFile(fn string, data string, openFunc func() (*os.File, error)) error {
baseDir := filepath.Dir(fn)
if err := os.MkdirAll(baseDir, 0644); err != nil {
return err
}
f, err := openFunc()
if err != nil {
return err
}
_, err = f.WriteString(data)
return err
}
func init() {
rand.Seed(time.Now().UnixNano())
}
func Retry(attempts int, sleep time.Duration, f func() error) error {
if err := f(); err != nil {
if s, ok := err.(stop); ok {
// Return the original error for later checking
return s.error
}
if attempts--; attempts > 0 {
// Add some randomness to prevent creating a Thundering Herd
jitter := time.Duration(rand.Int63n(int64(sleep)))
sleep = sleep + jitter/2
time.Sleep(sleep)
return Retry(attempts, 2*sleep, f)
}
return err
}
return nil
}
t
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
go
| 2 |
package util
import (
"github.com/1071496910/mysh/cons"
"io"
"math/rand"
"net"
"net/http"
"os"
"path/filepath"
"time"
)
func PullCert() error {
resp, err := http.DefaultClient.Get("https://" + cons.Domain + ":443/get_cert")
if err != nil {
return err
}
defer resp.Body.Close()
crtContent := []byte{}
_, err = resp.Body.Read(crtContent)
if err != nil {
return err
}
baseDir := filepath.Dir(cons.UserCrt)
if err := os.MkdirAll(baseDir, 0755); err != nil {
return err
}
f, err := os.Create(cons.UserCrt)
if err != nil {
return err
}
_, err = io.Copy(f, resp.Body)
return err
}
func FileExist(f string) bool {
if finfo, err := os.Stat(f); err == nil {
return !finfo.IsDir()
}
return false
}
func AppendFile(fn string, data string) error {
return writeFile(fn, data, func() (*os.File, error) {
return os.OpenFile(fn, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
})
}
func OverWriteFile(fn string, data string) error {
return writeFile(fn, data, func() (*os.File, error) {
return os.Create(fn)
})
}
func CheckTCP(endpint string) bool {
if conn, err := net.Dial("tcp", endpint); err == nil {
conn.Close()
return true
}
return false
}
func writeFile(fn string, data string, openFunc func() (*os.File, error)) error {
baseDir := filepath.Dir(fn)
if err := os.MkdirAll(baseDir, 0644); err != nil {
return err
}
f, err := openFunc()
if err != nil {
return err
}
_, err = f.WriteString(data)
return err
}
func init() {
rand.Seed(time.Now().UnixNano())
}
func Retry(attempts int, sleep time.Duration, f func() error) error {
if err := f(); err != nil {
if s, ok := err.(stop); ok {
// Return the original error for later checking
return s.error
}
if attempts--; attempts > 0 {
// Add some randomness to prevent creating a Thundering Herd
jitter := time.Duration(rand.Int63n(int64(sleep)))
sleep = sleep + jitter/2
time.Sleep(sleep)
return Retry(attempts, 2*sleep, f)
}
return err
}
return nil
}
type stop struct {
error
}
|
Below is an extract from a shell script. Evaluate whether it has a high educational value and could help teach shell scripting. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the script contains valid shell commands, even if it's not educational, like simple system calls or basic file operations.
- Add another point if the script addresses practical shell scripting concepts (e.g., variables, conditionals), even if it lacks comments.
- Award a third point if the script is suitable for educational use and introduces key concepts in shell scripting, even if the topic is somewhat advanced (e.g., functions, process management). The script should be well-structured and contain some comments.
- Give a fourth point if the script is self-contained and highly relevant to teaching shell scripting. It should be similar to a tutorial example or a shell scripting course section, demonstrating good practices in script organization.
- Grant a fifth point if the script is outstanding in its educational value and is perfectly suited for teaching shell scripting. It should be well-written, easy to understand, and contain step-by-step explanations in comments.
The extract:
echo "foo $((42 * 42)) baz"
echo '$((42 * 42))'
echo="ciao mondo"
echo TEST=1
! echo run | echo cry
variable=$(echo \\`echo ciao\\`)
echo $variable
echo world
variable=$((42 + 43)) $ciao
echo $variable
echoword=$#
echoword=$@
(echo)
( ls )
TEST1=1 TEST2=2 echo world
until true; do sleep 1; done
ls $var > gen/res.txt
variable=$((42 + 43))
echo \'$((42 * 42))\'
echo "\\$(\\(42 * 42))"
variable=$((42 + 43)) $ciao
echo $((42 + 43))
variable=$((42 + 43))
echo world
echo \\\n\\\n\\\n\\\nthere
TEST=1 echo run
TEST=1
echo run && echo stop
echo run || echo cry
echo run | echo cry
! echo run | echo cry
echo TEST=1
TEST1=1 TEST2=2 echo world
echo; echo nls;
{ echo; ls; }
{ echo; ls; } > file.txt
echo world > file.txt < input.dat
{ echo; ls; } > file.txt < input.dat
echo;ls
echo&ls
echo && ls &
echo && ls & echo ciao
ls > file.txt
command foo --lol
ls 2> file.txt
( ls )
text=$(ls)
echo ${text:2:4}
echo ${!text*}
echo ${!text@}
echo ${text:2}
echo ${var/a/b}
echo ${var//a/b}
echo ${!text[*]}
echo ${!text[@]}
echo ${text^t}
echo ${text^^t}
echo ${text,t}
echo ${text,,t}
echo ${text^}
echo ${text^^}
echo ${text,}
echo ${text,,}
echo ${text@Q}
echo ${text@E}
echo ${text@P}
echo ${text@A}
echo ${text@a}
echo ${!text}
variable=$(echo ciao)
echo \'`echo ciao`\'
echo $(echo ciao)
echo `echo ciao`
variable=$(echo ciao)
variable=`echo ciao`
variable=$(echo \\`echo ciao\\`)
echo () { printf %s\\n "$*" ; }
for x in a b c; do echo $x; done
for x in; do echo $x; done
if true; then echo 1; fi
if true; then echo 1; else echo 2; fi
if true; then echo 1; elif false; then echo 3; else echo 2; fi
a=1 b=2 echo
echo
ls | grep *.js
echo 42 43
echo > 43
echo 2> 43
a=1 b=2 echo 42 43
until true || 1; do sleep 1;echo ciao; done
echo
(echo)
echo; echo ciao;
echo 42
echoword=${other}test
echo "\\$ciao"
echo "\\${ciao}"
echo foo ${other} bar baz
echo word${other}test
echo word${other}t$est
$other
echoword=$@
echoword=$*
echoword=$#
echoword=$?
echoword=$-
echoword=$$
echoword=$!
echoword
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
shell
| 3 |
echo "foo $((42 * 42)) baz"
echo '$((42 * 42))'
echo="ciao mondo"
echo TEST=1
! echo run | echo cry
variable=$(echo \\`echo ciao\\`)
echo $variable
echo world
variable=$((42 + 43)) $ciao
echo $variable
echoword=$#
echoword=$@
(echo)
( ls )
TEST1=1 TEST2=2 echo world
until true; do sleep 1; done
ls $var > gen/res.txt
variable=$((42 + 43))
echo \'$((42 * 42))\'
echo "\\$(\\(42 * 42))"
variable=$((42 + 43)) $ciao
echo $((42 + 43))
variable=$((42 + 43))
echo world
echo \\\n\\\n\\\n\\\nthere
TEST=1 echo run
TEST=1
echo run && echo stop
echo run || echo cry
echo run | echo cry
! echo run | echo cry
echo TEST=1
TEST1=1 TEST2=2 echo world
echo; echo nls;
{ echo; ls; }
{ echo; ls; } > file.txt
echo world > file.txt < input.dat
{ echo; ls; } > file.txt < input.dat
echo;ls
echo&ls
echo && ls &
echo && ls & echo ciao
ls > file.txt
command foo --lol
ls 2> file.txt
( ls )
text=$(ls)
echo ${text:2:4}
echo ${!text*}
echo ${!text@}
echo ${text:2}
echo ${var/a/b}
echo ${var//a/b}
echo ${!text[*]}
echo ${!text[@]}
echo ${text^t}
echo ${text^^t}
echo ${text,t}
echo ${text,,t}
echo ${text^}
echo ${text^^}
echo ${text,}
echo ${text,,}
echo ${text@Q}
echo ${text@E}
echo ${text@P}
echo ${text@A}
echo ${text@a}
echo ${!text}
variable=$(echo ciao)
echo \'`echo ciao`\'
echo $(echo ciao)
echo `echo ciao`
variable=$(echo ciao)
variable=`echo ciao`
variable=$(echo \\`echo ciao\\`)
echo () { printf %s\\n "$*" ; }
for x in a b c; do echo $x; done
for x in; do echo $x; done
if true; then echo 1; fi
if true; then echo 1; else echo 2; fi
if true; then echo 1; elif false; then echo 3; else echo 2; fi
a=1 b=2 echo
echo
ls | grep *.js
echo 42 43
echo > 43
echo 2> 43
a=1 b=2 echo 42 43
until true || 1; do sleep 1;echo ciao; done
echo
(echo)
echo; echo ciao;
echo 42
echoword=${other}test
echo "\\$ciao"
echo "\\${ciao}"
echo foo ${other} bar baz
echo word${other}test
echo word${other}t$est
$other
echoword=$@
echoword=$*
echoword=$#
echoword=$?
echoword=$-
echoword=$$
echoword=$!
echoword=$0
default_value=1
value=2
# other=
# ${other:-default_value}
# ${other-default_value}
# ${#default_value}
# ${other:=default_value}
# ${other=default_value}
# ${other:=default$value}
# ${other:?default_value}
# ${other?default_value}
# ${other:+default_value}
# ${other+default_value}
# ${other%default$value}
# ${other#default$value}
# ${other%%default$value}
# ${other##default$value}
echo say ${other} plz
echo say "${other} plz"
echo
a=echo
echoword=$1ciao
echoword=${11}test
echoword=$1
echoword=$11
|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package sudoku;
import javax.swing.*;
import java.awt.*;
public class Grid extends JPanel{
private OneLetterField[][] fields;
/** Skapar en panel som består ett rutnät 9 * 9 av klassen OneLetterField */
public Grid(View view, OneLetterField[][] fields) {
this.fields = fields;
setLayout(new GridLayout(9, 9));
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
fields[i][j] = new OneLetterField();
fields[i][j].setText("");
if(i/3 != 1 && j/3 != 1 || i/3 == 1 && j/3 == 1) {
fields[i][j].setBackground(new Color(180, 180, 180));
}
add(fields[i][j]);
}
}
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
java
| 3 |
package sudoku;
import javax.swing.*;
import java.awt.*;
public class Grid extends JPanel{
private OneLetterField[][] fields;
/** Skapar en panel som består ett rutnät 9 * 9 av klassen OneLetterField */
public Grid(View view, OneLetterField[][] fields) {
this.fields = fields;
setLayout(new GridLayout(9, 9));
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
fields[i][j] = new OneLetterField();
fields[i][j].setText("");
if(i/3 != 1 && j/3 != 1 || i/3 == 1 && j/3 == 1) {
fields[i][j].setBackground(new Color(180, 180, 180));
}
add(fields[i][j]);
}
}
}
}
|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package com.probsjustin.KAAS;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class logger_internal {
String internalDebugLevel = "debug";
Map<String,Integer> internalDebugMap = new HashMap<String,Integer>();
logger_internal(){
this.internalDebugMap.put("info", 1);
this.internalDebugMap.put("warn", 2);
this.internalDebugMap.put("error", 3);
this.internalDebugMap.put("debug", 4);
this.internalDebugMap.put("servlet", 0);
}
void debug(String func_debugMessage) {
this.writeLog("debug", func_debugMessage);
}
void error(String func_debugMessage) {
this.writeLog("error", func_debugMessage);
}
void writeLog(String func_debugFlag, String func_debugMessage) {
String holder_timestamp = "";
Date date = new Date();
Timestamp timestamp = new Timestamp(date.getTime());
if(timestamp.toString().length() <= 22) {
if(timestamp.toString().length() <= 21) {
holder_timestamp = timestamp.toString() + " ";
}else {
holder_timestamp = timestamp.toString() + " ";
}
}else {
holder_timestamp = timestamp.toString();
}
if(this.internalDebugMap.get(internalDebugLevel) <= this.internalDebugMap.get(func_debugFlag)){
switch(this.internalDebugMap.get(func_debugFlag)) {
case 1: {
String tempDebugString = "[INFO ] " + holder_timestamp + " | " + func_debugMessage.toString();
System.out.println(tempDebugString);
break;
}
case 2: {
String tempDebugString = "[WARN ] " + holder_timestamp + " | " + func_debugMessage.toString();
System.out.println(tempDebugString);
break;
}
case 3: {
String tempDebugString = "[ERROR] " + holder_timestamp + " | " + func_debugMessage.toString();
System.out.println(tempDebugString);
break;
}
case 4: {
String tempDebugString = "[DEBUG] " + holder_timestamp + " | " + func_debugMessage.toString();
System.out.println(tempDebugString);
break;
}
}
}
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
java
| 3 |
package com.probsjustin.KAAS;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class logger_internal {
String internalDebugLevel = "debug";
Map<String,Integer> internalDebugMap = new HashMap<String,Integer>();
logger_internal(){
this.internalDebugMap.put("info", 1);
this.internalDebugMap.put("warn", 2);
this.internalDebugMap.put("error", 3);
this.internalDebugMap.put("debug", 4);
this.internalDebugMap.put("servlet", 0);
}
void debug(String func_debugMessage) {
this.writeLog("debug", func_debugMessage);
}
void error(String func_debugMessage) {
this.writeLog("error", func_debugMessage);
}
void writeLog(String func_debugFlag, String func_debugMessage) {
String holder_timestamp = "";
Date date = new Date();
Timestamp timestamp = new Timestamp(date.getTime());
if(timestamp.toString().length() <= 22) {
if(timestamp.toString().length() <= 21) {
holder_timestamp = timestamp.toString() + " ";
}else {
holder_timestamp = timestamp.toString() + " ";
}
}else {
holder_timestamp = timestamp.toString();
}
if(this.internalDebugMap.get(internalDebugLevel) <= this.internalDebugMap.get(func_debugFlag)){
switch(this.internalDebugMap.get(func_debugFlag)) {
case 1: {
String tempDebugString = "[INFO ] " + holder_timestamp + " | " + func_debugMessage.toString();
System.out.println(tempDebugString);
break;
}
case 2: {
String tempDebugString = "[WARN ] " + holder_timestamp + " | " + func_debugMessage.toString();
System.out.println(tempDebugString);
break;
}
case 3: {
String tempDebugString = "[ERROR] " + holder_timestamp + " | " + func_debugMessage.toString();
System.out.println(tempDebugString);
break;
}
case 4: {
String tempDebugString = "[DEBUG] " + holder_timestamp + " | " + func_debugMessage.toString();
System.out.println(tempDebugString);
break;
}
}
}
}
}
|
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
Add another point if the program addresses practical C# concepts, even if it lacks comments.
Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments.
Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section.
Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
using System;
using System.Collections.Generic;
using System.Linq;
namespace AS
{
public class FeatureFilmMenu : IMenu
{
private IFind IdFinder => new IDFind();
private IFind NameFinder => new NameFind();
private IFind NationFinder => new NationFind();
private IFind DeletedFinder => new DeletedFind();
private IView DefaultView => new DefaultView();
private IView PriceInsView => new PriceInsView();
private IView PriceDesView => new PriceDesView();
private IView DeletedView => new DeletedView();
public void ShowMenu()
{
Console.WriteLine("___________________________ FEATURE FILM MENU ____________________________");
Console.WriteLine(" [1] Add Movie");
Console.WriteLine(" [2] Update Movie");
Console.WriteLine(" [3] Delete Movie");
Console.WriteLine(" [4] Restore Movie");
Console.WriteLine(" [5] Find Movie");
Console.WriteLine(" [6] View All Movie");
Console.WriteLine(" [7] View Deleted Movie");
Console.WriteLine(" [8] Back");
Console.WriteLine("__________________________________________________________________________");
}
public string ChooseMenu()
{
Console.Write("Select your option: ");
string option = Console.ReadLine();
switch (option)
{
case "1":
{
BEGIN:
Console.Clear();
IMovie newMovie = new FeatureFilm();
newMovie = newMovie.Add(newMovie);
newMovie.ID = Program.ListFeatureFilms.Count + 1001;
Program.ListFeatureFilms.Add(newMovie);
Console.WriteLine("Do you want to add another? [y/n]");
if (Console.ReadLine().ToLower().Equals("y"))
{
goto BEGIN;
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
csharp
| 2 |
using System;
using System.Collections.Generic;
using System.Linq;
namespace AS
{
public class FeatureFilmMenu : IMenu
{
private IFind IdFinder => new IDFind();
private IFind NameFinder => new NameFind();
private IFind NationFinder => new NationFind();
private IFind DeletedFinder => new DeletedFind();
private IView DefaultView => new DefaultView();
private IView PriceInsView => new PriceInsView();
private IView PriceDesView => new PriceDesView();
private IView DeletedView => new DeletedView();
public void ShowMenu()
{
Console.WriteLine("___________________________ FEATURE FILM MENU ____________________________");
Console.WriteLine(" [1] Add Movie");
Console.WriteLine(" [2] Update Movie");
Console.WriteLine(" [3] Delete Movie");
Console.WriteLine(" [4] Restore Movie");
Console.WriteLine(" [5] Find Movie");
Console.WriteLine(" [6] View All Movie");
Console.WriteLine(" [7] View Deleted Movie");
Console.WriteLine(" [8] Back");
Console.WriteLine("__________________________________________________________________________");
}
public string ChooseMenu()
{
Console.Write("Select your option: ");
string option = Console.ReadLine();
switch (option)
{
case "1":
{
BEGIN:
Console.Clear();
IMovie newMovie = new FeatureFilm();
newMovie = newMovie.Add(newMovie);
newMovie.ID = Program.ListFeatureFilms.Count + 1001;
Program.ListFeatureFilms.Add(newMovie);
Console.WriteLine("Do you want to add another? [y/n]");
if (Console.ReadLine().ToLower().Equals("y"))
{
goto BEGIN;
}
return "FeatureFilmMenu";
}
case "2":
{
BEGIN:
Console.Clear();
Console.Write("Enter ID: ");
string id = Console.ReadLine();
List<IMovie> result = IdFinder.Find(id,Program.ListFeatureFilms);
if (result.Count == 0)
{
Console.WriteLine("Do you want to continue? [y/n]");
if (Console.ReadLine().ToLower().Equals("y"))
{
goto BEGIN;
}
}
else
{
result.First().Update(result.First());
}
return "FeatureFilmMenu";
}
case "3":
{
BEGIN:
Console.Clear();
Console.Write("Enter ID: ");
string id = Console.ReadLine();
List<IMovie> result = IdFinder.Find(id, Program.ListFeatureFilms);
if (result.Count == 0)
{
Console.WriteLine("Do you want to continue? [y/n]");
if (Console.ReadLine().ToLower().Equals("y"))
{
goto BEGIN;
}
}
else
{
result.First().Delete(result.First());
}
return "FeatureFilmMenu";
}
case "4":
{
BEGIN:
Console.Clear();
Console.Write("Enter ID: ");
string id = Console.ReadLine();
List<IMovie> result = DeletedFinder.Find(id, Program.ListFeatureFilms);
if (result.Count == 0)
{
Console.WriteLine("Do you want to continue? [y/n]");
if (Console.ReadLine().ToLower().Equals("y"))
{
goto BEGIN;
}
}
else
{
result.First().Restore(result.First());
}
return "FeatureFilmMenu";
}
case "5":
{
BEGIN:
Console.Clear();
Console.WriteLine("[1] Find by ID");
Console.WriteLine("[2] Find by Name");
Console.WriteLine("[3] Find by Nation");
Console.Write("Select your option: ");
string select = Console.ReadLine();
Console.Clear();
switch (select)
{
case "1":
{
Console.Write("Enter keyword: ");
string keyword = Console.ReadLine();
IdFinder.Find(keyword, Program.ListFeatureFilms);
break;
}
case "2":
{
Console.Write("Enter keyword: ");
string keyword = Console.ReadLine();
NameFinder.Find(keyword,Program.ListFeatureFilms);
break;
}
case "3":
{
Console.Write("Enter keyword: ");
string keyword = Console.ReadLine();
NationFinder.Find(keyword, Program.ListFeatureFilms);
break;
}
default:
{
goto BEGIN;
}
}
Console.WriteLine("Press any key to continue..");
Console.ReadKey();
return "FeatureFilmMenu";
}
case "6":
{
BEGIN:
Console.Clear();
Console.WriteLine("[1] View by Ascending Price Order");
Console.WriteLine("[2] View by Descending Price Order");
Console.WriteLine("[3] View by Default Order");
Console.Write("Select your option: ");
string select = Console.ReadLine();
Console.Clear();
switch (select)
{
case "1":
{
PriceInsView.View(Program.ListFeatureFilms);
break;
}
case "2":
{
PriceDesView.View(Program.ListFeatureFilms);
break;
}
case "3":
{
DefaultView.View(Program.ListFeatureFilms);
break;
}
default:
{
goto BEGIN;
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
return "FeatureFilmMenu";
}
case "7":
{
Console.Clear();
DeletedView.View(Program.ListFeatureFilms);
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
return "FeatureFilmMenu";
}
case "8": return "Main";
default: return "FeatureFilmMenu";
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.