prompt
stringlengths 1.3k
3.64k
| language
stringclasses 16
values | label
int64 -1
5
| text
stringlengths 14
130k
|
---|---|---|---|
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:
//
// CustomScrollViewController.swift
// CustomViews
//
// Created by <NAME> on 22.02.20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
open class CustomScrollViewController: BaseViewController {
var bottomConstraint: NSLayoutConstraint?
public var contentViews: [UIView] {
return scrollContentView.subviews
}
private lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
return scrollView
}()
private lazy var scrollContentView: UIView = {
let scrollView = UIView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
return scrollView
}()
override public init() {
//self.viewModel = viewModel
super.init()
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupViews()
setupConstraints()
}
override open func setupViews() {
super.setupViews()
view.addSubview(scrollView)
scrollView.addSubview(scrollContentView)
}
@objc dynamic open override func setupConstraints() {
super.setupConstraints()
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(greaterThanOrEqualTo: view.topAnchor),
scrollView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
scrollView.widthAnchor.constraint(equalTo: view.widthAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
NSLayoutConstraint.activate([
scrollContentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
scrollContentView.centerXAnchor.constraint(equalTo: scrollView.center
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 | //
// CustomScrollViewController.swift
// CustomViews
//
// Created by <NAME> on 22.02.20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
open class CustomScrollViewController: BaseViewController {
var bottomConstraint: NSLayoutConstraint?
public var contentViews: [UIView] {
return scrollContentView.subviews
}
private lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
return scrollView
}()
private lazy var scrollContentView: UIView = {
let scrollView = UIView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
return scrollView
}()
override public init() {
//self.viewModel = viewModel
super.init()
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupViews()
setupConstraints()
}
override open func setupViews() {
super.setupViews()
view.addSubview(scrollView)
scrollView.addSubview(scrollContentView)
}
@objc dynamic open override func setupConstraints() {
super.setupConstraints()
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(greaterThanOrEqualTo: view.topAnchor),
scrollView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
scrollView.widthAnchor.constraint(equalTo: view.widthAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
NSLayoutConstraint.activate([
scrollContentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
scrollContentView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
scrollContentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor),
scrollContentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor)
])
bottomConstraint = NSLayoutConstraint(item: scrollContentView, attribute: .bottom,
relatedBy: .equal, toItem: scrollContentView,
attribute: .bottom, multiplier: 1, constant: 0)
scrollContentView.addConstraint(bottomConstraint!)
scrollView.scrollIndicatorInsets = scrollView.contentInset
}
public func addToContentView(_ views: UIView...) {
for view in views { scrollContentView.addSubview(view) }
}
public func getContentViewTopAnchor() -> NSLayoutYAxisAnchor {
return scrollContentView.topAnchor
}
public func getContentViewBottomAnchor() -> NSLayoutYAxisAnchor {
return scrollContentView.bottomAnchor
}
public func getContentViewLeadingAnchor() -> NSLayoutXAxisAnchor {
return scrollContentView.leadingAnchor
}
public func getContentViewTrailingAnchor() -> NSLayoutXAxisAnchor {
return scrollContentView.trailingAnchor
}
public func setContentViewTopAnchor(_ anchor: NSLayoutYAxisAnchor) {
NSLayoutConstraint.activate([scrollView.topAnchor.constraint(equalTo: anchor)])
}
public func setContentViewBottom(view: UIView) {
guard let bottomConstraint = bottomConstraint else { return }
scrollContentView.removeConstraint(bottomConstraint)
self.bottomConstraint = NSLayoutConstraint(item: view, attribute: .bottom,
relatedBy: .equal, toItem: scrollContentView,
attribute: .bottom, multiplier: 1, constant: -20)
scrollContentView.addConstraint(self.bottomConstraint!)
scrollContentView.setNeedsUpdateConstraints()
}
public func scrollRectToVisible(_ bounds: CGRect, animated: Bool) {
self.scrollView.scrollRectToVisible(bounds, animated: true)
}
public func setContentInsets(_ insets: UIEdgeInsets) {
scrollView.contentInset = insets
scrollView.scrollIndicatorInsets = insets
}
//public func setContentScrollIndicatorInsets(_ insets: UIEdgeInsets) {
// scrollView.scrollIndicatorInsets = insets
//}
}
|
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::support::geom::Point;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Rect
{
min_x: i64,
min_y: i64,
max_x: i64,
max_y: i64,
}
impl Rect
{
#[allow(dead_code)]
pub fn new(p1: Point, p2: Point) -> Self
{
Rect
{
min_x: i64::min(p1.x, p2.x),
min_y: i64::min(p1.y, p2.y),
max_x: i64::max(p1.x, p2.x),
max_y: i64::max(p1.y, p2.y),
}
}
#[allow(dead_code)]
pub fn new_from_coords(x1: i64, y1: i64, x2: i64, y2: i64) -> Self
{
Rect
{
min_x: i64::min(x1, x2),
min_y: i64::min(y1, y2),
max_x: i64::max(x1, x2),
max_y: i64::max(y1, y2),
}
}
#[allow(dead_code)]
pub fn get_min_x(&self) -> i64
{
self.min_x
}
#[allow(dead_code)]
pub fn get_min_y(&self) -> i64
{
self.min_y
}
#[allow(dead_code)]
pub fn get_max_x(&self) -> i64
{
self.max_x
}
#[allow(dead_code)]
pub fn get_max_y(&self) -> i64
{
self.max_y
}
#[allow(dead_code)]
pub fn area(&self) -> i64
{
(self.max_x - self.min_x) * (self.max_y - self.min_y)
}
#[allow(dead_code)]
pub fn perimeter(&self) -> i64
{
2 * (self.max_x - self.min_x)
+ 2 * (self.max_y - self.min_y)
}
#[allow(dead_code)]
pub fn intersection(&self, other: Rect) -> Option<Self>
{
let max_min_x = i64::max(self.min_x, other.min_x);
let max_min_y = i64::max(self.min_y, other.min_y);
let min_max_x = i64::min(self.max_x, other.max_x);
let min_max_y = i64::min(self.max_y, other.max_y);
if (max_min_x <= min_max_x) && (max_min_y <= min_max_y)
{
Some(Rect
{
min_x: max_min_x,
min_y: max_min_y,
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::support::geom::Point;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Rect
{
min_x: i64,
min_y: i64,
max_x: i64,
max_y: i64,
}
impl Rect
{
#[allow(dead_code)]
pub fn new(p1: Point, p2: Point) -> Self
{
Rect
{
min_x: i64::min(p1.x, p2.x),
min_y: i64::min(p1.y, p2.y),
max_x: i64::max(p1.x, p2.x),
max_y: i64::max(p1.y, p2.y),
}
}
#[allow(dead_code)]
pub fn new_from_coords(x1: i64, y1: i64, x2: i64, y2: i64) -> Self
{
Rect
{
min_x: i64::min(x1, x2),
min_y: i64::min(y1, y2),
max_x: i64::max(x1, x2),
max_y: i64::max(y1, y2),
}
}
#[allow(dead_code)]
pub fn get_min_x(&self) -> i64
{
self.min_x
}
#[allow(dead_code)]
pub fn get_min_y(&self) -> i64
{
self.min_y
}
#[allow(dead_code)]
pub fn get_max_x(&self) -> i64
{
self.max_x
}
#[allow(dead_code)]
pub fn get_max_y(&self) -> i64
{
self.max_y
}
#[allow(dead_code)]
pub fn area(&self) -> i64
{
(self.max_x - self.min_x) * (self.max_y - self.min_y)
}
#[allow(dead_code)]
pub fn perimeter(&self) -> i64
{
2 * (self.max_x - self.min_x)
+ 2 * (self.max_y - self.min_y)
}
#[allow(dead_code)]
pub fn intersection(&self, other: Rect) -> Option<Self>
{
let max_min_x = i64::max(self.min_x, other.min_x);
let max_min_y = i64::max(self.min_y, other.min_y);
let min_max_x = i64::min(self.max_x, other.max_x);
let min_max_y = i64::min(self.max_y, other.max_y);
if (max_min_x <= min_max_x) && (max_min_y <= min_max_y)
{
Some(Rect
{
min_x: max_min_x,
min_y: max_min_y,
max_x: min_max_x,
max_y: min_max_y,
})
}
else
{
None
}
}
pub fn does_point_intersect(&self, p: Point) -> bool
{
p.x >= self.min_x && p.x <= self.max_x && p.y >= self.min_y && p.y <= self.max_y
}
}
#[cfg(test)]
mod tests
{
use super::*;
#[test]
fn test_rect_intersection()
{
assert_eq!(Rect::new_from_coords(0, 0, 0, 0).intersection(Rect::new_from_coords(0, 0, 0, 0)),
Some(Rect::new_from_coords(0, 0, 0, 0)));
}
}
|
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:
一一二
在她柔荑摆处,由谷底行出了两队人来,一队,是手端菜肴的黑衣彪形大汉,另一队,则是手执银壶的青衣美貌婢女。
主人艳绝尘寰,侍婢自也不会太俗,那队青衣美婢,个个国色天香,姿色上乘,可说是选尽天下美色。
上菜了,青衣美婢随带香风,翩若惊鸿,一席两名,为座上嘉宾,武林豪雄,把盏斟酒。
这些个三山五岳,四海八荒的草莽人物,平日里的享受,无非是些大碗酒大块肉而已,几曾见过这等场面,这等阵仗?
由始至终,这一席酒宴,吃喝得好不舒服,自然不在话下!
有些生具寡人之疾的黑道邪魔,目光尽管贪婪,引人心恶的色迷馋像,尽管暴露,又食指尽管大动特动,但慑于主座上那三位威名,可丝毫不敢有明显放肆的举动。固然牡丹花下死,做鬼也风流,实在说起来,还是吃饭的家伙要紧,也只好望着美色而暗暗兴叹了!
酒过三巡,菜过五味,主座上突然站起了执杯的燕小飞,他长眉双挑,朗声发话说道:“诸位,燕小飞先敬诸位一杯,然后有桩大事奉告!”
面对“铁血墨龙”,群豪不敢怠慢,纷纷执杯站起。
“不敢当,我等该敬燕大侠!”
“好说!”燕小飞扬眉笑道:“燕小飞恭为东主,先干为敬!”
说完,举杯一仰而干,然后举手请那些也自饮尽一杯的武林群豪落坐,并扬声又道:“承蒙诸位侠驾辱临,燕小飞这里先致谢意,水酒淡薄,菜肴粗陋,虽然不成敬意,却是主人一片诚心,但请各位尽兴一次!”
一面说话,一面抱着手环揖,继续笑道:“虽说邀宴,但无事不敢惊动诸位,本意是想藉此机会,向诸位揭穿一桩骇人听闻,与举世武林安危,极有关系的绝大阴谋……”
此言一出,群豪之中,立刻起了一阵骚动,有人扬声叫道:“燕大侠只管请说,我等洗耳恭听!”
“不敢当!”燕小飞淡笑说道:“在座均为当世高人,面对高人,燕小飞不敢有所隐瞒,再说,此事已非秘密,燕小飞也无须讳言,诸位此次不远千里,不惜牺牲,尝风霜之苦,冒性命之险,会聚于江浙,多半均是为了争夺武林至宝‘蟠龙鼎’而来,但,诸位可否知道,‘蟠龙鼎’究竟落在何方?落在何处?……”
群豪无一人开口,显然个个都有了私心。
燕小飞扬眉一笑,道:“我可以奉告,其实诸位也知道,‘蟠龙鼎’落在当世首富,所谓世代殷商的‘金陵卓家’……”
群豪中,又是一阵骚动!
“诸位虽知道‘蟠龙鼎’落在‘金陵卓家’,可是燕小飞敢说,在座除了霍观音门下的‘一俊二娇’外,无人知道这是一桩意欲一网打尽天下武林精英的绝大阴谋……”
骚动再起,并有部份目光,纷纷投向东隅座上的“一俊二娇”。
“一俊二娇”泰然安祥,视若无见,不愧高人门下。
须臾,有人叫道:“老朽斗胆,请问燕大侠,怎见得,这是一桩意欲一网打尽武林精英的绝大阴谋?”
燕小飞目光投注,见发话之人,是一精神矍铄,五旬上下的青衣老者,燕小飞颇不陌生,淡然一笑说道:“是河北‘朝天堡’的顾堡主么?”
青衣老者抱拳起立答道:“不敢,老朽正是顾兴武。”
“顾堡主请坐!”燕小飞还了一礼,道:“恐怕顾堡主跟在座的诸位一样,只知道‘金陵卓家’是世代殷商,而不知道‘金陵卓家’不但个个会武,而且功力高绝,奇人深隐,卧虎藏龙,不啻……当……”
群豪中突然有人笑道:“恕陈某人斗胆插嘴,燕大侠似乎言之过重,据陈某人所知,‘金陵卓家’虽有会武者,那也不过是几名护院的武师而已!”
发话者,为一灰衣老者,是“蜀中一剑”陈天南。
燕小飞望了他一眼笑道:“陈大侠错了,据燕某所知,‘金陵卓家’少主人卓少君,一身功力,足列一流,由此看,他卓家无须什么武师护院!”
陈天南大笑说道:“谁不知道那卓少君是个文质彬彬的风流公子哥儿……”
“陈大侠,我燕小飞试过!”燕小飞截口笑道:“再说,当此之际,那卓少君要是个文质彬彬的风流公子哥儿,他敢终日闯荡街头么?”
陈天南呆了一呆,道:“那有可能,他不知道消息走漏,天下武林人物,都已闻风而来!”
燕小飞道:“在座有几位恐怕知道,那放出风声的,不是别人,而是他卓少君自己手下!”
陈天南一怔,默然不语,却又有人说道:“有道是,书呆子既呆又痴不怕死……”
“他或不怕。”燕小飞道:“但我以为在座诸位之中,必有人打算劫持卓少君,以换‘蟠龙鼎’。我试问,哪几位可曾跟梢过他么?我不相信,凭他一个手无缚鸡之力的文弱书生,还能摆脱在座的老江湖!”
那发话之人,寂然无声,没再说话!
燕小飞笑了一笑,又道:“天下武林齐集金陵,且是为了‘蟠龙鼎’而来,若说‘金陵卓家’不知道,那也是欺人之谈。既然知道,我也不以为凭一个殷实商家,在群雄环伺,旦不保夕的情况下,还能处之泰然,毫无惧色!”
目光一扫群豪,换口气,
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 | 一一二
在她柔荑摆处,由谷底行出了两队人来,一队,是手端菜肴的黑衣彪形大汉,另一队,则是手执银壶的青衣美貌婢女。
主人艳绝尘寰,侍婢自也不会太俗,那队青衣美婢,个个国色天香,姿色上乘,可说是选尽天下美色。
上菜了,青衣美婢随带香风,翩若惊鸿,一席两名,为座上嘉宾,武林豪雄,把盏斟酒。
这些个三山五岳,四海八荒的草莽人物,平日里的享受,无非是些大碗酒大块肉而已,几曾见过这等场面,这等阵仗?
由始至终,这一席酒宴,吃喝得好不舒服,自然不在话下!
有些生具寡人之疾的黑道邪魔,目光尽管贪婪,引人心恶的色迷馋像,尽管暴露,又食指尽管大动特动,但慑于主座上那三位威名,可丝毫不敢有明显放肆的举动。固然牡丹花下死,做鬼也风流,实在说起来,还是吃饭的家伙要紧,也只好望着美色而暗暗兴叹了!
酒过三巡,菜过五味,主座上突然站起了执杯的燕小飞,他长眉双挑,朗声发话说道:“诸位,燕小飞先敬诸位一杯,然后有桩大事奉告!”
面对“铁血墨龙”,群豪不敢怠慢,纷纷执杯站起。
“不敢当,我等该敬燕大侠!”
“好说!”燕小飞扬眉笑道:“燕小飞恭为东主,先干为敬!”
说完,举杯一仰而干,然后举手请那些也自饮尽一杯的武林群豪落坐,并扬声又道:“承蒙诸位侠驾辱临,燕小飞这里先致谢意,水酒淡薄,菜肴粗陋,虽然不成敬意,却是主人一片诚心,但请各位尽兴一次!”
一面说话,一面抱着手环揖,继续笑道:“虽说邀宴,但无事不敢惊动诸位,本意是想藉此机会,向诸位揭穿一桩骇人听闻,与举世武林安危,极有关系的绝大阴谋……”
此言一出,群豪之中,立刻起了一阵骚动,有人扬声叫道:“燕大侠只管请说,我等洗耳恭听!”
“不敢当!”燕小飞淡笑说道:“在座均为当世高人,面对高人,燕小飞不敢有所隐瞒,再说,此事已非秘密,燕小飞也无须讳言,诸位此次不远千里,不惜牺牲,尝风霜之苦,冒性命之险,会聚于江浙,多半均是为了争夺武林至宝‘蟠龙鼎’而来,但,诸位可否知道,‘蟠龙鼎’究竟落在何方?落在何处?……”
群豪无一人开口,显然个个都有了私心。
燕小飞扬眉一笑,道:“我可以奉告,其实诸位也知道,‘蟠龙鼎’落在当世首富,所谓世代殷商的‘金陵卓家’……”
群豪中,又是一阵骚动!
“诸位虽知道‘蟠龙鼎’落在‘金陵卓家’,可是燕小飞敢说,在座除了霍观音门下的‘一俊二娇’外,无人知道这是一桩意欲一网打尽天下武林精英的绝大阴谋……”
骚动再起,并有部份目光,纷纷投向东隅座上的“一俊二娇”。
“一俊二娇”泰然安祥,视若无见,不愧高人门下。
须臾,有人叫道:“老朽斗胆,请问燕大侠,怎见得,这是一桩意欲一网打尽武林精英的绝大阴谋?”
燕小飞目光投注,见发话之人,是一精神矍铄,五旬上下的青衣老者,燕小飞颇不陌生,淡然一笑说道:“是河北‘朝天堡’的顾堡主么?”
青衣老者抱拳起立答道:“不敢,老朽正是顾兴武。”
“顾堡主请坐!”燕小飞还了一礼,道:“恐怕顾堡主跟在座的诸位一样,只知道‘金陵卓家’是世代殷商,而不知道‘金陵卓家’不但个个会武,而且功力高绝,奇人深隐,卧虎藏龙,不啻……当……”
群豪中突然有人笑道:“恕陈某人斗胆插嘴,燕大侠似乎言之过重,据陈某人所知,‘金陵卓家’虽有会武者,那也不过是几名护院的武师而已!”
发话者,为一灰衣老者,是“蜀中一剑”陈天南。
燕小飞望了他一眼笑道:“陈大侠错了,据燕某所知,‘金陵卓家’少主人卓少君,一身功力,足列一流,由此看,他卓家无须什么武师护院!”
陈天南大笑说道:“谁不知道那卓少君是个文质彬彬的风流公子哥儿……”
“陈大侠,我燕小飞试过!”燕小飞截口笑道:“再说,当此之际,那卓少君要是个文质彬彬的风流公子哥儿,他敢终日闯荡街头么?”
陈天南呆了一呆,道:“那有可能,他不知道消息走漏,天下武林人物,都已闻风而来!”
燕小飞道:“在座有几位恐怕知道,那放出风声的,不是别人,而是他卓少君自己手下!”
陈天南一怔,默然不语,却又有人说道:“有道是,书呆子既呆又痴不怕死……”
“他或不怕。”燕小飞道:“但我以为在座诸位之中,必有人打算劫持卓少君,以换‘蟠龙鼎’。我试问,哪几位可曾跟梢过他么?我不相信,凭他一个手无缚鸡之力的文弱书生,还能摆脱在座的老江湖!”
那发话之人,寂然无声,没再说话!
燕小飞笑了一笑,又道:“天下武林齐集金陵,且是为了‘蟠龙鼎’而来,若说‘金陵卓家’不知道,那也是欺人之谈。既然知道,我也不以为凭一个殷实商家,在群雄环伺,旦不保夕的情况下,还能处之泰然,毫无惧色!”
目光一扫群豪,换口气,接着道:“再说,前些时,仲孙谷主为此曾在这谷中,困住了多位武林同道,想不到几天后的一个夜里,却突然被悉数纵去,而纵去这多位武林同道之人,也是来自所谓‘世代殷商’的‘金陵卓家’,诸位均为明智高人,有这许多疑点,我认为很够了!”
群豪鸦雀无声,个个变色,显然这些正邪两道的高手们,已有所疑。但,突然,陈天南一跃而起,大叫说道:“燕大侠,事关重大,陈天南斗胆要说一句话,‘铁血墨龙’四字,威震武林,既有所教,我等不敢不信,只是,空口无凭,燕大侠若想藉这句话儿,便使在座同道,放弃夺宝之争,只怕很难。”
燕小飞一笑说道:“多谢陈大侠明教,燕小飞也知道空口无凭,难以使在座相信,燕小飞也有鉴于此,所以今夜也特地请到几位有力证人……”
陈天南一怔说道:“怎么?燕大侠尚有人证,莫非?……”
燕小飞笑道:“陈大侠如今莫问,稍待自知分晓。”
陈天南未再说话,却仍然流露不信与不服神色。
燕小飞却极其从容,挥手轻声喝道:“带人!”
只听得谷底有人遥遥应了一声,走出一行人来。
那是以乐长宫为首,“白衣四灵”殿后,中间押着“子午追魂手”鲍耀寰,及那名唤秦尤的中年汉子等五个兄弟的队伍。
这行队伍一出现,群豪无不悚然动容,一齐目光投注!主座上,南宫隐停止了吃喝,各席上的两名青衣美婢,也放下了手中银壶,个个出神注视着座上群豪,微现紧张地一动不动!
|
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: post
title: "Yet Another Facemash?"
date: 2012-06-25 22:35
---
> If you guys were the inventors of Facebook, you'd have invented Facebook.
昨天看到了华科同学的杰作,扒了他们学校教务系统学生的头像,据说大部分是四六级时候照的(难怪~),并进行了公开投票(不得不承认,华科的妹子质量不错哈:p),站点是:*hust-facemash.com*,当然目前站点已经被和谐了(弱弱地补充一下,其实……我有备份来着。)。刚看到这条消息的时候,**Another Facebook?**,哈哈,当年小马哥就是这么干的嘛!所以……我也拿我们学校的来试试!
当然凭本菜这种实力搞点儿正经的hack是很困难的,不过看了俺们的教务系统……好吧,就是一个脚本的事情,代码我就不贴了,丢人。
四个年级的照片,140M左右。不过……必然都是证件照。。。而且作为一个正版工科学校,男女比例是相当吓人的。
好吧,我无聊了,要这些照片来也没用。。。没事儿看看吧。
如果有校领导什么的看到这篇文章,请放心,我是正经人,不会公开的。
免责申明什么的就算了。
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 | ---
layout: post
title: "Yet Another Facemash?"
date: 2012-06-25 22:35
---
> If you guys were the inventors of Facebook, you'd have invented Facebook.
昨天看到了华科同学的杰作,扒了他们学校教务系统学生的头像,据说大部分是四六级时候照的(难怪~),并进行了公开投票(不得不承认,华科的妹子质量不错哈:p),站点是:*hust-facemash.com*,当然目前站点已经被和谐了(弱弱地补充一下,其实……我有备份来着。)。刚看到这条消息的时候,**Another Facebook?**,哈哈,当年小马哥就是这么干的嘛!所以……我也拿我们学校的来试试!
当然凭本菜这种实力搞点儿正经的hack是很困难的,不过看了俺们的教务系统……好吧,就是一个脚本的事情,代码我就不贴了,丢人。
四个年级的照片,140M左右。不过……必然都是证件照。。。而且作为一个正版工科学校,男女比例是相当吓人的。
好吧,我无聊了,要这些照片来也没用。。。没事儿看看吧。
如果有校领导什么的看到这篇文章,请放心,我是正经人,不会公开的。
免责申明什么的就算了。
|
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 assert_cmd::{crate_name, Command};
use assert_fs::{
fixture::{FileWriteStr, PathChild},
TempDir,
};
use predicates::prelude::{predicate, PredicateStrExt};
use std::fs;
type TestResult = Result<(), Box<dyn std::error::Error>>;
#[test]
fn belay_in_non_git_dir() -> TestResult {
let working_dir = TempDir::new()?;
Command::cargo_bin(crate_name!())?
.current_dir(working_dir.path())
.assert()
.failure()
.stderr(predicate::str::similar(r#"Error: "Failed to find git root""#).trim());
Ok(())
}
#[test]
fn belay_in_no_ci_dir() -> TestResult {
let working_dir = TempDir::new()?;
Command::new("git")
.arg("init")
.current_dir(working_dir.path())
.assert()
.success();
Command::cargo_bin(crate_name!())?
.current_dir(working_dir.path())
.assert()
.failure()
.stderr(predicate::str::similar(r#"Error: "Unable to find CI configuration""#).trim());
Ok(())
}
#[test]
fn belay_in_github_ci_dir_with_restricted_applicability() -> TestResult {
let working_dir = TempDir::new()?;
Command::new("git")
.arg("init")
.current_dir(working_dir.path())
.assert()
.success();
fs::create_dir_all(working_dir.child(".github").child("workflows").path())?;
let github_yaml = include_str!("./github_parse_check_on_push_to_branch.yml");
working_dir
.child(".github")
.child("workflows")
.child("rust.yml")
.write_str(github_yaml)?;
// Should run while on master branch
Command::cargo_bin(crate_name!())?
.current_dir(working_dir.path())
.assert()
.success()
.stdout(
predicate::str::similar(
r#"Checking 'A Step':
stepping
Success!
"#,
)
.normalize(),
);
// Should not run while on other branch
Command::new("git")
.arg("checkout")
.arg("-b")
.arg("develop")
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 assert_cmd::{crate_name, Command};
use assert_fs::{
fixture::{FileWriteStr, PathChild},
TempDir,
};
use predicates::prelude::{predicate, PredicateStrExt};
use std::fs;
type TestResult = Result<(), Box<dyn std::error::Error>>;
#[test]
fn belay_in_non_git_dir() -> TestResult {
let working_dir = TempDir::new()?;
Command::cargo_bin(crate_name!())?
.current_dir(working_dir.path())
.assert()
.failure()
.stderr(predicate::str::similar(r#"Error: "Failed to find git root""#).trim());
Ok(())
}
#[test]
fn belay_in_no_ci_dir() -> TestResult {
let working_dir = TempDir::new()?;
Command::new("git")
.arg("init")
.current_dir(working_dir.path())
.assert()
.success();
Command::cargo_bin(crate_name!())?
.current_dir(working_dir.path())
.assert()
.failure()
.stderr(predicate::str::similar(r#"Error: "Unable to find CI configuration""#).trim());
Ok(())
}
#[test]
fn belay_in_github_ci_dir_with_restricted_applicability() -> TestResult {
let working_dir = TempDir::new()?;
Command::new("git")
.arg("init")
.current_dir(working_dir.path())
.assert()
.success();
fs::create_dir_all(working_dir.child(".github").child("workflows").path())?;
let github_yaml = include_str!("./github_parse_check_on_push_to_branch.yml");
working_dir
.child(".github")
.child("workflows")
.child("rust.yml")
.write_str(github_yaml)?;
// Should run while on master branch
Command::cargo_bin(crate_name!())?
.current_dir(working_dir.path())
.assert()
.success()
.stdout(
predicate::str::similar(
r#"Checking 'A Step':
stepping
Success!
"#,
)
.normalize(),
);
// Should not run while on other branch
Command::new("git")
.arg("checkout")
.arg("-b")
.arg("develop")
.current_dir(working_dir.path())
.assert()
.success();
// add and commit here to allow our current branch name
// lookup to work
Command::new("git")
.arg("add")
.arg(".")
.current_dir(working_dir.path())
.assert()
.success();
Command::new("git")
.arg("-c")
.arg("user.name='Josh'")
.arg("-c")
.arg("user.email='<EMAIL>'")
.arg("commit")
.arg("-m")
.arg("\"test commit\"")
.current_dir(working_dir.path())
.assert()
.success();
Command::cargo_bin(crate_name!())?
.current_dir(working_dir.path())
.assert()
.success()
.stdout(predicate::str::similar(""));
// should run if upstream is set, since the yml specifies it
// is triggered on pull request
Command::new("git")
.arg("remote")
.arg("add")
.arg("upstream")
.arg("test.com")
.current_dir(working_dir.path())
.assert()
.success();
Command::cargo_bin(crate_name!())?
.current_dir(working_dir.path())
.assert()
.success()
.stdout(
predicate::str::similar(
r#"Checking 'A Step':
stepping
Success!
"#,
)
.normalize(),
);
Ok(())
}
#[test]
fn belay_in_github_ci_dir() -> TestResult {
let working_dir = TempDir::new()?;
Command::new("git")
.arg("init")
.current_dir(working_dir.path())
.assert()
.success();
fs::create_dir_all(working_dir.child(".github").child("workflows").path())?;
let github_yaml = include_str!("./github_passing_integration_test.yml");
working_dir
.child(".github")
.child("workflows")
.child("rust.yml")
.write_str(github_yaml)?;
Command::cargo_bin(crate_name!())?
.current_dir(working_dir.path())
.assert()
.success()
.stdout(
predicate::str::similar(
r#"Checking 'Say hello':
hello
Success!
Checking 'Say goodbye':
goodbye
Success!
"#,
)
.normalize(),
);
Ok(())
}
#[test]
fn belay_in_github_ci_dir_with_multiple_workflows() -> TestResult {
let working_dir = TempDir::new()?;
Command::new("git")
.arg("init")
.current_dir(working_dir.path())
.assert()
.success();
fs::create_dir_all(working_dir.child(".github").child("workflows").path())?;
let github_yaml = include_str!("./github_passing_integration_test.yml");
working_dir
.child(".github")
.child("workflows")
.child("rust.yml")
.write_str(github_yaml)?;
let github_yaml = include_str!("./github_failing_integration_test.yml");
working_dir
.child(".github")
.child("workflows")
.child("rust2.yml")
.write_str(github_yaml)?;
// workflows should run in alphabetical order, and scripts which
// are exactly the same should not be run again
Command::cargo_bin(crate_name!())?
.current_dir(working_dir.path())
.assert()
.failure()
.stdout(
predicate::str::similar(
r#"Checking 'Say hello':
hello
Success!
Checking 'Say goodbye':
goodbye
Success!
Checking 'tough test':
"#,
)
.normalize(),
)
.stderr(predicate::str::similar("Error: \"Failed\"").trim());
Ok(())
}
#[test]
fn belay_in_gitlab_ci_dir() -> TestResult {
let working_dir = TempDir::new()?;
Command::new("git")
.arg("init")
.current_dir(working_dir.path())
.assert()
.success();
let github_yaml = include_str!("./gitlab_passing_integration_test.yml");
working_dir.child(".gitlab-ci.yml").write_str(github_yaml)?;
Command::cargo_bin(crate_name!())?
.current_dir(working_dir.path())
.assert()
.success()
.stdout(
predicate::str::similar(
r#"Checking 'echo hello':
hello
Success!
"#,
)
.normalize(),
);
Ok(())
}
#[test]
fn belay_in_github_ci_dir_fails() -> TestResult {
let working_dir = TempDir::new()?;
Command::new("git")
.arg("init")
.current_dir(working_dir.path())
.assert()
.success();
fs::create_dir_all(working_dir.child(".github").child("workflows").path())?;
let github_yaml = include_str!("./github_failing_integration_test.yml");
working_dir
.child(".github")
.child("workflows")
.child("rust.yml")
.write_str(github_yaml)?;
Command::cargo_bin(crate_name!())?
.current_dir(working_dir.path())
.assert()
.failure()
.stdout(
predicate::str::similar(
r#"Checking 'Say hello':
hello
Success!
Checking 'tough test':
"#,
)
.normalize(),
)
.stderr(predicate::str::similar("Error: \"Failed\"").trim());
Ok(())
}
#[test]
fn belay_hook_push() -> TestResult {
let working_dir = TempDir::new()?;
Command::new("git")
.arg("init")
.current_dir(working_dir.path())
.assert()
.success();
Command::cargo_bin(crate_name!())?
.arg("hook")
.arg("push")
.current_dir(working_dir.path())
.assert()
.success()
.stdout(predicate::str::similar("Created hook `.git/hooks/pre-push`").trim());
assert!(working_dir
.child(".git")
.child("hooks")
.child("pre-push")
.path()
.exists());
Ok(())
}
|
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:
//
// WBStatus.swift
// Weibo
//
// Created by 何强 on 2019/12/6.
// Copyright © 2019 何强. All rights reserved.
//
import UIKit
import YYModel
class WBStatus: NSObject {
var id: Int64 = 0
var text: String?
var created_at: String? {
didSet {
createDate = Date.cz_sinaDate(string: created_at ?? "")
}
}
var createDate: Date?
var source: String? {
didSet {
source = "来自于" + (source?.cz_href()?.text ?? "")
}
}
var reposts_count: Int = 0
var comments_count: Int = 0
var attitudes_count: Int = 0
var user: WBUser?
var retweeted_status: WBStatus?
var pic_urls: [WBStatusPicture]?
override var description: String {
return yy_modelDescription()
}
class func modelContainerPropertyGenericClass() -> [String: AnyClass] {
return ["pic_urls": WBStatusPicture.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>"
| swift | 3 | //
// WBStatus.swift
// Weibo
//
// Created by 何强 on 2019/12/6.
// Copyright © 2019 何强. All rights reserved.
//
import UIKit
import YYModel
class WBStatus: NSObject {
var id: Int64 = 0
var text: String?
var created_at: String? {
didSet {
createDate = Date.cz_sinaDate(string: created_at ?? "")
}
}
var createDate: Date?
var source: String? {
didSet {
source = "来自于" + (source?.cz_href()?.text ?? "")
}
}
var reposts_count: Int = 0
var comments_count: Int = 0
var attitudes_count: Int = 0
var user: WBUser?
var retweeted_status: WBStatus?
var pic_urls: [WBStatusPicture]?
override var description: String {
return yy_modelDescription()
}
class func modelContainerPropertyGenericClass() -> [String: AnyClass] {
return ["pic_urls": WBStatusPicture.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:
use imgui;
use imgui_sys;
use autograph::gfx;
use autograph::cache::{Cache, CacheTrait};
use autograph::gl;
use autograph::gl::types::*;
use autograph::gfx::glsl::GraphicsPipelineBuilderExt;
use autograph::gfx::draw::{DrawExt, DrawCmd};
use glutin;
use std::path::Path;
use std::sync::Arc;
use failure::Error;
pub struct Renderer {
pipeline: gfx::GraphicsPipeline,
texture: gfx::RawTexture,
}
static IMGUI_SHADER_PATH: &str = "data/shaders/imgui.glsl";
fn load_pipeline(gctx: &gfx::Context, path: &Path) -> Result<gfx::GraphicsPipeline, Error> {
Ok(gfx::GraphicsPipelineBuilder::new()
.with_glsl_file(path)?
.with_rasterizer_state(&gfx::RasterizerState {
fill_mode: gl::FILL,
..Default::default()
})
.with_all_blend_states(&gfx::BlendState {
enabled: true,
mode_rgb: gl::FUNC_ADD,
mode_alpha: gl::FUNC_ADD,
func_src_rgb: gl::SRC_ALPHA,
func_dst_rgb: gl::ONE_MINUS_SRC_ALPHA,
func_src_alpha: gl::ONE,
func_dst_alpha: gl::ZERO,
})
.build(gctx)?)
}
impl Renderer {
pub fn new(
imgui: &mut imgui::ImGui,
gctx: &gfx::Context,
cache: &Arc<Cache>,
) -> Renderer {
let pipeline = cache
.add_and_watch(IMGUI_SHADER_PATH.to_owned(), |path, reload_reason| {
load_pipeline(gctx, Path::new(path)).ok()
})
.unwrap();
let texture = imgui.prepare_texture(|handle| {
let desc = gfx::TextureDesc {
format: gfx::Format::R8G8B8A8_SRGB,
dimensions: gfx::TextureDimensions::Tex2D,
options: gfx::TextureOptions::empty(),
width: handle.width,
height: handle.height,
depth: 1,
mip_map_count: gfx::MipMaps::Count(1),
sample_count: 1,
};
let texture = gfx::RawTexture::with_pixels(gctx, &de
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 imgui;
use imgui_sys;
use autograph::gfx;
use autograph::cache::{Cache, CacheTrait};
use autograph::gl;
use autograph::gl::types::*;
use autograph::gfx::glsl::GraphicsPipelineBuilderExt;
use autograph::gfx::draw::{DrawExt, DrawCmd};
use glutin;
use std::path::Path;
use std::sync::Arc;
use failure::Error;
pub struct Renderer {
pipeline: gfx::GraphicsPipeline,
texture: gfx::RawTexture,
}
static IMGUI_SHADER_PATH: &str = "data/shaders/imgui.glsl";
fn load_pipeline(gctx: &gfx::Context, path: &Path) -> Result<gfx::GraphicsPipeline, Error> {
Ok(gfx::GraphicsPipelineBuilder::new()
.with_glsl_file(path)?
.with_rasterizer_state(&gfx::RasterizerState {
fill_mode: gl::FILL,
..Default::default()
})
.with_all_blend_states(&gfx::BlendState {
enabled: true,
mode_rgb: gl::FUNC_ADD,
mode_alpha: gl::FUNC_ADD,
func_src_rgb: gl::SRC_ALPHA,
func_dst_rgb: gl::ONE_MINUS_SRC_ALPHA,
func_src_alpha: gl::ONE,
func_dst_alpha: gl::ZERO,
})
.build(gctx)?)
}
impl Renderer {
pub fn new(
imgui: &mut imgui::ImGui,
gctx: &gfx::Context,
cache: &Arc<Cache>,
) -> Renderer {
let pipeline = cache
.add_and_watch(IMGUI_SHADER_PATH.to_owned(), |path, reload_reason| {
load_pipeline(gctx, Path::new(path)).ok()
})
.unwrap();
let texture = imgui.prepare_texture(|handle| {
let desc = gfx::TextureDesc {
format: gfx::Format::R8G8B8A8_SRGB,
dimensions: gfx::TextureDimensions::Tex2D,
options: gfx::TextureOptions::empty(),
width: handle.width,
height: handle.height,
depth: 1,
mip_map_count: gfx::MipMaps::Count(1),
sample_count: 1,
};
let texture = gfx::RawTexture::with_pixels(gctx, &desc, handle.pixels);
texture
});
imgui.set_texture_id(texture.gl_object() as usize);
Renderer { pipeline, texture }
}
pub fn render<'a>(
&mut self,
frame: &gfx::Frame,
target: &gfx::Framebuffer,
ui: imgui::Ui<'a>,
) {
// hot-reload pipeline from file
//self.pipeline.update();
ui.render(move |ui, draw_list| -> Result<(), String> {
self.render_draw_list(frame, target, ui, &draw_list)
});
}
pub fn render_draw_list<'a>(
&mut self,
frame: &gfx::Frame,
target: &gfx::Framebuffer,
ui: &imgui::Ui<'a>,
draw_list: &imgui::DrawList<'a>,
) -> Result<(), String>
{
let vertex_buffer = frame.upload(draw_list.vtx_buffer);
let index_buffer = frame.upload(draw_list.idx_buffer);
let (width, height) = ui.imgui().display_size();
let (scale_width, scale_height) = ui.imgui().display_framebuffer_scale();
if width == 0.0 || height == 0.0 {
return Ok(());
}
let matrix: [[f32; 4]; 4] = [
[2.0 / width as f32, 0.0, 0.0, 0.0],
[0.0, 2.0 / -(height as f32), 0.0, 0.0],
[0.0, 0.0, -1.0, 0.0],
[-1.0, 1.0, 0.0, 1.0],
];
let font_texture_id = self.texture.gl_object() as usize;
let mut idx_start = 0 as usize;
for cmd in draw_list.cmd_buffer {
// We don't support custom textures...yet!
assert!(cmd.texture_id as usize == font_texture_id);
let idx_end = idx_start + cmd.elem_count as usize;
let uniforms = frame.upload(&matrix);
frame.draw(target, &self.pipeline, DrawCmd::DrawIndexed { first: idx_start, count: cmd.elem_count as usize, base_vertex: 0 })
.with_vertex_buffer(0, &vertex_buffer)
.with_index_buffer(&index_buffer)
.with_uniform_buffer(0, &uniforms)
.with_texture(0,
&self.texture,
&gfx::SamplerDesc {
addr_u: gfx::TextureAddressMode::Wrap,
addr_v: gfx::TextureAddressMode::Wrap,
addr_w: gfx::TextureAddressMode::Wrap,
mag_filter: gfx::TextureMagFilter::Nearest,
min_filter: gfx::TextureMinFilter::Linear,
});
/*frame.begin_draw(target, &self.pipeline)
.with_vertex_buffer(0, &vertex_buffer)
.with_index_buffer(&index_buffer)
.with_uniform_buffer(0, &uniforms)
.with_texture(
0,
&self.texture,
&gfx::SamplerDesc {
addr_u: gfx::TextureAddressMode::Wrap,
addr_v: gfx::TextureAddressMode::Wrap,
addr_w: gfx::TextureAddressMode::Wrap,
mag_filter: gfx::TextureMagFilter::Nearest,
min_filter: gfx::TextureMinFilter::Linear,
},
)
.with_all_scissors(Some((
(cmd.clip_rect.x * scale_width) as i32,
((height - cmd.clip_rect.w) * scale_height) as i32,
((cmd.clip_rect.z - cmd.clip_rect.x) * scale_width) as i32,
((cmd.clip_rect.w - cmd.clip_rect.y) * scale_height) as i32,
)))
.draw_indexed(
idx_start,
cmd.elem_count as usize,
0,
);*/
idx_start = idx_end;
}
Ok(())
}
}
#[derive(Copy, Clone, PartialEq, Debug, Default)]
pub struct MouseState {
pos: (i32, i32),
pressed: (bool, bool, bool),
wheel: f32,
}
pub fn init(
context: &gfx::Context,
cache: &Arc<Cache>,
replacement_font: Option<&str>,
) -> (imgui::ImGui, Renderer, MouseState) {
// setup ImGui
let mut imgui = imgui::ImGui::init();
// load font from file
if let Some(replacement_font) = replacement_font {
unsafe {
use std::ffi::{CStr, CString};
let path = CString::new(replacement_font).unwrap();
let imgui_io = &mut *imgui_sys::igGetIO();
imgui_sys::ImFontAtlas_AddFontFromFileTTF(
imgui_io.fonts,
path.as_ptr(),
20.0,
0 as *const _,
0 as *const _,
);
};
}
// create an imgui renderer
let renderer = Renderer::new(&mut imgui, context, cache);
(imgui, renderer, MouseState::default())
}
pub fn handle_event(
imgui: &mut imgui::ImGui,
event: &glutin::Event,
mouse_state: &mut MouseState,
) -> bool {
use glutin::{ElementState, Event, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent};
use glutin::WindowEvent::*;
match event {
&Event::WindowEvent { ref event, .. } => {
match event {
&KeyboardInput { input, .. } => {
use glutin::VirtualKeyCode as Key;
let pressed = input.state == ElementState::Pressed;
match input.virtual_keycode {
Some(Key::Tab) => imgui.set_key(0, pressed),
Some(Key::Left) => imgui.set_key(1, pressed),
Some(Key::Right) => imgui.set_key(2, pressed),
Some(Key::Up) => imgui.set_key(3, pressed),
Some(Key::Down) => imgui.set_key(4, pressed),
Some(Key::PageUp) => imgui.set_key(5, pressed),
Some(Key::PageDown) => imgui.set_key(6, pressed),
Some(Key::Home) => imgui.set_key(7, pressed),
Some(Key::End) => imgui.set_key(8, pressed),
Some(Key::Delete) => imgui.set_key(9, pressed),
Some(Key::Back) => imgui.set_key(10, pressed),
Some(Key::Return) => imgui.set_key(11, pressed),
Some(Key::Escape) => imgui.set_key(12, pressed),
Some(Key::A) => imgui.set_key(13, pressed),
Some(Key::C) => imgui.set_key(14, pressed),
Some(Key::V) => imgui.set_key(15, pressed),
Some(Key::X) => imgui.set_key(16, pressed),
Some(Key::Y) => imgui.set_key(17, pressed),
Some(Key::Z) => imgui.set_key(18, pressed),
Some(Key::LControl) | Some(Key::RControl) => imgui.set_key_ctrl(pressed),
Some(Key::LShift) | Some(Key::RShift) => imgui.set_key_shift(pressed),
Some(Key::LAlt) | Some(Key::RAlt) => imgui.set_key_alt(pressed),
Some(Key::LWin) | Some(Key::RWin) => imgui.set_key_super(pressed),
_ => {}
}
}
&CursorMoved {
position: (x, y), ..
} => mouse_state.pos = (x as i32, y as i32),
&MouseInput { state, button, .. } => match button {
MouseButton::Left => mouse_state.pressed.0 = state == ElementState::Pressed,
MouseButton::Right => mouse_state.pressed.1 = state == ElementState::Pressed,
MouseButton::Middle => mouse_state.pressed.2 = state == ElementState::Pressed,
_ => {}
},
&MouseWheel {
delta: MouseScrollDelta::LineDelta(_, y),
phase: TouchPhase::Moved,
..
} |
&MouseWheel {
delta: MouseScrollDelta::PixelDelta(_, y),
phase: TouchPhase::Moved,
..
} => mouse_state.wheel = y,
&ReceivedCharacter(c) => imgui.add_input_character(c),
_ => (),
}
// update mouse
let scale = imgui.display_framebuffer_scale();
imgui.set_mouse_pos(
mouse_state.pos.0 as f32 / scale.0,
mouse_state.pos.1 as f32 / scale.1,
);
imgui.set_mouse_down(&[
mouse_state.pressed.0,
mouse_state.pressed.1,
mouse_state.pressed.2,
false,
false,
]);
imgui.set_mouse_wheel(mouse_state.wheel / scale.1);
mouse_state.wheel = 0.0;
true
}
_ => false,
}
}
|
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_blog.html' %}
{% block title %}
{% endblock %}`
{% block content %}
<div class="col-md-offset-3 col-12 col-xl-8 col-md-8">
<div class="col-md-offset-2 row">
<div class=" col"></div>
<div class="col-6">
<div class="alert alert-primary" role="alert">
중부신문고, 살스타그램 가입을 축하드립니다!
</div>
<table>
<tr>
<td><a href="{% url 'blog:index' %}" class="btn btn-success" role="button">홈으로</a></td>
<td><a href="{% url 'accounts:login' %}" class="btn btn-info" role="button">로그인</a></td>
</tr>
</table>
</form>
</div>
<div class="col"></div>
</div>
</div>
{% endblock %}
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 | 1 | {% extends 'base_blog.html' %}
{% block title %}
{% endblock %}`
{% block content %}
<div class="col-md-offset-3 col-12 col-xl-8 col-md-8">
<div class="col-md-offset-2 row">
<div class=" col"></div>
<div class="col-6">
<div class="alert alert-primary" role="alert">
중부신문고, 살스타그램 가입을 축하드립니다!
</div>
<table>
<tr>
<td><a href="{% url 'blog:index' %}" class="btn btn-success" role="button">홈으로</a></td>
<td><a href="{% url 'accounts:login' %}" class="btn btn-info" role="button">로그인</a></td>
</tr>
</table>
</form>
</div>
<div class="col"></div>
</div>
</div>
{% endblock %} |
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:
/*
* mnn.c
* The implementation of a pre-trained time-predictable meta neural network, generated by MNN2C.py.
*/
#include <stdbool.h>
#include "libcorethread/corethread.h"
#include "mnn.h"
#define DELAY_AIBRO_B_TO_OUTPUTS 1
#define DELAY_INPUTS_TO_AIBRO_B 1
// Cluster 0
// aibro_b's connection 0, from inputs
// Source range(s)
#define CONN_INPUTS_TO_AIBRO_B_0_DIM_0_START 0
#define CONN_INPUTS_TO_AIBRO_B_0_DIM_0_STOP 4
// Destination range(s) and length(s)
#define CONN_AIBRO_B_FROM_INPUTS_0_DIM_0_START 0
#define CONN_AIBRO_B_FROM_INPUTS_0_DIM_0_STOP 4
#define CONN_AIBRO_B_FROM_INPUTS_0_DIM_0_LEN 4
// Outputs
// outputs's connection 0, from aibro_b
// Source range(s)
#define CONN_AIBRO_B_TO_OUTPUTS_0_DIM_0_START 0
#define CONN_AIBRO_B_TO_OUTPUTS_0_DIM_0_STOP 2
// Destination range(s) and length(s)
#define CONN_OUTPUTS_FROM_AIBRO_B_0_DIM_0_START 0
#define CONN_OUTPUTS_FROM_AIBRO_B_0_DIM_0_STOP 2
#define CONN_OUTPUTS_FROM_AIBRO_B_0_DIM_0_LEN 2
void increment_index(int *index, int length)
{
if (++(*index) >= length)
{
*index = 0;
}
}
// Load and run functions
// Cluster 0
void run_unit_aibro_b(NN_META_DATA *mnn_data)
{
int src_dim_0_index;
int dst_dim_0_index;
src_dim_0_index = CONN_INPUTS_TO_AIBRO_B_0_DIM_0_START;
// Iterate over destination indices
//#pragma loopbound min CONN_AIBRO_B_FROM_INPUTS_0_DIM_0_LEN max CONN_AIBRO_B_FROM_INPUTS_0_DIM_0_LEN
for (dst_dim_0_index = CONN_AIBRO_B_FROM_INPUTS_0_DIM_0_START; dst_dim_0_index < CONN_AIBRO_B_FROM_INPUTS_0_DIM_0_STOP; dst_dim_0_index++)
{
mnn_data->aibro_b.inputs[dst_dim_0_index] =
mnn_data->inputs[mnn_data->aibro_b_pl_conn_0_inputs][src_dim_0_index];
src_dim_0_index++;
}
// assert(src_dim_0_index == CONN_INPUTS_TO_AIBRO_B_0_DIM_0_STOP);
increment_index(&mnn_data->aibro_b_pl_conn_0_inputs, NN_META_IN_PL_LEN);
nn_run_aibro_b(&mnn_data->aibro_b);
}
void run_cluster_0(NN_META_DATA *mnn_data)
{
run_unit_aibro_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>"
| c | 2 | /*
* mnn.c
* The implementation of a pre-trained time-predictable meta neural network, generated by MNN2C.py.
*/
#include <stdbool.h>
#include "libcorethread/corethread.h"
#include "mnn.h"
#define DELAY_AIBRO_B_TO_OUTPUTS 1
#define DELAY_INPUTS_TO_AIBRO_B 1
// Cluster 0
// aibro_b's connection 0, from inputs
// Source range(s)
#define CONN_INPUTS_TO_AIBRO_B_0_DIM_0_START 0
#define CONN_INPUTS_TO_AIBRO_B_0_DIM_0_STOP 4
// Destination range(s) and length(s)
#define CONN_AIBRO_B_FROM_INPUTS_0_DIM_0_START 0
#define CONN_AIBRO_B_FROM_INPUTS_0_DIM_0_STOP 4
#define CONN_AIBRO_B_FROM_INPUTS_0_DIM_0_LEN 4
// Outputs
// outputs's connection 0, from aibro_b
// Source range(s)
#define CONN_AIBRO_B_TO_OUTPUTS_0_DIM_0_START 0
#define CONN_AIBRO_B_TO_OUTPUTS_0_DIM_0_STOP 2
// Destination range(s) and length(s)
#define CONN_OUTPUTS_FROM_AIBRO_B_0_DIM_0_START 0
#define CONN_OUTPUTS_FROM_AIBRO_B_0_DIM_0_STOP 2
#define CONN_OUTPUTS_FROM_AIBRO_B_0_DIM_0_LEN 2
void increment_index(int *index, int length)
{
if (++(*index) >= length)
{
*index = 0;
}
}
// Load and run functions
// Cluster 0
void run_unit_aibro_b(NN_META_DATA *mnn_data)
{
int src_dim_0_index;
int dst_dim_0_index;
src_dim_0_index = CONN_INPUTS_TO_AIBRO_B_0_DIM_0_START;
// Iterate over destination indices
//#pragma loopbound min CONN_AIBRO_B_FROM_INPUTS_0_DIM_0_LEN max CONN_AIBRO_B_FROM_INPUTS_0_DIM_0_LEN
for (dst_dim_0_index = CONN_AIBRO_B_FROM_INPUTS_0_DIM_0_START; dst_dim_0_index < CONN_AIBRO_B_FROM_INPUTS_0_DIM_0_STOP; dst_dim_0_index++)
{
mnn_data->aibro_b.inputs[dst_dim_0_index] =
mnn_data->inputs[mnn_data->aibro_b_pl_conn_0_inputs][src_dim_0_index];
src_dim_0_index++;
}
// assert(src_dim_0_index == CONN_INPUTS_TO_AIBRO_B_0_DIM_0_STOP);
increment_index(&mnn_data->aibro_b_pl_conn_0_inputs, NN_META_IN_PL_LEN);
nn_run_aibro_b(&mnn_data->aibro_b);
}
void run_cluster_0(NN_META_DATA *mnn_data)
{
run_unit_aibro_b(mnn_data);
}
void copy_outputs(NN_META_DATA *mnn_data)
{
int src_dim_0_index;
int dst_dim_0_index;
// Copy unit outputs to MNN outputs
src_dim_0_index = CONN_AIBRO_B_TO_OUTPUTS_0_DIM_0_START;
// Iterate over destination indices
//#pragma loopbound min CONN_OUTPUTS_FROM_AIBRO_B_0_DIM_0_LEN max CONN_OUTPUTS_FROM_AIBRO_B_0_DIM_0_LEN
for (dst_dim_0_index = CONN_OUTPUTS_FROM_AIBRO_B_0_DIM_0_START; dst_dim_0_index < CONN_OUTPUTS_FROM_AIBRO_B_0_DIM_0_STOP; dst_dim_0_index++)
{
mnn_data->outputs[dst_dim_0_index] =
mnn_data->aibro_b.outputs[mnn_data->outputs_pl_conn_0_aibro_b][src_dim_0_index];
src_dim_0_index++;
}
// assert(src_dim_0_index == CONN_AIBRO_B_TO_OUTPUTS_0_DIM_0_STOP);
increment_index(&mnn_data->outputs_pl_conn_0_aibro_b, AIBRO_B_MAX_PL_LEN);
}
void tick_controller(WORKER_DATA *worker_data, int status)
{
int worker_index;
// Wait for all workers to arrive
for (worker_index = 0; worker_index < WORKER_COUNT; worker_index++)
{
while (!worker_data->worker_flags[worker_index])
{
inval_dcache();
}
}
// Set status
worker_data->status = status;
// Reset flags
for (worker_index = 0; worker_index < WORKER_COUNT; worker_index++)
{
worker_data->worker_flags[worker_index] = false;
}
// Toggle barrier, releasing workers
worker_data->tick_barrier = !worker_data->tick_barrier;
}
void tick_worker(WORKER_DATA *worker_data, int id)
{
int barrier_sample = worker_data->tick_barrier;
// Mark self as arrived
worker_data->worker_flags[id] = true;
// Wait for a signal from the controller (a change in tick_barrier value)
while (worker_data->tick_barrier == barrier_sample)
{
inval_dcache();
}
}
int mnn_init(NN_META_DATA *mnn_data)
{
nn_init_aibro_b();
// Input
mnn_data->input_pl_index = 0;
// Cluster 0
mnn_data->aibro_b_pl_conn_0_inputs = (NN_META_IN_PL_LEN - DELAY_INPUTS_TO_AIBRO_B) % NN_META_IN_PL_LEN;
// Output
mnn_data->outputs_pl_conn_0_aibro_b = AIBRO_B_MAX_PL_LEN - DELAY_AIBRO_B_TO_OUTPUTS;
mnn_data->worker_data.status = STATUS_RUNNING;
return 0;
}
int mnn_response(NN_META_DATA *nn_data)
{
increment_index(&nn_data->input_pl_index, NN_META_IN_PL_LEN);
copy_outputs(nn_data);
run_cluster_0(nn_data);
tick_controller(&nn_data->worker_data, STATUS_RUNNING);
return nn_data->input_pl_index; // The buffer to which new input data must be written
}
void mnn_free(NN_META_DATA *mnn_data)
{
tick_controller(&mnn_data->worker_data, STATUS_FINISHED);
int *ret;
for (int worker_index = 0; worker_index < WORKER_COUNT; worker_index++)
{
corethread_join(worker_index + 1, (void **)&ret);
if (ret != NULL)
{
printf("Worker exited with unexpected return status: %p", ret);
exit(1);
}
}
} |
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 { MessageEmbed } from 'discord.js'
import { Command } from '@customTypes/commands'
import { CommandContext } from '@models/command_context'
import functions from '../../functions'
export default class BanCommand implements Command {
commandNames = ['ban']
commandExamples = [
{
example: 'd.ban @『 ♥ deepz ♥ 』#4008 ugly...',
description: 'Ban that guy!!!',
},
]
commandCategory = 'Moderation'
commandUsage = 'd.ban <user> <time> <reason>'
getHelpMessage(commandPrefix: string): string {
return `Use ${commandPrefix}ban to ban someone from the guild.`
}
async run({ originalMessage, args }: CommandContext): Promise<void> {
const bUser = functions.getMember(originalMessage, args.shift())
if (!bUser || bUser.user.id === originalMessage.author.id) {
originalMessage.channel.send(
`**:x: Please provide a valid user to ban!**`
)
return
}
if (bUser.hasPermission('BAN_MEMBERS')) {
originalMessage.channel.send(`**:x: The user can't be banned!**`)
return
}
const bReason = args.join(' ')
if (!bReason) {
originalMessage.channel.send(
`**:x: Please provide a reason for banning him!**`
)
return
}
const embed = new MessageEmbed()
.setDescription(`**Ban**`)
.setColor('#4360FB')
.addField(`Banned user`, `${bUser} with ID ${bUser.id}`)
.addField(
`Banned by`,
`<@${originalMessage.author.id}> with ID ${originalMessage.author.id}`
)
.addField(`Banned in`, originalMessage.channel)
.addField(`Time`, originalMessage.createdAt)
.addField(`Reason`, bReason)
originalMessage.guild.member(bUser).ban({
reason: bReason,
})
originalMessage.channel.send(embed)
}
hasPermissionToRun({ originalMessage }: CommandContext): boolean {
if (!originalMessage.member.hasPermission('BAN_MEMBERS')) {
return false
} else {
return 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>"
| typescript | 3 | import { MessageEmbed } from 'discord.js'
import { Command } from '@customTypes/commands'
import { CommandContext } from '@models/command_context'
import functions from '../../functions'
export default class BanCommand implements Command {
commandNames = ['ban']
commandExamples = [
{
example: 'd.ban @『 ♥ deepz ♥ 』#4008 ugly...',
description: 'Ban that guy!!!',
},
]
commandCategory = 'Moderation'
commandUsage = 'd.ban <user> <time> <reason>'
getHelpMessage(commandPrefix: string): string {
return `Use ${commandPrefix}ban to ban someone from the guild.`
}
async run({ originalMessage, args }: CommandContext): Promise<void> {
const bUser = functions.getMember(originalMessage, args.shift())
if (!bUser || bUser.user.id === originalMessage.author.id) {
originalMessage.channel.send(
`**:x: Please provide a valid user to ban!**`
)
return
}
if (bUser.hasPermission('BAN_MEMBERS')) {
originalMessage.channel.send(`**:x: The user can't be banned!**`)
return
}
const bReason = args.join(' ')
if (!bReason) {
originalMessage.channel.send(
`**:x: Please provide a reason for banning him!**`
)
return
}
const embed = new MessageEmbed()
.setDescription(`**Ban**`)
.setColor('#4360FB')
.addField(`Banned user`, `${bUser} with ID ${bUser.id}`)
.addField(
`Banned by`,
`<@${originalMessage.author.id}> with ID ${originalMessage.author.id}`
)
.addField(`Banned in`, originalMessage.channel)
.addField(`Time`, originalMessage.createdAt)
.addField(`Reason`, bReason)
originalMessage.guild.member(bUser).ban({
reason: bReason,
})
originalMessage.channel.send(embed)
}
hasPermissionToRun({ originalMessage }: CommandContext): boolean {
if (!originalMessage.member.hasPermission('BAN_MEMBERS')) {
return false
} else {
return true
}
}
}
|
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.github.marty_suzuki.uniosample.counterunio
import com.github.marty_suzuki.unio.UnioFactory
import com.github.marty_suzuki.unio.UnioViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class CounterViewModel @Inject constructor(
unioFactory: UnioFactory<CounterUnioInput, CounterUnioOutput>,
) : UnioViewModel<CounterUnioInput, CounterUnioOutput>(unioFactory)
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.github.marty_suzuki.uniosample.counterunio
import com.github.marty_suzuki.unio.UnioFactory
import com.github.marty_suzuki.unio.UnioViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class CounterViewModel @Inject constructor(
unioFactory: UnioFactory<CounterUnioInput, CounterUnioOutput>,
) : UnioViewModel<CounterUnioInput, CounterUnioOutput>(unioFactory) |
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 <fstream>
#include "scanner.hpp"
using namespace lake;
using TokenKind = lake::Parser::token;
using Lexeme = lake::Parser::semantic_type;
void lake::Scanner::outputTokens( std::ostream& out )
{
Lexeme lexeme;
int tokenTag;
while(true){
tokenTag = this->yylex(&lexeme);
switch (tokenTag){
case TokenKind::END:
out << "EOF" << std::endl;
return;
case TokenKind::BOOL:
out << "bool" << std::endl;
break;
case TokenKind::INT:
out << "int" << std::endl;
break;
case TokenKind::VOID:
out << "void" << std::endl;
break;
case TokenKind::TRUE:
out << "true" << std::endl;
break;
case TokenKind::FALSE:
out << "false" << std::endl;
break;
case TokenKind::IF:
out << "if" << std::endl;
break;
case TokenKind::ELSE:
out << "else" << std::endl;
break;
case TokenKind::WHILE:
out << "while" << std::endl;
break;
case TokenKind::RETURN:
out << "return" << std::endl;
break;
case TokenKind::ID:
{
IDToken * tok = static_cast<IDToken *>(
lexeme.tokenValue);
out << "ID:" << tok->value() << std::endl;
break;
}
case TokenKind::INTLITERAL:
{
IntLitToken * tok = static_cast<IntLitToken *>(
lexeme.tokenValue);
out << "INTLIT:" << tok->value() << std::endl;
break;
}
case TokenKind::STRINGLITERAL:
{
StringLitToken * tok = static_cast<StringLitToken *>(
lexeme.tokenValue);
out << "STRINGLIT:" << tok->value() << std::endl;
break;
}
case TokenKind::LBRACE:
out << "[" << std::endl;
break;
case TokenKind::RBRACE:
out << "]" << std::endl;
break;
case TokenKind::LCURLY:
out << "{" << std::endl;
break;
case TokenKind::RCURLY:
out << "}" << std::endl;
break;
case TokenKind::LPAREN:
out << "(" << std::endl;
break;
case TokenKind::RPAREN:
out << ")" << std::endl;
break;
case TokenKind::SEMICOLON:
out << ";" << std::endl;
break;
case TokenKind::COMMA:
out << "," << std::endl;
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>"
| cpp | 3 | #include <fstream>
#include "scanner.hpp"
using namespace lake;
using TokenKind = lake::Parser::token;
using Lexeme = lake::Parser::semantic_type;
void lake::Scanner::outputTokens( std::ostream& out )
{
Lexeme lexeme;
int tokenTag;
while(true){
tokenTag = this->yylex(&lexeme);
switch (tokenTag){
case TokenKind::END:
out << "EOF" << std::endl;
return;
case TokenKind::BOOL:
out << "bool" << std::endl;
break;
case TokenKind::INT:
out << "int" << std::endl;
break;
case TokenKind::VOID:
out << "void" << std::endl;
break;
case TokenKind::TRUE:
out << "true" << std::endl;
break;
case TokenKind::FALSE:
out << "false" << std::endl;
break;
case TokenKind::IF:
out << "if" << std::endl;
break;
case TokenKind::ELSE:
out << "else" << std::endl;
break;
case TokenKind::WHILE:
out << "while" << std::endl;
break;
case TokenKind::RETURN:
out << "return" << std::endl;
break;
case TokenKind::ID:
{
IDToken * tok = static_cast<IDToken *>(
lexeme.tokenValue);
out << "ID:" << tok->value() << std::endl;
break;
}
case TokenKind::INTLITERAL:
{
IntLitToken * tok = static_cast<IntLitToken *>(
lexeme.tokenValue);
out << "INTLIT:" << tok->value() << std::endl;
break;
}
case TokenKind::STRINGLITERAL:
{
StringLitToken * tok = static_cast<StringLitToken *>(
lexeme.tokenValue);
out << "STRINGLIT:" << tok->value() << std::endl;
break;
}
case TokenKind::LBRACE:
out << "[" << std::endl;
break;
case TokenKind::RBRACE:
out << "]" << std::endl;
break;
case TokenKind::LCURLY:
out << "{" << std::endl;
break;
case TokenKind::RCURLY:
out << "}" << std::endl;
break;
case TokenKind::LPAREN:
out << "(" << std::endl;
break;
case TokenKind::RPAREN:
out << ")" << std::endl;
break;
case TokenKind::SEMICOLON:
out << ";" << std::endl;
break;
case TokenKind::COMMA:
out << "," << std::endl;
break;
case TokenKind::WRITE:
out << "<<" << std::endl;
break;
case TokenKind::READ:
out << ">>" << std::endl;
break;
case TokenKind::CROSSCROSS:
out << "++" << std::endl;
break;
case TokenKind::DASHDASH:
out << "--" << std::endl;
break;
case TokenKind::CROSS:
out << "+" << std::endl;
break;
case TokenKind::DASH:
out << "-" << std::endl;
break;
case TokenKind::STAR:
out << "*" << std::endl;
break;
case TokenKind::SLASH:
out << "/" << std::endl;
break;
case TokenKind::NOT:
out << "!" << std::endl;
break;
case TokenKind::AND:
out << "&&" << std::endl;
break;
case TokenKind::OR:
out << "||" << std::endl;
break;
case TokenKind::EQUALS:
out << "==" << std::endl;
break;
case TokenKind::NOTEQUALS:
out << "!=" << std::endl;
break;
case TokenKind::LESS:
out << "<" << std::endl;
break;
case TokenKind::GREATER:
out << ">" << std::endl;
break;
case TokenKind::LESSEQ:
out << "<=" << std::endl;
break;
case TokenKind::GREATEREQ:
out << ">=" << std::endl;
break;
case TokenKind::ASSIGN:
out << "=" << std::endl;
break;
case TokenKind::DEREF:
out << "@" << std::endl;
break;
case TokenKind::REF:
out << "^" << std::endl;
break;
default:
out << "UNKNOWN TOKEN" << std::endl;
break;
}
}
}
|
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:
---
title: NetTCPBinding
ms.date: 03/30/2017
ms.assetid: 1690b42f-acfd-4bb3-8f0d-0b17cd5ca36c
ms.openlocfilehash: bab4f89d197f18a5294c6d48998f2ae6e905151a
ms.sourcegitcommit: 9b552addadfb57fab0b9e7852ed4f1f1b8a42f8e
ms.translationtype: MT
ms.contentlocale: ja-JP
ms.lasthandoff: 04/23/2019
ms.locfileid: "61972407"
---
# <a name="nettcpbinding"></a>NetTCPBinding
このセクションには、Windows Communication Foundation (WCF) の TCP バインディングの使用を示すサンプルが含まれています。
## <a name="in-this-section"></a>このセクションの内容
[既定の NetTcpBinding](../../../../docs/framework/wcf/samples/default-nettcpbinding.md)
<xref:System.ServiceModel.NetTcpBinding> バインディングの使用方法を示します。
[Net.TCP ポート共有のサンプル](../../../../docs/framework/wcf/samples/net-tcp-port-sharing-sample.md)
WCF での共有 TCP ポートを示します。
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 | ---
title: NetTCPBinding
ms.date: 03/30/2017
ms.assetid: 1690b42f-acfd-4bb3-8f0d-0b17cd5ca36c
ms.openlocfilehash: bab4f89d197f18a5294c6d48998f2ae6e905151a
ms.sourcegitcommit: 9b552addadfb57fab0b9e7852ed4f1f1b8a42f8e
ms.translationtype: MT
ms.contentlocale: ja-JP
ms.lasthandoff: 04/23/2019
ms.locfileid: "61972407"
---
# <a name="nettcpbinding"></a>NetTCPBinding
このセクションには、Windows Communication Foundation (WCF) の TCP バインディングの使用を示すサンプルが含まれています。
## <a name="in-this-section"></a>このセクションの内容
[既定の NetTcpBinding](../../../../docs/framework/wcf/samples/default-nettcpbinding.md)
<xref:System.ServiceModel.NetTcpBinding> バインディングの使用方法を示します。
[Net.TCP ポート共有のサンプル](../../../../docs/framework/wcf/samples/net-tcp-port-sharing-sample.md)
WCF での共有 TCP ポートを示します。
|
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 <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> ns;
ns.push_back(2);
ns.push_back(1);
ns.push_back(3);
sort(ns.begin(), ns.end());
for (int i=0; i<ns.size(); i++) {
cout<<ns[i]<<endl;
}
}
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 | 3 | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> ns;
ns.push_back(2);
ns.push_back(1);
ns.push_back(3);
sort(ns.begin(), ns.end());
for (int i=0; i<ns.size(); i++) {
cout<<ns[i]<<endl;
}
}
|
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/sh
# Copyright (c) 2012-2016 General Electric Company. All rights reserved.
# The copyright to the computer software herein is the property of
# General Electric Company. The software may be used and/or copied only
# with the written permission of General Electric Company or in accordance
# with the terms and conditions stipulated in the agreement/contract
# under which the software has been supplied.
# This is the status that will be written if the script exits unexpectedly
starttime=$(date +%s)
status="failure"
errorcode="51"
message="Installation failed unexpectedly."
# This install script will be called by yeti which will provide three arguements
# The first argument is the Predix Home directory which is the directory to the
# Predix Machine container
# The second arguement is the path to the application directory. This contains
# the new application to be installed.
# The third arguement is the name of the zip. This must be used to create
# the JSON file to verify the status of the installation. The JSON must be
# placed in the appdata/packageframework directory with the name $ZIPNAME.json
# Updating the application proceeds as follows:
# 1. Make a backup of previous application
# 2. Add new application
# 3. Return an error code or 0 for success
PREDIX_MACHINE_HOME=$1
UPDATEDIR=$2
ZIPNAME=$3
STARTED_BY_AGENT=$4
# Let Agent handle restarting Predix Machine if install script is started by Agent
echo "STARTED_BY_AGENT=$STARTED_BY_AGENT"
DATE=`date +%m%d%y%H%M%S`
# Replace this with the name of your application directory
application=machine
PACKAGEFRAMEWORK=$PREDIX_MACHINE_HOME/appdata/packageframework
# All output from this file is redirected to a log file in logs/installations/packagename-x.x.x using file descriptor 6
# Fix any permissions issues with the incoming scripts caused by the zipping process
fixFilePermissions () {
# On some systems the tmp directory belongs to the wheel user group
chown -R :"$(id -gn)" "$UPDATEDIR"
echo "Fixing scri
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 | #!/bin/sh
# Copyright (c) 2012-2016 General Electric Company. All rights reserved.
# The copyright to the computer software herein is the property of
# General Electric Company. The software may be used and/or copied only
# with the written permission of General Electric Company or in accordance
# with the terms and conditions stipulated in the agreement/contract
# under which the software has been supplied.
# This is the status that will be written if the script exits unexpectedly
starttime=$(date +%s)
status="failure"
errorcode="51"
message="Installation failed unexpectedly."
# This install script will be called by yeti which will provide three arguements
# The first argument is the Predix Home directory which is the directory to the
# Predix Machine container
# The second arguement is the path to the application directory. This contains
# the new application to be installed.
# The third arguement is the name of the zip. This must be used to create
# the JSON file to verify the status of the installation. The JSON must be
# placed in the appdata/packageframework directory with the name $ZIPNAME.json
# Updating the application proceeds as follows:
# 1. Make a backup of previous application
# 2. Add new application
# 3. Return an error code or 0 for success
PREDIX_MACHINE_HOME=$1
UPDATEDIR=$2
ZIPNAME=$3
STARTED_BY_AGENT=$4
# Let Agent handle restarting Predix Machine if install script is started by Agent
echo "STARTED_BY_AGENT=$STARTED_BY_AGENT"
DATE=`date +%m%d%y%H%M%S`
# Replace this with the name of your application directory
application=machine
PACKAGEFRAMEWORK=$PREDIX_MACHINE_HOME/appdata/packageframework
# All output from this file is redirected to a log file in logs/installations/packagename-x.x.x using file descriptor 6
# Fix any permissions issues with the incoming scripts caused by the zipping process
fixFilePermissions () {
# On some systems the tmp directory belongs to the wheel user group
chown -R :"$(id -gn)" "$UPDATEDIR"
echo "Fixing script permissions"
for script in $(find "$UPDATEDIR" -type f -name "*.sh"); do
echo "Fixing permissions on $script"
chmod 744 "$script"
sync
done
}
# A trap method that's called on install completion. Writes the status file
finish () {
echo "$message"
printf "{\n\t\"status\" : \"$status\",\n\t\"errorcode\" : $errorcode,\n\t\"message\" : \"$message\",\n\t\"starttime\" : $starttime,\n\t\"endtime\" : $(date +%s)\n}\n" > "$PACKAGEFRAMEWORK/$ZIPNAME.json"
sync
# Start the container before exiting
if [ -f "$PREDIX_MACHINE_HOME/yeti/watchdog/start_watchdog.sh" ]; then
sh "$PREDIX_MACHINE_HOME/yeti/watchdog/start_watchdog.sh" &
elif [ -f "$PREDIX_MACHINE_HOME/mbsa/bin/mbsa_start.sh" ]; then
sh "$PREDIX_MACHINE_HOME/mbsa/bin/mbsa_start.sh" &
fi
exit $errorcode
}
trap finish EXIT
rollback () {
directory=$1
echo "Update unsuccessful. Attempting to rollback."
if [ -d "$PREDIX_MACHINE_HOME/$directory" ]; then
rm -v -r "$PREDIX_MACHINE_HOME/$directory/"
fi
mv -v "$PREDIX_MACHINE_HOME/$directory.old/" "$PREDIX_MACHINE_HOME/$directory/"
if [ $? -eq 0 ]; then
echo "Rollback successful."
else
echo "Rollback unsuccessful."
fi
sync
}
# Performs the application install. Uses the $application environmental variable set to determine the application to update
applicationInstall () {
# Shutdown container for update
echo "$(date +"%m/%d/%y %H:%M:%S") ##########################################################################"
echo "$(date +"%m/%d/%y %H:%M:%S") # Shutting down container for update #"
echo "$(date +"%m/%d/%y %H:%M:%S") ##########################################################################"
if [ -f "$PREDIX_MACHINE_HOME/yeti/watchdog/stop_watchdog.sh" ]; then
sh "$PREDIX_MACHINE_HOME/yeti/watchdog/stop_watchdog.sh"
elif [ -f "$PREDIX_MACHINE_HOME/mbsa/bin/mbsa_stop.sh" ]; then
sh "$PREDIX_MACHINE_HOME/mbsa/bin/mbsa_stop.sh"
elif [ $STARTED_BY_AGENT == "true" ]; then
echo "Container restart will be handled by Predix Machine Agent."
else
message="Unable to find a valid shutdown method for the Predix Machine framework. Install failed"
errorcode="52"
status="failure"
exit
fi
# Remove the connected signal file if it exists, this will be written back by
# cloud gateway at the next sync
if [ -f "$CLOUDGATEWAY/connected" ]; then
rm -vf "$CLOUDGATEWAY/connected"
sync
fi
echo "Updating the $application directory."
if [ -d "$PREDIX_MACHINE_HOME/$application" ]; then
echo "Updating $application application. Backup of current application stored in $application.old."
if [ -d "$PREDIX_MACHINE_HOME/$application.old" ]; then
echo "Updating $application.old application backup to revision before this update."
rm -v -r "$PREDIX_MACHINE_HOME/$application.old/"
if [ $? -eq 0 ]; then
echo "Previous $application.old removed."
else
message="Previous $application.old could not be removed."
errorcode="54"
status="failure"
exit
fi
fi
mv -v "$PREDIX_MACHINE_HOME/$application/" "$PREDIX_MACHINE_HOME/$application.old/"
if [ $? -eq 0 ]; then
sync
echo "The $application application backup created as $application.old."
else
message="The $application application could not be renamed to $application.old."
errorcode="55"
status="failure"
exit
fi
fi
mv -v "$UPDATEDIR/$application/" "$PREDIX_MACHINE_HOME/$application/"
if [ $? -eq 0 ]; then
chmod +x "$PREDIX_MACHINE_HOME/$application/bin/predix/start_container.sh"
sync
chmod +x "$PREDIX_MACHINE_HOME/$application/bin/predix/stop_container.sh"
sync
message="The $application application was updated successfully."
errorcode="0"
status="success"
exit
else
message="The $application application could not be updated."
errorcode="56"
status="failure"
# Attempt a rollback
rollback "$application"
exit
fi
}
# Update the $application application by removing any old backups, renaming the
# current installed application to $application.old, and adding the updated
# application
fixFilePermissions
applicationInstall
|
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::collections::HashMap;
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct CoinFile {
pub coins: HashMap<String, Name>,
}
#[derive(Deserialize, Debug, Clone)]
#[serde(untagged, deny_unknown_fields)]
pub enum Name {
Simple(String),
Detailed(DetailedName),
}
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct DetailedName {
pub long_name: String,
pub bitfinex: Option<String>,
pub coinmarketcap: Option<CoinMarketCap>,
}
#[derive(Deserialize, Debug, Clone)]
#[serde(untagged, deny_unknown_fields)]
pub enum CoinMarketCap {
Simple(String),
Detailed(DetailedCoinMarketCap),
}
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct DetailedCoinMarketCap {
pub id: String,
pub conversion_symbol: 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>"
| rust | 2 | use std::collections::HashMap;
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct CoinFile {
pub coins: HashMap<String, Name>,
}
#[derive(Deserialize, Debug, Clone)]
#[serde(untagged, deny_unknown_fields)]
pub enum Name {
Simple(String),
Detailed(DetailedName),
}
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct DetailedName {
pub long_name: String,
pub bitfinex: Option<String>,
pub coinmarketcap: Option<CoinMarketCap>,
}
#[derive(Deserialize, Debug, Clone)]
#[serde(untagged, deny_unknown_fields)]
pub enum CoinMarketCap {
Simple(String),
Detailed(DetailedCoinMarketCap),
}
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct DetailedCoinMarketCap {
pub id: String,
pub conversion_symbol: String,
}
|
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:
extern crate dat;
extern crate image;
extern crate cgmath_geometry;
use std::slice;
use dat::SkylineAtlas;
use image::{DynamicImage, ColorType};
use cgmath_geometry::DimsRect;
fn main() {
let mut atlas = SkylineAtlas::new([0; 4], DimsBox::new2(512, 512));
let doge = extract_buffer(image::open("test_images/doge.png").unwrap());
let ffx = extract_buffer(image::open("test_images/ffx.png").unwrap());
let rust = extract_buffer(image::open("test_images/rust.png").unwrap());
let tf = extract_buffer(image::open("test_images/tf.png").unwrap());
let mut rectangles = vec![];
for _ in 0..4 {
rectangles.push(atlas.add_image(ffx.0, ffx.0.into(), &ffx.1).unwrap());
rectangles.push(atlas.add_image(tf.0, tf.0.into(), &tf.1).unwrap());
}
rectangles.push(atlas.add_image(doge.0, doge.0.into(), &doge.1).unwrap());
rectangles.push(atlas.add_image(ffx.0, ffx.0.into(), &ffx.1).unwrap());
rectangles.push(atlas.add_image(rust.0, rust.0.into(), &rust.1).unwrap());
rectangles.push(atlas.add_image(tf.0, tf.0.into(), &tf.1).unwrap());
rectangles.push(atlas.add_image(ffx.0, ffx.0.into(), &ffx.1).unwrap());
rectangles.push(atlas.add_image(doge.0, doge.0.into(), &doge.1).unwrap());
rectangles.push(atlas.add_image(ffx.0, ffx.0.into(), &ffx.1).unwrap());
rectangles.push(atlas.add_image(rust.0, rust.0.into(), &rust.1).unwrap());
rectangles.push(atlas.add_image(tf.0, tf.0.into(), &tf.1).unwrap());
rectangles.push(atlas.add_image(ffx.0, ffx.0.into(), &ffx.1).unwrap());
println!();
atlas.compact(&mut rectangles);
let pixels = atlas.pixels();
image::save_buffer("./skyline_atlas.bmp", unsafe{slice::from_raw_parts(pixels.as_ptr() as *const u8, pixels.len() * 4)}, 512, 512, ColorType::RGBA(8)).unwrap();
}
fn extract_buffer(img: DynamicImage) -> (DimsRect<u32>, Vec<[u8; 4]>) {
match img {
DynamicImage::ImageRgba8(img) => {
let rect = DimsBox::new2(img.width(), img.height());
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 | extern crate dat;
extern crate image;
extern crate cgmath_geometry;
use std::slice;
use dat::SkylineAtlas;
use image::{DynamicImage, ColorType};
use cgmath_geometry::DimsRect;
fn main() {
let mut atlas = SkylineAtlas::new([0; 4], DimsBox::new2(512, 512));
let doge = extract_buffer(image::open("test_images/doge.png").unwrap());
let ffx = extract_buffer(image::open("test_images/ffx.png").unwrap());
let rust = extract_buffer(image::open("test_images/rust.png").unwrap());
let tf = extract_buffer(image::open("test_images/tf.png").unwrap());
let mut rectangles = vec![];
for _ in 0..4 {
rectangles.push(atlas.add_image(ffx.0, ffx.0.into(), &ffx.1).unwrap());
rectangles.push(atlas.add_image(tf.0, tf.0.into(), &tf.1).unwrap());
}
rectangles.push(atlas.add_image(doge.0, doge.0.into(), &doge.1).unwrap());
rectangles.push(atlas.add_image(ffx.0, ffx.0.into(), &ffx.1).unwrap());
rectangles.push(atlas.add_image(rust.0, rust.0.into(), &rust.1).unwrap());
rectangles.push(atlas.add_image(tf.0, tf.0.into(), &tf.1).unwrap());
rectangles.push(atlas.add_image(ffx.0, ffx.0.into(), &ffx.1).unwrap());
rectangles.push(atlas.add_image(doge.0, doge.0.into(), &doge.1).unwrap());
rectangles.push(atlas.add_image(ffx.0, ffx.0.into(), &ffx.1).unwrap());
rectangles.push(atlas.add_image(rust.0, rust.0.into(), &rust.1).unwrap());
rectangles.push(atlas.add_image(tf.0, tf.0.into(), &tf.1).unwrap());
rectangles.push(atlas.add_image(ffx.0, ffx.0.into(), &ffx.1).unwrap());
println!();
atlas.compact(&mut rectangles);
let pixels = atlas.pixels();
image::save_buffer("./skyline_atlas.bmp", unsafe{slice::from_raw_parts(pixels.as_ptr() as *const u8, pixels.len() * 4)}, 512, 512, ColorType::RGBA(8)).unwrap();
}
fn extract_buffer(img: DynamicImage) -> (DimsRect<u32>, Vec<[u8; 4]>) {
match img {
DynamicImage::ImageRgba8(img) => {
let rect = DimsBox::new2(img.width(), img.height());
println!("{:?}", rect);
(rect, img.pixels().map(|p| p.data).collect())
},
_ => unimplemented!()
}
}
|
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:
INSERT INTO Person (username, password, firstName, lastName, email) VALUES
('A', 'A', 'Ann', 'Andrews', '<EMAIL>'),
('B', 'B', 'Bill', 'Barker', '<EMAIL>'),
('C', 'C', 'Cathy', 'Chen', '<EMAIL>'),
('D', 'D', 'Dave', 'Davis', '<EMAIL>'),
('E', 'E', 'Emily', 'Elhaj', '<EMAIL>');
INSERT INTO Photo (pID, postingdate, filepath, allFollowers, caption, poster) VALUES
(1, '2020-01-01 00:00:00', '1.jpg', 1, 'photo 1', 'A'),
(2, '2020-02-02 00:00:00', '2.jpg', 1, 'photo 2', 'C'),
(3, '2020-1-11 00:00:00', '3.jpg', 1, 'photo 3', 'D'),
(4, '2020-2-11 00:00:00', '4.jpg', 1, NULL, 'D'),
(5, '2020-3-11 00:00:00', '5.jpg', 0, 'photo 5', 'E');
INSERT INTO FriendGroup (groupName, groupCreator, description) VALUES
('best friends', 'E', 'Emily: best friends'),
('best friends', 'D', 'Dave: best friends'),
('roommates', 'D', 'Dave: roommates');
INSERT INTO BelongTo (username, groupName, groupCreator) VALUES
('A', 'best friends', 'E'),
('B', 'roommates', 'D');
INSERT INTO Follow (follower, followee, followStatus) VALUES
('B', 'A', 1),
('C', 'A', 0),
('D', 'A', 0),
('B', 'D', 1),
('A', 'B', 1),
('E', 'A', 1),
('D', 'B', 1),
('E', 'B', 0),
('D', 'C', 1),
('A', 'E', 1);
INSERT INTO Tag (pID, username, tagStatus) VALUES
(1, 'B', 0),
(1, 'C', 1),
(2, 'D', 1),
(1, 'E', 1);
INSERT INTO ReactTo (username, pID, reactionTime, comment, emoji) VALUES
('D', 2, '2020-04-03 00:00:00', 'nice photo!', 'heart'),
('E', 1, '2020-04-03 00:00:00', NULL, 'thumbs up');
INSERT INTO SharedWith (pID, groupName, groupCreator) VALUES
(2, 'best friends', 'E'),
(3, 'best friends', 'D');
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 | INSERT INTO Person (username, password, firstName, lastName, email) VALUES
('A', 'A', 'Ann', 'Andrews', '<EMAIL>'),
('B', 'B', 'Bill', 'Barker', '<EMAIL>'),
('C', 'C', 'Cathy', 'Chen', '<EMAIL>'),
('D', 'D', 'Dave', 'Davis', '<EMAIL>'),
('E', 'E', 'Emily', 'Elhaj', '<EMAIL>');
INSERT INTO Photo (pID, postingdate, filepath, allFollowers, caption, poster) VALUES
(1, '2020-01-01 00:00:00', '1.jpg', 1, 'photo 1', 'A'),
(2, '2020-02-02 00:00:00', '2.jpg', 1, 'photo 2', 'C'),
(3, '2020-1-11 00:00:00', '3.jpg', 1, 'photo 3', 'D'),
(4, '2020-2-11 00:00:00', '4.jpg', 1, NULL, 'D'),
(5, '2020-3-11 00:00:00', '5.jpg', 0, 'photo 5', 'E');
INSERT INTO FriendGroup (groupName, groupCreator, description) VALUES
('best friends', 'E', 'Emily: best friends'),
('best friends', 'D', 'Dave: best friends'),
('roommates', 'D', 'Dave: roommates');
INSERT INTO BelongTo (username, groupName, groupCreator) VALUES
('A', 'best friends', 'E'),
('B', 'roommates', 'D');
INSERT INTO Follow (follower, followee, followStatus) VALUES
('B', 'A', 1),
('C', 'A', 0),
('D', 'A', 0),
('B', 'D', 1),
('A', 'B', 1),
('E', 'A', 1),
('D', 'B', 1),
('E', 'B', 0),
('D', 'C', 1),
('A', 'E', 1);
INSERT INTO Tag (pID, username, tagStatus) VALUES
(1, 'B', 0),
(1, 'C', 1),
(2, 'D', 1),
(1, 'E', 1);
INSERT INTO ReactTo (username, pID, reactionTime, comment, emoji) VALUES
('D', 2, '2020-04-03 00:00:00', 'nice photo!', 'heart'),
('E', 1, '2020-04-03 00:00:00', NULL, 'thumbs up');
INSERT INTO SharedWith (pID, groupName, groupCreator) VALUES
(2, 'best friends', 'E'),
(3, 'best friends', 'D'); |
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;
using System.Text;
using System.Threading.Tasks;
using Sandbox.ModAPI;
using Sandbox.Common;
using VRage.Utils;
namespace Digi.Utils
{
class Log
{
public const string MOD_NAME = "Realistic Thrusters";
public const int WORKSHOP_ID = 575893643;
public const string LOG_FILE = "info.log";
private static System.IO.TextWriter writer = null;
private static IMyHudNotification notify = null;
private static int indent = 0;
private static StringBuilder cache = new StringBuilder();
public static void IncreaseIndent()
{
indent++;
}
public static void DecreaseIndent()
{
if (indent > 0)
indent--;
}
public static void ResetIndent()
{
indent = 0;
}
public static void Error(Exception e)
{
Error(e.ToString());
}
public static void Error(string msg)
{
Info("ERROR: " + msg);
try
{
MyLog.Default.WriteLineAndConsole(MOD_NAME + " error: " + msg);
string text = MOD_NAME + " error - open %AppData%/SpaceEngineers/Storage/" + WORKSHOP_ID + "_" + MOD_NAME + "/" + LOG_FILE + " for details";
if(notify == null)
{
notify = MyAPIGateway.Utilities.CreateNotification(text, 10000, MyFontEnum.Red);
}
else
{
notify.Text = text;
notify.ResetAliveTime();
}
notify.Show();
}
catch (Exception e)
{
Info("ERROR: Could not send notification to local client: " + e.ToString());
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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sandbox.ModAPI;
using Sandbox.Common;
using VRage.Utils;
namespace Digi.Utils
{
class Log
{
public const string MOD_NAME = "Realistic Thrusters";
public const int WORKSHOP_ID = 575893643;
public const string LOG_FILE = "info.log";
private static System.IO.TextWriter writer = null;
private static IMyHudNotification notify = null;
private static int indent = 0;
private static StringBuilder cache = new StringBuilder();
public static void IncreaseIndent()
{
indent++;
}
public static void DecreaseIndent()
{
if (indent > 0)
indent--;
}
public static void ResetIndent()
{
indent = 0;
}
public static void Error(Exception e)
{
Error(e.ToString());
}
public static void Error(string msg)
{
Info("ERROR: " + msg);
try
{
MyLog.Default.WriteLineAndConsole(MOD_NAME + " error: " + msg);
string text = MOD_NAME + " error - open %AppData%/SpaceEngineers/Storage/" + WORKSHOP_ID + "_" + MOD_NAME + "/" + LOG_FILE + " for details";
if(notify == null)
{
notify = MyAPIGateway.Utilities.CreateNotification(text, 10000, MyFontEnum.Red);
}
else
{
notify.Text = text;
notify.ResetAliveTime();
}
notify.Show();
}
catch (Exception e)
{
Info("ERROR: Could not send notification to local client: " + e.ToString());
}
}
public static void Info(string msg)
{
Write(msg);
}
private static void Write(string msg)
{
try
{
if(writer == null)
{
if (MyAPIGateway.Utilities == null)
throw new Exception("API not initialied but got a log message: " + msg);
writer = MyAPIGateway.Utilities.WriteFileInLocalStorage(LOG_FILE, typeof(Log));
}
cache.Clear();
cache.Append(DateTime.Now.ToString("[HH:mm:ss] "));
for(int i = 0; i < indent; i++)
{
cache.Append("\t");
}
cache.Append(msg);
writer.WriteLine(cache);
writer.Flush();
cache.Clear();
}
catch(Exception e)
{
MyLog.Default.WriteLineAndConsole(MOD_NAME + " had an error while logging message='"+msg+"'\nLogger error: " + e.Message + "\n" + e.StackTrace);
}
}
public static void Close()
{
if(writer != null)
{
writer.Flush();
writer.Close();
writer = null;
}
indent = 0;
cache.Clear();
}
}
} |
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 { NextApiRequest, NextApiResponse } from "next";
const withMongo = handler => async (
req: NextApiRequest,
res: NextApiResponse
) => {
console.log("In Middleware");
const MongoClient = require("mongodb").MongoClient;
const client = new MongoClient(process.env.mongo_url);
try {
await client.connect();
const db = client.db(process.env.mongo_name, {
useUnifiedTopology: true,
useNewUrlParser: true
});
console.log("connected to database");
await handler(req, res, db);
} catch (err) {
console.error("connection to mongodb failed: " + err);
} finally {
client.close();
console.log("disconnected from database");
}
};
export default withMongo;
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 { NextApiRequest, NextApiResponse } from "next";
const withMongo = handler => async (
req: NextApiRequest,
res: NextApiResponse
) => {
console.log("In Middleware");
const MongoClient = require("mongodb").MongoClient;
const client = new MongoClient(process.env.mongo_url);
try {
await client.connect();
const db = client.db(process.env.mongo_name, {
useUnifiedTopology: true,
useNewUrlParser: true
});
console.log("connected to database");
await handler(req, res, db);
} catch (err) {
console.error("connection to mongodb failed: " + err);
} finally {
client.close();
console.log("disconnected from database");
}
};
export default withMongo;
|
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.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Models
{
public class Member : BaseModel
{
private string memberName;
public string MemberName
{
get { return memberName; }
set { memberName = value;
RaisePropertyChanged("MemberName");
}
}
private int badge;
public int Badge
{
get { return badge; }
set { badge = value; }
}
private ObservableCollection<TrainingActivity> activities;
public ObservableCollection<TrainingActivity> Activities
{
get { return activities; }
set { activities = value;
RaisePropertyChanged("Activities");
}
}
public string NameIndex { get => $"{memberName[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>"
| csharp | 2 | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Models
{
public class Member : BaseModel
{
private string memberName;
public string MemberName
{
get { return memberName; }
set { memberName = value;
RaisePropertyChanged("MemberName");
}
}
private int badge;
public int Badge
{
get { return badge; }
set { badge = value; }
}
private ObservableCollection<TrainingActivity> activities;
public ObservableCollection<TrainingActivity> Activities
{
get { return activities; }
set { activities = value;
RaisePropertyChanged("Activities");
}
}
public string NameIndex { get => $"{memberName[0]}"; }
}
}
|
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:
/**
* @file
* co.parabox.scene.get.mesh node implementation.
*
* @copyright
*/
#include "node.h"
#include "VuoMesh.h"
#include "VuoSceneObject.h"
#include "VuoList_VuoMesh.h"
VuoModuleMetadata({
"title" : "Get Meshes in Scene",
"keywords" : [ "world", "model", "space" ],
"version" : "1.0.0",
"description": "Recursively retreive meshes in a SceneObject.",
"dependencies" : [
],
"node" : {
"exampleCompositions" : [ "" ]
}
});
void GetMeshesRecursive(const VuoSceneObject* object, VuoList_VuoMesh list)
{
if(object != NULL && object->mesh != NULL)
{
if(object->mesh != NULL)
VuoListAppendValue_VuoMesh(list, object->mesh);
}
int children = VuoListGetCount_VuoSceneObject(object->childObjects);
for(int i = 0; i < children; i++)
{
VuoSceneObject child = VuoListGetValue_VuoSceneObject(object->childObjects, i+1);
GetMeshesRecursive(&child, list);
}
}
void nodeEvent
(
VuoInputData(VuoSceneObject) sceneObject,
VuoOutputData(VuoList_VuoMesh) meshes
)
{
VuoList_VuoMesh list = VuoListCreate_VuoMesh();
GetMeshesRecursive(&sceneObject, *meshes);
}
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 | /**
* @file
* co.parabox.scene.get.mesh node implementation.
*
* @copyright
*/
#include "node.h"
#include "VuoMesh.h"
#include "VuoSceneObject.h"
#include "VuoList_VuoMesh.h"
VuoModuleMetadata({
"title" : "Get Meshes in Scene",
"keywords" : [ "world", "model", "space" ],
"version" : "1.0.0",
"description": "Recursively retreive meshes in a SceneObject.",
"dependencies" : [
],
"node" : {
"exampleCompositions" : [ "" ]
}
});
void GetMeshesRecursive(const VuoSceneObject* object, VuoList_VuoMesh list)
{
if(object != NULL && object->mesh != NULL)
{
if(object->mesh != NULL)
VuoListAppendValue_VuoMesh(list, object->mesh);
}
int children = VuoListGetCount_VuoSceneObject(object->childObjects);
for(int i = 0; i < children; i++)
{
VuoSceneObject child = VuoListGetValue_VuoSceneObject(object->childObjects, i+1);
GetMeshesRecursive(&child, list);
}
}
void nodeEvent
(
VuoInputData(VuoSceneObject) sceneObject,
VuoOutputData(VuoList_VuoMesh) meshes
)
{
VuoList_VuoMesh list = VuoListCreate_VuoMesh();
GetMeshesRecursive(&sceneObject, *meshes);
}
|
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:
# /etc/profile.d/anaconda.sh
# Sets anaconda up for global usage.
export PATH="/home/anaconda3/bin:$PATH"
__conda_setup="$(CONDA_REPORT_ERRORS=false '/home/anaconda3/bin/conda' shell.bash hook 2> /dev/null)"
if [ $? -eq 0 ]; then
\eval "$__conda_setup"
else
if [ -f "/home/anaconda3/etc/profile.d/conda.sh" ]; then
. "/home/anaconda3/etc/profile.d/conda.sh"
CONDA_CHANGEPS1=false conda activate base
else
\export PATH="/home/anaconda3/bin:$PATH"
fi
fi
unset __conda_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>"
| shell | 3 | # /etc/profile.d/anaconda.sh
# Sets anaconda up for global usage.
export PATH="/home/anaconda3/bin:$PATH"
__conda_setup="$(CONDA_REPORT_ERRORS=false '/home/anaconda3/bin/conda' shell.bash hook 2> /dev/null)"
if [ $? -eq 0 ]; then
\eval "$__conda_setup"
else
if [ -f "/home/anaconda3/etc/profile.d/conda.sh" ]; then
. "/home/anaconda3/etc/profile.d/conda.sh"
CONDA_CHANGEPS1=false conda activate base
else
\export PATH="/home/anaconda3/bin:$PATH"
fi
fi
unset __conda_setup
|
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:
// (c) <NAME> 2018 - http://awebpros.com/
// License: MIT License (https://opensource.org/licenses/MIT)
//
// short overview of copyright rules:
// 1. you can use this framework in any commercial or non-commercial
// product as long as you retain this copyright message
// 2. Do not blame the author(s) of this software if something goes wrong.
//
// Also, please, mention this software in any documentation for the
// products that use it.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace NP.Utilities
{
public static class CollectionUtils
{
public static void DoForEach<T>
(
this IEnumerable<T> collection,
Action<T> action
)
{
if (collection == null)
return;
foreach (T item in collection)
{
action(item);
}
}
public static void DoForEach<T>
(
this IEnumerable<T> collection,
Action<T, int> action
)
{
if (collection == null)
return;
int i = 0;
foreach (T item in collection)
{
action(item, i);
i++;
}
}
public static int Count(this IEnumerable collection)
{
if (collection == null)
return 0;
int count = 0;
foreach(var item in collection)
{
count++;
}
return count;
}
public static IEnumerable<ResultType>
GetItemsOfType<BaseType, ResultType>(this IEnumerable<BaseType> inputCollection)
where ResultType : BaseType
{
return inputCollection
.Where((item) => item is ResultType)
.Select(item => item.TypeConvert<ResultType>());
}
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 | // (c) <NAME> 2018 - http://awebpros.com/
// License: MIT License (https://opensource.org/licenses/MIT)
//
// short overview of copyright rules:
// 1. you can use this framework in any commercial or non-commercial
// product as long as you retain this copyright message
// 2. Do not blame the author(s) of this software if something goes wrong.
//
// Also, please, mention this software in any documentation for the
// products that use it.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace NP.Utilities
{
public static class CollectionUtils
{
public static void DoForEach<T>
(
this IEnumerable<T> collection,
Action<T> action
)
{
if (collection == null)
return;
foreach (T item in collection)
{
action(item);
}
}
public static void DoForEach<T>
(
this IEnumerable<T> collection,
Action<T, int> action
)
{
if (collection == null)
return;
int i = 0;
foreach (T item in collection)
{
action(item, i);
i++;
}
}
public static int Count(this IEnumerable collection)
{
if (collection == null)
return 0;
int count = 0;
foreach(var item in collection)
{
count++;
}
return count;
}
public static IEnumerable<ResultType>
GetItemsOfType<BaseType, ResultType>(this IEnumerable<BaseType> inputCollection)
where ResultType : BaseType
{
return inputCollection
.Where((item) => item is ResultType)
.Select(item => item.TypeConvert<ResultType>());
}
public static IEnumerable<T> ToTypedCollection<T>(this IEnumerable coll)
{
if (coll == null)
yield break;
foreach (object obj in coll)
{
yield return (T)obj;
}
}
public static IEnumerable<T> ToCollection<T>(this T item)
{
if (item == null)
return Enumerable.Empty<T>();
return new T[] { item };
}
public static IEnumerable<T> Concat<T>(this IEnumerable<T> coll, T item)
{
return coll.Concat(item.ToCollection());
}
public static void AddAll
(
this IList collection,
IEnumerable collectionToAdd,
bool noDuplicates = false
)
{
if ((collection == null) || (collectionToAdd == null))
return;
foreach (object el in collectionToAdd)
{
if (noDuplicates)
{
if (collection.Contains(el))
continue;
}
collection.Add(el);
}
}
public static void AddAll<T>
(
this ICollection<T> collection,
IEnumerable<T> collectionToAdd,
bool noDuplicates = false
)
{
if ((collection == null) || (collectionToAdd == null))
return;
foreach (T el in collectionToAdd)
{
if (noDuplicates)
{
if (collection.Contains(el))
continue;
}
collection.Add(el);
}
}
public static (T, int) FindMatching<T, TKey>
(
this IEnumerable<T> collection,
T item,
Func<T, TKey> itemToKey
)
{
var valToCompare = itemToKey(item);
return collection.Select((v, idx) => (v, idx)).FirstOrDefault(val => itemToKey(val.v).ObjEquals(valToCompare));
}
public static void RemoveMatching<T, LookupType>
(
this ICollection<T> collection,
LookupType lookupItem,
Func<T, LookupType, bool> predicate
)
{
IEnumerable<T> matchingItems =
collection.FindItems(lookupItem, predicate).ToList();
foreach (T item in matchingItems)
{
collection.Remove(item);
}
}
public static void DeleteAll
(
this IList collection,
IEnumerable itemsToRemove)
{
if (itemsToRemove == null)
return;
foreach(object itemToRemove in itemsToRemove)
{
collection.Remove(itemToRemove);
}
}
public static void RemoveAll<T>
(
this IList<T> collection,
IEnumerable<T> itemsToRemove)
{
if (itemsToRemove == null)
return;
foreach (T itemToRemove in itemsToRemove)
{
collection.Remove(itemToRemove);
}
}
public static void RemoveAll(this IList collection)
{
if (collection == null)
return;
var elements =
collection.ToTypedCollection<object>().ToList();
foreach (object el in elements)
{
collection.Remove(el);
}
}
public static void RemoveAllTyped<T>(this ICollection<T> collection)
{
if (collection == null)
return;
var elements =
new List<T>(collection);
foreach (T el in elements)
{
collection.Remove(el);
}
}
public static bool IsNullOrEmpty(this IEnumerable collection)
{
if (collection == null)
return true;
int i = 0;
foreach (object obj in collection)
{
i++;
if (i > 0)
return false;
}
return true;
}
public static bool HasData(this IEnumerable collection)
{
return !collection.IsNullOrEmpty();
}
public static IEnumerable NullToEmpty(this IEnumerable collection)
{
if (collection == null)
yield break;
foreach (object obj in collection)
yield return obj;
}
public static IEnumerable<T> NullToEmpty<T>(this IEnumerable<T> collection)
{
if (collection == null)
return Enumerable.Empty<T>();
return collection;
}
public static bool HasElementByPredicate<T, LookupType>
(
this IEnumerable<T> coll,
LookupType element,
Func<T, LookupType, bool> predicate
)
{
return !coll.Where((item) => predicate(item, element)).IsNullOrEmpty();
}
public static IEnumerable<(T Item, int Idx)> FindItemsAndIndecies<T, TLookup>
(
this IEnumerable<T> coll,
TLookup lookupItem,
Func<T, TLookup, bool> predicate
)
{
return coll.Select((item, idx) => (item, idx)).Where(tuple => predicate(tuple.item, lookupItem));
}
public static IEnumerable<T> FindItems<T, TLookup>
(
this IEnumerable<T> coll,
TLookup lookupItem,
Func<T, TLookup, bool> predicate
)
{
return coll.FindItemsAndIndecies(lookupItem, predicate).Select(tuple => tuple.Item); //coll.Where(item => predicate(item, lookupItem));
}
public static (T Item, int Idx) FindItemAndIdx<T, LookupType>
(
this IEnumerable<T> coll,
LookupType lookupItem,
Func<T, LookupType, bool> predicate = null
)
where T : class
{
if (predicate == null)
{
predicate = (item, searchItem) => item.ObjEquals(searchItem);
}
return coll.FindItemsAndIndecies(lookupItem, predicate).FirstOrDefault();
}
public static T FindItem<T, LookupType>
(
this IEnumerable<T> coll,
LookupType lookupItem,
Func<T, LookupType, bool> predicate = null
)
where T : class
{
return coll.FindItemAndIdx(lookupItem, predicate).Item;
}
public static int FindIdx<T, LookupType>
(
this IEnumerable<T> coll,
LookupType lookupItem,
Func<T, LookupType, bool> predicate = null
)
where T : class
{
return coll.FindItemAndIdx(lookupItem, predicate).Idx;
}
public static int IndexOf<T>
(
this IEnumerable<T> collection,
Func<T, bool> f)
{
int i = -1;
foreach(T item in collection)
{
i++;
if (f(item))
{
return i;
}
}
return -1;
}
public static int LastIndexOf<T>
(
this IEnumerable<T> collection,
Func<T, bool> lastIdxFn)
{
int i = collection.Count();
foreach (T item in collection.Reverse())
{
i--;
if (lastIdxFn(item))
{
return i;
}
}
return -1;
}
public static void InsertAfterLastIndexOf<T>
(
this IList<T> list,
Func<T, bool> lastIdxFn,
T itemToInsert)
{
int lastIdx = list.LastIndexOf(lastIdxFn);
list.Insert(lastIdx + 1, itemToInsert);
}
public static void AddIfNotThere<T>
(
this IList<T> collection,
T elementToAdd,
Func<T, T, bool> predicate = null
)
{
if (predicate == null)
predicate = (el, elToAdd) => el.ObjEquals(elToAdd);
if (collection.HasElementByPredicate(elementToAdd, predicate))
return;
collection.Add(elementToAdd);
}
public static void AddIfNotThereSimple<T>(
this IList<T> collection,
T elementToAdd)
{
collection.AddIfNotThere(elementToAdd);
}
public static void RemoveItem<T>(this IList<T> collection, T elementToRemove)
{
collection.Remove(elementToRemove);
}
public static void AddRangeIfNotThere<T>
(
this IList<T> collection,
IEnumerable<T> elementsToAdd,
Func<T, T, bool> predicate = null
)
{
if (predicate == null)
predicate = (el, elToAdd) => el.ObjEquals(elToAdd);
foreach(T elementToAdd in elementsToAdd )
{
AddIfNotThere(collection, elementToAdd, predicate);
}
}
/// <summary>
/// check if the collections have the equivalent entries, but perhaps in different order
/// WE ASSUME, THERE ARE NO DUPLICATION IN coll1 collection !!! Otherwise - this won't work
/// </summary>
/// <returns></returns>
public static bool AreEquivalentCollections<T>
(
this IEnumerable<T> coll1,
IEnumerable<T> coll2,
Func<T, T, bool>? comparisonFn = null)
{
bool AreTheSame(T v1, T v2)
{
return v1.ObjEquals(v2);
}
if (comparisonFn == null)
{
comparisonFn = AreTheSame;
}
if (coll1.IsNullOrEmptyCollection())
return coll2.IsNullOrEmptyCollection();
if (coll2.IsNullOrEmptyCollection())
return false;
if (coll1.Count() != coll2.Count())
return false;
// Assuming there are no duplicates in coll1,
// one comparison iteration should be enough
foreach(var v1 in coll1)
{
if (coll2.All(v2 => !comparisonFn(v1, v2)))
return false;
}
return true;
}
public static bool AreEquivalent<T>
(
this IEnumerable<T> coll1,
IEnumerable<T> coll2,
Func<T, T, bool>? comparisonFn = null)
{
return AreEquivalentCollections(coll1, coll2, comparisonFn);
}
public static bool IsInValCollection<T>(this T obj, IEnumerable<object> valueCollection)
{
if (valueCollection.IsNullOrEmpty())
return false;
foreach (object val in valueCollection)
{
if (obj.ObjEquals(val))
return true;
}
return false;
}
public static bool IsIn<T>(this T obj, params object[] vals)
{
return obj.IsInValCollection(vals);
}
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable collection)
{
if (collection == null)
return null;
ObservableCollection<T> result = new ObservableCollection<T>();
foreach (object obj in collection)
{
result.Add((T)obj);
}
return result;
}
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> collection)
{
return ((IEnumerable)collection).ToObservableCollection<T>();
}
public static IEnumerable<object> ToSingleObjectCollection(this object obj)
{
return new []{ obj };
}
public static IEnumerable<object> ToCollection(this object obj)
{
if (obj == null)
return Enumerable.Empty<object>();
IEnumerable<object> result = obj as IEnumerable<object>;
if (result != null)
return result;
return obj.ToSingleObjectCollection();
}
public static void InsertInOrder<T, TKey>
(
this IList<T> list,
T item,
Func<T, TKey> keyGetter,
Func<TKey, TKey, int> comparisonFn)
{
int idx = 0;
foreach(T listItem in list)
{
if (comparisonFn(keyGetter(listItem), keyGetter(item)) >= 0)
{
list.Insert(idx, item);
return;
}
idx++;
}
list.Add(item);
}
public static void InsertInOrder<T>
(
this IList<T> list,
T item,
Func<T, T, int> comparisonFn)
{
list.InsertInOrder<T, T>(item, v => v, comparisonFn);
}
public static void InsertAllInOrder<T, TKey>
(
this IList<T> list,
IEnumerable<T> items,
Func<T, TKey> keyGetter,
Func<TKey, TKey, int> comparisonFn)
{
if (items == null)
return;
items.DoForEach(item => list.InsertInOrder(item, keyGetter, comparisonFn));
}
public static void InsertAllInOrder<T>
(
this IList<T> list,
IEnumerable<T> items,
Func<T, T, int> comparisonFn)
{
list.InsertAllInOrder<T, T>(items, v => v, comparisonFn);
}
public static void InsertCollectionAtStart<T>(this IList<T> col, IEnumerable<T> collToInsert)
{
if (collToInsert == null)
return;
collToInsert.Reverse().DoForEach(item => col.Insert(0, item));
}
public static void DeleteAllOneByOne(this IList list)
{
ArrayList arrayList = new ArrayList(list);
foreach(var item in arrayList)
{
list.Remove(item);
}
}
public static void RemoveAllOneByOne<T>(this IList<T> list)
{
List<T> arrayList = new List<T>(list);
foreach (var item in arrayList)
{
list.Remove(item);
}
}
public static IEnumerable<T> UnionSingle<T>
(
this IEnumerable<T> collection,
params T[] additionalParams)
{
return collection.Union(additionalParams.NullToEmpty().Where(additionalParam => additionalParam != null));
}
public static void InsertUpdateOrRemove<T>
(
this IList<T> collection,
T item,
Func<IEnumerable<T>, T, (T, int)> getMatchingItemAndIdxFn,
Func<T, bool> shouldRemoveFn,
Action<T, T> updateFn,
Action<IList<T>, T> insertFn
)
{
if (collection == null)
return;
(T matchingItem, int matchingItemIdx) = getMatchingItemAndIdxFn(collection, item);
bool shouldRemove = shouldRemoveFn(item);
if (matchingItemIdx < 0 && !shouldRemove) // item not found, so it is an insert
{
insertFn(collection, item);
return;
}
if (shouldRemove)
{
if (matchingItemIdx >= 0)
{
collection.RemoveAt(matchingItemIdx);
}
return;
}
// matching item found and it should not be removed, so it should be updated:
// this will not work if the collection items are value types (in that case,
// we would have to update a reference or remove and insert, but most of the cases will be
// covered by the update below.
updateFn(matchingItem, item);
}
}
}
|
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
/**
* @file
* Contains a Result object.
*/
namespace Vultan\Vultan;
use Vultan\Document\DocumentInterface;
use MongoCursor;
/**
* Class Result
*
* @package Drupal\vultan\Vultan
*/
class Result {
/**
* result
*
* @var array
*/
public $results;
/**
* success
*
* @var bool
*/
public $success;
/**
* id
*
* @var string|bool
*/
public $id;
/**
* The Document on which the operation was performed.
*
* @var \Vultan\Document\DocumentInterface
*/
public $document;
/**
* error
*
* @var array
*/
public $error;
/**
* The kind of operation.
*
* @var string
*/
public $operation;
/**
* The message variable.
*
* @var string
*/
public $message;
/**
* Set the value for Id.
*
* @param bool|string $id
* The value to set.
*/
public function setId($id) {
$this->id = $id;
}
/**
* Get the value for Id.
*
* @return bool|string
* The value of Id.
*/
public function getId() {
if (isset($this->id)) {
return $this->id;
}
return FALSE;
}
/**
* Set the value for Result.
*
* @param array $result
* The value to set.
*/
public function setResult($result) {
$this->results = $result;
}
/**
* Get the value for Result.
*
* @return array|MongoCursor
* The value of Result.
*/
public function getResult() {
if (isset($this->results)) {
return $this->results;
}
return array();
}
/**
* Set the value for Success.
*
* @param bool $success
* The value to set.
*/
public function setSuccess($success) {
$this->success = $success;
}
/**
* Get the value for Success.
*
* @return bool
* The value of Success.
*/
public function getSuccess() {
if (isset($this->success)) {
return $this->success;
}
return NULL;
}
/**
* Set the Document.
*
* @param \Vultan\Documen
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
/**
* @file
* Contains a Result object.
*/
namespace Vultan\Vultan;
use Vultan\Document\DocumentInterface;
use MongoCursor;
/**
* Class Result
*
* @package Drupal\vultan\Vultan
*/
class Result {
/**
* result
*
* @var array
*/
public $results;
/**
* success
*
* @var bool
*/
public $success;
/**
* id
*
* @var string|bool
*/
public $id;
/**
* The Document on which the operation was performed.
*
* @var \Vultan\Document\DocumentInterface
*/
public $document;
/**
* error
*
* @var array
*/
public $error;
/**
* The kind of operation.
*
* @var string
*/
public $operation;
/**
* The message variable.
*
* @var string
*/
public $message;
/**
* Set the value for Id.
*
* @param bool|string $id
* The value to set.
*/
public function setId($id) {
$this->id = $id;
}
/**
* Get the value for Id.
*
* @return bool|string
* The value of Id.
*/
public function getId() {
if (isset($this->id)) {
return $this->id;
}
return FALSE;
}
/**
* Set the value for Result.
*
* @param array $result
* The value to set.
*/
public function setResult($result) {
$this->results = $result;
}
/**
* Get the value for Result.
*
* @return array|MongoCursor
* The value of Result.
*/
public function getResult() {
if (isset($this->results)) {
return $this->results;
}
return array();
}
/**
* Set the value for Success.
*
* @param bool $success
* The value to set.
*/
public function setSuccess($success) {
$this->success = $success;
}
/**
* Get the value for Success.
*
* @return bool
* The value of Success.
*/
public function getSuccess() {
if (isset($this->success)) {
return $this->success;
}
return NULL;
}
/**
* Set the Document.
*
* @param \Vultan\Document\DocumentInterface|array $data
* The value to set.
*/
public function setDocument($data) {
$this->document = $data;
}
/**
* Get the Document.
*
* @return array
* The value of Data.
*/
public function getDocument() {
if (isset($this->document)) {
return $this->document;
}
return NULL;
}
/**
* Set the value for Error.
*
* @param array $error
* The value to set.
*/
public function setError($error) {
$this->error = $error;
}
/**
* Get the value for Error.
*
* @return array
* The value of Error.
*/
public function getError() {
if (isset($this->error)) {
return $this->error;
}
return NULL;
}
/**
* Set the value for Operation.
*
* @param string $operation
* The value to set.
*/
public function setOperation($operation) {
$this->operation = $operation;
}
/**
* Get the value for Operation.
*
* @return string
* The value of Operation.
*/
public function getOperation() {
return $this->operation;
}
/**
* Return a human readable result message.
*
* @return string
* The message.
*/
public function getMessage() {
if ($this->getSuccess() == TRUE) {
return 'Successfully ' . $this->changeOperationTense($this->getOperation()) . ' document with ID: ' . $this->getId();
}
else {
return 'Failed to ' . $this->getOperation() . ' document with ID: ' . $this->getId();
}
}
/**
* Helper to turn an operation into a past-participle verb.
*
* @param string $op
* The operation.
*
* @return string
* The verb.
*/
protected function changeOperationTense($op) {
if ($op == 'insert') {
return 'inserted';
}
if ($op == 'update') {
return 'updated';
}
if ($op == 'upsert') {
return 'upserted';
}
}
/**
* Determine if there is more than one result for an operation.
*
* @return bool
* TRUE if there is more than one result.
*/
public function hasManyResults() {
if (count($this->results) > 1) {
return TRUE;
}
return FALSE;
}
}
|
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.id.zul.submission5kade.adapter.match
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.id.zul.submission5kade.R
import com.id.zul.submission5kade.database.FavoriteMatch
class FavoriteMatchAdapter(private val context: Context, private val favorite: List<FavoriteMatch>) :
RecyclerView.Adapter<FavoriteMatchAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, position: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(context)
.inflate(R.layout.recycler_favorite_match_template, parent, false)
)
}
override fun getItemCount(): Int {
return favorite.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindItem(favorite[position])
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val textViewDate = itemView.findViewById<TextView>(R.id.text_date_favorite_match_template)
private val textViewTime = itemView.findViewById<TextView>(R.id.text_time_favorite_match_template)
private val textViewHomeTeam = itemView.findViewById<TextView>(R.id.text_team1_favorite_match_template)
private val textViewAwayTeam = itemView.findViewById<TextView>(R.id.text_team2_favorite_match_template)
private val textViewHomeScore = itemView.findViewById<TextView>(R.id.text_score1_favorite_match_template)
private val textViewAwayScore = itemView.findViewById<TextView>(R.id.text_score2_favorite_match_template)
fun bindItem(items: FavoriteMatch) {
textViewDate.text = items.matchDate
textViewTime.text = items.matchTime
textViewHomeTeam.text = items.matchHomeTeam
textViewAwayTeam.text = items.matchAwayTeam
textViewHomeScore.text = items.matchH
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.id.zul.submission5kade.adapter.match
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.id.zul.submission5kade.R
import com.id.zul.submission5kade.database.FavoriteMatch
class FavoriteMatchAdapter(private val context: Context, private val favorite: List<FavoriteMatch>) :
RecyclerView.Adapter<FavoriteMatchAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, position: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(context)
.inflate(R.layout.recycler_favorite_match_template, parent, false)
)
}
override fun getItemCount(): Int {
return favorite.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindItem(favorite[position])
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val textViewDate = itemView.findViewById<TextView>(R.id.text_date_favorite_match_template)
private val textViewTime = itemView.findViewById<TextView>(R.id.text_time_favorite_match_template)
private val textViewHomeTeam = itemView.findViewById<TextView>(R.id.text_team1_favorite_match_template)
private val textViewAwayTeam = itemView.findViewById<TextView>(R.id.text_team2_favorite_match_template)
private val textViewHomeScore = itemView.findViewById<TextView>(R.id.text_score1_favorite_match_template)
private val textViewAwayScore = itemView.findViewById<TextView>(R.id.text_score2_favorite_match_template)
fun bindItem(items: FavoriteMatch) {
textViewDate.text = items.matchDate
textViewTime.text = items.matchTime
textViewHomeTeam.text = items.matchHomeTeam
textViewAwayTeam.text = items.matchAwayTeam
textViewHomeScore.text = items.matchHomeScore
textViewAwayScore.text = items.matchAwayScore
}
}
} |
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 System.Linq;
using UnityEngine;
using PState = PlayerStateController.PlayerState;
/// <summary>
/// アタッチされたゲームオブジェクトの位置に理論球を生成し最初にヒットしたオブジェクトの情報を取り扱う
///
/// </summary>
public sealed class AimControl : MonoBehaviour
{
private GameObject aim;//ヒットしたゲームオブジェクト
private RaycastHit rch;
private GameObject aimPtr;
private PlayerStateController psc;
public string[] ignoreTag;//衝突判定を無視するゲームオブジェクトのタグを設定出来る
[SerializeField]
private GameObject aimPointerPrefab = default(GameObject);
[SerializeField]
private float rayRadius = 1;//レイの半径
[SerializeField]
private float rayDistance = 1;//レイの飛距離
private AimControl()
{
}
private void Awake()
{
psc = PlayerStateController.GetInstance();
}
private void Start()
{
if(this.tag != "AimControl")
Destroy(this);
aimPtr = Instantiate(aimPointerPrefab) as GameObject;
aimPtr.SetActive(false);
}
private void Update()
{
//レイによってヒットしたオブジェクトの情報を得る
//レイヤーはデフォルトのものを指定
if(!psc.IsState(PState.Aim))//狙っている状態の時は特別で、他のオブジェクトを参照しないようにする
rch = Physics.SphereCastAll(transform.position, rayRadius, transform.forward, rayDistance, 1 << LayerMask.NameToLayer("Default"))
.FirstOrDefault(_ => !ignoreTag.Contains(_.collider.tag));
aim = rch.collider != null ? rch.collider.gameObject : null;
//既に透明化されている生物だった場合は強制的にnullにする
if(aim != null)
{
var creature = aim.GetComponent<CreatureController>();
if(creature != null && creature.IsTransed())
aim = null;
}
//AimPointerの表示/非表示
SwitchAimPtr();
}
/// <summary>
/// 特定の条件でAimPointerの表示/非表示を切り替える
/// </summary>
private void SwitchAimPtr()
{
if(aim != null && !psc.IsState(PState.HuntFish))
{
aimPtr.SetActive(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>"
| csharp | 2 | using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using PState = PlayerStateController.PlayerState;
/// <summary>
/// アタッチされたゲームオブジェクトの位置に理論球を生成し最初にヒットしたオブジェクトの情報を取り扱う
///
/// </summary>
public sealed class AimControl : MonoBehaviour
{
private GameObject aim;//ヒットしたゲームオブジェクト
private RaycastHit rch;
private GameObject aimPtr;
private PlayerStateController psc;
public string[] ignoreTag;//衝突判定を無視するゲームオブジェクトのタグを設定出来る
[SerializeField]
private GameObject aimPointerPrefab = default(GameObject);
[SerializeField]
private float rayRadius = 1;//レイの半径
[SerializeField]
private float rayDistance = 1;//レイの飛距離
private AimControl()
{
}
private void Awake()
{
psc = PlayerStateController.GetInstance();
}
private void Start()
{
if(this.tag != "AimControl")
Destroy(this);
aimPtr = Instantiate(aimPointerPrefab) as GameObject;
aimPtr.SetActive(false);
}
private void Update()
{
//レイによってヒットしたオブジェクトの情報を得る
//レイヤーはデフォルトのものを指定
if(!psc.IsState(PState.Aim))//狙っている状態の時は特別で、他のオブジェクトを参照しないようにする
rch = Physics.SphereCastAll(transform.position, rayRadius, transform.forward, rayDistance, 1 << LayerMask.NameToLayer("Default"))
.FirstOrDefault(_ => !ignoreTag.Contains(_.collider.tag));
aim = rch.collider != null ? rch.collider.gameObject : null;
//既に透明化されている生物だった場合は強制的にnullにする
if(aim != null)
{
var creature = aim.GetComponent<CreatureController>();
if(creature != null && creature.IsTransed())
aim = null;
}
//AimPointerの表示/非表示
SwitchAimPtr();
}
/// <summary>
/// 特定の条件でAimPointerの表示/非表示を切り替える
/// </summary>
private void SwitchAimPtr()
{
if(aim != null && !psc.IsState(PState.HuntFish))
{
aimPtr.SetActive(true);
aimPtr.transform.position = aim.gameObject.transform.position + Vector3.up * 2;
}
else if(aim == null || psc.IsState(PState.HuntFish))
aimPtr.SetActive(false);
}
/// <summary>
/// 狙っているゲームオブジェクトを返す
/// 無ければnull
/// </summary>
/// <returns>
/// 狙っているゲームオブジェクト
/// なければNull
/// </returns>
public GameObject GetAimObject()
{
return aim;
}
/// <summary>
/// 狙っているゲームオブジェクトのタグを返す
/// </summary>
/// <returns></returns>
public string GetAimObjectTag()
{
if(aim == null)
return string.Empty;
return aim.tag;
}
/// <summary>
/// 指定したオブジェクトと現在狙ってるオブジェクトが等しいか判定する
/// </summary>
/// <param name="target">調べたいゲームオブジェクト</param>
/// <returns></returns>
public bool CompareAimObject(GameObject target)
{
return ReferenceEquals(aim, target);
}
/// <summary>
/// 指定したタグをもつオブジェクトが狙われているかどうかを返す
/// 狙っているオブジェクトがなければ常にfalseを返す
/// </summary>
/// <param name="tag">調べたいタグ</param>
/// <returns></returns>
public bool CompareAimObjectTag(string tag)
{
string buf = GetAimObjectTag();
return buf != string.Empty ? buf == tag : false;
}
} |
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 sofa
// #include "sofa.h"
import "C"
import (
"math"
"github.com/8i8/sofa/en"
)
var errJdcalf = en.New(1, "Jdcalf", []string{
"date out of range",
"OK",
"NDP not 0-9 (interpreted as 0)",
})
// CgoJdcalf Julian Date to Gregorian Calendar, expressed in a form
// convenient for formatting messages: rounded to a specified
// precision.
//
// - - - - - - -
// J d c a l f
// - - - - - - -
//
// This function is part of the International Astronomical Union's
// SOFA (Standards Of Fundamental Astronomy) software collection.
//
// Status: support function.
//
// Given:
// ndp int number of decimal places of days in fraction
// dj1,dj2 double dj1+dj2 = Julian Date (Note 1)
//
// Returned:
// iymdf int[4] year, month, day, fraction in Gregorian
// calendar
//
// Returned (function value):
// int status:
// -1 = date out of range
// 0 = OK
// +1 = NDP not 0-9 (interpreted as 0)
//
// Notes:
//
// 1) The Julian Date is apportioned in any convenient way between
// the arguments dj1 and dj2. For example, JD=2450123.7 could
// be expressed in any of these ways, among others:
//
// dj1 dj2
//
// 2450123.7 0.0 (JD method)
// 2451545.0 -1421.3 (J2000 method)
// 2400000.5 50123.2 (MJD method)
// 2450123.5 0.2 (date & time method)
//
// 2) In early eras the conversion is from the "Proleptic Gregorian
// Calendar"; no account is taken of the date(s) of adoption of
// the Gregorian Calendar, nor is the AD/BC numbering convention
// observed.
//
// 3) Refer to the function iauJd2cal.
//
// 4) NDP should be 4 or less if internal overflows are to be
// avoided on machines which use 16-bit integers.
//
// Called:
// iauJd2cal JD to Gregorian calendar
//
// Referenc
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 sofa
// #include "sofa.h"
import "C"
import (
"math"
"github.com/8i8/sofa/en"
)
var errJdcalf = en.New(1, "Jdcalf", []string{
"date out of range",
"OK",
"NDP not 0-9 (interpreted as 0)",
})
// CgoJdcalf Julian Date to Gregorian Calendar, expressed in a form
// convenient for formatting messages: rounded to a specified
// precision.
//
// - - - - - - -
// J d c a l f
// - - - - - - -
//
// This function is part of the International Astronomical Union's
// SOFA (Standards Of Fundamental Astronomy) software collection.
//
// Status: support function.
//
// Given:
// ndp int number of decimal places of days in fraction
// dj1,dj2 double dj1+dj2 = Julian Date (Note 1)
//
// Returned:
// iymdf int[4] year, month, day, fraction in Gregorian
// calendar
//
// Returned (function value):
// int status:
// -1 = date out of range
// 0 = OK
// +1 = NDP not 0-9 (interpreted as 0)
//
// Notes:
//
// 1) The Julian Date is apportioned in any convenient way between
// the arguments dj1 and dj2. For example, JD=2450123.7 could
// be expressed in any of these ways, among others:
//
// dj1 dj2
//
// 2450123.7 0.0 (JD method)
// 2451545.0 -1421.3 (J2000 method)
// 2400000.5 50123.2 (MJD method)
// 2450123.5 0.2 (date & time method)
//
// 2) In early eras the conversion is from the "Proleptic Gregorian
// Calendar"; no account is taken of the date(s) of adoption of
// the Gregorian Calendar, nor is the AD/BC numbering convention
// observed.
//
// 3) Refer to the function iauJd2cal.
//
// 4) NDP should be 4 or less if internal overflows are to be
// avoided on machines which use 16-bit integers.
//
// Called:
// iauJd2cal JD to Gregorian calendar
//
// Reference:
//
// Explanatory Supplement to the Astronomical Almanac,
// <NAME> (ed), University Science Books (1992),
// Section 12.92 (p604).
//
// This revision: 2020 April 13
//
// SOFA release 2020-07-21
//
// Copyright (C) 2020 IAU SOFA Board. See notes at end.
//
// CgoJdcalf Julian Date to Gregorian Calendar, expressed in a form
// convenient for formatting messages: rounded to a specified
// precision.
func CgoJdcalf(ndp int, dj1, dj2 float64) (
iymdf [4]int, err en.ErrNum) {
var cIymdf [4]C.int
cI := C.iauJdcalf(C.int(ndp), C.double(dj1), C.double(dj2),
&cIymdf[0])
if n := int(cI); n != 0 {
err = errJdcalf.Set(n)
}
return v4sIntC2Go(cIymdf), err
}
// GoJdcalf Julian Date to Gregorian Calendar, expressed in a form
// convenient for formatting messages: rounded to a specified
// precision.
func GoJdcalf(ndp int, dj1, dj2 float64) (
iymdf [4]int, err en.ErrNum) {
var err1 en.ErrNum
var denom, d1, d2, f1, f2, d, djd, f, rf float64
// Denominator of fraction (e.g. 100 for 2 decimal places).
if (ndp >= 0) && (ndp <= 9) {
denom = float64(pow(10.0, ndp))
} else {
err = errJdcalf.Set(1)
denom = 1.0
}
// Copy the date, big then small.
if math.Abs(dj1) >= math.Abs(dj2) {
d1 = dj1
d2 = dj2
} else {
d1 = dj2
d2 = dj1
}
// Realign to midnight (without rounding error).
d1 -= 0.5
// Separate day and fraction (as precisely as possible).
d = dnint(d1)
f1 = d1 - d
djd = d
d = dnint(d2)
f2 = d2 - d
djd += d
d = dnint(f1 + f2)
f = (f1 - d) + f2
if f < 0.0 {
f += 1.0
d -= 1.0
}
djd += d
// Round the total fraction to the specified number of places.
rf = dnint(f*denom) / denom
// Re-align to noon.
djd += 0.5
// Convert to Gregorian calendar.
iymdf[0], iymdf[1], iymdf[2], f, err1 = GoJd2cal(djd, rf)
if err1 == nil {
iymdf[3] = int(dnint(f * denom))
} else {
err = err1
}
return
}
|
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.mg.studio.tuktuk.resourcemanager;
public class MyImageInfo {
String assetPath;
float scale;
boolean linear;
public MyImageInfo(String assetPath, float scale,boolean linear) {
super();
this.assetPath = assetPath;
this.scale = scale;
this.linear = linear;
}
public String getAssetPath() {
return assetPath;
}
public float getScale() {
return scale;
}
public boolean isLinear() {
return linear;
}
}
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.mg.studio.tuktuk.resourcemanager;
public class MyImageInfo {
String assetPath;
float scale;
boolean linear;
public MyImageInfo(String assetPath, float scale,boolean linear) {
super();
this.assetPath = assetPath;
this.scale = scale;
this.linear = linear;
}
public String getAssetPath() {
return assetPath;
}
public float getScale() {
return scale;
}
public boolean isLinear() {
return linear;
}
}
|
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:
/*
* Rainbow SDK sample
*
* Copyright (c) 2018, ALE International
* All rights reserved.
*
* ALE International Proprietary Information
*
* Contains proprietary/trade secret information which is the property of
* ALE International and must not be made available to, or copied or used by
* anyone outside ALE International without its written authorization
*
* Not to be disclosed or used except in accordance with applicable agreements.
*/
import UIKit
import Rainbow
class MainViewController: UIViewController {
@IBOutlet weak var contactsButton: UIButton!
@IBOutlet weak var conversationsButton: UIButton!
@IBOutlet weak var unreadMessagesCountLabel: UILabel!
var totalNbOfUnreadMessagesInAllConversations = 0
var conversationsLoaded = false
var contactsLoaded = false
override func viewDidLoad() {
super.viewDidLoad()
contactsButton.isEnabled = contactsLoaded
conversationsButton.isEnabled = conversationsLoaded
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
unreadMessagesCountLabel.text = "\(totalNbOfUnreadMessagesInAllConversations)"
// notification related to the ContactManagerService
NotificationCenter.default.addObserver(self, selector: #selector(didEndPopulatingMyNetwork(notification:)), name: NSNotification.Name(kContactsManagerServiceDidEndPopulatingMyNetwork), object: nil)
// notifications related to unread conversation count
NotificationCenter.default.addObserver(self, selector: #selector(didEndLoadingConversations(notification:)), name:NSNotification.Name(kConversationsManagerDidEndLoadingConversations), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didUpdateMessagesUnreadCount(notification:)), name:NSNotification.Name(kConversationsManagerDidUpdateMessagesUnreadCount), object: nil)
}
override func viewWillDisappear(_ animated: Bo
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 | /*
* Rainbow SDK sample
*
* Copyright (c) 2018, ALE International
* All rights reserved.
*
* ALE International Proprietary Information
*
* Contains proprietary/trade secret information which is the property of
* ALE International and must not be made available to, or copied or used by
* anyone outside ALE International without its written authorization
*
* Not to be disclosed or used except in accordance with applicable agreements.
*/
import UIKit
import Rainbow
class MainViewController: UIViewController {
@IBOutlet weak var contactsButton: UIButton!
@IBOutlet weak var conversationsButton: UIButton!
@IBOutlet weak var unreadMessagesCountLabel: UILabel!
var totalNbOfUnreadMessagesInAllConversations = 0
var conversationsLoaded = false
var contactsLoaded = false
override func viewDidLoad() {
super.viewDidLoad()
contactsButton.isEnabled = contactsLoaded
conversationsButton.isEnabled = conversationsLoaded
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
unreadMessagesCountLabel.text = "\(totalNbOfUnreadMessagesInAllConversations)"
// notification related to the ContactManagerService
NotificationCenter.default.addObserver(self, selector: #selector(didEndPopulatingMyNetwork(notification:)), name: NSNotification.Name(kContactsManagerServiceDidEndPopulatingMyNetwork), object: nil)
// notifications related to unread conversation count
NotificationCenter.default.addObserver(self, selector: #selector(didEndLoadingConversations(notification:)), name:NSNotification.Name(kConversationsManagerDidEndLoadingConversations), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didUpdateMessagesUnreadCount(notification:)), name:NSNotification.Name(kConversationsManagerDidUpdateMessagesUnreadCount), object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
// MARK: - ContactManagerService notifications
@objc func didEndPopulatingMyNetwork(notification : Notification) {
// Enforce that this method is called on the main thread
if !Thread.isMainThread {
DispatchQueue.main.async {
self.didEndPopulatingMyNetwork(notification: notification)
}
return
}
NSLog("[MainViewController] Did end populating my network");
contactsLoaded = true
if isViewLoaded {
contactsButton.isEnabled = true
}
}
// MARK: - Notifications related to unread conversation count
@objc func didEndLoadingConversations(notification : Notification) {
conversationsLoaded = true
// Read the unread message count in a asynchronous block as it is a synchronous method protected by a lock
DispatchQueue.global().async {
DispatchQueue.main.async {
if self.isViewLoaded {
self.conversationsButton.isEnabled = true
}
}
self.totalNbOfUnreadMessagesInAllConversations = ServicesManager.sharedInstance().conversationsManagerService.totalNbOfUnreadMessagesInAllConversations
NSLog("[MainViewController] totalNbOfUnreadMessagesInAllConversations=%ld", self.totalNbOfUnreadMessagesInAllConversations)
}
}
@objc func didUpdateMessagesUnreadCount(notification : Notification) {
// Read the unread message count in a asynchronous block as it is a synchronous method protected by a lock
DispatchQueue.global().async {
self.totalNbOfUnreadMessagesInAllConversations = ServicesManager.sharedInstance().conversationsManagerService.totalNbOfUnreadMessagesInAllConversations
NSLog("[MainViewController] totalNbOfUnreadMessagesInAllConversations=%ld", self.totalNbOfUnreadMessagesInAllConversations)
}
}
// MARK: - IBAction
@IBAction func logoutAction(_ sender: Any) {
performSegue(withIdentifier: "BackToLoginSegue", sender: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:
#[cfg(feature = "failure")]
use failure::{Backtrace, Context, Fail};
use std;
use std::fmt::{self, Display};
#[derive(Debug)]
pub struct Error {
#[cfg(feature = "failure")]
inner: Context<ErrorKind>,
#[cfg(not(feature = "failure"))]
inner: ErrorKind,
}
// To suppress false positives from cargo-clippy
#[cfg_attr(feature = "cargo-clippy", allow(empty_line_after_outer_attr))]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum ErrorKind {
BadAbsolutePath,
BadRelativePath,
CannotFindBinaryPath,
CannotGetCurrentDir,
CannotCanonicalize,
}
#[cfg(feature = "failure")]
impl Fail for ErrorKind {}
impl Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let display = match *self {
ErrorKind::BadAbsolutePath => "Bad absolute path",
ErrorKind::BadRelativePath => "Bad relative path",
ErrorKind::CannotFindBinaryPath => "Cannot find binary path",
ErrorKind::CannotGetCurrentDir => "Cannot get current directory",
ErrorKind::CannotCanonicalize => "Cannot canonicalize path",
};
f.write_str(display)
}
}
#[cfg(feature = "failure")]
impl Fail for Error {
fn cause(&self) -> Option<&dyn Fail> {
self.inner.cause()
}
fn backtrace(&self) -> Option<&Backtrace> {
self.inner.backtrace()
}
}
#[cfg(not(feature = "failure"))]
impl std::error::Error for Error {}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&self.inner, f)
}
}
impl Error {
pub fn kind(&self) -> ErrorKind {
#[cfg(feature = "failure")]
{
*self.inner.get_context()
}
#[cfg(not(feature = "failure"))]
{
self.inner
}
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Error {
Error {
#[cfg(feature = "failure")]
inner: Context::new(kind),
#[cfg(n
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 | -1 | #[cfg(feature = "failure")]
use failure::{Backtrace, Context, Fail};
use std;
use std::fmt::{self, Display};
#[derive(Debug)]
pub struct Error {
#[cfg(feature = "failure")]
inner: Context<ErrorKind>,
#[cfg(not(feature = "failure"))]
inner: ErrorKind,
}
// To suppress false positives from cargo-clippy
#[cfg_attr(feature = "cargo-clippy", allow(empty_line_after_outer_attr))]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum ErrorKind {
BadAbsolutePath,
BadRelativePath,
CannotFindBinaryPath,
CannotGetCurrentDir,
CannotCanonicalize,
}
#[cfg(feature = "failure")]
impl Fail for ErrorKind {}
impl Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let display = match *self {
ErrorKind::BadAbsolutePath => "Bad absolute path",
ErrorKind::BadRelativePath => "Bad relative path",
ErrorKind::CannotFindBinaryPath => "Cannot find binary path",
ErrorKind::CannotGetCurrentDir => "Cannot get current directory",
ErrorKind::CannotCanonicalize => "Cannot canonicalize path",
};
f.write_str(display)
}
}
#[cfg(feature = "failure")]
impl Fail for Error {
fn cause(&self) -> Option<&dyn Fail> {
self.inner.cause()
}
fn backtrace(&self) -> Option<&Backtrace> {
self.inner.backtrace()
}
}
#[cfg(not(feature = "failure"))]
impl std::error::Error for Error {}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&self.inner, f)
}
}
impl Error {
pub fn kind(&self) -> ErrorKind {
#[cfg(feature = "failure")]
{
*self.inner.get_context()
}
#[cfg(not(feature = "failure"))]
{
self.inner
}
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Error {
Error {
#[cfg(feature = "failure")]
inner: Context::new(kind),
#[cfg(not(feature = "failure"))]
inner: kind,
}
}
}
#[cfg(feature = "failure")]
impl From<Context<ErrorKind>> for Error {
fn from(inner: Context<ErrorKind>) -> Error {
Error { inner }
}
}
pub type Result<T> = std::result::Result<T, Error>;
|
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:
<body>
<p>
I Série - Número 35
</p>
<p>
Sábado, 9 de Janeiro de 1982
</p>
<p>
Diário da Assembleia da República
</p>
<p>
II LEGISLATURA - 2.ª SESSÃO LEGISLATIVA (1981 - 1982)
</p>
<p>
REUNIÃO PLENÁRIA DE 8 DE JANEIRO DE (1981-1982)
</p>
<p>
Presidente: Exmo. Sr. <NAME>
</p>
<p>
Secretários: Exmos. Srs. <NAME>
<br />
<NAME>
<br />
<NAME>
<br />
<NAME>
</p>
<p>
SUMÁRIO - O Sr. Presidente declarou aberta a sessão às 10 horas e 35 minutos.
</p>
<p>
Antes da ordem do dia. - A propósito da declaração política que produziu na última sessão, o Sr. Deputado Portugal da Silveira (PPM) respondeu a pedidos de esclarecimento do Sr. Deputado Sousa Marques (PCP).
<br />
Em declaração política, o Sr. Deputado Mário Tomé (UDP) referiu-se a vários aspectos da actual situação política, criticando o Governo a esse propósito.
<br />
Numa intervenção, o Sr. Deputado Bento de Azevedo (PS) referiu-se ao sector cooperativo, criticando o responsável do Governo pelo sector. No fim, respondeu a pedidos de esclarecimento e a protestos dos Srs. Deputados <NAME> (PSD), <NAME> (PSD) e <NAME> (PPM).
</p>
<p>
Ordem do dia - Iniciou-se a discussão das ratificações n.ºs 99/II (PCP) e 103/II (PS), respeitantes ao Decreto-Lei n.º 266/81, de 15 de Setembro, que regulamenta a associação de municípios.
<br />
Intervieram no debate os Srs. Deputados <NAME> (PCP), <NAME> (PSD), <NAME> (PS), <NAME> (PSD), <NAME> (PCP), Portugal da Silveira (PPM) e <NAME> (PS).
<br />
O Sr. Presidente encerrou a sessão às 13 horas.
</p>
<p>
O Sr. Presidente: - Srs. Deputados, temos quorum, pelo que declaro aberta a sessão.
<br />
Eram 10 horas e 35 minutos.
</p>
<p>
Estavam presentes os seguintes Srs. Deputados:
</p>
<p>
Partido Social - Democrata (PSD)
<br />
<NAME>.
<br />
Afonso de <NAME>.
<br />
<NAME>.
<br />
Á<NAME>.
<br />
Álvaro <NAME>.
<br />
Amâ<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME> e <NAME>.
<br />
<NAME>. <NAME>.
<br />
<NAME>.
<br /
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 | 1 |
<body>
<p>
I Série - Número 35
</p>
<p>
Sábado, 9 de Janeiro de 1982
</p>
<p>
Diário da Assembleia da República
</p>
<p>
II LEGISLATURA - 2.ª SESSÃO LEGISLATIVA (1981 - 1982)
</p>
<p>
REUNIÃO PLENÁRIA DE 8 DE JANEIRO DE (1981-1982)
</p>
<p>
Presidente: Exmo. Sr. <NAME>
</p>
<p>
Secretários: Exmos. Srs. <NAME>
<br />
<NAME>
<br />
<NAME>
<br />
<NAME>
</p>
<p>
SUMÁRIO - O Sr. Presidente declarou aberta a sessão às 10 horas e 35 minutos.
</p>
<p>
Antes da ordem do dia. - A propósito da declaração política que produziu na última sessão, o Sr. Deputado Portugal da Silveira (PPM) respondeu a pedidos de esclarecimento do Sr. Deputado Sousa Marques (PCP).
<br />
Em declaração política, o Sr. Deputado Mário Tomé (UDP) referiu-se a vários aspectos da actual situação política, criticando o Governo a esse propósito.
<br />
Numa intervenção, o Sr. Deputado Bento de Azevedo (PS) referiu-se ao sector cooperativo, criticando o responsável do Governo pelo sector. No fim, respondeu a pedidos de esclarecimento e a protestos dos Srs. Deputados <NAME> (PSD), <NAME> (PSD) e <NAME> (PPM).
</p>
<p>
Ordem do dia - Iniciou-se a discussão das ratificações n.ºs 99/II (PCP) e 103/II (PS), respeitantes ao Decreto-Lei n.º 266/81, de 15 de Setembro, que regulamenta a associação de municípios.
<br />
Intervieram no debate os Srs. Deputados <NAME> (PCP), <NAME> (PSD), <NAME> (PS), <NAME> (PSD), <NAME> (PCP), Portugal da Silveira (PPM) e <NAME> (PS).
<br />
O Sr. Presidente encerrou a sessão às 13 horas.
</p>
<p>
O Sr. Presidente: - Srs. Deputados, temos quorum, pelo que declaro aberta a sessão.
<br />
Eram 10 horas e 35 minutos.
</p>
<p>
Estavam presentes os seguintes Srs. Deputados:
</p>
<p>
Partido Social - Democrata (PSD)
<br />
<NAME>.
<br />
Afonso de <NAME>.
<br />
<NAME>.
<br />
Á<NAME>.
<br />
Álvaro <NAME>.
<br />
Amâ<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME> e <NAME>.
<br />
<NAME>. <NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
Casimiro Pires.
<br />
Cecília Pita Catarino.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
Leonel Santa Rita Pires.
</p>
</body>
<body>
<p>
1382 I SÉRIE - NÚMERO 35
</p>
<p>
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>ca.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME> e Paiva.
<br />
<NAME> <NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
R<NAME> Amaral.
<br />
<NAME>.
<br />
Vasco Francisco <NAME>.
</p>
<p>
Partido Socialista (PS)
</p>
<p>
<NAME>.
<br />
<NAME>valho.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
António <NAME>.
<br />
<NAME>.
<br />
<NAME> Macedo.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
Aquilino Ribeiro Machado.
<br />
Armando dos Santos Lopes.
<br />
Bento Elísio de Azevedo.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
Francisco de Almeida Salgado Zenha.
<br />
<NAME>tos.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME> Costa.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
Júlio <NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>tos.
<br />
Manuel Francisco da Costa.
<br />
<NAME>.
<br />
<NAME>. <NAME>.
<br />
<NAME>.
<br />
Raul d'Assunção Pimenta Rêgo.
<br />
Teó<NAME> dos Santos.
</p>
<p>
Centro Democrático Social (CDS)
</p>
<p>
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME> e Sousa.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
Luísa <NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
Paulo Oliveira Ascenção.
<br />
<NAME>.
<br />
Rui <NAME>.
<br />
<NAME>.
<br />
<NAME>.
</p>
<p>
Partido Comunista Português (PCP)
</p>
<p>
<NAME>.
<br />
Álvaro Favas Brasileiro.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
António da Sil<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
<br />
<NAME> Santos.
<br />
<NAME>.
<br />
<NAME>.
</p>
<p>
Partido Popular Monárquico (PPM)
</p>
<p>
<NAME>.
<br />
<NAME>.
</p>
</body>
<body>
<p>
9 DE JANEIRO DE 1982 1383
</p>
<p>
<NAME>.
<br />
<NAME>.
</p>
<p>
Acção Social - Democrata Independente (ASDI)
</p>
<p>
<NAME>.
<br />
<NAME>.
<br />
<NAME>.
</p>
<p>
União da Esquerda para a Democracia Socialista (UEDS)
</p>
<p>
<NAME>.
<br />
António <NAME>.
<br />
<NAME>.
</p>
<p>
Movimento Democrático Português (MDP/CDE)
</p>
<p>
<NAME>.
</p>
<p>
União Democrática Popular (UDP)
</p>
<p>
<NAME> Tomé.
</p>
<p>
ANTES DA ORDEM DO DIA
</p>
<p>
O Sr. Presidente:- Vai proceder-se à leitura do expediente.
</p>
<p>
O Sr. Secretário (<NAME>): - Na última sessão foram apresentados os seguintes requerimentos: ao Ministro da Justiça, formulado .pelo Sr. Deputado Guerreiro Norte; ao Governo (3), formulados pelo Sr. Deputado <NAME>, e à Radiotelevisão Portuguesa, formulado pelo Sr. Deputado <NAME>.
<br />
Foram ainda recebidas as seguintes respostas a requerimentos: do Governo, aos requerimentos apresentados pelos Srs. Deputados: <NAME>, na sessão de 16 de Janeiro; <NAME>, na sessão de 23 de Abril; <NAME>, na sessão de 6 de Maio; <NAME> e <NAME>, na sessão de 12 de Maio; <NAME>, na sessão de 14 de Maio; <NAME>, na sessão de 7 de Julho; <NAME>, <NAME> e <NAME>, na sessão de 9 de Julho; <NAME>, na sessão de 16 de Setembro; <NAME> e <NAME>, na sessão de 24 de Setembro.
</p>
<p>
O Sr. Presidente: - Srs. Deputados, a declaração política feita ontem no período de antes da ordem do dia pelo Sr. Deputado Portugal da Silveira deu origem a várias intervenções. No entanto, ficaram inscritos para hoje alguns deputados que não puderam usar da palavra na última sessão.
<br />
Por esse motivo, tem a palavra o Sr. Deputado <NAME>, para pedir esclarecimentos ao Sr. Deputado Portugal da Silveira.
</p>
<p>
O Sr. <NAME> (PCP): - Sr. Deputado Portugal da Silveira, a sua declaração política de ontem tinha em conta determinados aspectos políticos que me parecem de referir. Numa altura em que a própria Juventude Social - Democrata critica severamente o seu Ministro da Educação e das Universidades, numa altura em que o CDS também o critica - provavelmente porque, para além de já ter o domínio sobre as pastas económicas e sociais deste governo, ainda quer juntar a pasta da Educação e da Cultura, entregando-a ao Sr. <NAME> ou ao Sr. <NAME> -, ...
</p>
<p>
O Sr. <NAME> (CDS): - Esses processos de intenção são eternos!
</p>
<p>
O Orador: - ... numa altura em que o Ministro da Educação e das Universidades está cada vez mais desacreditado, numa altura em que uma luta de professores é levada a cabo com o êxito que o próprio Sr. Deputado Portugal da Silveira reconhece, é que o Sr. Deputado do PPM vem aqui a esta Assembleia descobrir uma questão que finalmente pode unir a AD no campo da educação, ou seja no facto de chamar terroristas aos professores, no dizer que a acção do Sindicato dos Professores pode ser comparada à acção de associações terroristas.
<br />
Pela gravidade das suas afirmações e pelo silêncio que se fez sentir nas bancadas do PSD e do CDS, o Sr. Deputado conseguiu o seu objectivo, até porque nesse dia, no dia em que o Sr. Deputado fazia essa declaração, o Sr. Ministro da Educação e das Universidades vinha aqui à Assembleia. Era preciso, primeiro, atacar os professores para depois conseguir aqui um clima de solidariedade entre a AD e o desacreditado Ministro da Educação e das Universidades.
<br />
Gostava de lhe recordar um despacho de Janeiro de 1974, do então Secretário de Estado da Instrução e Cultura, <NAME>, que chamou aos grupos de estudo que então havia e que eram constituídos pelos professores «associações secretas». Ora, nesse mesmo despacho ameaçava os membros desses grupos de estudo de expulsão da função pública e de prisões de 6 meses a 2 anos. Naturalmente que hoje nem o Sr. Deputado Portugal da Silveira nem qualquer Sr. Deputado da AD pode vir aqui a esta Assembleia ameaçar os professores de expulsão ou com prisão de 6 meses a 2 anos, mas podem - como fez o Sr. Secretário de Estado fascista - compará-los a associações secretas ou a associações terroristas.
<br />
As perguntas que lhe queria fazer, Sr. Deputado Portugal da Silveira, são estas: o Sr. Deputado conhece os métodos de avaliação que estão a ser seguidos nas escolas? O Sr. Deputado sabe que os professores procederam à avaliação dós seus alunos e que apenas não divulgaram os seus resultados para chamar a atenção da opinião pública e para sensibilizar os encarregados de educação de que a política seguida só serve para prejudicar os próprios alunos? O Sr. Deputado sabe que no meio do próximo período os encarregados de educação terão conhecimento da avaliação que foi feita aos seus filhos e que, segundo os modernos métodos seguidos nas escolas, a avaliação de conhecimentos é feita no final do ano em relação à nota do último período, sendo nessa altura que se toma conhecimento da nota média de avaliação em cada uma das cadeiras?
<br />
Devo dizer-lhe, Sr. Deputado, que não houve qualquer prejuízo para os estudantes e, aliás, os estudantes perceberam isso, os encarregados de educação perceberam isso. Os professores levaram a cabo uma forma de luta que conseguiu, com grande êxito, prestigiar a sua classe. É isso que nos distingue do Sr. Deputado Portugal da Silveira, pois nós não chamamos terroristas àqueles que se prestigiaram
</p>
</body>
<body>
<p>
1384 I SÉRIE - NÚMERO 35
</p>
<p>
com uma luta que, quanto a nós, foi totalmente correcta.
</p>
<p>
Aplausos do PCP.
</p>
<p>
O Sr. Presidente: - Tem a palavra o Sr. Deputado Portugal da Silveira para responder às questões que lhe foram colocadas, tanto na sessão de ontem como na de hoje.
</p>
<p>
O Sr. Portugal da Silveira (PPM): - Sr. Presidente, Srs. Deputados: Responderia de uma forma geral aos Srs. Deputados <NAME>, <NAME> e <NAME>, porque todos eles, de .um modo geral, focaram da minha intervenção aquela parte em que eu dizia que os métodos seguidos pelos professores se aproximavam dos métodos do terrorismo internacional. Devo dizer aos Srs. Deputados que não tenho uma vírgula a retirar à comparação que fiz porque a verdade é esta: como é que os professores esperam ter o nosso apoio, se para assumir uma forma de luta se comportam, podemos dizê-lo, com "uma meia de seda enfiada na cabeça"? É uma luta que, assumida desta forma, retira legitimidade às acusações que fazem à degradação do ensino.
<br />
Todos nós temos conhecimento dessa degradação, todos nós a sentimos. Mas a forma como a contestação é assumida é verdadeiramente de "meia de seda enfiada na cabeça", porque nem sequer se pode chamar uma luta, visto que uma luta implica risco, implica qualquer tipo de sofrimento, e o professor, ao assumir este tipo de greve, não assumiu risco, foi uma manifestação que não comportou para ele qualquer sofrimento. O professor chegou ao fim de 3 meses de .trabalho e não deu os resultados do mesmo. Pior do que isso, não o deu oficialmente, mas ciciou-o, a um por um, aos seus alunos: "olha tu estás positivo, olha tu está negativo". É esta a forma de luta que eu não posso aceitar. Se os Srs. Deputados lerem a minha intervenção verificarão que está lá escrito que eu não considero que o ensino em Portugal esteja a decorrer da forma que todos desejaríamos. No entanto, pôr em destaque essa degradação por este método é contribuir não para a sua regularização mas sim para a continuidade dessa degradação. O Sr. Deputado disse que os alunos e os pais dos alunos compreenderam a forma de luta, mas eu digo-lhe que não compreenderam.
<br />
Gostaria ainda de dizer o seguinte: sou, com certeza, dos mais velhos nesta Câmara e por isso tenho algum conhecimento nesta matéria. O ensino em Portugal, a .partir de 1933-1934, entra na sua decadência com o diploma que regulamentou a reforma do ensino, feito .pelo professor <NAME>. É aí que o ensino entra no caos que mais tarde se vem a verificar, quando na década de 60 se dá a explosão de frequência escolar, quando massas enormes de jovens ocorrem às escolas. Aí, a educação fica à beira do abismo.
<br />
Vem 1974-1975 e a educação, que estava à beira do abismo, deu um grande passo em frente: caiu no abismo! Foi a partir dessa data que a recuperação se começou a fazer, e quero desde já render homenagem a quem primeiro arrancou com essa recuperação, que foi o Ministro Sottomay<NAME>.
<br />
Todos nós nos lembramos quando é que há 2 anos começavam as aulas na esmagadora maioria das esco-
</p>
<p>
Ias deste país - Janeiro e Fevereiro e em Março e Abril ainda eram colocados professores. Hoje a situação não é boa, está longe disso, mas é incomparavelmente melhor do que aquela de há 3, 4, 5 anos. Mesmo assim todos nós sabemos que ela está longe de atingir um nível minimamente aceitável.
<br />
Esta é que é a realidade objectiva e concreta que está à nossa frente.
</p>
<p>
Vozes do PSD: - Muito bem!
</p>
<p>
O Orador: - É fácil atirar para cima da AD, como para mim seria fácil atirar para cima dos governos socialistas, dos governos gonçalvistas, ou da (pesada herança" - que estamos a pagar e que temos de pagar- a crise do ensino. Apesar de tudo estamos a caminhar no bom sentido. Há faltas, erros..., há, isso há, mas se lerem a minha intervenção elas estão lá apontadas. Eu não dou o aval completo e total ao Governo, ao Ministro, porque reconheço que há erros. Simplesmente, temos é de reconhecer que o caminho está aberto.
</p>
<p>
O Sr. <NAME> (PCP): - Sr. Deputado, dá-me licença que o interrompa?
</p>
<p>
O Orador:- Faça ,favor, Sr. Deputado.
</p>
<p>
O Sr. <NAME>: (PCP): - Sr. Deputado, gostava de lhe fazer duas observações: parece-me grave que não retire as afirmações que fez ontem e que, pelo contrário, as mantenha. Não sei se o Sr. Deputado sabe, mas a sua intervenção de ontem já está a dar os seus resultados nas escolas. Eu próprio já tive hoje um contacto com o Sindicato dos Professores e já sei qual a reacção às suas palavras que, aliás, apareceram ontem no Telejornal.
<br />
A outra questão é esta: Sr. Deputado Portugal da Silveira, as lutas levadas a cabo pelos professores tiveram objectivos concretos. O Sr. Deputado conhece-os? O Sr. Deputado sabe quais os documentos discutidos entre os Sindicatos, e o Ministério é que o Ministério não publicou? O Sr. Deputado sabe quais as leis da Assembleia da República que o Ministério ainda não regulamentou, etc., etc., etc.? O Sr. Deputado sabe isso ou apenas se utilizou da forma de luta dos professores para vir aqui fazer a sua declaração política?
</p>
<p>
O Orador: - Conheço, Sr. Deputado. Ontem, dizia o Sr. Deputado <NAME>: "A minha mulher é professora e conhece muito bem os assuntos." Pois eu digo-lhe que também a minha o é, também eu conheço as questões, e é porque as conheço que as coloquei da forma como o fiz. Este tipo de greve, continuo a dizê-lo, é insidioso - há aqui qualquer coisa de sadismo -, não a greve em si, mas a forma como é assumida, e nesta matéria não tenho uma palavra a retirar, pois continuo a pensar exactamente o que pensava.
</p>
<p>
Aplausos do PPM, do PSD e do CDS.
</p>
<p>
O Sr. Presidente: -.Para uma declaração política, tem a palavra o Sr. Deputado <NAME>.
</p>
<p>
O Sr. <NAME> (UDP): - Sr. Presidente, Srs. Deputados: A vida para a grande maioria dos
</p>
</body>
<body>
<p>
9 DE JANEIRO DE 1982 1385
</p>
<p>
portugueses é, cada vez mais, um pesado fardo repleto de sacrifícios, de carências, de alguma desorientação e até de desespero.
<br />
A consciência de que o governo AD tem de ser - como principal responsável - derrubado, custe o que custar, cresce e firma-se no seio do povo e dos trabalhadores.
<br />
Mesmo para aqueles que votaram AD, na falsa perspectiva de verem melhorar a sua vida ou, pelo menos, estabilizar a situação política e sentirem um mínimo de segurança para si e para os seus filhos, a perflexibilidade, o desengano e a raiva surda substituem as ilusões-defraudadas.
<br />
Face à auscultação e à percepção da vaga de fundo que se está formando o Governo desmultiplica-se, já não em promessas descaradas, como ousara fazer l ano atrás, mas na parlapatanice, na demagogia, na ameaça e na provocação aos trabalhadores.
<br />
Enquanto vai preparando as condições para o seu Estado de direita, reforçando e aumentando os efectivos policiais, consolidando o poder económico dos grandes tubarões, aperfeiçoando a legislação antilaboral, consolidando a rede de traficantes, corruptos» mixordeiros, aldrabões, especuladores, bufos e caciques única base social de apoio que não se desagrega e, pelo contrário, se reforça, o Governo aperfeiçoa os laços que o ligam e submetem ao imperialismo americano e às multinacionais da Europa, dá garantias cada vez mais gravosas à NATO e ao belicismo imperialista. É a lógica dos parasitas e dos lacaios: por um lado, sugar a seiva viva e pujante do corpo são e, por outro lado, obter a protecção e a segurança dos mais fortes, submetendo-se e dando-lhes a primazia no banquete reaccionário.
<br />
Face à impossibilidade de conter a hemorragia da dívida externa, de parar a inflação, de estabilizar o desemprego, de garantir o pão, a saúde, a habitação e a educação, sequer a níveis mínimos, ou seja face à falência total da sua política aos olhos do povo, o Governo opta pela grande ofensiva ideológica: assegura o controle férreo dos principais órgãos de comunicação social, que, como tudo em que toca, vão piorando a olhos vistos; garante o reforço da sua mais poderosa e eficaz aliada, a hierarquia da Igreja, concedendo-lhe a possibilidade inconstitucional de explorar ou de se apoderar de uma estação emissora da TV.
<br />
Já não chega ao Governo a possibilidade de pôr e dispor o seu bel-prazer de televisão e da rádio para destilar a demagogia e tentar fazer passar gato por lebre e pôr os trabalhadores uns contra os outros, mascarando a contradição entre trabalhadores e parasitas, entre exploradores e explorados, com falsas contradições entre pais e filhos, entre doentes e saudáveis, entre grevistas e não grevistas, entre funcionários e utentes, entre novos e velhos.
<br />
Precisa, rapidamente, que o fogo do Inferno ameace de forma mais poderosa e eficaz os malcomportados, os réprobos, os pecadores, os insatisfeitos; que as delícias do paraíso garantam a submissão e a humildade e recompensem os flagelados, os sofredores, que o silício substitua a luta e a revolta.
<br />
Sr. Presidente, Srs. Deputados: O Ministro dos Assuntos Sociais diz ao povo que precisa de pagar, de forma incomportável, ainda por cima, a saúde a
<br />
que tem direito, de forma geral, universal e gratuita, se quiser garantir o futuro dos seus filhos.
<br />
Os Ministros do Trabalho e dos Transportes dizem aos trabalhadores que não devem fazer greve, porque as greves são políticas e destinam-se a desestabilizar a situação e a desorganizar a sociedade.
<br />
Outro ministro qualquer diz que os Portugueses vivem acima das suas possibilidades.
<br />
O Primeiro-Ministro chama parasitas aos trabalhadores.
<br />
O Ministro das Finanças e do Plano afiança-nos que é preciso desempregar para assegurar o emprego.
<br />
O Ministro da Habitação jura, a pés juntos que se torna necessário desocupar casas, haver casas vazias e a apodrecer, para garantir o direito à habitação.
<br />
O Ministro da Educação e das Universidades não tem dúvidas de que a universidade deve ser dirigida pelo Governo para lhe assegurar a autonomia.
<br />
O Ministro da Defesa, nas suas homílias, ameaça-nos com o fogo atómico se não deixarmos os americanos semearem a nossa terra de bombas atómicas.
<br />
O Ministro da Qualidade de Vida promete-nos o equilíbrio ecológico e o ambiente saudável, como contrapartida a deixarmos que os grandes capitalistas atirem as suas imundícies nos nossos rios e campos.
<br />
O Ministro da Agricultura Comércio e Pescas garante que temos o pão de que necessitamos se a comercialização dos cereais for feita pelos monopólios americanos; assegura a produção agrícola com a miséria de milhares de camponeses e a liquidação da Reforma Agrária; garante o preço da batata se deixarmos apodrecer a nossa produção e, a importarmos, e pôr-nos-á o peixe à nossa mesa se consentirmos na liquidação da frota pesqueira e não nos importarmos que os Espanhóis e outros nos destrocem os bancos e arrastem os fundos ou mesmo alguma criança que, por descuido, esteja à beira do mar quando passar um dos seus arrastões, tão perto da praia eles arrastam.
<br />
O Governo assegura-nos a independência nacional se as multinacionais puderem tomar conta das nossas estruturas produtivas e económicas e se nos submetermos às exigências da CEE. É este o nosso governo abençoado, e como não temos outro há que derrubá-lo urgentemente.
<br />
Sr. Presidente, Srs. Deputados: O desemprego foi este ano acrescido de mais 66000 desempregados. A produção industrial está praticamente estagnada e a utilização das capacidades produtivas diminuiu. A produção agrícola teve tanta queda acentuada e não apenas devido à seca. O crescimento do produto nacional, prometido no início do ano para 4,8 %, não ultrapassará 1,6 %, que corresponde, na prática, à estagnação da economia.
<br />
A inflação, prometida para 16 % com o objectivo de conter os salários a esse nível, ultrapassará provavelmente os 20 % ou mesmo os 25 %. As exportações baixaram, o défice da balança de pagamentos chega aos 130 milhões de contos.
<br />
Portugal pagará no próximo ano mais juros da dívida externa do que a amortização da mesma, com valores situados respectivamente nos 97 e 37 milhões de contos. Em 1982 teremos de importar 76 % dos produtos alimentares.
<br />
A resposta do Governo a esta situação 6 o aumento brutal dos transportes, o aumento dos géneros de
</p>
</body>
<body>
<p>
1386 I SÉRIE - NÚMERO 35
</p>
<p>
primeira necessidade, o aumento do custo da saúde para níveis tais que, só eles, justificariam a queda do Governo, a licenciosidade da lei dos despedimentos, a penalização dos aumentos de salários, o aumento na função pública comido pela cobrança de imposto profissional, a histeria dos ritmos de trabalho e do aumento de produtividade, a repressão e a arbitrariedade nas empresas, o terrorismo patronal.
<br />
Assim se garante que os lucros não diminuam com a crise, antes cresçam alarvemente enquanto as massas populares são obrigadas a suportar os seus brutais efeitos que se agravam de dia para dia.
<br />
Mas os trabalhadores também têm a sua resposta assente na justa perspectiva de que se são os ricos a provocar a crise terão de ser eles a pagá-la integralmente.
<br />
E também não estão dispostos a ficar à espera que Eanes resolva, quando lhe convier, demitir o Governo para encontrar outro igual ou semelhante que permita levar por diante os mesmos objectivos: recuperação capitalista, integração na CEE, submissão à NATO, acrescidos de um outro que é o de servir de intermediário às ambições neocolonialistas dos governos da CEE e à implantação das multinacionais europeias em África.
<br />
Os trabalhadores estão chegando à conclusão de que só pela luta firme, unida, ampla e radical poderão: em primeiro lugar, impedir a prossecução da política de rapina a que estão sujeitos; em segundo lugar, cercar e isolar o Governo e finalmente derrubá-lo, sem deixar espaço de manobra à grande burguesia e ao imperialismo para mudar apenas as moscas.
<br />
A crise do Verão passado mostra-lhes que se a luta não for suficientemente acutilante e audaciosa contribuirá para agravar a crise da AD e do seu governo, mas não será suficiente para criar condições efectivamente favoráveis à alteração real da política que os molesta.
<br />
Os trabalhadores sabem que só garantirão o futuro dos seus filhos se não consentirem .hoje em sacrifícios cuja única finalidade é garantir o reforço do poder dos exploradores para que no futuro a exploração seja ainda mais forte e intolerável.
<br />
A saúde e a educação dos seus filhos só serão uma realidade se garantida hoje, desde já, com a criação de condições de vida dignas para os pais.
<br />
A política do Governo não garante o futuro, antes o compromete totalmente. Por isso os trabalhadores estão mostrando o caminho. Com a experiência de 1975 lançam-se a impor os seus direitos, como no sector da habitação. Centenas de famílias rejeitam definitivamente a indignidade das barracas e da promiscuidade, a insalubridade da convivência com os ratos e ocupam bairros inteiros.
<br />
No Vale de Amoreira, apesar de brutal repressão resistem. Na Quinta da Quintinha, em Loures, 150 famílias estão decididas a impor o seu direito à habitação.
<br />
À Câmara, onde o CDS, como lhe compete, já fez propostas para que se accionassem os mecanismos repressivos dos esbirros do patronato e do Governo, os ocupantes dizem que não sairão e que não estão dispostos a serem eles a pagar o roubo do Governo às finanças locais. Dizem mais, que é exactamente por ser uma Câmara de maioria democrática que mais
<br />
garantias eles devem ter de que a sua luta será vitoriosa e lhes será reconhecida o direito à habitação digna. Exigem rendas compatíveis com o carácter social que deve revestir a habitação e recusam-se a comprar os andares, porque os operários não querem ser proprietários, apenas exigem o direito a uma casa digna. A Câmara só tem um caminho democrático, porque hoje, depois do 25 de Abril e apesar do 25 de Novembro, a democracia só se defende e reforça correspondendo às necessidades fundamentais e essenciais dos trabalhadores: reconhecer a ocupação, legalizá-la e definir rendas de acordo com as possibilidades de cada família, através de um inquérito - que já está a fazer- e com o aval da comissão de luta dos ocupantes.
<br />
Algumas das famílias ocupantes que ainda estivessem nas barracas, aquando do temporal, teriam perecido retalhadas pelo zinco das coberturas.
<br />
Sr. Presidente, Srs. Deputados: As lutas mais firmes como a da MOCAR, Panasqueira, têxteis da Covilhã, MESSA, Camboumac, mostram, por um lado, o caminho a todos os trabalhadores e, por outro, põem a nu a demagogia e o carácter brutal e repressivo do Governo e a sua ilegitimidade.
<br />
A cobertura aos despedimentos, nomeadamente ao da Standard, que reocupou os lugares deixados vagos pelas operárias afrontosamente despedidas com contratos a prazo e dando o trabalho necessário a empreitores exteriores à empresa, passa a um nível superior com a proposta de lei ultra-reaccionária e inconstitucional que a maioria aprovou nesta Assembleia da República.
<br />
Este facto, um entre muitos, reforça a necessidade do alargamento e solidariedade das lutas e impõe que elas assumam claramente o carácter político que lhes deve corresponder.
<br />
A luta não é contra este ou aquele patrão mal-intencionado, mas é contra todos eles unidos e cristalizados em torno do seu representante - o Governo.
<br />
É necessário que a isto' corresponda a unificação das lutas, corresponda a exigência política de demissão imediata do Governo e que a AD vá para a rua.
<br />
A greve dos transportes, que saudamos com toda a nossa alegria e convicção, foi um passo importante. É necessário que o movimento sindical unitário desmascare a demagogia dos amarelos da UGT, corresponda ao sentimento que alastra célere nas massas trabalhadoras e que se vai tornando uma efectiva exigência, e prepare com seriedade, audácia e decisão, correspondendo também ao apelo dos sindicalistas revolucionários da CGTP-IN, uma greve geral que sirva para unificar de facto os trabalhadores, esvazie ainda mais a UGT dos trabalhadores que a ela aderiram, na ilusão de que iam melhorar a sua capacidade de luta contra a exploração, dê consciência da sua força e poder às massas laborais; isole e paralise o Governo, ponha os ricos a comer aquilo que produzem, ou seja, nada, e exija e imponha a demissão do Governo.
<br />
Aos Srs. Ministros uma única resposta: as greves são políticas. As greves são uma arma da política dos trabalhadores contra a política de exploração dos grandes capitalistas e do seu governo. São, por enquanto, a arma mais eficaz para opor a todo o arsenal bélico do poder da grande burguesia.
</p>
</body>
<body>
<p>
9 DE JANEIRO DE 1982 1387
</p>
<p>
Mas são uma arma eficaz desde que assente na democracia operária, na unidade e na vontade de luta radical dos trabalhadores e não sirvam apenas de força de pressão para a recomposição do poder da burguesia.
<br />
É a luta firme, embora dura que unifica as fileiras dos trabalhadores lhes dá força e consciência de classe e permite destroçar de facto as hostes inimigas.
<br />
Mãos à obra, pois. Governo AD, rua!
<br />
Entretanto, assumiu a Presidência o Sr. Vice-Presidente Tito de Morais.
</p>
<p>
O Sr. Presidente: - Tem a palavra o Sr. Deputado Bento de Azevedo para uma intervenção.
</p>
<p>
O Sr. Bento de Azevedo (PS): - Sr. Presidente, Srs. Deputados: O mal-estar que grassa no sector cooperativo obriga-me a fazer esta intervenção, a poucas semanas de se discutir nesta Assembleia um denominado Código Cooperativo, que de código só tem o nome.
<br />
Nele ressalta a contradição do seu preâmbulo com alguns dos seus principais dispositivos. Na realidade, enquanto no preâmbulo se condenam as características acentuadamente mercantis introduzidas nas cooperativas pelo Código Comercial, constata-se uma miscelânea tal que não se enxerga onde começa o cooperativismo e acaba o mercantilismo ou onde começa este e acaba aquele. De facto, a simbiose do comercial e do mercantil com o cooperativismo é notória, embora que disfarçada sob pinceladas jurídicas mais ou menos hábeis. É óbvio que tal visão ((iluminada» do cooperativismo não nos surpreende, pois sabemos muito bem -e disso não temos dúvidas que este Governo não defende nem lhe interessam os ideais cooperativistas. Antes se serve deles (como recentemente o fez o Primeiro-Ministro na Televisão) para à sua imagem e na óptica da sua filosofia política atingir outros objectivos que têm perseguido sob as mais diversas formas e, reconheça-se, com alguma persistência e desfaçatez. £ quais são esses objectivos? Eis alguns, entre outros:
<br />
1) Criar os meios concorrenciais à banca nacionalizada, mesmo que, para isso, se utilizem meios inconstitucionais;
<br />
2) A viabilizar a introdução de capitais privados em sectores intervencionados ou mesmo nacionalizados;
<br />
3) Inviabilizar a concorrência de um sector cooperativo forte e independente, através da criação de pseudocooperativas (que se enquadrariam mais adequadamente na família das sociedades anónimas); ao fazer depender as cooperativas do controle e da dependência do crédito; ao tentar dirigir e controlar as cooperativas através de uma reestruturação do Instituto António Sérgio do Sector Cooperativo (INSCOOP);
<br />
4) Partidarizar o movimento.
<br />
Porém, outras razões graves existem para que o* descontentamento alastre no movimento cooperativo.
<br />
Tomámos conhecimento recente de alguns factos que reputamos de graves e que gostaríamos de ver
<br />
esclarecidos com a brevidade que os casos requerem. Assim:
<br />
Uniões e federações de cooperativas que publicamente se queixam da protecção privilegiada que o secretário de Estado concede a uma federação de cooperativas (UCREPA), onde pontifica, como secretário-geral, um seu particular amigo.
<br />
Cooperativas de habitação que paralisaram as obras já há meses (algumas em fase de acabamentos) por congelamento processado aos créditos anteriormente concedidos, como é o caso de diversas cooperativas do Porto, que têm dado um exemplo de dinamismo e capacidade (ultrapassando mesmo a iniciativa privada) para resolver alguns dos múltiplos problemas habitacionais daquela cidade nortenha, a qual, como todos sabem, se encontra numa situação de emergência e calamidade habitacional, agora agravada pelos recentes temporais. Mas o congelamento dos créditos atinge muitas outras cooperativas de habitação, a nível nacional, e permite acções desencorajantes e cerceadoras por parte de câmaras municipais, como a do Porto.
<br />
Cooperativas de habitação que agora são obrigadas a peculiar controle contabilístico a exercer, nos termos de um recente «despacho comum» (assinado em 14 de Outubro passado pelo referido secretário de Estado e pelo ministro Viana Baptista), através do «parecer favorável» de uma Secretaria de Estado do Fomento Cooperativo que não tem sequer existência legal, por não estar prevista na lei orgânica deste VIII Governo. <NAME> é, na realidade, um mero «secretário de Estado sem Secretaria de Estado». E embora esta anomalia não pareça incomodá-lo muito (pois assim se intitula e se assinala em papel de ofício timbrado e no indicativo da porta do seu gabinete), a verdade é que se trata de uma «secretaria de Estado fantasma», que subverte a lei orgânica do seu próprio Governo e a contabilidade de distribuição das autênticas secretarias de Estado, tão acerrimamente disputadas pelos diversos parceiros da AD;
<br />
Inúmeras cooperativas, de diversos ramos, que solicitaram créditos há largos meses e apresentaram os respectivos estudos económicos exigidos e vêem os seus processos paralisados na Secretaria de Estado de Emprego.
<br />
O pedido de demissão dos vice-presidentes do Instituto António Sérgio dó Sector Cooperativo (INSCOOP), cuja fundação se deve à iniciativa de um ilustre e respeitado cooperativista que, como todos sabem, é o Prof. <NAME> e que foi ministro do I Governo Constitucional.
</p>
<p>
O Sr. <NAME> (PS): - Muito bem!
</p>
<p>
O Orador: - A situação caótica da casa de António Sérgio, que continua a degradar-se cada vez mais, por inoperância da AD, e apesar das vangloriadas afirmações produzidas neste hemiciclo pelo então deputado <NAME>;
<br />
Funcionários de núcleos de apoio às cooperativas (NACs) que, face a uma projectada remodelação que se pretende impor ao INSCOOP, não sabem, neste momento, qual a gaveta em que já adivinham ficar esquecidos...;
</p>
</body>
<body>
<p>
1388 I SÉRIE - NÚMERO 35
</p>
<p>
Uma funcionária em comissão de serviço, que de terceiro-oficial dos serviços administrativos do Ministério da Defesa passou para técnica superior de 2.B classe, saltando assim, num passo de mágica, 4 escalões da função pública de uma só vez, o que, saliente-se, em termos normais e só com boa classificação profissional, demoraria, pelo menos, 12 anos a processar-se ...;
<br />
O vazio legislativo já criado às cooperativas pela falta de publicação atempada no Diário da República do prorrogamento do prazo para adaptação dos estatutos das cooperativas ao novo Código.
<br />
Sr. Presidente, Srs. Deputados: Outros factos se poderiam apontar para exprimirmos os nossos receios quanto às anormalidades que pela negativa e pela omissão começam a grassar, como um verdadeiro cancro, o edifício cooperativo. Para tanto, já bastaram para o desgastar e incaracterizar os 40 anos de fascismo.
<br />
Nesta Assembleia, sempre realçámos e defendemos o cooperativismo e a necessidade de consolidar o seu movimento, com a dignidade que lhe consagra a Constituição e com o respeito dos princípios que o norteiam, porque pensamos que o movimento cooperativo tem um papel muito importante a desempenhar no Portugal de Abril. Por isso, em 1978 defendemos a existência de um autêntico Código Cooperativo, não só para revogar muita legislação caduca e cerceadora do movimento, mas principalmente para autonomizar o direito cooperativo em relação ao direito comercial, a fim de o cooperativismo poder cabalmente desempenhar a sua genuína missão.
<br />
As diversas intervenções que fizemos neste plenário desde 1976 são disso testemunho.
<br />
Mas perante as anormalidades que atrás referi e perante as tentativas que estão a ser feitas em nome do cooperativismo, para o desvirtuar e o enfraquecer, não podemos deixar de protestar e condenar com veemência este estado de coisas, que são a negação das proclamadas boas intenções daqueles que tanto aqui bradaram, injustamente, aliás, contra pretensas interferências e arbitrariedades dos governos que antecederam a AD.
<br />
Por último, esperamos sinceramente que os que se afirmam cooperativistas e da escola sergiana não se julguem «iluminados» e que, mais tarde, não venham a ser acusados de «algozes» do cooperativismo.
<br />
<NAME> condenava o individualismo, o sectarismo, a fraude e a jactância. E se ainda fosse vivo, não deixaria, por certo, de reafirmar: «Sob o véu mais cerrado das suas operações de tendeiro, tal era a beleza da juventude angélica do cooperativismo: a liberdade, a igualdade, a fraternidade entre os homens, trazidas para o campo material na vida.»
<br />
No próximo dia 24 de Janeiro faz 23 anos que <NAME> faleceu. Saibam os Portugueses e, em especial, os cooperativistas serem dignos da sua memória e do valor da sua obra, para que continuemos a ter esperança na liberdade, na igualdade e na fraternidade. Para que finalmente haja justiça neste país. Justiça que já tarda.
<br />
Disse.
</p>
<p>
Aplausos do PS, da ASDI, da UEDS e do MDP/CDE.
</p>
<p>
O Sr. <NAME> (PSD): - Sr. Presidente, peço a palavra para fazer um protesto.
</p>
<p>
O Sr. Presidente: - Faça favor, Sr. Deputado.
</p>
<p>
O Sr. <NAME> (PS): - Eu e a minha bancada decerto que também prestam homenagem a António Sérgio. Aliás, julgo que é limitativo, se se pretende homenagear a pessoa, fazê-lo enquanto cooperativista. Foi um aspecto do pensamento e da acção dessa grande figura nacional, mas António Sérgio foi bastante mais do que um cooperativista, foi, se quisermos, um político no sentido global da palavra, isto é, também um filósofo, um cidadão, um pedagogo - mas chamemo-lo cooperativista. De qualquer modo, homenageamo-lo como um grande cidadão do nosso país.
<br />
Procurando aplicar a pedagogia, não farei acto de jactância. Mas, Sr. Deputado da bancada do Partido Socialista, como poderemos nós seguir as lições do pedagogo quando não reconhecemos os factos tal como eles são? Este Governo e esta maioria, bem ou mal, foram os que pela primeira vez depois do 25 de Abril praticaram actos concretos, quer no domínio legislativo, quer no administrativo, quer no de outras formas de apoio, ao movimento cooperativista. No sentido errado, decerto, mas quem sabe, a prior i, qual é o sentido justo da história? Para quem é democrata, decide esse problema de filosofia em termos de eleições. Nós somos maioria, VV. Ex.ªs são oposição. Quando a maioria do povo português entender que as vossas propostas de apoio ao cooperativismo são as melhores, decerto que serão os senhores a aplicá-las através da via legislativa, administrativa ou outra.
<br />
Já foram governo e não o fizeram, por certo porque não tiveram tempo. Aceite, ao menos, Sr. Deputado, que enquanto formos maioria apliquemos o caminho que nos parece melhor ao cooperativismo. Mas reconheça que nós o fazemos.
</p>
<p>
Aplausos do PSD, do CDS e do PPM.
</p>
<p>
O Sr. Presidente: - Como o Sr. Deputado Bento de Azevedo manifesta o desejo de responder no fim, dou a palavra ao Sr. Deputado Araújo dos Santos.
</p>
<p>
O Sr. Araújo «<NAME> (PSD): - As objecções que a intervenção do Sr. Deputado Bento de Azevedo provocaram levam a que oportunamente faça nesta Câmara uma intervenção procurando responder-lhe ponto por ponto, já que tenho como pretensão e entendo que todas as afirmações que se fazem nesta Câmara devem ser ponderadas e terem como fundamentos principais um profundo e claro esclarecimento.
<br />
Não vi na intervenção do Sr. Deputado Bento de Azevedo essas condições fundamentais.
<br />
Como não sou porta-voz do Sr. Secretário de Estado, não vou responder aos ataques pessoais que o Sr. Deputado lhe dirigiu. Penso que o Sr. Secretário de Estado, se entender conveniente, lhe dará a devida resposta. Vou, sim, contrariar algumas das afirmações e algumas das intenções subjacentes à intervenção do Sr. Deputado Bento de Azevedo.
</p>
</body>
<body>
<p>
9 DE JANEIRO DE 1982 1389
</p>
<p>
Começou por chamar ao actual Código Cooperativo, do qual esta Assembleia pediu ratificação, «denominado Código Cooperativo», e afirma que em 1978 o Partido Socialista, esse sim, apresentou para discussão e discutiu uma proposta de lei aqui nesta Assembleia que era um verdadeiro código cooperativo. A realidade é bem diferente l De facto o actual Código Cooperativo é a imagem daquilo que o movimento cooperativo português pretendeu e o do Partido Socialista era um documento desfasado desse mesmo movimento cooperativo, pois era apenas gerado no seio do Partido Socialista.
<br />
Quando o Sr. Deputado Bento de Azevedo diz que o actual Código Cooperativo pretende introduzir uma concorrência inconstitucional à banca nacionalizada, pretenderá, naturalmente, referir-se às Caixas de Crédito Agrícola Mútuo. Portanto, pergunto-lhe o que é que o actual Código Cooperativo altera relativamente ao estatuto dessas mesmas Caixas.
<br />
Disse também o Sr. Deputado que actualmente se pretende dirigir as cooperativas, e um dos meios para o fazer é a reestruturação do Instituto António Sérgio. Também gostaria de lhe perguntar se sabe a forma como se está a pretender reestruturar o Instituto, se conhece o programa eleitoral da Aliança Democrática e o Programa do Governo sobre esta matéria.
<br />
Dava-lhe como última informação, visto que o tempo não dá para mais, que de facto existe uma proposta de reestruturação produzida pelo Instituto António Sérgio que foi enviada à Secretaria de Estado do Fomento Cooperativo, sobre a qual o Sr. Secretário de Estado decidiu ouvir o movimento cooperativo. Mas deu a sua opinião, que assenta, segundo o seu ponto de vista, em que qualquer reestruturação do Instituto António Sérgio deve corresponder aos seguintes objectivos: manutenção da actual forma mista do Instituto, aproveitando-se ao máximo o articulado da actual lei; preservar a completa autonomia do' sector em relação ao Instituto e ao poder político constituído; ampliar as funções do Instituto para, a área da assistência formativa, técnica e financeira, incluindo as soluções previstas no Código' Cooperativo; o conselho directivo deve ser um órgão colegial e não presidencialista; integração do assessor no serviço especializado do Instituto; fazer passar para o* conselho coordenador a preparação atempada das opções do Plano para o sector cooperativo a propor ao' Governo.
<br />
O Sr. Secretário de Estado assumiu a responsabilidade de dizer ao movimento cooperativo o que pensa e, neste momento, esse mesmo movimento está a ser ouvido para dar as suas opiniões relativamente à proposta que em tempo oportuno lhe foi enviada pelo conselho directivo do Instituto António Sérgio.
<br />
Assim, pergunto-lhe, Sr. Deputado, em que é que isto contraria os ideais cooperativos.
</p>
<p>
Aplausos do PSD.
</p>
<p>
O Sr. Presidente: - Tem a palavra o Sr. Deputado <NAME>.
</p>
<p>
O Sr. <NAME> (PPM): - A intervenção do Sr. Deputado Bento de Azevedo deixou-me atónito. E isto pela simples razão de que verifico que tentou
<br />
trazer antecipadamente para este Parlamento a discussão' na especialidade do Código Cooperativo.
<br />
Ora, quando todos os dias se fazem sessões para discutir na especialidade o Código Cooperativo, vir para aqui o Sr. Deputado dar palpites, formar juízos de valor e tentar pressionar as pessoas que estão a discuti-lo, julgo que não lhe fica bem. E por mais respeito que tenha pelo, Sr. Deputado - e tenho, como sabe, somos até do mesmo círculo eleitoral -, não posso deixar de protestar. Não posso também deixar de protestar quando se utilizam críticas fáceis ao Sr. Secretário de Estado Bento Gonçalves, pessoa a quem o cooperativismo já muito deve e de quem a história do cooperativismo em Portugal não se esquecerá com certeza.
</p>
<p>
Aplausos do PPM, do PSD e do CDS.
<br />
<br />
O Sr. Presidente: - Tem a palavra o Sr. Deputado Bento de Azevedo, para responder.
</p>
<p>
O Sr. Bento de Azevedo (PS): - Quanto ao protesto do Sr. Deputado <NAME>, devo dizer-lhe que fico satisfeito por verificar que também rende homenagem a António Sérgio.
<br />
É precisamente dentro da filosofia sergiana que penso que tentar fazer alguma coisa pelo cooperativismo é homenagear simultaneamente a memória de António Sérgio, mas tendo em conta a filosofia do cooperativismo por ele defendido.
<br />
Disse o Sr. Deputado que, bem ou mal, este governo tem feito alguma coisa em favor do cooperativismo. Penso que não deveria fazer mal, mas, sim, bem. Ao encarar a problemática do cooperativismo não se deveria tentar mistificá-lo, mas sim ter em conta o que António Sérgio defendia.
<br />
A partir do momento em que um cooperativista se diz sergiano, isso será mais uma responsabilidade para reforçar tudo aquilo que na verdade se diz ser.
</p>
<p>
O Sr. <NAME> (PSD): - Dá-me licença que o interrompa, Sr. Deputado?
</p>
<p>
O Orador: - Faça favor, Sr. Deputado.
</p>
<p>
O Sr. <NAME> (PSD): - Sr. Deputado, não ponho em causa a sua interpretação do pensamento de António Sérgio. No entanto, o Sr. Deputado pode pôr em causa a minha.
<br />
De qualquer modo, nesta nossa divergência, se o Sr. Deputado se posiciona, no plano democrático, como oposição e eu como maioria, deixe o problema ao eleitorado português!...
</p>
<p>
O Orador: - O Sr. Deputado reforçou, e continua a fazê-lo, a ideia de que é maioria.
<br />
O facto de ter sido maioria eleitoral não quer dizer que tenha a maioria do apoio dos cooperativistas. Porque o cooperativismo não deve, de maneira nenhuma, ser conduzido ou liderado por qualquer maioria. O cooperativismo tem de ser liderado pelos próprios cooperativistas, Sr. Deputado!
<br />
Portanto, não é uma maioria parlamentar ou uma maioria política que deve conduzir o cooperativismo segundo o seu âmbito ou segundo o seu pensamento.
</p>
<p>
O Sr. <NAME> (PS): - Não sabe isso! ...
</p>
</body>
<body>
<p>
1390 I SÉRIE - NÚMERO 35
</p>
<p>
O Orador: - O Sr. Deputado <NAME> ficou admirado com as afirmações que fiz e diz não saber se são fundamentadas. Pode crer, Sr. Deputado, que as fiz devidamente fundamentadas. Aliás, se passar uma vista de olhos por vários jornais, e alguns até da sua área política, verificará que há alguma angústia quanto à forma como está a ser conduzido o problema do cooperativismo em Portugal.
<br />
No que se refere à reestruturação do INSCOOP, devo dizer-lhe o que se pretende - e espero não venha a ser atingido. Quando foi da discussão do Decreto-Lei n.º 902/76, que fundou o Instituto António Sérgio, foi levantada aqui grande celeuma, principalmente pelo Sr. Deputado B<NAME>, a quem não ataquei pessoalmente, mas critiquei o modo como está a conduzir o cooperativismo, dentro da óptica sergiana que diz defender. Foi no aspecto cooperativista que o condenei, e não no aspecto político. Procurar retirar ao presidente a possibilidade de nomear os vice-presidentes e estes passarem a ser nomeados pelo Sr. Secretário de Estado pode ser um dos objectivos dessa reestruturação.
<br />
Ora é evidente que isso não deve ser permitido. Aí poderá haver partidarização, pois podem indicar-se pessoas que sejam da confiança pessoal do Sr. Secretário de Estado e não da dos cooperativistas.
<br />
Por outro lado, também há uma reformulação a fazer no conselho coordenador. Como sabe} esse conselho é formado por representantes de estruturas de cooperativas e por representantes de ministérios de tutela. A partir do momento em que se pretende alterar este statu quo do conselho coordenador, é evidente que também lá se podem meter pessoas amigas, proteger determinadas pessoas ou determinadas cooperativas, como é o caso concreto, que referi, da UCREPA.
<br />
Aliás, em toda a minha intervenção aparecem problemas concretos. Referi o problema das cooperativas de habitação, o do despacho comum e do parecer favorável que é necessário para a concessão de créditos e também o do congelamento de créditos. Ora, todas as cooperativas e todos os cooperativistas sabem que isto é verdade. É um problema público e as próprias cooperativas e federações têm vindo a esta Assembleia queixar-se dessa e de outras anomalias.
<br />
O Sr. Deputado vai ter ocasião de receber na subcomissão, como coordenador, e -nós também, a FENACHE que é uma estrutura representativa do movimento cooperativo. É o próprio movimento cooperativo que se encontra angustiado a partir do momento em que se f az o congelamento de créditos às cooperativas de base e se concede à UCREPA, depois de .ter recebido já substanciais créditos, mais 1 um crédito de 15 000 contos. A UCREPA, como toda a gente sabe, é uma cooperativa de retalhistas e comerciantes. Tudo isto são factos concretos que todos os cooperativistas, aqueles que defendem o cooperativismo, não podem deixar passar em branco.
</p>
<p>
Vozes do PS: - Muito bem!
</p>
<p>
O Orador. - Não me referi ao problema das caixas de crédito, porque não sou contrário a elas. Existem prerrogativas através da reestruturação feita pela Lei n.º 265, de 1911. No entanto, há determinados pormenores que é necessário serem discutidos. É preciso que as estruturas das caixas de crédito não se
<br />
transformem em bancos ou possam ser concorrenciais à banca nacionalizada, enquanto a Constituição o não permitir.
<br />
Há projectos de bancos cooperativos. Não sou contra eles, mas é evidente que não posso aceitar a sua existência enquanto a Constituição não for revista nesse aspecto.
<br />
Quanto ao Sr. Deputado <NAME>, a quem deixei atónito, devo dizer-lhe que penso que as explicações que dei foram suficientemente claras para que os elementos que estão na subcomissão de cooperativismo possam, na realidade, tomar consciência de que o movimento cooperativo está a atravessar uma crise agudíssima.
<br />
O movimento cooperativo pode ter um .papel fundamental neste país. Teremos problemas que serão insolúveis - com a nossa entrada no Mercado Comum, se ela se der- se não forem resolvidos através do cooperativismo. Será, por exemplo, o caso da agricultura minifundiária. Mas através de um cooperativismo sério. Não é transformar, por exemplo, os grémios agrícolas em cooperativas e continuarem a funcionar como se fossem grémios corporativos.
</p>
<p>
Aplausos do PS, da ASDI, da UEDS e do MDP/CDE.
</p>
<p>
O Sr. Presidente: - Srs. Deputados, está esgotado o período de antes da ordem do dia, pelo que entramos no período da ordem do dia.
</p>
<p>
ORDEM DO DIA
</p>
<p>
Da ordem do dia constam os pedidos de sujeição a ratificação n.ºs 99/II, apresentado pelo PCP, e 103/II, apresentado pelo PS, respeitantes ao Decreto-Lei n.º 266/81, de 15 de Setembro, que regulamenta a associação de municípios.
<br />
Para o efeito, tem a palavra o Sr. Deputado <NAME>.
</p>
<p>
O Sr. <NAME> (PCP): - Sr. Presidente, quero chamar a atenção para o facto de o Governo não estar presente.
</p>
<p>
O Sr. Presidente: - Sr. Deputado, o Governo foi avisado e penso que estará a chegar.
</p>
<p>
O Sr. Deputado <NAME>, que já está inscrito, poderá iniciar a sua intervenção, se assim o quiser.
</p>
<p>
O Sr. Silva Graça (PCP): - Sr. Presidente, sugeriria que - tal como ontem sucedeu em relação à discussão referente à autonomia das universidades - se suspendesse a sessão até à chegada do Governo.
</p>
<p>
O Sr. Presidente: - Fica então suspensa a sessão por 5 minutos.
<br />
Eram 11 horas e 30 minutos.
</p>
<p>
O Sr. Presidente: - Está reaberta a sessão. Eram 11 horas e 40 minutos.
<br />
Entretanto, tomou assento na bancada do Governo o Sr. Secretário de Estado da Administração Regional e Local (Roberto Carneiro).
</p>
</body>
<body>
<p>
9 DE JANEIRO DE 1982 1391
</p>
<p>
O Sr. Presidente: - Tem a palavra o Sr. Deputado <NAME>.
</p>
<p>
O Sr. <NAME> (PCP): - Sr. Presidente, Srs. Deputados, Sr. Secretário de Estado da Administração Regional e Local: O Grupo Parlamentar do PCP solicitou a ratificação do Decreto-Lei n.º 266/81, sobre a associação de municípios, por variadas ordens de razões. Sublinhamos que a metodologia do processo encontrada peai AD para fazer publicar o seu texto legal é inadmissível e revelador do que a AD pensa sobre a Assembleia da República e o seu papel e do que pensa sobre a utilidade dos debates nesta Assembleia. De facto, o Governo apresentou uma proposta de lei em Março de 1981, depois de, designadamente, estar na mesa, há meses, o projecto de lei do PS sobre esta matéria; por razões já aduzidas aqui nas intervenções do debate de 26 de Junho de 1981, não houve agendamento deste assunto até ao final da 1.ª sessão legislativa. Mas a AD - Governo, procurando apressar o fazer da obra legislativa que a AD na Assembleia da República não permite, exigiu uma autorização legislativa que os grupos parlamentares que integram a AD praticamente nem discutiram. Por este processo se furtou a discussão de uma matéria como associação de municípios na especialidade - como os Srs. Deputados sabem, estas matérias do poder local são discutíveis na especialidade na Assembleia da República; por este processo o Governo teve autorização legislativa para uma matéria da competência reservada da Assembleia da República. Só que não a usou em tempo. E saliente-se que o governo caiu antes de fazer publicar no Diário da Assembleia o decreto-lei autorizado pela sua maioria. E, em vez de vir aqui retomar o processo, sanando-lhe os vícios de que já enfermava, decidiu agravá-los até ao limite da inconstitucionalidade, fazendo publicar o Decreto-Lei n.º 266/81 já depois de ter caducado a autorização que obtivera, porque, entretanto, caíra em 14 de Setembro, data da sua exoneração.
<br />
O texto legal em apreço, por sobre este vício inultrapassável, apresenta ainda uma característica que exprime bem a natureza e métodos dos governantes da AD.
<br />
Lembrar-se-ão, certamente, Sr. Presidente, Srs. Deputados e Sr. Secretário de Estado e poderão verificar pela leitura do Diário da Assembleia da República- que o Governo então pela voz do Secretário de Estado de então, apresentou a sua proposta de lei de autorização legislativa, procurando, de alguma forma, sair de maneira airosa desta intromissão claríssima, prometendo que teria em conta, na utilização da autorização legislativa, aspectos citados do projecto de lei n.º 166/II: citou (p. 3518 do Diário da República n.º 88) «que esse projecto define de uma forma bastante mais minuciosa aquilo que os estatutos deverão conter», sublinhando aliás -continuo a citar o então membro do Governo- «que esta matéria é verdadeiramente importante, uma vez que os estatutos devem obedecer ao princípio da especialidade e, como tal, devem consagrar as regras essenciais para a sua elaboração».
<br />
O que é que se constata? Constata-se que, quando da publicação do decreto-lei, as promessas do Governo aqui feias, designadamente no debate de 26 de Junho,
<br />
designadamente, até, na intervenção do Sr. De<NAME>, do CDS foram como as promessas da AD são, isto é, puros artifícios eleiçoeiros,...
</p>
<p>
Vozes do PCP: - Muito bem!
</p>
<p>
O Orador: -... apressadores de votação ou ganhadores de votos, porque aqui, na Assembleia da República, esses artifícios não deram resultados, já que a votação positiva da autorização legislativa foi apenas um acto de seguidismo da parte dos deputados da AD, na circunstância verdadeiros terminais da vontade do Governo. Aqui, como noutras áreas, as promessas da AD são um puro circunstancionalismo justificativo, são asserções infundamentadas e peregrinas.
<br />
Quando o assunto aqui veio, na discussão de 26 de Junho, o Sr. Deputado <NAME> assinalou bastantes dúvidas sobre a problemática da associação de municípios radicando as suas dúvidas numa questão de filosofia que sintetizou na expressão de que «a lei não deve limitar de forma alguma ou coarctar a livre iniciativa que deve competir essencialmente aos próprios municípios». Aliás, no decorrer da discussão o assunto voltou. E pareceu-nos que o texto da proposta não respondia às dúvidas apresentadas. Se, como é o caso, o texto do decreto-lei, agora chamado a ratificação pelo Grupo Parlamentar do PCP, e que foi também chamado a ratificação pelo Grupo Parlamentar do Partido Socialista - e podemos verificá-lo por página, linha, palavra, vírgula e ponto final -, é, de facto, igual ao texto da proposta que referimos, parece-nos de interesse saber qual a posição que o CDS vai tomar face à ostensiva igualdade dos dois textos: aquele que foi aqui apresentado como proposta do Governo que iria ser melhorada e aquele que saiu publicado no Diário da República com a data de 15 de Setembro, porque as promessas valem o que valem e as pessoas têm que as dizer e afirmar. E as pessoas, naturalmente, assumem-se nas palavras que dizem.
<br />
Sr. Presidente, Srs. Deputados, Sr. Secretário da Administração Regional e Local: Estamos, neste momento, com toda a força que as palavras podem ter, perante uma ofensiva geral do governo da AD ao quadro constitucional e legislativo que tem regulado o exercício do poder local, importantíssima conquista do 25 de Abril. E já se conhecem os contornos dos aspectos mais salientes anunciados em Conselho de Ministros: um deles é o da ameaça de uma escandalosa nova lei das finanças locais que levaria os municípios a serem aquilo que agora são pela aplicação fraudulenta da lei: gestores de uma penúria ostensiva. Seria o fazer voltar das benesses, das dádivas, das comparticipações centrais, sob a forma de investimentos intermunicipais, claramente selectivos, como já são actualmente, discriminatórios para certas zonas do País. Seria a expectativa todos os anos, a nível de município, impedindo o planeamento, do que viria para os municípios, gerando-se uma situação que não favorece a gestão racional atempada, digerida dos recursos técnicos, humanos, financeiros, uma situação que não privilegia as tarefas do planeamento dos investimentos da maior repercussão directa, indirecta e diferida.
<br />
Outro dos pontos do ataque legislativo do actual MAI atenta-se às áreas da regionalização: é uma
</p>
</body>
<body>
<p>
1392 I SÉRIE - NÚMERO 35
</p>
<p>
área de contornos imprecisos, em que se prepara uma grande operação por um lado de marketing eleiçoeiro e favorável ao clientelismo, por outro de esvaziamento, não das competências do aparelho central do Estado, mas das autarquias, dos municípios.
<br />
Neste contexto, o diploma que agora discutimos tem também o seu papel para esta AD e para este governo.
<br />
A Constituição da República prevê que os municípios se possam associar livremente, no artigo 254.º, n.º 1, fundamentalmente em vista de uma melhor «prossecução de interesses próprios das populações respectivas». Aliás, este número é mantido, nesta forma, nos projectos de revisão constitucional do PCP, do MDP, e da FRS. É também um sinal o facto de este artigo ter sido eliminado no projecto de revisão inconstitucional da AD. Sabe-se bem que a revitalização dos municípios após o 25 de Abril de 1974 e que ninguém pode contestar, revitalização que se nota em todos os quadrantes das suas atribuições, apesar da prática fraudulenta dos dinheiros municipais, tem posto a nu limitações e barreiras da própria organização administrativa. Entende-se, e entendemos nós, também, que é na cooperação intermunicípios que se promove o desenvolvimento de um poder local como a Constituição refere: mas nós temo-lo salientado esta cooperação tem de estar alicerçada rigorosamente no princípio da independência e autonomia do poder local, expressamente acolhido no n.º 2 do artigo 237.º da Constituição e que não pode haver qualquer tutela especial do processo de constituição...
</p>
<p>
Vozes do PCP: - Muito bem!
</p>
<p>
O Orador: -... que não podem resultar dessa formação discriminações positivas e negativas que façam dessas associações estruturas permissivas do clientelismo e dos favores, por onde um qualquer Ministro, um qualquer <NAME> percorra de cheque em mão e de sorriso aberto, em pleno prolegómeno de uma qualquer campanha de demagogia, filtrada em marketing.
</p>
<p>
Aplausos do PCP e do MDP/CDE.
</p>
<p>
Ora, o diploma presente não passou o crivo de um debate demorado - os senhores sabem bem que quiseram pôr, claramente, entre parêntesis a Assembleia da República e que quiseram fazer do Governo do Verão a Assembleia da República em férias. Essa ausência de debate proporciona alçapões de grande profundidade. Um deles refere-se à perfeita discutibilidade de todo o referido no artigo 3.º, salientando que os municípios se associarão em termos dos actuais agrupamentos fixados nos diplomas que regulam os GATs. Para além da mediocridade do texto, do diz e não diz que são os n.ºs 1 e 2 desse artigo, temos uma limitação censória à atitude da associação, que regista aliás apoio no artigo 10.º, fazendo que a assessoria técnica às associações seja da competência do GAT respectivo. Não está acautelada a defesa dos interesses e dos poderes dos municípios face a potenciais atitudes lesivas e abusivas por parte das associações, que, isoladas e apoiadas por uma qualquer CCR,
<br />
queiram esvaziar os termos da actuação de um município. Releve-se, aliás - e o Sr. Deputado <NAME>, particularmente, é capaz de ser sensível a este argumento, porque lhe lembra o 26 de Junho de 1981 e o debate dessa data -, que se mantém, como se nada se tivesse dito aqui durante a discussão da autorização legislativa, que o município é livre de entrar na associação, mas não o é para dela sair.
<br />
O artigo 19.º mantém a mesma redacção. A forma de cessação da associação é uma forma limitativa da autonomia do município.
<br />
Outro aspecto é o da composição da assembleia intermunicipal. O texto demora-se a dizer quem vai e quem não vai. Nós chegámos aqui a referir, e parece-me que com justeza aliás, fomos citados depois -, que a associação de municípios pode transformar-se, Sr. Secretário de Estado da Administração Regional e Local, numa associação de presidentes de municípios. Nós dissemo-lo.
<br />
Quase que os senhores querem regulamentar, também, as vírgulas do' que vão ser as associações.
<br />
Aliás, o Ministério da Administração Interna era capaz de ter um diploma que tivesse anexo um exemplar de estatutos, para tudo ser igual e paralelo e para poder orientar do alto ou do baixo do Ministério da Administração Interna a vida dos 305 municípios, vida que ele não percebe em muitos aspectos, vida de que manifestamente não gosta, em muitos deles, na sua variedade e riqueza e vida que vai mudando muitas situações e dados no nosso país.
</p>
<p>
Vozes do PCP: - Muito bem!
</p>
<p>
O Orador: - Dizia alguém na Conferência do Poder Local do Partido Comunista Português que esta coisa do poder local vai tirando o fascismo da cabeça de muitas pessoas.
</p>
<p>
Vozes do PCP: - Muito bem!
</p>
<p>
Uma voz do CDS: - É o comunismo, não é o fascismo.
</p>
<p>
O Sr. <NAME> (PCP): - Está enganado!
</p>
<p>
O Orador. - E é verdade, é um facto! O poder local vai tirando o fascismo da cabeça das pessoas.
<br />
Um terceiro aspecto a relevar é o das receitas. Aqui, Srs. Deputados e Sr. Secretário de Estado da Administração Regional e Local, é a ilegitimidade completa, é o renegar de uma constante após Abril de 1974 que tem sido a luta por uma situação em que mais não haja o' saco azul ou o saco laranja da distribuição e em que não haja a mão estendida às comparticipações ou aos subsídios.
<br />
Quanto ao artigo 14.º, eu pedia que ele fosse relido, pois recria estas atitudes, dá-lhes a força da permissividade, que é intolerável para todos os que nesta bancada - e quero crer que em outras bancadas - querem um país dignificado em que a distribuição dos recursos públicos seja decorrente de critérios fundamentais na mais estrita objectividade.
</p>
<p>
Vozes do PCP: - Muito bem!
</p>
<p>
O Orador - Este decreto-lei é significativo das operações em curso. Significa que a AD-Governo
</p>
</body>
<body>
<p>
9 DE JANEIRO DE 1982 1393
</p>
<p>
nada ligou a qualquer dos pontos referidos na discussão de Junho, significa que a AD-Governo recria, nesta área do poder local, as possibilidades de actuação ilegal, fraudulenta, caciqueira, clientelista,...
</p>
<p>
Vozes do PCP: - Muito bem!
</p>
<p>
O Orador: -... pelo menos não se livra da possibilidade disto, significa que a AD-Governo tanto queria este decreto que o aprovou nas vésperas da sua queda, sendo o diploma irregular, como já disse, por ter sido publicado quando o Governo, que solicitara a autorização legislativa, já tropeçara, e já caíra, porque os pés, os dois ou três pés que o sustentam, que o sustentavam estavam e estão permanentemente baralhados e confundidos, de tanto num pé querer estar à frente de outro pé.
<br />
Votaremos contra a ratificação deste decreto-lei e propomos que, face à importância do diploma, o assunto, após a não ratificação, seja rapidamente agendado.
</p>
<p>
Aplausos do PCP e do MDP/CDE.
</p>
<p>
O Sr. <NAME> (PSD): - Sr. Presidente, peço a palavra para interpelar a Mesa.
</p>
<p>
O Sr. Presidente: - Faça favor, Sr. Deputado.
</p>
<p>
O Sr. <NAME> (PSD): - Quero interpelar a Mesa para saber se não ficou estabelecido na conferência dos líderes (parlamentares que os grupos parlamentares utilizariam o seu tempo como quisessem. Se assim foi, não preciso de invocar qualquer figura regimental.
</p>
<p>
O Sr. Presidente: - Ficou acordado na conferência dos líderes parlamentares que há tempos limites e a Mesa precisa de saber se o Sr. Deputado deseja usar da palavra para uma intervenção ou para pedir esclarecimentos, pois há outras inscrições na Mesa.
</p>
<p>
O Sr. <NAME> (PSD): - Certo, Sr. Presidente, mas é que, se o tempo tem limite, seja para pedir esclarecimentos ou para protestar, ficarei, com certeza, limitado ao tempo regulamentar.
</p>
<p>
O Sr. Presidente: - Sem dúvida!
</p>
<p>
O Sr. <NAME> (PSD): - É essa a interpelação da Mesa, Sr. Presidente?
</p>
<p>
O Sr. Presidente: - É, sim, Sr. Deputado. Mas o Sr. Deputado deseja fazer um pedido de esclarecimento?
</p>
<p>
O Sr. <NAME> (PSD): - Sim, Sr. Presidente.
</p>
<p>
O Sr. Presidente: - Então, faça favor.
</p>
<p>
O Sr. <NAME> (PSD): - Mas, Sr. Presidente, o que eu desejo saber é se no pedido de esclarecimento que vou fazer sou obrigado a respeitar os 3 minutos regulamentares ou se posso ultrapassar esses 3 minutos.
</p>
<p>
O Sr. Presidente: - Pode ultrapassá-los, mas o tempo que gastar será descontado no tempo do seu grupo parlamentar, evidentemente.
</p>
<p>
O Sr. <NAME> (PSD): - O meu pedido de esclarecimento será breve porque as considerações feitas pelo Sr. Deputado <NAME>, e também o respeito que ele merece, exigirão mais tempo' da minha parte e serão comentadas através de uma intervenção.
<br />
Assim, por agora, quero apenas fazer um ligeiro comentário e alguns pedidos de esclarecimento. O comentário é o seguinte: a intervenção do' Sr. Deputado foi mais -ou pretendeu ser- uma interpelação ao Governo sobre matéria de poder local do que propriamente uma intervenção de discussão do diploma que está em ratificação. Desde as matérias obrigadas à Lei das Finanças Locais até à regionalização e aos investimentos intermunicipais, tudo aqui foi trazido.
<br />
Ora, nós estamos limitados a uma ordem do dia e, portanto, limitar-me-ei a esse conteúdo.
<br />
Mas o que eu quero perguntar ao Sr. Deputado <NAME> é o seguinte: V. Ex.ª citou, como situação grave e atentatória da liberdade de os próprios municípios se associarem, o facto de eles ficarem, em determinados casos, circunscritos à área dos GATs.
<br />
V. Ex.ª deve ter reparado, com certeza, que a norma que prevê essa preferência pela área dos GATs é imediatamente elidida com a possibilidade de os municípios livremente deliberarem que a área não é essa mas outra qualquer.
<br />
Ora, o que acontece é que precisamente a determinação que está feita relativamente à área dos GATs, que é uma norma puramente indicativa, tem um conteúdo de natureza prática e encontra-se inserida noutros diplomas, nomeadamente no diploma de criação dos GATs.
<br />
V. Ex.ª recorda-se com certeza deste diploma em que se considera que os GATs serão transferidos imediatamente para a administração dos municípios, desde que as assembleias municipais assim o deliberem, depois de constituída a respectiva associação.
<br />
Portanto, a finalidade desta disposição é uma finalidade prática que tem precisamente em vista incentivar a aplicação correcta desse princípio, ou seja, libertar os GATs da superintendência ou da tutela administrativa do Ministério da Administração Interna ...
</p>
<p>
Vozes do PSD: - Muito bem!
</p>
<p>
O Orador: - ...e não é restritiva em coisa nenhuma referente à autonomia; pelo contrário, tenta fomentar essa autonomia libertando os GATs da tutela governamental.
<br />
Eu gostaria que V. Ex.ª me dissesse se, quando fez esta afirmação, teve em consideração estes aspectos que eu acabo de focar.
<br />
Relativamente a outros aspectos, ou seja, àquilo que V. Ex.ª referiu também como restritivo da autonomia e especialmente ligado a determinadas matérias que estão muito regulamentadas - segundo o Sr. Deputado - no diploma que está em ratificação, eu queria dizer que é lógico que essa regulamentação
</p>
</body>
<body>
<p>
1394 I SÉRIE - NÚMERO 35
</p>
<p>
que aí está não é excessiva, porque ela tem essencialmente três objectivos fundamentais: determinar a competência dos órgãos, o que é rigorosamente função da lei como a Constituição exige: determinar as respectivas atribuições, o que é também função da lei como a Constituição exige, e ainda fazer com que a protecção dos direitos e interesses individuais, nas relações com a própria associação de municípios, fique melhor salvaguardados.
<br />
Com efeito, não podemos esquecer que os actos das associações de municípios ou dos seus órgãos representativos são actos administrativos sujeitos a recurso contencioso e, portanto, se não estiverem regulamentados os direitos das pessoas, na sua contratação com as associações de municípios, estas poderiam ficar definitivamente prejudicados ou, pelo menos, postos em risco.
<br />
Assim, queria também perguntar a V. Ex.ª se houve consideração da sua parte relativamente a esta matéria ao fazer a afirmação de quebra de autonomia por parte do respectivo diploma.
<br />
Por agora, ficar-me-ei por estas perguntas.
</p>
<p>
O Sr. Presidente: - Tem a palavra o Sr. Deputado <NAME>, para responder, se o desejar.
</p>
<p>
O Sr. <NAME> (PCP): - Sr. Deputado <NAME>, eu trouxe aqui uma análise decorrente da ratificação n.º 103/II ao Decreto-Lei n.º 266/81, de 15 de Setembro, e naturalmente fi-la integrada numa perspectiva geral, porque não é descabido nem incorrecto pensar que a AD pretende levar a cabo uma operação de grande vulto em matéria de poder local com vista a um cerceamento da autonomia. Entendemo-lo desta forma, temo-lo denunciado e as associações de municípios não são desenquadráveis disto.
<br />
Mas fiz também uma análise, artigo a artigo, enumerando os elementos fundamentais. Citei aqui, a título de exemplo, repito, os artigos 3.º, 10.º, 14.º e 19.º, ou seja, fiz uma análise integrada e uma análise do Decreto-Lei n.º 266/81.
<br />
Em relação aos GATs há, de facto, uma lei da Assembleia -aliás na sequência de um decreto-lei do governo Mota Pinto- que considera essa possibilidade de inserção dos GATs. E o Sr. Deputado fez bem em recordar esse elemento que é o elemento que fará a integração -positiva, como é natural - desses meios de ajuda técnica nos municípios. Mas é necessário sublinhar também que a prevenção do acto censório está na determinação tanto do artigo 3.º da fórmula que se encontrou como do artigo 10.º quando se sublinha que a ajuda à associação de municípios deverá ser dada pelo GAT da região.
<br />
Por outras palavras, dir-se-á que não há outra atitude censória prévia, mas que se impõe que a associação de municípios tenha o limite de uma certa vizinhança para ter a possibilidade da ajuda técnica do GAT. São estes os termos do raciocínio, que não são invalidados pela forma que o Sr. Deputado lembrou - da lei de 1980 desta Assembleia.
<br />
O Sr. Deputado <NAME> indicou três planos fundamentais de uma lei quadro. Nós sublinhámos na intervenção que não contrariamos a necessidade de uma lei de associação de municípios. Aliás, julgo que terá posto entre parêntesis o aspecto do financiamento, que seria um quarto aspecto fundamental a determinar a economia de um diploma deste tipo. Não o fez porque naturalmente, em matéria de financiamento, a AD é capaz de não ter a consciência tranquila sobre a forma da discriminação positiva, e negativa para outros, que faz em relação à distribuição dos dinheiros públicos pelas associações intermunicipais. O meu camarada <NAME> fez referência a isso na sessão de 26 de Junho, apresentando números. Sublinha-se que são actos administrativos. Pois são. São actos administrativos que necessitam de ficar com uma certa economia e com um certo número de elementos. O que sublinhamos é que a lei pormenoriza actos que devem vir na parte dos estatutos das associações e não devemos ir para uma lei quadro que discipline a variedade de associações de municípios que, dentro de um enquadramento geral, vão existir por esse país. Hoje há variados modelos de estatutos de assembleia municipal, de câmara municipal, de regulamentos e de regimentos. Isso não impede até o avanço do poder local como conquista fundamental e irreversível do 25 de Abril.
</p>
<p>
Vozes do PCP: - Muito bem!
</p>
<p>
O Sr. Presidente: - Para uma intervenção, tem a palavra o Sr. Deputado <NAME>.
</p>
<p>
O Sr. <NAME> (PS): - Sr. Presidente, Srs. Deputados, Sr. Secretário de Estado: É conhecida a posição do meu partido na defesa das associações de municípios. A minha bancada teve ocasião de apresentar um projecto de lei sobre a matéria, o projecto de lei n.º 166/II, relativo a uma lei quadro das associações, de municípios.
<br />
Poderíamos, por isso, ter requerido neste debate a inserção da discussão do projecto de lei por nós apresentado.
<br />
Pensamos, no entanto, que a defesa das associações de municípios tem que se fazer de forma activa e positiva, e não apenas de forma processual e formal. Por isso, preferimos e vamos apresentar propostas de alteração ao Decreto-Lei n.º 266/81, em discussão.
<br />
Queríamos, em todo o caso, salientar que não podemos deixar de denunciar aqui um expediente que não nos parece aceitável numa prática democrática. Se queremos prestigiar este Parlamento, se queremos evitar que o Parlamento seja dia a dia mais desacreditado, mais esvaziado de sentido e de conteúdo político, não podemos aceitar certo tipo de práticas. Uma delas é a do Governo que, usando uma maioria legítima que dispõe nesta Assembleia, vem aqui requerer - como o fez no Verão passado - uma autorização legislativa sobre uma matéria reservada desta Assembleia para, seguidamente, com base nessa autorização, se eximir à discussão de dois diplomas - um do Partido Socialista, outro do próprio Governo.
<br />
E mais do que isto: com base nessa autorização legislativa, o Governo não apresenta uma solução autónoma, uma alternativa própria. Transcreve ipsis verbis, linha por linha, vírgula por vírgula, como já aqui foi dito, o próprio texto da proposta que tinha sido apresentada nesta Assembleia.
<br />
Queríamos, assim, denunciar este tipo de procedimentos que, a nosso ver, não prestigia esta Assembleia, não prestigia as relações entre o Governo e a
</p>
</body>
<body>
<p>
9 DE JANEIRO DE 1982 1395
</p>
<p>
Assembleia da República e, sobretudo, prejudica a nosso ver, a própria imagem de democracia que queremos ver construída em Portugal.
</p>
<p>
Vozes do PS - Muito bem!
</p>
<p>
O Orador: - Desde já dizemos que aceitamos não votar contra a ratificação do diploma em apreço, desde que seja possível garantir a introdução de alterações que, a nosso ver, no mínimo são importantes para melhorar e validar a necessidade deste diploma.
<br />
Para lá dos aspectos formais que pretendemos ainda abordar e entrando um pouco na matéria de fundo - que nos parece que não pode estar ausente num debate deste tipo -, queria lembrar as razões e argumentos que temos aduzido em debates anteriores a favor da defesa da criação de associações de municípios.
<br />
Não querendo alongar excessivamente o nosso tempo de intervenção, penso que é importante não esquecer 4 grandes argumentos a favor da criação das associações de municípios.
<br />
Em primeiro lugar, pensamos que a associação é um instrumento voluntário que permite a utilização de agrupamentos de municípios para uma actuação mais concreta e mais precisa em áreas de interesse mútuo dos respectivos municípios.
<br />
Em segundo lugar, pensamos que a associação pode fornecer uma unidade de planeamento e de execução da actividade dos municípios mais adequada à eficácia, à celeridade e até ao bom êxito dos resultados de um conjunto muito vasto de funções e tarefas que os municípios têm já a seu cargo.
<br />
Em terceiro lugar, a própria entreajuda técnica e financeira dos municípios pode beneficiar largamente com a utilização da figura de associação de municípios, criando-lhe um espaço adicional até de autonomia financeira, sem a dependência de recursos, por exemplo, do poder central.
<br />
Finalmente, o quarto argumento que nos parece importante é que a associação será um instrumento de peso considerável na própria prossecução de uma política de desenvolvimento regional e inter-regional, designadamente em ordem a permitir a correcção dos desequilíbrios por vezes flagrantes e injustos, desequilíbrios de situação económica e social.
<br />
Por outro lado, pensamos que neste momento, em que muito se fala de regionalização e de descentralização, a figura da associação de. municípios tem também aí de ser considerada. Não nos parece fácil abordar a dinâmica da descentralização e da regionalização, ignorando aquilo que, a nosso ver, constitui uma espécie de dialéctica que terá de ser considerada na definição das competências e no âmbito de actuação dos municípios e de outros níveis de autarquias locais.
<br />
De resto, a nosso ver, essa dialéctica polariza-se em dois pólos: por um lado, o Estado que tem de manter um conjunto de funções que são inalienáveis do poder central, do poder do Estado enquanto unidade do território e enquanto unidade nacional e, por outro, o nível municipal que para os socialistas é a entidade base do autogoverno e da autonomia do poder local. É neste contexto de dois pólos -o nível do Estado e o nível dos municípios e, dentro do nível dos municípios, as próprias freguesias - que, a nosso
<br />
ver, aparece a dinâmica e a razão de ser das regiões como nível intermédio de conciliação. Um nível de conciliação em torno de atribuições e competências que devem ser descentralizadas, mas cuja complexidade e escala de tratamento não se compadece com o nível municipal e, por outro, um nível de conciliação em torno de funções e competências que originalmente até podem competir aos municípios mas que, pelas interferências que têm em áreas adjacentes ou por razões de coordenação, podem justificar a necessidade e compatibilizá-las a um nível supramunicipal.
<br />
Por isso, tendo em conta a defesa que fazemos de um município como unidade central, como comunidade base que não pode ser ignorada no desenvolvimento de uma política de descentralização, e até por razões, que não iremos desenvolver aqui, de ordem social e histórica que, no nosso contexto, pensamos que têm uma importância particular, os socialistas consideram que a figura de associação de municípios pode reforçar justamente esse papel, essa função e esse patamar de responsabilidades que queremos para os municípios.
<br />
Ninguém pode aceitar que não seja no âmbito dos municípios que as comunidades populacionais respectivas deixem de encontrar resposta a um conjunto de necessidades básicas, como, por exemplo, a educação, os cuidados de saúde, os abastecimentos de primeira necessidade, o saneamento básico, a habitação, os equipamentos colectivos, os transportes. Tendo em conta a dimensão geográfica e humana de muitos dos municípios que existem até por razões históricas e culturais que na realidade actual poderia não ter justificação mas que também não se podem alterar facilmente, a nosso ver-, essa dificuldade de conciliação da dimensão do espaço municipal com as funções que lhe queremos atribuir pode ser suprida, aceitando a existência da figura de associação de municípios.
<br />
Neste ponto coloca-se uma questão adicional: a de saber se, não obstante o artigo 254.º da Constituição prever a possibilidade de as associações de municípios terem um carácter voluntário, se deve ou não nalguns casos, no âmbito da lei, definir a sua obrigatoriedade.
<br />
Enquanto não forem aqui discutidas e aprovadas, de forma um pouco mais detalhada, as delimitações e competências que ficarão a cargo dos municípios e, portanto, a .possibilidade de ficarem, por delegação, a cargo das próprias associações de municípios, e enquanto não se discutir aqui quais os condicionamentos financeiros que poderão ser finalmente aceites como definição da nova lei das finanças locais que o Governo e a maioria propõem alterar, gostaríamos de deixar em aberto essa questão, embora, a nosso ver, nos pareça que há áreas em que, de forma justificada, se aceitaria bem a figura de associações de municípios de carácter obrigatório.
<br />
Por exemplo, não vemos como resolver o problema da habitação social sem conferir as associações de municípios competências e recursos próprios nessa área e sem lhes conferir também, com carácter obrigatório, um conjunto preciso de obrigações a ser cumprido pela associação de municípios.
<br />
Quanto às principais alterações que julgamos ser indispensável introduzir, quero referir sumariamente as seguintes: por um lado, vamos propor alterações
</p>
</body>
<body>
<p>
1396 I SÉRIE - NÚMERO 35
</p>
<p>
ao artigo 2.º, já que pensamos ser útil melhorar a definição do objecto da associação de municípios. É que sem essa definição fica, à partida, a figura da associação de municípios a ser uma figura vaga e retórica, como está neste momento previsto no decreto-lei do Governo.
<br />
Pensamos que, quanto a este aspecto, se coloca ainda uma importante questão de fundo. A nosso ver, é inadmissível a actual redacção do artigo 3.º do Decreto - Lei n.º 266/81. E, mais do que inadmissível, ele é uma base de inconstitucionalidade deste diploma.
<br />
Ninguém nesta Assembleia poderá politicamente aceitar que se queira impor limites da autonomia nos próprios municípios, dizendo-lhes como e em que termos os municípios, que têm autonomia e liberdade, se poderão associar.
<br />
Pensamos que poderão ser estabelecidos critérios e que poderão ser definidas regras. Pensamos que será útil propor e facilitar a associação de municípios dentro de alguns quadros de referência, mas de forma alguma deveremos impor, como é feito por princípio, que a associação de municípios seja composta pelos municípios pertencentes ao mesmo agrupamento fixado no diploma que regula os gabinetes de apoio técnico às autarquias, os chamados GATs.
<br />
Os GATs são neste momento órgãos dependentes da administração central, do Ministério da Administração Interna. Não são, apor isso, órgãos próprios do poder local. Ora, a nosso ver, bastaria isto para invalidar e tornar inaceitável afigura prevista de delimi2ação que o Governo propõe no seu decreto lei.
<br />
Mas, indo um pouco mais longe do que certos argumentos já aqui apresentados pela bancada do Partido Comunista, diremos que a própria delimitação feita nesse decreto-lei que cria os GATs corresponde a uma expressão que foi, feita à revelia das autarquias e cuja iniciativa legislativa teve uma sanção a posteriori desta Assembleia, mas que não foi aqui discutida para outros efeitos que não o da constituição desses gabinetes. E ,por isso essa delimitação que serviu de base à existência dos GATs não pode nem deve ter qualquer incidência na delimitação das áreas de constituição das associações de municípios.
<br />
Pensamos ser igualmente indispensável introduzir melhorias na redacção do artigo 7.º, relativo à assembleia intermunicipal, por razões também já aqui referidas aquando da discussão do pedido de autorização legislativa, e ao artigo 9.º, relativo às competências dos próprios, órgãos da associação. Do mesmo modo, julgamos ser necessário melhorar o conteúdo do artigo 10.º, relativo à assessoria técnica, sem o que consideramos que na prática continuamos a admitir aquilo que na teoria dizemos não ser aceitável. Ou seja, o de transferirmos responsabilidades e competências para as associações de municípios sem lhes darmos os meios e as competências necessárias para as associações poderem desempenhar com. eficácia e com dinamismo essas mesmas responsabilidades.
<br />
Pensamos ainda introduzir propostas de alteração aos artigos 13.º, 15.º 18.º e 19-º, melhorias de base formal e que, portanto, dispensam agora, no debate na generalidade, uma apresentação detalhada. Julgamos que uma discussão na especialidade se revelará suficiente para a sua apresentação.
<br />
Finalmente, julgamos ser indispensável nas alterações que iremos propor introduzir dois novos artigos que constavam do nosso projecto de. lei relativo às associações de municípios e que - digamos - não tem paralelo na economia ido articulado proposto pelo Governo no decreto-lei em apreço. Trata-se dos artigos 20.º e 21.º, para os quais iremos propor redacções próximas das que constavam do nosso próprio projecto ,de lei e que são relativas à apresentação anual de programas de acção por parte dos órgãos executivos das associações de municípios e também da apresentação anual de relatórios de actividade.
<br />
Sem isto pensamos ser difícil que os municípios envolvidos nas associações municipais e os próprios órgãos do poder soberano, como a Assembleia da República e o Governo, dificilmente poderão exercer funções tutelares de fiscalização ,genérica que, a nosso ver, têm de ser preservadas a qualquer nível e sobretudo a nível de democracia geral do País, de forma a tornar transparente a actividade das associações dos municípios e a garantir que os seus programas e a sua actuação possam ser objecto de análise, de censura ou de aplausos, apoiado em documentos e em propostas que têm a sanção e o conhecimento dos órgãos representativos.
<br />
Por este conjunto de razões, pensamos que desde que a Assembleia aceite a introdução atempada destas nossas propostas ou, polo menos, aceite a sua discussão, não seremos nós a recusar a possibilidade da ratificação do Decreto - Lei n.º 266/81.
</p>
<p>
O Sr. Presidente: - Para pedir esclarecimentos, tem apalavra o Sr. Deputado <NAME>.
</p>
<p>
O Sr. <NAME> (PSD): - Sr. Deputado <NAME>, sobre a parte do seu discurso em que referiu a possibilidade futura da criação de associações obrigatórias, queria perguntar a V. Ex.ª se estava a referir apenas às áreas metropolitanas ou também a outro tipo de associações mais genéricas.
<br />
Relativamente ao problema levantado sobre a intervenção ou não dos municípios na delimitação da área dos GATs, gostaria apenas de lhe lembrar que o espírito do diploma que criou os GATs ia no sentido de que essas áreas tivessem objectivos exclusivamente técnicos e não no sentido da criação de qualquer tipo de autarquia ou de qualquer associação de outro tipo.
</p>
<p>
O Sr. Presidente: - Tem apalavra o Sr. Deputado <NAME>, para responder, se assim o entender.
</p>
<p>
O Sr. <NAME> (PS): - Muito brevemente quero dizer ao Sr. Deputado <NAME> que foi ele próprio quem deu a resposta, visto que, como eu disse na minha intervenção, nós pensamos que após uma análise ponderada dos meios e das responsabilidades que efectivamente venham a ser cometidas aos municípios se pode justificar que para determinadas áreas de responsabilidades - e não me refiro a áreas geográficas nem a áreas de poder local - se torne obrigatória a figura da associação de municípios. E referi que é numa área técnica que, a nosso ver, essa obrigatoriedade se pode justificar como garantia de que um determinado programa, por exemplo o da habitação social, seja efectivamente cumprido a nível de todo o território. Então se
</p>
</body>
<body>
<p>
9 DE JANEIRO DE 1982
</p>
<p>
poderá exigir aí que a associação de municípios seja uma figura defensável.
<br />
Em todo o caso, como disse na minha intervenção, não queremos tomar uma posição definitiva sobre esta matéria sem conhecer e sem podermos discutir as condicionantes dessa mesma figura obrigatória.
<br />
De qualquer maneira e em relação às áreas metropolitanas quero tornar claro que pensamos que se trata de uma associação, não para efeitos de cooperação em áreas técnicas precisas e específicas, de cooperação de prestação de serviços e de áreas afins, mas, sim, de uma associação que visa transformar-se numa figura diferente, numa figura de poder local. Parece-nos, portanto, que não serão as associações de municípios a figura adequada para poder substituir a eventual necessidade de órgãos de poder local adequados a áreas metropolitanas.
</p>
<p>
O Sr. Presidente: - Cumpre-me informar que estão inscritos em relação a esta matéria os Srs. Deputados <NAME>, Portugal da Silveira e Silva Graça.
<br />
Tem a palavra o Sr. Deputado <NAME> para uma intervenção.
</p>
<p>
O Sr. <NAME> (PSD): - Sr. Presidente, Srs. Deputados: Conforme já aqui dissemos, não nos parece que o Governo tenha atropelado as regras democráticas ao requerer a autorização legislativa e não houve nenhum "seguidismo" da parte dos deputados do PSD ou dos deputados da .maioria, porque até aqui foram efectuadas algumas críticas e sugestões ao diploma então apresentado.
<br />
Por isso, é-nos estranha a afirmação feita pelo Sr. Deputado <NAME>, do Partido Comunista, de que o seu grupo parlamentar não votará favoravelmente as ratificações agora em discussão, rejeitando logo à partida e dessa maneira a possibilidade do consenso do próprio Partido Comunista. O PCP entende, pois, não apresentar alterações que porventura da nossa parte pudessem merecer consenso e apoio no sentido de melhorar o texto.
<br />
O Sr. Deputado <NAME>, por outro lado, insistiu no facto de o decreto-lei delimitar a área da associação de municípios aos GATs existentes. Ora, não é isso o que realmente o texto do decreto-lei contempla, embora aponte nesse sentido. Efectivamente, fica aberta aos municípios a possibilidade de estabelecerem entre si a associação fora, portanto, da área dos GATs.
<br />
Aliás, na própria intervenção final efectuada em Junho pelo Partido Socialista se dizia que fundamentalmente eram contra o pedido de autorização legislativa, por sair do âmbito da Assembleia da República para o Governo um assunto que devia aqui ser discutido. Não era, pois, uma questão de fundo que estava em causa, até porque o Governo tinha apresentado a sua proposta de lei, não caindo a autorização legislativa no vazio.
<br />
Desse modo, quando o Governo solicitou a esta Assembleia a autorização legislativa sobre associação de municípios, existia já uma proposta de lei sobre a matéria, tal como existia o projecto de lei apresentado pelo PS.
<br />
Diversos Srs. Deputados afirmaram então que, de qualquer modo, não estávamos a discutir a proposta de lei n.º 53/11 ou o projecto de lei n.º 166/11, mas
</p>
<p>
1397
</p>
<p>
sim a autorização legislativa. Embora em termos formais fosse essa a realidade, não se poderia abstrair do facto concreto de se conhecer o teor do diploma emanado do Governo, que foi posto em contraponto com o projecto de lei apresentado pelo Partido Socialista, também ele abordando a questão da associação de municípios.
<br />
Muitos pontos de convergência se detectaram entre o projecto de lei e a proposta de lei, e na intervenção efectuada pelo Governo na apresentação do pedido de , autorização legislativa também se manifestou a disponibilidade para a introdução de normas que melhorassem o conteúdo do clausulado, o que admitimos possa efectuar-se agora através do pedido de ratificação, o qual também será aproveitado pela maioria e pela totalidade dos deputados aqui presentes para dar um âmbito mais lato ao diploma. Nesse sentido a maioria apresentou já algumas propostas de alteração.
</p>
<p>
Por isso, Sr. Presidente e Srs. Deputados, votaremos favoravelmente a ratificação pedida, tal como votaremos a favor do pedido de baixa à comissão, apresentado pelo PS, para aí se introduzir e discutir, então, quais e onde se devem verificar as alterações, sempre -repito- no sentido de melhorar o texto, de o adaptar às condições reais e de dotar os municípios com melhor legislação, dotá-los com um novo diploma que os ajude a resolver os problemas que os afectam.
</p>
<p>
Aplausos do PSD,
</p>
<p>
O Sr. Presidente:- Tem a palavra o Sr. Deputado Portugal da Silveira.
</p>
<p>
O Sr. Portugal da Silveira (PPM): - Sr. Presidente, Srs. Deputados: Nesta minha intervenção proponho-me fazer, por um lado, alguns comentários e, por outro, alguns pedidos de esclarecimento.
</p>
<p>
O Sr. Deputado <NAME>, quando iniciou a sua intervenção, fez um resumo dos diplomas que conjuntamente com o decreto-lei, cuja ratificação estamos a apreciar, existiam. Referiu concretamente o projecto de lei subscrito pelo PS, dizendo que tinha entrado em Março, o projecto de lei apresentado pela AD em Maio e depois o decreto-lei que o Governo elaborou ao abrigo da autorização legislativa que lhe foi concedida.
<br />
Pareceu, com isso, querer ocultar a existência anterior da proposta de lei da autoria do governo Sá Carneiro. De algum modo, deu a entender que a AD tinha vindo a correr sobre um projecto de lei apresentado pelo PS, apresentando ela própria, e 2 meses depois, um projecto de lei e que, ainda mais a correr, veio o Governo elaborar o seu decreto-lei.
<br />
É óbvio que, como já se disse, não foi assim. A regionalização está contemplada no Programa da AD e este governo até lhe dá prioridade. Portanto, é neste contexto que temos que examinar a situação.
<br />
Por outro lado, pareceu-nos também que o Sr. Deputado pretendeu aflorar uma certa crítica, acusando de inconstitucionalidade este diploma.
<br />
Eu não sou um constitucionalista. Todavia, ao ver o decreto-lei verifico que ele já foi promulgado pelo Sr. Presidente da República, o que, obviamente, me leva a crer que ele ouviu o parecer do órgão constitu-
</p>
</body>
<body>
<p>
1398
</p>
<p>
I SÉRIE - NÚMERO 35
</p>
<p>
cionalmente encarregue de averiguar da constitucionalidade das leis - o Conselho da Revolução - e que só depois o terá promulgado.
<br />
Isso levanta-me dúvidas. Por isso, peço ao Sr. Deputado <NAME> que me esclareça sobre a crítica ou a acusação de inconstitucionalidade do diploma que me pareceu ter feito.
</p>
<p>
O Sr. Presidente: - Tem a palavra o Sr. Deputado <NAME>.
</p>
<p>
O Sr. <NAME> (PCP) - Sr. Presidente, Srs. Deputados, na ausência do Sr. Ministro - que deve estar distribuindo cheques ...! - Sr. Secretário de Estado: Pedi a palavra para sossegar o Sr. Deputado <NAME> no sentido de lhe explicar o motivo, que depois, no decurso do debate, será ainda melhor aprofundado, do nosso voto contra o pedido de ratificação.
<br />
O Sr. Deputado <NAME> teve razão quando disse que mais parecia estarmos perante uma interpelação do que perante a discussão deste decreto-lei, porque este decreto-lei é uma das peças do sórdido mecanismo da AD para liquidar a autonomia do poder local em Portugal.
</p>
<p>
Vozes do PCP: - Muito bem!
</p>
<p>
O Orador: - E daí que o meu companheiro Anselmo Aníbal tivesse necessariamente de falar do projecto de revisão inconstitucional da AD nesta matéria; de falar da Lei das Finanças Locais, que já está pronta para acabar ,com a autonomia financeira dos municípios; da e lei pipeta, que dirá todos os anos o que irá ou não para o poder local em matéria de competência, de atribuições para os municípios - a bel-prazer da AD, como se esta estivesse muito tempo no Governo, é evidente!; da alteração à Lei n.º 79/77, que vai liquidar o carácter democrático de funcionamento dos órgãos de poder local, e por aí fora.
<br />
Desse modo, necessariamente que a intervenção do meu companheiro Anselmo Aníbal teria que ser como .foi e de ter o conteúdo que teve.
<br />
E é exactamente porque este decreto-lei é peça fundamental desse mecanismo mais global que nós iremos votar contra.
<br />
Todavia, Sr. <NAME>, devo recordar-lhe, por outro lado, quanto às críticas formuladas pelos partidos da AD, que da sua bancada só ouvi louvores ou só ouvi grande defesa do decreto-lei por parte do então Secretário de Estado, actual deputado e presidente da Comissão de Poder Local. Provavelmente, o PSD já antevia ou profetizava que o Sr. Deputado <NAME> regressaria muito rapidamente às bancadas do Parlamento, como regressou, dado que o Governo já caiu e muita água já correu debaixo das pontes.
<br />
E só ouvimos críticas a este decreto-lei da parte da bancada do CDS, concretamente da parte do Sr. Deputado <NAME>. Dispenso-me de ler algumas afirmações que fez contra o diploma e, mais, a esperança e convicção absoluta que tinha de que ele não seria publicado pela forma cromo foi - vírgula, ponto a ponto, ipsis verbis, igual!. Afinal, parece que o Governo não ouviu nada do que disse o CDS nesta matéria. Pelo menos na matéria do poder local, o CDS
</p>
<p>
não contou rigorosamente, nada, no tocante ao aspecto do associativismo municipal.
<br />
Sr. Deputado <NAME>, esteja sossegado; nós temos um requerimento para baixar o diploma à Comissão e temos numerosas alterações em relação ao problema do associativismo municipal.
<br />
Nós encaramos o associativismo municipal dentro de uma perspectiva de descentralização. Nós não querermos associações de municípios para roubar poderes aos municípios; queremos associações de municípios para resolver problemas concretos ã volta de determinadas áreas e zonas e em determinados .pontos do País; não queremos mais terminais, em que vocês são hábeis para roubar autonomia e poder aos municípios.
</p>
<p>
Vozes do PCP: - Muito bem!
</p>
<p>
Entretanto, reassumiu a presidência o Sr. Presidente <NAME>.
</p>
<p>
O Sr. <NAME> (PSD): -- Sr. Presidente, peço a palavra para fazer um protesto.
</p>
<p>
O Sr. Presidente: - Faça favor, Sr. Deputado.
</p>
<p>
O Sr. <NAME> (,PSD): - Sr. Presidente, Srs. Deputados: Nós, que temos autarcas e somos maioria num grande número de municípios deste país, e que felizmente temos também connosco a grande maioria do povo português - ainda não nos demonstraram que isso não é assim e estaremos aqui para discutir já este ano novas eleições -, estamos perfeitamente à vontade e estaremos na altura própria com a resposta que o povo saberá dar.
</p>
<p>
Aplausos do PSD.
</p>
<p>
No entanto, queria dizer ao Sr. Deputado que não roubamos coisa nenhuma aos municípios e que o decreto-lei que o Governo trouxe, também ele não roubou coisa nenhuma aos municípios. O que nós pretendemos foi dotar os municípios, tão depressa quanto possível, com a lei quadro da associação de municípios, de modo a que estes pudessem avançar com projectos que muitos deles, isoladamente, o não' poderiam fazer. E se a proposta de lei do Governo não foi agendada antes, não foi por culpa do Governo; foi por culpa desta Câmara e talvez por culpa de nós próprios, mas de vocês também. E se o projecto de lei do Partido Socialista também não avançou, não foi por culpa da AD, não foi por culpa do PSD. O que era necessário era levar aos municípios a legislação que eles há muito esperavam.
</p>
<p>
Aplausos do PSD.
</p>
<p>
O Sr. Presidente: ' Para uma intervenção, tem a palavra o Sr. Deputado <NAME>,
</p>
<p>
O Sr. <NAME> (MDP/CDE ): - Prescindo, Sr. Presidente.
</p>
<p>
O Sr. Presidente - Sendo assim, para uma intervenção, tem a palavra o Sr. Deputado <NAME>.
</p>
<p>
O Sr. <NAME> (PS): - Sr. Presidente, Srs. Deputados, Sr. Secretário de Estado:
</p>
</body>
<body>
<p>
9 DE ;JANEIRO DE 1982
</p>
<p>
1399
</p>
<p>
A análise do texto do Decreto - Lei n.º 266/81, de 15 de Setembro, faz ressaltar logo da leitura do prolegómeno a seguinte frase: "Na conjuntura político - administrativa decorrente da aplicação da Lei das Finanças Locais, torna-se imperioso dotar os municípios com instrumentos jurídicos."
</p>
<p>
Efectivamente, nós verificamos que este decreto-lei terá sido, em parte, congeminado dentro do contexto de encontrar uma saída para a Lei das Finanças Locais. E esta referência que aqui se faz, um pouco marginalmente à Lei das Finanças Locais, não tem outro entendimento.
</p>
<p>
De facto, se verificarmos o que se passa com o artigo 15.º, n.º 3, nós temos oportunidade de ler, também, que "na execução da política financeira do Governo poderão ser directamente afectados meios orçamentais a associações de municípios ou estabelecidas a favor destas linhas de crédito bonificado", o que não é outra coisa senão a ultrapassagem da Lei das Finanças Locais, que estabelece, muito taxativamente, que para os municípios serão feitas distribuições de acordo com o que a mesma lei determina.
</p>
<p>
Aqui, cria-se a possibilidade da excepção, uma vez que constituída a associação dos municípios o Governo, dentro do contexto da sua política financeira, deliberará dotar estas associações com verbas, consoante muito bem entender, de acordo com o livre arbítrio do Governo, o que é, para todos os efeitos, romper o equilíbrio e a estrutura da Lei das Finanças Locais. É, por conseguinte e para todos os efeitos, para inclusão deste pequeno número no artigo 15.º que, de algum modo, a apresentação deste decreto-lei deverá ser entendida.
</p>
<p>
Nós verificamos que, em grande parte, as associações de municípios, muito embora correspondam a uma necessidade inquestionável e a uma aspiração também efectivamente sentida, não encontraram ainda uma expressão real naquilo que até agora aconteceu no País. E não será por falta de uma lei quadro, como aqui se afirma, que não se permitirá que essas associações se constituam. As associações não se constituíam por razões de fundo que importaria analisar e que não cabe talvez aqui, no quadro deste debate, fazê-lo.
<br />
Nós temos várias críticas a formular à maneira como este articulado foi ordenado e concebido. Parece-nos que de algum modo ele é em muitos aspectos bastante canhestro e noutros perfeitamente desajustado à realidade que constitui a lei que determinou as competências dos órgãos dos municípios.
<br />
Verificamos antes de mais nada, que as assembleias municipais são completamente esquecidas e, por este processo, iremos criar um órgão que substituirá os municípios naqueles poderes que forem delegados para as associações, e estas passarão a funcionar, de ora em diante, sem qualquer espécie de controle por parte das assembleias municipais. Isto não se compreende muito bem: é como se constituísse dentro da área dos municípios associados um supermunicípio.
<br />
Pretendemos de algum modo remediar esta situação com as alterações que apresentamos, mas não podemos também deixar de reconhecer que nesta matéria houve inconsideração grave.
</p>
<p>
Também entendemos que no artigo 18.º é deixada uma abertura para a constituição de quadros no âmbito das associações - quadros a definir pela assembleia intermunicipal. Nada se diz, porém, sobre a forma de recrutamento e promoção dos funcionários que integrarão esses quadros nem do regime a que ficarão sujeitos.
</p>
<p>
Para obviar também a este inconveniente, pretendemos que sejam equiparados, para todos os efeitos, ao regime do funcionalismo público. E consideramos indispensável, pára que isto não se torne uma forma enviesada de, para associações de tempo limitado, permitir o enquadramento noutros sectores administrativos dos funcionários assim admitidos, que esses funcionários, caso as associações se dissolvam, venham a ser integrados no quadro geral de adidos.
</p>
<p>
Vozes do PS.- Muito bem!
</p>
<p>
O Sr. Presidente: - Tem a palavra o Sr. Deputado <NAME> para pedir esclarecimentos.
</p>
<p>
O Sr. <NAME> (PSD): - Sr. Presidente, Srs. Deputados, Sr. Secretário de Estado: Em relação á questão, do pessoal, embora de quadro próprio, parece-nos que será pessoal requisitado aos próprios quadros das autarquias, logo, pertencentes ao funcionalismo municipal. Não nos parece que daí advenha algum prejuízo ou que se vá inovar coisa alguma.
</p>
<p>
Perguntava ainda ao Sr. Deputado <NAME> se não existe já um decreto-lei sobre os investimentos intermunicipais sem que ninguém tivesse pedido a sua ratificação. Portanto, parece-me que o seu conteúdo é aquele que estaria de acordo com o sentir e o querer dos Srs. Deputados, uma vez que a oposição tem .pedido a ratificação de todos os diplomas que ao poder dizem respeito.
</p>
<p>
O Sr. Presidente: - Tem a palavra o Sr. Deputado <NAME> para responder, se assim o entender.
</p>
<p>
O Sr. <NAME> (PS): - Sr. Presidente, Srs. Deputados, Sr. Secretário de Estado: No que se refere à primeira questão, que se reporta ao problema do pessoal, o n.º 1 do artigo 18.º é uma norma genérica; ,porém, o seu n.º 2 é uma norma especial que permite a criação de quadros. Nós entendemos que, ,para estes quadros assim criados, o regime jurídico do pessoal, incluindo o ' respectivo recrutamento, selecção e provimento para o quadro próprio da associação, será idêntico ao estabelecido na lei .para o pessoal da administração local. Esta não referência é relativamente grave sob o nosso ponto de vista, dado que neste quadro, tal como está redigido, .podem ser criadas categorias que não estejam sujeitas a todos os critérios de selecção e provimento que a lei estabelece para os restantes funcionários.
<br />
E também entendemos que, no caso de a associação se dissolver, não serão estes funcionários assim promovidos que deverão entrar em igualdade de categorias e em concorrência com aqueles que já se encontram no quadro dos municípios.
<br />
No tocante às assembleias intermunicipais, uma coisa é o princípio de ordem geral outra é a prática
</p>
</body>
<body>
<p>
1400 I SÉRIE - NÚMERO 35
</p>
<p>
de que têm sido objecto. Nós, porém, não concordamos nem com o princípio nem com a prática, e é sobretudo alertados ,pela prática que pretendemos que esta disposição não seja aqui consagrada.
</p>
<p>
O Sr. Presidente:- Srs. Deputados: Estamos praticamente no limite do tempo regimental, de forma que vou encerrar a :sessão.
</p>
<p>
Anunciaria, entretanto, que a nossa próxima sessão será na terça-feira, dia 12, às 15 horas.
</p>
<p>
Conforme o acordo estabelecido na última Conferência dos Grupos Parlamentares, no período de antes da ordem do dia haverá apenas declarações políticas que se considerem especialmente importantes.
</p>
<p>
No período da ordem do dia teremos: na primeira parte, a apreciação do pedido de inquérito parlamentar ,n.º 10/II, apresentado pela ASDI, acerca da compra e venda de aviões; na segunda parte concluiremos a discussão e votação das ratificações n.ºs 99/II e 103/11. Os tempos disponíveis dos vários grupos parlamentares serão distribuídos pela Mesa no início da próximo sessão.
</p>
<p>
Está ainda agendada a ratificação n.º 92/II, que respeita à comercialização de cortiça, matéria acerca da qual foi acordado que, tanto o Governo como qualquer dos partidos e grupos parlamentares disporiam de 15 minutos.
</p>
<p>
Deu entrada na Mesa o pedido de ratificação n.º 119/II, subscrito pelos Srs. Deputados <NAME> e outros do Grupo Parlamentar do Partido Comunista, que incide sobre o Decreto - Lei n.º 352/81, de 28 de Dezembro, acerca do Estatuto da Ordem dos Engenheiros.
</p>
<p>
Deram também entrada na Mesa os .projectos de lei: n.º 292/11, apresentado pelo Grupo Parlamentar do Partido Socialista, referente à declaração de calamidade pública das zonas degradadas das freguesias de Sé e Miragaia, do concelho do Porto; n.º 293/11, apresentado pelo Grupo Parlamentar do CDS, respeitante a quadros privativos do pessoal de municípios.
</p>
<p>
Ambos vão baixar à Comissão da Administração Interna e Poder. Local.
<br />
Deu entrada ainda o projecto de lei n.º 294/11, subscrito por Srs. Deputados de todos os partidos, respeitante à amnistia e infracções disciplinares praticadas nos meios de comunicação social, referidos no n.º 3 do artigo 39.º da Constituição.
<br />
Está encerrada a sessão.
</p>
<p>
Eram 13 horas.
</p>
<p>
Entraram durante a sessão os seguinte' Srs. Deputados:
</p>
<p>
Partido Social - Democrata (PSD)
</p>
<p>
<NAME>. <NAME>. <NAME>. <NAME>. <NAME>. <NAME>. <NAME>. <NAME> <NAME>. Natália de <NAME>. <NAME>.
</p>
<p>
Partido Socialista (PS)
</p>
<p>
<NAME> <NAME>. <NAME>. <NAME>. <NAME>. <NAME>. <NAME>. <NAME>. <NAME>. <NAME>. Leonel <NAME>. <NAME>. <NAME>. <NAME>.
</p>
<p>
Centro Democrático Social (CDS)
</p>
<p>
<NAME>. <NAME>. <NAME>. <NAME>. <NAME>. <NAME>.
</p>
<p>
Partido Comunista Português (PCP)
</p>
<p>
<NAME>.
</p>
<p>
Partido Popular Monárquico (PPM)
</p>
<p>
<NAME> <NAME>.
</p>
<p>
Faltaram à sessão os seguintes Srs. Deputados:
</p>
<p>
Partido Social - Democrata (PSD)
</p>
<p>
<NAME>. <NAME>. Bernardino da Costa Pereira. <NAME>. Fernando dos Reis Condesso. Francisco de Sousa Tavares. <NAME>. João Vasco da Luz Botelho Paiva. Manuel da Costa Andrade. <NAME>alvão Machado. Virgílio Ant<NAME>.
</p>
<p>
Partido Socialista (PS)
</p>
<p>
<NAME>. <NAME>. <NAME>. <NAME>. Costa Candal. <NAME>. <NAME>. Francisco Mesquita Machado. <NAME>. Jú<NAME>. <NAME>. <NAME>. <NAME>. Parcídio Summavielle Soares. <NAME>.
</p>
<p>
Centro Democrático Social (CDS)
</p>
<p>
<NAME>. Francisco G. C<NAME>ira. Francisco <NAME> Falcão.
</p>
</body>
<body>
<p>
9 DE JANEIRO DE 1982 1401
</p>
<p>
<NAME>. <NAME>. <NAME>. <NAME>. <NAME>. <NAME>. <NAME>. <NAME>. <NAME>. <NAME>.
</p>
<p>
Partido Comunista Português (PCP)
<br />
<NAME>. Domingos <NAME>. <NAME>. <NAME>. <NAME>. <NAME>. Zita <NAME>abra Roseiro.
</p>
<p>
Partido Popular Monárquico (PPM)
<br />
<NAME>.
</p>
<p>
Acção Social - Democrata Independente (ASDI)
<br />
<NAME>.
</p>
<p>
União da Esquerda para a Democracia Socialista
<br />
(UEDS)
<br />
Antón<NAME>.
</p>
<p>
Movimento Democrático Português (MDP/CDE)
<br />
Ra<NAME> de Morais e Castro.
</p>
<p>
OS REDACTORES DE 1.º CLASSE, <NAME>
<br />
<NAME> - <NAME>.
</p>
</body>
|
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.example.sitam.models.proposal
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class DataProposal(
val created_at: String,
val id: Int,
val judul_proposal: String,
val konsentrasi: String,
val mahasiswa: String,
val nilai: Float,
val pembimbing: String,
val penguji: String,
val seminar: Int,
val status: String,
val tahun_pengajuan: Int,
val topik: String,
val updated_at: String
) : Parcelable
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.example.sitam.models.proposal
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class DataProposal(
val created_at: String,
val id: Int,
val judul_proposal: String,
val konsentrasi: String,
val mahasiswa: String,
val nilai: Float,
val pembimbing: String,
val penguji: String,
val seminar: Int,
val status: String,
val tahun_pengajuan: Int,
val topik: String,
val updated_at: String
) : Parcelable |
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:
COPY q2
FROM
'q2.tbl' DELIMITER '|';
COPY q2_supplier
FROM
'q2_supplier.tbl' DELIMITER '|';
COPY q3
FROM
'q3.tbl' 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 | 1 | COPY q2
FROM
'q2.tbl' DELIMITER '|';
COPY q2_supplier
FROM
'q2_supplier.tbl' DELIMITER '|';
COPY q3
FROM
'q3.tbl' DELIMITER '|';
|
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::path::PathBuf;
use stm32_metapac_gen::*;
fn main() {
let out_dir = PathBuf::from("out");
let data_dir = PathBuf::from("../../stm32-data/data");
let chips = std::fs::read_dir(data_dir.join("chips"))
.unwrap()
.filter_map(|res| res.unwrap().file_name().to_str().map(|s| s.to_string()))
.filter(|s| s.ends_with(".yaml"))
.filter(|s| !s.starts_with("STM32L1")) // cursed gpio stride
.map(|s| s.strip_suffix(".yaml").unwrap().to_string())
.collect();
gen(Options {
out_dir,
data_dir,
chips,
})
}
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::path::PathBuf;
use stm32_metapac_gen::*;
fn main() {
let out_dir = PathBuf::from("out");
let data_dir = PathBuf::from("../../stm32-data/data");
let chips = std::fs::read_dir(data_dir.join("chips"))
.unwrap()
.filter_map(|res| res.unwrap().file_name().to_str().map(|s| s.to_string()))
.filter(|s| s.ends_with(".yaml"))
.filter(|s| !s.starts_with("STM32L1")) // cursed gpio stride
.map(|s| s.strip_suffix(".yaml").unwrap().to_string())
.collect();
gen(Options {
out_dir,
data_dir,
chips,
})
}
|
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 storage
import (
"context"
"database/sql"
"time"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"github.com/pkg/errors"
)
type Postgres struct {
dbx *sqlx.DB
}
func NewPostgres(connectURL string) (*Postgres, error) {
db, err := sqlx.Open("postgres", connectURL)
if err != nil {
return nil, errors.Wrap(err, "failed to create a DB connector")
}
// Retry connecting up to 10 times
for i := 0; i < 10; i++ {
err = db.Ping()
if err == nil {
return &Postgres{dbx: db}, nil
}
time.Sleep(time.Second)
}
return nil, errors.Wrap(err, "failed to connect to DB")
}
var loadQuery = `
SELECT u.url
FROM urls u
JOIN links l
ON l.urlID = u.id
WHERE l.link = $1;
`
func (p *Postgres) Load(ctx context.Context, rawShort string) (string, error) {
short, err := sanitizeShort(rawShort)
if err != nil {
return "", err
}
var url string
switch err := p.dbx.GetContext(ctx, &url, loadQuery, short); err {
case nil:
return url, nil
case sql.ErrNoRows:
return "", ErrShortNotSet
default:
return "", errors.Wrap(err, "load from DB failed")
}
}
var saveURLQuery = `
INSERT INTO urls(url)
VALUES (:url)
ON CONFLICT DO NOTHING;
`
var saveLinkQuery = `
WITH url_id AS (
SELECT id
FROM urls
WHERE url = :url
)
INSERT INTO links (link, urlID)
VALUES
(:link, (SELECT id FROM url_id))
ON CONFLICT (link)
DO UPDATE
SET urlID = (SELECT id FROM url_id)
WHERE links.link = :link
;
`
func saveLink(ctx context.Context, dbx *sqlx.DB, short string, url string) error {
tx, err := dbx.BeginTxx(ctx, nil)
if err != nil {
return errors.Wrap(err, "failed to start transaction")
}
if _, err := tx.NamedExecContext(
ctx,
saveURLQuery,
&struct{ URL string }{url},
); err != nil {
return errors.Wrap(err, "failed to insert url")
}
if _, err := tx.NamedExecContext(ctx,
saveLinkQuery,
&struct {
Link string
URL string
}{short, url},
); err != nil {
return errors.Wrap(err, "failed to insert short")
}
if er
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 storage
import (
"context"
"database/sql"
"time"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"github.com/pkg/errors"
)
type Postgres struct {
dbx *sqlx.DB
}
func NewPostgres(connectURL string) (*Postgres, error) {
db, err := sqlx.Open("postgres", connectURL)
if err != nil {
return nil, errors.Wrap(err, "failed to create a DB connector")
}
// Retry connecting up to 10 times
for i := 0; i < 10; i++ {
err = db.Ping()
if err == nil {
return &Postgres{dbx: db}, nil
}
time.Sleep(time.Second)
}
return nil, errors.Wrap(err, "failed to connect to DB")
}
var loadQuery = `
SELECT u.url
FROM urls u
JOIN links l
ON l.urlID = u.id
WHERE l.link = $1;
`
func (p *Postgres) Load(ctx context.Context, rawShort string) (string, error) {
short, err := sanitizeShort(rawShort)
if err != nil {
return "", err
}
var url string
switch err := p.dbx.GetContext(ctx, &url, loadQuery, short); err {
case nil:
return url, nil
case sql.ErrNoRows:
return "", ErrShortNotSet
default:
return "", errors.Wrap(err, "load from DB failed")
}
}
var saveURLQuery = `
INSERT INTO urls(url)
VALUES (:url)
ON CONFLICT DO NOTHING;
`
var saveLinkQuery = `
WITH url_id AS (
SELECT id
FROM urls
WHERE url = :url
)
INSERT INTO links (link, urlID)
VALUES
(:link, (SELECT id FROM url_id))
ON CONFLICT (link)
DO UPDATE
SET urlID = (SELECT id FROM url_id)
WHERE links.link = :link
;
`
func saveLink(ctx context.Context, dbx *sqlx.DB, short string, url string) error {
tx, err := dbx.BeginTxx(ctx, nil)
if err != nil {
return errors.Wrap(err, "failed to start transaction")
}
if _, err := tx.NamedExecContext(
ctx,
saveURLQuery,
&struct{ URL string }{url},
); err != nil {
return errors.Wrap(err, "failed to insert url")
}
if _, err := tx.NamedExecContext(ctx,
saveLinkQuery,
&struct {
Link string
URL string
}{short, url},
); err != nil {
return errors.Wrap(err, "failed to insert short")
}
if err := tx.Commit(); err != nil {
return errors.Wrap(err, "SaveName transaction failed")
}
return nil
}
func (p *Postgres) SaveName(ctx context.Context, rawShort string, url string) error {
short, err := sanitizeShort(rawShort)
if err != nil {
return err
}
if _, err := validateURL(url); err != nil {
return err
}
return saveLink(ctx, p.dbx, short, url)
}
|
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 Fragaria
import WebKit
extension SMLTextView {
fileprivate struct AssociatedKeys {
static var optionClickPopover = "org.cocoapods.CocoaPods.optionClickPopover"
static var selectedPodRange = "org.cocoapods.CocoaPods.selectedPodRange"
static var hoveredPodRange = "org.cocoapods.CocoaPods.hoveredPodRange"
static var optionKeyDown = "org.cocoapods.CocoaPods.optionKeyDown"
}
var optionClickPopover: NSPopover? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.optionClickPopover) as? NSPopover
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.optionClickPopover, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// The pod name range where the NSPopover currently is
var selectedPodRange: NSRange? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.selectedPodRange) as? NSRange
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.selectedPodRange, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// The pod name range currently hovered with option key down (excluding when that range is the same
// as the one where the popover is)
var hoveredPodRange: NSRange? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.hoveredPodRange) as? NSRange
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.hoveredPodRange, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var isOptionKeyDown: Bool {
get {
return (objc_getAssociatedObject(self, &AssociatedKeys.optionKeyDown) as? Bool) ?? false
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.optionKeyDown, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
open override func mouseMoved(with theEvent: NSEvent) {
super.mouseMoved(with: theEvent)
guard theEvent.modifierFlags.contains(NSEvent.ModifierFlags.option) else {
return
}
processPodMouseHover()
}
open override func mouseDown(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>"
| swift | 2 | import Fragaria
import WebKit
extension SMLTextView {
fileprivate struct AssociatedKeys {
static var optionClickPopover = "org.cocoapods.CocoaPods.optionClickPopover"
static var selectedPodRange = "org.cocoapods.CocoaPods.selectedPodRange"
static var hoveredPodRange = "org.cocoapods.CocoaPods.hoveredPodRange"
static var optionKeyDown = "org.cocoapods.CocoaPods.optionKeyDown"
}
var optionClickPopover: NSPopover? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.optionClickPopover) as? NSPopover
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.optionClickPopover, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// The pod name range where the NSPopover currently is
var selectedPodRange: NSRange? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.selectedPodRange) as? NSRange
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.selectedPodRange, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// The pod name range currently hovered with option key down (excluding when that range is the same
// as the one where the popover is)
var hoveredPodRange: NSRange? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.hoveredPodRange) as? NSRange
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.hoveredPodRange, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var isOptionKeyDown: Bool {
get {
return (objc_getAssociatedObject(self, &AssociatedKeys.optionKeyDown) as? Bool) ?? false
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.optionKeyDown, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
open override func mouseMoved(with theEvent: NSEvent) {
super.mouseMoved(with: theEvent)
guard theEvent.modifierFlags.contains(NSEvent.ModifierFlags.option) else {
return
}
processPodMouseHover()
}
open override func mouseDown(with theEvent: NSEvent) {
super.mouseDown(with: theEvent)
guard theEvent.modifierFlags.contains(NSEvent.ModifierFlags.option) else {
return
}
quickLook(with: theEvent)
}
open override func quickLook(with event: NSEvent) {
guard let pod = checkForPodNameBelowMouseLocation() else {
optionClickPopover?.close()
return
}
hoveredPodRange = nil
showPodPopover(forPodWithName: pod.podName, atRange: pod.location)
updateUnderlineStyle(forPodAtRange: pod.location)
selectedPodRange = pod.location
}
open override func flagsChanged(with theEvent: NSEvent) {
if theEvent.modifierFlags.contains(NSEvent.ModifierFlags.option) {
processPodMouseHover()
isOptionKeyDown = true
} else if isOptionKeyDown {
removeUnderlineStyle(forPodAtRange: hoveredPodRange)
hoveredPodRange = nil
isOptionKeyDown = false
}
super.flagsChanged(with: theEvent)
}
fileprivate func processPodMouseHover() {
removeUnderlineStyle(forPodAtRange: hoveredPodRange)
hoveredPodRange = nil
guard let pod = checkForPodNameBelowMouseLocation() else {
return
}
updateUnderlineStyle(forPodAtRange: pod.location)
if selectedPodRange == nil || selectedPodRange!.location != pod.location.location {
hoveredPodRange = pod.location
}
}
fileprivate func checkForPodNameBelowMouseLocation() -> (podName: String, location: NSRange)? {
let hoveredCharIndex = characterIndex(for: NSEvent.mouseLocation)
let lineRange = (string as NSString).lineRange(for: NSRange(location: hoveredCharIndex, length: 0))
let line = (string as NSString).substring(with: lineRange)
let hoveredCharLineIndex = hoveredCharIndex - lineRange.location
guard let hoveredChar = (line as NSString).substring(from: hoveredCharLineIndex).characters.first, hoveredChar != "\n" && hoveredChar != "'" && hoveredChar != "\"" && hoveredCharLineIndex > 0 else {
return nil
}
var podStartIndex = -1, podEndIndex = -1
// Starting at the mouse location...
// Iterate to the right of the text line in search of the first occurrence of a " or '
// →
let rightSideRange = NSRange(location: hoveredCharLineIndex, length: line.characters.count - hoveredCharLineIndex)
for (index, char) in (line as NSString).substring(with: rightSideRange).characters.enumerated() {
if char == "'" || char == "\"" {
podEndIndex = hoveredCharLineIndex + index
break
}
}
// Iterate to the left of the text line in search of the first occurence of a " or '
// ←
let leftSideRange = NSRange(location: 0, length: hoveredCharLineIndex)
for (index, char) in (line as NSString).substring(with: leftSideRange).characters.reversed().enumerated() {
if char == "'" || char == "\"" {
podStartIndex = hoveredCharLineIndex - index
break
}
}
guard podStartIndex >= 0 && podEndIndex >= 0 &&
(line as NSString).substring(with: NSRange(location: 0, length: podStartIndex - 1)).trim().hasSuffix("pod") else {
return nil
}
// We need to update the cursor to be inside the pod name so the `autoCompleteDelegate`
// gets the autocompletions from the `CPPodfileEditorViewController`
setSelectedRange(NSRange(location: hoveredCharIndex, length: 0))
let podName = (line as NSString).substring(with: NSRange(location: podStartIndex, length: podEndIndex - podStartIndex))
guard let _ = autoCompleteDelegate.completions().index(where: { ($0 as? String) == podName }) else {
return nil
}
let podNameRange = NSRange(location: lineRange.location + podStartIndex, length: podEndIndex - podStartIndex)
return (podName, podNameRange)
}
fileprivate func updateUnderlineStyle(forPodAtRange range: NSRange) {
textStorage?.beginEditing()
textStorage?.addAttributes([
NSAttributedStringKey.underlineStyle: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue as Int),
NSAttributedStringKey.underlineColor: CPFontAndColourGateKeeper().cpLinkRed
], range: range)
textStorage?.endEditing()
}
fileprivate func removeUnderlineStyle(forPodAtRange range: NSRange?) {
guard let range = range else { return }
textStorage?.beginEditing()
textStorage?.removeAttribute(NSAttributedStringKey.underlineStyle, range: range)
textStorage?.endEditing()
}
fileprivate func resetUnderlineStyles() {
removeUnderlineStyle(forPodAtRange: hoveredPodRange)
hoveredPodRange = nil
removeUnderlineStyle(forPodAtRange: selectedPodRange)
selectedPodRange = nil
}
fileprivate func showPodPopover(forPodWithName podName: String, atRange: NSRange) {
guard let window = window,
let podURL = URL(string: "https://cocoapods.org/pods/\(podName)") else {
return
}
let customCSSFilePath = (Bundle.main.resourcePath)! + "/CocoaPods.css"
optionClickPopover?.close()
let webView = WebView(frame: NSRect(x: 0, y: 0, width: 320, height: 350))
webView.wantsLayer = true
webView.policyDelegate = self
webView.preferences.userStyleSheetEnabled = true
webView.preferences.userStyleSheetLocation = URL(fileURLWithPath: customCSSFilePath)
webView.mainFrame.load(URLRequest(url: podURL))
let popoverViewController = NSViewController()
popoverViewController.view = webView
var podNameRect = firstRect(forCharacterRange: atRange, actualRange: nil)
podNameRect = window.convertFromScreen(podNameRect)
podNameRect = convert(podNameRect, to: nil)
podNameRect.size.width = 1
// We use the width of the range starting at the beginning of the line until the middle of the pod name
// as the x coordinate for the popover (the popover is always centered to the pod name, no matter
// where the option-click/three finger tap occurred)
let lineRange = (string as NSString).lineRange(for: atRange)
let startToMiddlePodRange =
NSRange(location: lineRange.location,
length: atRange.location - lineRange.location + atRange.length / 2 + (atRange.length % 2 == 0 ? 0 : 1))
podNameRect.origin.x = firstRect(forCharacterRange: startToMiddlePodRange, actualRange: nil).width
let popover = NSPopover()
popover.contentViewController = popoverViewController
popover.behavior = .transient
popover.delegate = self
popover.show(relativeTo: podNameRect, of: self, preferredEdge: .maxY)
optionClickPopover = popover
}
open override func shouldChangeText(in affectedCharRange: NSRange, replacementString: String?) -> Bool {
resetUnderlineStyles()
return super.shouldChangeText(in: affectedCharRange, replacementString: replacementString)
}
}
// MARK: - NSPopoverDelegate
extension SMLTextView: NSPopoverDelegate {
public func popoverWillClose(_ notification: Notification) {
resetUnderlineStyles()
}
}
// MARK: - WebPolicyDelegate
extension SMLTextView: WebPolicyDelegate {
public func webView(_ webView: WebView!, decidePolicyForNavigationAction actionInformation: [AnyHashable: Any]!,
request: URLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) {
if let _ = actionInformation?[WebActionElementKey],
let externalURL = actionInformation[WebActionOriginalURLKey] as? URL {
// An action has ocurred (link click): redirect the user to the browser
listener.ignore()
NSWorkspace.shared.open(externalURL)
} else {
// Loading the CocoaPods pod page: accept
listener.use()
}
}
}
|
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 APP_PARAM_HPP
#define APP_PARAM_HPP
#ifndef APP_PARAM_ID_BASE
#define APP_PARAM_ID_BASE 0x10000000
#endif
#ifndef IDLE_TASK_PARAM_ID_BASE
#define IDLE_TASK_PARAM_ID_BASE APP_PARAM_ID_BASE + 0x100
#endif
#ifndef IDLE_TASK_PWR_ON_RESET_CNT_PARAM
#define IDLE_TASK_PWR_ON_RESET_CNT_PARAM IDLE_TASK_PARAM_ID_BASE + 0x0
#endif
#endif //APP_PARAM_HPP
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 APP_PARAM_HPP
#define APP_PARAM_HPP
#ifndef APP_PARAM_ID_BASE
#define APP_PARAM_ID_BASE 0x10000000
#endif
#ifndef IDLE_TASK_PARAM_ID_BASE
#define IDLE_TASK_PARAM_ID_BASE APP_PARAM_ID_BASE + 0x100
#endif
#ifndef IDLE_TASK_PWR_ON_RESET_CNT_PARAM
#define IDLE_TASK_PWR_ON_RESET_CNT_PARAM IDLE_TASK_PARAM_ID_BASE + 0x0
#endif
#endif //APP_PARAM_HPP
|
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 main
import (
"encoding/json"
"fmt"
"github.com/go-gulfstream/gulfstream/pkg/event"
"github.com/google/uuid"
)
const orderStream = "order"
var owner = uuid.New()
var streamID = uuid.New()
type order struct {
ShopID uuid.UUID
Items []OrderItem
Total int
Activate bool
}
func (o *order) String() string {
return fmt.Sprintf("order{ShopID:%s, activate:%v, total:%d, items:%v}",
o.ShopID, o.Activate, o.Total, o.Items,
)
}
func (o *order) MarshalBinary() ([]byte, error) {
return json.Marshal(o)
}
func (o *order) UnmarshalBinary(data []byte) error {
return json.Unmarshal(data, o)
}
func (o *order) Mutate(e *event.Event) {
switch e.Name() {
case activatedEvent:
o.Activate = true
case addedToCartEvent:
payload := e.Payload().(*addedToCart)
o.ShopID = payload.ShopID
o.Total = payload.Total
o.Items = append(o.Items, OrderItem{
Name: payload.Name,
Price: payload.Price,
})
}
}
type OrderItem struct {
Name string
Price float64
}
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 | 1 | package main
import (
"encoding/json"
"fmt"
"github.com/go-gulfstream/gulfstream/pkg/event"
"github.com/google/uuid"
)
const orderStream = "order"
var owner = uuid.New()
var streamID = uuid.New()
type order struct {
ShopID uuid.UUID
Items []OrderItem
Total int
Activate bool
}
func (o *order) String() string {
return fmt.Sprintf("order{ShopID:%s, activate:%v, total:%d, items:%v}",
o.ShopID, o.Activate, o.Total, o.Items,
)
}
func (o *order) MarshalBinary() ([]byte, error) {
return json.Marshal(o)
}
func (o *order) UnmarshalBinary(data []byte) error {
return json.Unmarshal(data, o)
}
func (o *order) Mutate(e *event.Event) {
switch e.Name() {
case activatedEvent:
o.Activate = true
case addedToCartEvent:
payload := e.Payload().(*addedToCart)
o.ShopID = payload.ShopID
o.Total = payload.Total
o.Items = append(o.Items, OrderItem{
Name: payload.Name,
Price: payload.Price,
})
}
}
type OrderItem struct {
Name string
Price float64
}
|
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:
# 约定
- 只有在练习时可以使用电脑,其他时间不需要
- 不需要记笔记,资料随后会分享出来
- 手机静音
- 请随时提问
- 语速太快、慢、大、小,请随时提醒
- 请大家遵守课堂纪律
# Basic Tools
## Git
- 一个分布式版本控制系统
- 最初由<NAME>在2005年设计开发
- Centralized Version Control Systems

- Distributed Version Control Systems

### Why Git
- 几乎所有操作都在本地
- 快速
- 小步提交的绝配
- 备份
- 直接记录快照,而非差异比较

- 轻量级的分支
Note: 完整历史 提交
### Install
http://msysgit.github.io/
### Basics
- 获取 Git 仓库
- `$ git init`
- `$ git clone`
Note: 一边演示一边操作
- 跟踪新文件
- `$ git add`
- 检查当前文件状态
- `$ git status`
- 暂存已修改文件
- `$ git add`
- 三种状态
- 已提交(committed)
- 已修改(modified)
- 已暂存(staged)

Note: 介绍三个区域及其流转顺序,在这个过程中对应的状态
- 提交更新
- `$ git commit`
- 查看提交历史
- `$ git log`
- `$ git log --oneline --decorate --color --graph`
### Exercise git basics
- Fork http://code.huawei.com/qixi/prs-capability.git
- `$ git clone`
- `$ git add`
- `$ git status`
- `$ git commit`
- `$ git log`
### config
- `$ git config --global user.name "<NAME>"`
- `$ git config --global user.email <EMAIL>`
- `$ git config --list`
### remote
- `$ git remote -v`
- `$ git fetch`
- `$ git pull`
- `$ git push`
Note: git pull = git fetch + git merge
### branch

- `$ git branch iss53`
- `$ git checkout iss53`
- `$ git branch`
Note: 如何创建一个分支
### merge

- `$ git checkout master`
- `$ git merge iss53`
- `$ git branch -d iss53`
### git-svn
- `$ git svn clone http://svn.example.com/project/trunk`
- `$ git svn rebase`
- `$ git svn dcommit`
Note: 可以用git操作svn仓库
## GitLab
一个利用 Ruby on Rails 开发的开源应用程序,实现一个自托管的Git项目仓库,可通过Web界面进行访问公开的或者私人项目。
### Code Club

- Distributed Version Control Systems

### Why Git
- 几乎所有操作都在本地
- 快速
- 小步提交的绝配
- 备份
- 直接记录快照,而非差异比较

- 轻量级的分支
Note: 完整历史 提交
### Install
http://msysgit.github.io/
### Basics
- 获取 Git 仓库
- `$ git init`
- `$ git clone`
Note: 一边演示一边操作
- 跟踪新文件
- `$ git add`
- 检查当前文件状态
- `$ git status`
- 暂存已修改文件
- `$ git add`
- 三种状态
- 已提交(committed)
- 已修改(modified)
- 已暂存(staged)

Note: 介绍三个区域及其流转顺序,在这个过程中对应的状态
- 提交更新
- `$ git commit`
- 查看提交历史
- `$ git log`
- `$ git log --oneline --decorate --color --graph`
### Exercise git basics
- Fork http://code.huawei.com/qixi/prs-capability.git
- `$ git clone`
- `$ git add`
- `$ git status`
- `$ git commit`
- `$ git log`
### config
- `$ git config --global user.name "<NAME>"`
- `$ git config --global user.email <EMAIL>`
- `$ git config --list`
### remote
- `$ git remote -v`
- `$ git fetch`
- `$ git pull`
- `$ git push`
Note: git pull = git fetch + git merge
### branch

- `$ git branch iss53`
- `$ git checkout iss53`
- `$ git branch`
Note: 如何创建一个分支
### merge

- `$ git checkout master`
- `$ git merge iss53`
- `$ git branch -d iss53`
### git-svn
- `$ git svn clone http://svn.example.com/project/trunk`
- `$ git svn rebase`
- `$ git svn dcommit`
Note: 可以用git操作svn仓库
## GitLab
一个利用 Ruby on Rails 开发的开源应用程序,实现一个自托管的Git项目仓库,可通过Web界面进行访问公开的或者私人项目。
### Code Club

### Merge/pull requests
- fork
- clone
- commit
- push
- merge request
Note: 动手演示
### Exercise Merge Requests
Note: 练习Merge Request,把刚才演示自己做一遍。改动内容是把自己和pair的邮箱作为文件名。
## IDE
### IntelliJ IDEA
- <https://www.jetbrains.com/idea/>
- bin/idea.exe.vmoptions `-Xmx1024m`
## Maven
- 2002年发布 (Ant in 2000)
- 约定 (Ant write all the commands)
- XML
- pom.xml
```xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.huawei</groupId>
<artifactId>basic-tools</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<version>1.1</version>
</plugin>
</plugins>
</build>
</project>
```
Note: XML的配置还是比较长的
## Gradle
- 2007年发布
- DSL Groovy
- Android
- build.gradle
```
apply plugin: 'java'
compileJava.options.encoding = 'UTF-8'
compileTestJava.options.encoding = 'UTF-8'
```
- build.gradle
```
apply plugin: 'jetty’
apply plugin: 'findbugs'
apply plugin: 'jacoco'
compileJava.options.encoding = 'UTF-8'
compileTestJava.options.encoding = 'UTF-8'
dependencies {
compile "org.springframework:spring-web:3.2.4.RELEASE”
}
findbugs {
ignoreFailures = true
excludeFilter = file("myExcludeFilter.xml")
}
test {
jacoco {
excludes = ['*_javassist_*']
}
}
```
Note: 采用DSL后配置明显简介了
## sbt
- Simple Build Tool
- 增量编译
- 拥有交互shell
- Scala
- DSL
build.sbt
```scala
lazy val root = (project in file(".")).
settings(
name := "hello",
version := "1.0",
scalaVersion := "2.11.4"
)
```
目录结构
```
src/
main/
resources/
<files to include in main jar here>
scala/
<main Scala sources>
java/
<main Java sources>
test/
resources
<files to include in test jar here>
scala/
<test Scala sources>
java/
<test Java sources>
```
src/main/scala/Hi.scala
```scala
object Hi {
def main(args: Array[String]) = println("Hi!")
}
```
`$ sbt run`
### Exercise sbt and IntelliJ IDEA
- build.sbt
```scala
lazy val root = (project in file(".")).
settings(
name := "hello",
version := "1.0",
scalaVersion := "2.11.4"
)
```
- src/main/scala/Hi.scala
```scala
object Hi {
def main(args: Array[String]) = println("Hi!")
}
```
- `sbt run`
- IntelliJ IDEA Import Project
## 课后练习
https://github.com/numbbbbb/progit-zh-pdf-epub-mobi
阅读前3章,下次培训时为大家讲解rebase操作。 |
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 DogSerializer < ActiveModel::Serializer
attributes :name, :position, :id
attribute :owner do
object.owner.name
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 | class DogSerializer < ActiveModel::Serializer
attributes :name, :position, :id
attribute :owner do
object.owner.name
end
end
|
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:
//used in the command plugin because thats the only place where sender is used
// check if sender is player
if (!(sender instanceof Player)) {
CommandAPI.fail(ReturnError.ErrorMessage(ErrorType.noPlayer, "en_us"));
return 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>"
| java | 2 | //used in the command plugin because thats the only place where sender is used
// check if sender is player
if (!(sender instanceof Player)) {
CommandAPI.fail(ReturnError.ErrorMessage(ErrorType.noPlayer, "en_us"));
return 0;
} |
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:
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
//
// @generated SignedSource<<fb5ff079a89c68380480970d4f614b8b>>
//
// To regenerate this file, run:
// hphp/hack/src/oxidized_regen.sh
use arena_trait::TrivialDrop;
use eq_modulo_pos::EqModuloPos;
use no_pos_hash::NoPosHash;
use ocamlrep::FromOcamlRepIn;
use ocamlrep::ToOcamlRep;
use ocamlrep_caml_builtins::Int64;
pub use oxidized::file_info::Mode;
pub use oxidized::file_info::NameType;
pub use prim_defs::*;
use serde::Deserialize;
use serde::Serialize;
#[allow(unused_imports)]
use crate::*;
/// We define two types of positions establishing the location of a given name:
/// a Full position contains the exact position of a name in a file, and a
/// File position contains just the file and the type of toplevel entity,
/// allowing us to lazily retrieve the name's exact location if necessary.
#[derive(
Clone,
Copy,
Debug,
Deserialize,
Eq,
FromOcamlRepIn,
Hash,
NoPosHash,
Ord,
PartialEq,
PartialOrd,
Serialize,
ToOcamlRep
)]
#[rust_to_ocaml(attr = "deriving (eq, show)")]
#[repr(C, u8)]
pub enum Pos<'a> {
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
Full(&'a pos::Pos<'a>),
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
#[rust_to_ocaml(inline_tuple)]
File(
&'a (
oxidized::file_info::NameType,
&'a relative_path::RelativePath<'a>,
),
),
}
impl<'a> TrivialDrop for Pos<'a> {}
arena_deserializer::impl_deserialize_in_arena!(Pos<'arena>);
/// An id contains a pos, name and a optional decl hash. The decl hash is None
/// only in the case when we didn't compute it for performance reasons
#[derive(
Clone,
Debug,
Deserialize,
Eq,
FromOcamlRepIn,
Hash,
NoPosHash,
Ord,
PartialEq,
PartialOrd,
Serialize,
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 | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
//
// @generated SignedSource<<fb5ff079a89c68380480970d4f614b8b>>
//
// To regenerate this file, run:
// hphp/hack/src/oxidized_regen.sh
use arena_trait::TrivialDrop;
use eq_modulo_pos::EqModuloPos;
use no_pos_hash::NoPosHash;
use ocamlrep::FromOcamlRepIn;
use ocamlrep::ToOcamlRep;
use ocamlrep_caml_builtins::Int64;
pub use oxidized::file_info::Mode;
pub use oxidized::file_info::NameType;
pub use prim_defs::*;
use serde::Deserialize;
use serde::Serialize;
#[allow(unused_imports)]
use crate::*;
/// We define two types of positions establishing the location of a given name:
/// a Full position contains the exact position of a name in a file, and a
/// File position contains just the file and the type of toplevel entity,
/// allowing us to lazily retrieve the name's exact location if necessary.
#[derive(
Clone,
Copy,
Debug,
Deserialize,
Eq,
FromOcamlRepIn,
Hash,
NoPosHash,
Ord,
PartialEq,
PartialOrd,
Serialize,
ToOcamlRep
)]
#[rust_to_ocaml(attr = "deriving (eq, show)")]
#[repr(C, u8)]
pub enum Pos<'a> {
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
Full(&'a pos::Pos<'a>),
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
#[rust_to_ocaml(inline_tuple)]
File(
&'a (
oxidized::file_info::NameType,
&'a relative_path::RelativePath<'a>,
),
),
}
impl<'a> TrivialDrop for Pos<'a> {}
arena_deserializer::impl_deserialize_in_arena!(Pos<'arena>);
/// An id contains a pos, name and a optional decl hash. The decl hash is None
/// only in the case when we didn't compute it for performance reasons
#[derive(
Clone,
Debug,
Deserialize,
Eq,
FromOcamlRepIn,
Hash,
NoPosHash,
Ord,
PartialEq,
PartialOrd,
Serialize,
ToOcamlRep
)]
#[rust_to_ocaml(attr = "deriving (eq, show)")]
#[repr(C)]
pub struct Id<'a>(
#[serde(deserialize_with = "arena_deserializer::arena", borrow)] pub Pos<'a>,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)] pub &'a str,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)] pub Option<&'a Int64>,
);
impl<'a> TrivialDrop for Id<'a> {}
arena_deserializer::impl_deserialize_in_arena!(Id<'arena>);
#[derive(
Clone,
Debug,
Deserialize,
Eq,
EqModuloPos,
FromOcamlRepIn,
Hash,
NoPosHash,
Ord,
PartialEq,
PartialOrd,
Serialize,
ToOcamlRep
)]
#[rust_to_ocaml(attr = "deriving eq")]
#[repr(C)]
pub struct HashType<'a>(
#[serde(deserialize_with = "arena_deserializer::arena", borrow)] pub Option<&'a Int64>,
);
impl<'a> TrivialDrop for HashType<'a> {}
arena_deserializer::impl_deserialize_in_arena!(HashType<'arena>);
/// The record produced by the parsing phase.
#[derive(
Clone,
Debug,
Deserialize,
Eq,
FromOcamlRepIn,
Hash,
NoPosHash,
Ord,
PartialEq,
PartialOrd,
Serialize,
ToOcamlRep
)]
#[rust_to_ocaml(attr = "deriving show")]
#[repr(C)]
pub struct FileInfo<'a> {
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub hash: &'a HashType<'a>,
pub file_mode: Option<oxidized::file_info::Mode>,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub funs: &'a [&'a Id<'a>],
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub classes: &'a [&'a Id<'a>],
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub typedefs: &'a [&'a Id<'a>],
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub consts: &'a [&'a Id<'a>],
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub modules: &'a [&'a Id<'a>],
/// None if loaded from saved state
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub comments: Option<&'a [(&'a pos::Pos<'a>, Comment<'a>)]>,
}
impl<'a> TrivialDrop for FileInfo<'a> {}
arena_deserializer::impl_deserialize_in_arena!(FileInfo<'arena>);
pub use oxidized::file_info::Names;
/// The simplified record stored in saved-state.
#[derive(
Clone,
Debug,
Deserialize,
Eq,
FromOcamlRepIn,
Hash,
NoPosHash,
Ord,
PartialEq,
PartialOrd,
Serialize,
ToOcamlRep
)]
#[rust_to_ocaml(prefix = "sn_")]
#[repr(C)]
pub struct SavedNames<'a> {
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub funs: s_set::SSet<'a>,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub classes: s_set::SSet<'a>,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub types: s_set::SSet<'a>,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub consts: s_set::SSet<'a>,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub modules: s_set::SSet<'a>,
}
impl<'a> TrivialDrop for SavedNames<'a> {}
arena_deserializer::impl_deserialize_in_arena!(SavedNames<'arena>);
#[derive(
Clone,
Debug,
Deserialize,
Eq,
FromOcamlRepIn,
Hash,
NoPosHash,
Ord,
PartialEq,
PartialOrd,
Serialize,
ToOcamlRep
)]
#[repr(C)]
pub struct Diff<'a> {
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub removed_funs: s_set::SSet<'a>,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub added_funs: s_set::SSet<'a>,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub removed_classes: s_set::SSet<'a>,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub added_classes: s_set::SSet<'a>,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub removed_types: s_set::SSet<'a>,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub added_types: s_set::SSet<'a>,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub removed_consts: s_set::SSet<'a>,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub added_consts: s_set::SSet<'a>,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub removed_modules: s_set::SSet<'a>,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)]
pub added_modules: s_set::SSet<'a>,
}
impl<'a> TrivialDrop for Diff<'a> {}
arena_deserializer::impl_deserialize_in_arena!(Diff<'arena>);
|
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.gram.color_android.network.set
enum class WriteSet {
WRITE_SUCCESS,
WRITE_FAIL,
UPDATE_SUCCESS,
UPDATE_FAIL
}
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.gram.color_android.network.set
enum class WriteSet {
WRITE_SUCCESS,
WRITE_FAIL,
UPDATE_SUCCESS,
UPDATE_FAIL
} |
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">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<title>Var att beställa Tenormin Kroatien - Brmethods.github.io</title>
<link rel="stylesheet" href="bootstrap.min.css">
<link rel="stylesheet" href="ie10-viewport-bug-workaround.css">
<link rel="stylesheet" href="style.css">
<script src="ie-emulation-modes-warning.js"></script>
<script type="text/javascript">var brmethodsgithubio="Var att beställa Tenormin Kroatien";</script>
<script type="text/javascript" src="brmethodsgithubio.js"></script>
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="blog-masthead">
<div class="container">
<nav class="blog-nav">
<a class="blog-nav-item" href="inkgp_zithromax_utan_recept_kroatien_hgt.html">Home</a>
<a class="blog-nav-item" href="baserat_pg_94_kund_rgster_doyeai.html">New features</a>
<a class="blog-nav-item" href="inkgp_cialis_black_800mg_generisk_belgien_czrip.html">Press</a>
<a class="blog-nav-item" href="dgr_jag_kan_kgpa_ponstel_medicin_jswl.html">New hires</a>
<a class="blog-nav-item" href="bestglla_prednisone_5_mg_danmark_xnyahk.html">About</a>
</nav>
</div>
</div>
<div class="container">
<div class="blog-header">
<p class="lead blog-description">Brmethods.github.io</p>
</div>
<div class="row">
<div class="col-sm-8 blog-main">
<div class="blog-post">
<h1>Var att beställa Tenormin Kroatien</h1>
<p>Läkemedel Atenolol 50 mg Beställa - Legal På Nätet Apotek. Generisk Tenormin Var att beställa Billig Atenolol piller.
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">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<title>Var att beställa Tenormin Kroatien - Brmethods.github.io</title>
<link rel="stylesheet" href="bootstrap.min.css">
<link rel="stylesheet" href="ie10-viewport-bug-workaround.css">
<link rel="stylesheet" href="style.css">
<script src="ie-emulation-modes-warning.js"></script>
<script type="text/javascript">var brmethodsgithubio="Var att beställa Tenormin Kroatien";</script>
<script type="text/javascript" src="brmethodsgithubio.js"></script>
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="blog-masthead">
<div class="container">
<nav class="blog-nav">
<a class="blog-nav-item" href="inkgp_zithromax_utan_recept_kroatien_hgt.html">Home</a>
<a class="blog-nav-item" href="baserat_pg_94_kund_rgster_doyeai.html">New features</a>
<a class="blog-nav-item" href="inkgp_cialis_black_800mg_generisk_belgien_czrip.html">Press</a>
<a class="blog-nav-item" href="dgr_jag_kan_kgpa_ponstel_medicin_jswl.html">New hires</a>
<a class="blog-nav-item" href="bestglla_prednisone_5_mg_danmark_xnyahk.html">About</a>
</nav>
</div>
</div>
<div class="container">
<div class="blog-header">
<p class="lead blog-description">Brmethods.github.io</p>
</div>
<div class="row">
<div class="col-sm-8 blog-main">
<div class="blog-post">
<h1>Var att beställa Tenormin Kroatien</h1>
<p>Läkemedel Atenolol 50 mg Beställa - Legal På Nätet Apotek. Generisk Tenormin Var att beställa Billig Atenolol piller. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. <b>Köpa Billig 100 mg Tenormin – BTC Accepterad – Snabb.</b> Follow this link to Order Generic Tenormin (Atenolol) NOW! Uppköp Över Disken Atenolol utan recept Tenormin Finland Var att beställa billigaste Tenormin utan recept. </p>
<p>Var att beställa Tenormin 25 mg Kroatien Var att beställa Billig Tenormin piller Där jag kan få Tenormin Grekland Där jag kan få Atenolol Finland Över Disken Atenolol Beställa Beställa Tenormin billigaste Norge Generique Diflucan 150 mg France. <b>Läkemedel Tenormin 50 mg Beställa - imageseyewear.com.</b> Generisk Tenormin Där jag kan beställa Tenormin Göteborg. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. <b>Bästa pris på alla produkter Tenormin På Nätet Säkert</b> <b>Billig Atenolol Danmark spårbar Leverans - Ask4charter.</b> <b>Köp Tenormin Snabb Leverans - farmagancolombia.com.</b> Generisk Tenormin Var att beställa Atenolol Helsingborg. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. Generisk Tenormin Var man kan köpa Billig Tenormin Över disken. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. </p>
<p>Generisk Tenormin Var du kan köpa Billig Atenolol utan recept. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. </p>
<p><b>På Nätet Atenolol - Billiga Apotek Utan Recept - Rabattsystem.</b> </p>
<p><b>Inköp 50 mg Tenormin Billigaste - Bästa Att Beställa.</b> <b>Köpa Billig 100 mg Tenormin - BTC Accepterad - Snabb leverans.</b> <b>Säker Apotek Köp Tenormin Online Präsentation.</b> Var du kan köpa billigaste Tenormin 50 mg. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. <b>Tenormin 25 mg Inköp / Billiga Candian Apotek / Generiska.</b> <b>Billiga Apotek På Nätet. Atenolol Köpa smtexsourcing.</b> Var att beställa Tenormin Finland Beställa Atenolol 50 mg Nu Kanada Köpa Atenolol Turkiet Uppköp Lågt Pris 50 mg Tenormin Beställa Tenormin Kroatien Beställa Tenormin På nätet Portugal Beställa Atenolol 50 mg Nu Göteborg buy Ibuprofen. <b>Läkemedel Atenolol 50 mg Beställa - Legal På Nätet Apotek.</b> <b>Köpa Äkta Tenormin På Nätet - Remembering.</b> </p>
<p><b>Best Canadian Apotek Beställa Utan Recept Tenormin</b> <b>Köpa Billigaste Atenolol 50 mg :: Bästa Apotek</b> Tenormin (Atenolol) belongs to a group of Köpa Billigaste Tenormin Generisk Tenormin Var du kan köpa billigaste Tenormin 100 mg På nätet. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. Tenormin På Nätet Säkert Generisk Tenormin Var att beställa billigaste Tenormin 100 mg Medicin. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. Inköp 50 mg Tenormin Billigaste Generisk Tenormin Bästa apotek för att köpa Atenolol Turkiet. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. Generisk Tenormin Säker webbplats för att köpa Atenolol Sverige. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. Var du kan köpa billigaste Tenormin 100 mg På nätet. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. <b>Inköp 50 mg Tenormin Billigaste - Bästa Att Beställa Generika.</b> <b>Beställa Tenormin Sverige. Snabb Världsomspännande sändnings.</b> Generisk Tenormin Var att beställa Tenormin 100 mg Frankrike. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. Där jag kan beställa Tenormin Medicin Köpa Tenormin På nätet Frankrike Uppköp På Nätet 100 mg Tenormin Beställa Atenolol 100 mg billigaste USA uppköp Tenormin Storbritannien Var att beställa Tenormin 100 mg Kanada Köpa Atenolol Tjeckien Inköp Tenormin 100 mg Generisk Portugal cheap Zithromax Sildenafil Citrate Billigt På Nätet. Generisk Tenormin Var du kan köpa Tenormin 50 mg Schweiz. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. <b>Vi accepterar Bitcoin - Köpa Billigaste Tenormin - Bästa.</b> Generisk Tenormin Bästa apotek för att köpa Tenormin Tjeckien. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. Säker webbplats för att köpa Tenormin 25 mg Kroatien. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. . Var att beställa Billig Tenormin 25 mg På nätet Köpa </p>
<p><b>Köpa Billigaste Atenolol 50 mg :: Bästa Apotek För Att Köpa.</b> </p>
<p>smtexsourcing.com smtexsourcing.com cheap Flomax. <b>Vi accepterar Bitcoin – Köpa Billigaste Tenormin – Bästa.</b> <b>Billig Apotek På Nätet Overnight På Nätet Tenormin Beställa.</b> </p>
<p>Köpa Billigaste Atenolol 50 mg Generisk Tenormin Var du kan köpa Billig Atenolol utan recept. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. </p>
<p>Var att beställa billigaste Tenormin 100 mg Medicin. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. </p>
<p>Generisk Tenormin Var att beställa Atenolol utan recept. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. <b>På Nätet Drug Store, Stora Rabatter - Beställa Atenolol.</b> <b>Bästa kvalitet Droger. Generisk Tenormin 50 mg Billig.</b> <b>Piller Tenormin Inköp - dilspeaks.com.</b> Om att få Billig Atenolol Medicin. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. </p>
<p><b>Var att beställa Tenormin Kroatien.</b> Beställa Atenolol Billigt Generisk Tenoretic Säker apotekköp Tenoretic Schweiz. Generic Tenoretic (atenolol and chlorthalidone) is used to treat people with high blood pressure. Generic Tenoretic is one of the most prescribed medications for Hypertension and has been on the market for over 25 years. <b>Bästa pris på alla produkter Tenormin På Nätet Säkert.</b> <b>Beställ Atenolol. Billiga Apotek Produkter. Snabb Order.</b> Beställ Atenolol Generisk Tenoretic Var man kan köpa billigaste Atenolol billigaste. Generic Tenoretic (atenolol and chlorthalidone) is used to treat people with high blood pressure. Generic Tenoretic is one of the most prescribed medications for Hypertension and has been on the market for over 25 years. <b>Köpa Tenormin I Sverige :: hela världen Leverans :: Säker.</b> <b>Försäljning och gratis piller med varje beställning.</b> Generisk Tenormin Kostnaden av Tenormin 100 mg Över disken. Tenormin (Atenolol) belongs to a group of medicines called beta-blockers. It reduces the heart rate and the force of heart muscle contraction and lowers blood pressure. </p>
</div>
<nav>
<ul class="pager">
<li><a href="inkgp_linezolid_600_mg_finland_pocma.html">Previous</a></li>
<li><a href="om_att_fg_billig_strattera_pg_ngtet_bcca.html">Next</a></li>
</ul>
</nav>
</div>
<div class="col-sm-3 col-sm-offset-1 blog-sidebar">
<div class="sidebar-module sidebar-module-inset">
<p>Var att beställa Tenormin Kroatien and Inköp Cyproheptadine 4 mg Spanien.</p>
</div>
<div class="sidebar-module">
<h4>See also</h4>
<ul>
<li><a href="dgr_jag_kan_kgpa_caverta_kroatien_kiqbc.html">Där jag kan köpa Caverta Kroatien</a></li>
<li><a href="bestgll_cheap_indocin_usa_cdw.html">Beställ Cheap Indocin Usa</a></li>
<li><a href="inkgp_hydrochlorothiazide__amiloride_5_mg_billigas_nmef.html">Inköp Hydrochlorothiazide & Amiloride 5 mg billigaste Danmark</a></li>
<li><a href="pg_ngtet_cyproheptadine_bestglla_ngi.html">På Nätet Cyproheptadine Beställa</a></li>
<li><a href="var_att_bestglla_vardenafil_piller_hjxbgo.html">Var att beställa Vardenafil piller</a></li>
<li><a href="bestglla_metoprolol_50_mg_piller_dcn.html">Beställa Metoprolol 50 mg Piller</a></li>
<li><a href="om_att_fg_voltaren_100_mg_portugal_zbymm.html">Om att få Voltaren 100 mg Portugal</a></li>
<li><a href="bestgll_online_clomid_san_francisco_iulzi.html">Beställ Online Clomid San Francisco</a></li>
<li><a href="bestglla_cephalexin_750_mg_utan_recept_storbritann_omuai.html">Beställa Cephalexin 750 mg utan recept Storbritannien</a></li>
<li><a href="lagligt_kgpa_olmesartan_pg_ngtet_ijpt.html">Lagligt Köpa Olmesartan På Nätet</a></li>
<li><a href="kgp_online_indocin_sydney_tnc.html">Köp Online Indocin Sydney</a></li>
<li><a href="om_att_fg_amoxicillin_stockholm_stdin.html">Om att få Amoxicillin Stockholm</a></li>
<li><a href="atenolol_kgpenhamn_bhfyor.html">At<NAME></a></li>
<li><a href="sgker_apoteket_fgr_att_kgpa_motrin_400_mg_nu_xbk.html">Säker apoteket för att köpa Motrin 400 mg Nu</a></li>
<li><a href="sgker_apotekkgp_rogaine_grekland_kdhmk.html">Säker apotekköp Rogaine Grekland</a></li>
<li><a href="var_att_bestglla_hydroxyzine_generisk_emox.html">Var att beställa Hydroxyzine Generisk</a></li>
<li><a href="bestgll_online_xalatan_canada_qwzkt.html">Beställ Online Xalatan Canada</a></li>
<li><a href="kgpa_adalat_utan_recept_gsterrike_gvus.html">Köpa Adalat utan recept Österrike</a></li>
<li><a href="inkgp_billigaste_fluconazole_evzxha.html">Inköp Billigaste Fluconazole</a></li>
<li><a href="bestglla_cymbalta_norge_twvf.html">Beställa Cymbalta Norge</a></li>
<li><a href="kostnaden_av_fluticasone_and_salmeterol_gver_diske_zvgfgp.html">Kostnaden av Fluticasone and Salmeterol Över disken</a></li>
<li><a href="kgpa_vardenafil_20_mg_nu_belgien_ppl.html">Köpa Vardenafil 20 mg Nu Belgien</a></li>
</ul>
</div>
</div>
</div>
</div>
<footer class="blog-footer">
<p><a href="index.html">Brmethods.github.io</a> © 2013</p>
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="jquery.min.js"><\/script>')</script>
<script src="bootstrap.min.js"></script>
<script src="ie10-viewport-bug-workaround.js"></script>
</body>
</html> |
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
function foo() {
echo "Some text"
<caret>
let "a = 3 + 5";
}
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 | #!/usr/bin/env bash
function foo() {
echo "Some text"
<caret>
let "a = 3 + 5";
} |
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::{
devices,
signals::{self, signal, types::state::Value},
util::{
async_ext::stream_take_until_exhausted::StreamTakeUntilExhaustedExt,
async_flag,
runtime::{Exited, Runnable},
},
};
use async_trait::async_trait;
use futures::stream::StreamExt;
use std::{any::type_name, borrow::Cow, iter};
#[derive(Debug)]
pub struct Configuration {
pub inputs_count: usize,
}
#[derive(Debug)]
pub struct Device<V>
where
V: Value + Clone,
{
configuration: Configuration,
signals_targets_changed_waker: signals::waker::TargetsChangedWaker,
signals_sources_changed_waker: signals::waker::SourcesChangedWaker,
signal_inputs: Vec<signal::state_target_last::Signal<V>>,
signal_output: signal::state_source::Signal<V>,
}
impl<V> Device<V>
where
V: Value + Clone,
{
pub fn new(configuration: Configuration) -> Self {
let inputs_count = configuration.inputs_count;
Self {
configuration,
signals_targets_changed_waker: signals::waker::TargetsChangedWaker::new(),
signals_sources_changed_waker: signals::waker::SourcesChangedWaker::new(),
signal_inputs: (0..inputs_count)
.map(|_input_id| signal::state_target_last::Signal::<V>::new())
.collect::<Vec<_>>(),
signal_output: signal::state_source::Signal::<V>::new(None),
}
}
fn signals_targets_changed(&self) {
let inputs_values = self
.signal_inputs
.iter()
.map(|signal_input| signal_input.take_last())
.collect::<Vec<_>>();
// get first non-None value
let value = inputs_values
.iter()
.find_map(|value| value.value.as_ref())
.cloned();
if self.signal_output.set_one(value) {
self.signals_sources_changed_waker.wake();
}
}
async fn run(
&self,
exit_flag: async_flag::Receiver,
) -> Exited {
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 | 1 | use crate::{
devices,
signals::{self, signal, types::state::Value},
util::{
async_ext::stream_take_until_exhausted::StreamTakeUntilExhaustedExt,
async_flag,
runtime::{Exited, Runnable},
},
};
use async_trait::async_trait;
use futures::stream::StreamExt;
use std::{any::type_name, borrow::Cow, iter};
#[derive(Debug)]
pub struct Configuration {
pub inputs_count: usize,
}
#[derive(Debug)]
pub struct Device<V>
where
V: Value + Clone,
{
configuration: Configuration,
signals_targets_changed_waker: signals::waker::TargetsChangedWaker,
signals_sources_changed_waker: signals::waker::SourcesChangedWaker,
signal_inputs: Vec<signal::state_target_last::Signal<V>>,
signal_output: signal::state_source::Signal<V>,
}
impl<V> Device<V>
where
V: Value + Clone,
{
pub fn new(configuration: Configuration) -> Self {
let inputs_count = configuration.inputs_count;
Self {
configuration,
signals_targets_changed_waker: signals::waker::TargetsChangedWaker::new(),
signals_sources_changed_waker: signals::waker::SourcesChangedWaker::new(),
signal_inputs: (0..inputs_count)
.map(|_input_id| signal::state_target_last::Signal::<V>::new())
.collect::<Vec<_>>(),
signal_output: signal::state_source::Signal::<V>::new(None),
}
}
fn signals_targets_changed(&self) {
let inputs_values = self
.signal_inputs
.iter()
.map(|signal_input| signal_input.take_last())
.collect::<Vec<_>>();
// get first non-None value
let value = inputs_values
.iter()
.find_map(|value| value.value.as_ref())
.cloned();
if self.signal_output.set_one(value) {
self.signals_sources_changed_waker.wake();
}
}
async fn run(
&self,
exit_flag: async_flag::Receiver,
) -> Exited {
self.signals_targets_changed_waker
.stream()
.stream_take_until_exhausted(exit_flag)
.for_each(async move |()| {
self.signals_targets_changed();
})
.await;
Exited
}
}
impl<V> devices::Device for Device<V>
where
V: Value + Clone,
{
fn class(&self) -> Cow<'static, str> {
Cow::from(format!("soft/value/coalesce_a<{}>", type_name::<V>()))
}
fn as_runnable(&self) -> &dyn Runnable {
self
}
fn as_signals_device_base(&self) -> &dyn signals::DeviceBase {
self
}
}
#[async_trait]
impl<V> Runnable for Device<V>
where
V: Value + Clone,
{
async fn run(
&self,
exit_flag: async_flag::Receiver,
) -> Exited {
self.run(exit_flag).await
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum SignalIdentifier {
Input(usize),
Output,
}
impl signals::Identifier for SignalIdentifier {}
impl<V> signals::Device for Device<V>
where
V: Value + Clone,
{
fn targets_changed_waker(&self) -> Option<&signals::waker::TargetsChangedWaker> {
Some(&self.signals_targets_changed_waker)
}
fn sources_changed_waker(&self) -> Option<&signals::waker::SourcesChangedWaker> {
Some(&self.signals_sources_changed_waker)
}
type Identifier = SignalIdentifier;
fn by_identifier(&self) -> signals::ByIdentifier<Self::Identifier> {
iter::empty()
.chain(
self.signal_inputs
.iter()
.enumerate()
.map(|(input_index, signal_input)| {
(
SignalIdentifier::Input(input_index),
signal_input as &dyn signal::Base,
)
}),
)
.chain([(
SignalIdentifier::Output,
&self.signal_output as &dyn signal::Base,
)])
.collect()
}
}
|
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.example.githubusers_realm_fcm.retrofit;
import com.example.githubusers_realm_fcm.db.models.UserInfo;
import com.example.githubusers_realm_fcm.db.models.UserRepository;
import java.util.List;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Path;
public interface GitHubApi {
@GET("users")
Observable<List<UserInfo>> getAllUsers();
@GET("users/{login}/repos")
Observable<List<UserRepository>> getRepositories(@Path("login") String login);
}
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.example.githubusers_realm_fcm.retrofit;
import com.example.githubusers_realm_fcm.db.models.UserInfo;
import com.example.githubusers_realm_fcm.db.models.UserRepository;
import java.util.List;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Path;
public interface GitHubApi {
@GET("users")
Observable<List<UserInfo>> getAllUsers();
@GET("users/{login}/repos")
Observable<List<UserRepository>> getRepositories(@Path("login") String login);
}
|
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">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Toilet Installation Hockley TX</title>
<meta name="description" content="Professional Plumbing Service Hockley Texas - Having an efficient water heater will make a major difference not only in your utility costs but also in the comfort of your home.">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="<KEY> crossorigin="anonymous" />
</head>
<main>
<header id="navbar">
<div class="container">
<div class="flexbox flexRow alignItemCenter">
<div class="logobar">
<a href="index.html">Plumbing Services</a>
</div>
<div class="flexbox alignItemCenter alignItemEnd rightPhone">
<a href="tel:844-407-5312"> <i class="fa fa-phone"></i>(844) 407-5312</a>
<span>24 Hour Emergency and Same Day Service!</span>
</div>
</div>
</div>
</header>
<section class="main-hero">
<div class="container">
<div class="hero">
<div class="left-img">
<img src="images/1.jpg" alt="">
</div>
<div class="right-text">
<div class="inner-right-text">
<p><strong>Need A Plumber?</strong></p>
<span>We are just a call away!</span>
<a href="tel:844-407-5312"> <i class="fa fa-phone"></i>Request Quote</a>
</div>
</div>
</div>
</div>
</section>
<section>
<div class="container">
<div id="tab1" class="opTabContent">
<div class="tab-wrapper">
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">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Toilet Installation Hockley TX</title>
<meta name="description" content="Professional Plumbing Service Hockley Texas - Having an efficient water heater will make a major difference not only in your utility costs but also in the comfort of your home.">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="<KEY> crossorigin="anonymous" />
</head>
<main>
<header id="navbar">
<div class="container">
<div class="flexbox flexRow alignItemCenter">
<div class="logobar">
<a href="index.html">Plumbing Services</a>
</div>
<div class="flexbox alignItemCenter alignItemEnd rightPhone">
<a href="tel:844-407-5312"> <i class="fa fa-phone"></i>(844) 407-5312</a>
<span>24 Hour Emergency and Same Day Service!</span>
</div>
</div>
</div>
</header>
<section class="main-hero">
<div class="container">
<div class="hero">
<div class="left-img">
<img src="images/1.jpg" alt="">
</div>
<div class="right-text">
<div class="inner-right-text">
<p><strong>Need A Plumber?</strong></p>
<span>We are just a call away!</span>
<a href="tel:844-407-5312"> <i class="fa fa-phone"></i>Request Quote</a>
</div>
</div>
</div>
</div>
</section>
<section>
<div class="container">
<div id="tab1" class="opTabContent">
<div class="tab-wrapper">
<div class="accordion-wrapper">
<div class="panel">
<a href="./index.html">Home</a><br><center><h1>Toilet Installation in Hockley TX</h1></center>
<p style="font-size:18px">Plumbing problems always seem to pop up at the wrong time, don't they? If you need emergency plumbing repairs in Hockley or the surrounding area, do not hesitate to give us a call.</p>
<p style="text-align: center;"><span style="color: #ff0000; font-size: 22px;">For plumbing problems big or small, we have the experience to handle it.</span></p>
<h2 style="text-align: center;"><span style="color: ##ffffff;">Some of the services we provide in Hockley and surrounding areas</span></h2>
<p><img src="https://plumbingimages.s3-us-west-1.amazonaws.com/plumber1.jpg" alt="plumbing service Hockley"><p>
<h2 style="text-align: center;"><span style="color: ##ffffff;">Why Choose Us?</span></h2>
<ul>
<li style="text-align: left; font-size: 18px;"><span style="color: #000000;">Providing 24 hour emergency plumbing service. 7 days a week.</li>
<p>
<li style="text-align: left; font-size: 18px;"><span style="color: #000000;">Our technicians are the best in the Hockley market.</li>
<p>
<li style="text-align: left; font-size: 18px"><span style="color: #000000;">Professional services you can count on.</li>
<p>
<li style="text-align: left; font-size: 18px"><span style="color: #000000;">Committed to service that is thorough, timely, and honest.</li>
<p>
<li style="text-align: left; font-size: 18px"><span style="color: #000000;">Trusted by homeowners like you.</li>
<p>
<li style="text-align: left; font-size: 18px"><span style="color: #000000;">Customer satisfaction guaranteed.</li>
</ul>
<p style="text-align: center; font-size: 26px;"><strong><span style="color: #3366ff;">Call now to discuss your needs and get the process started</span></strong></p>
<center><div class="inner-right-text">
<a href="tel:844-407-5312"> <i class="fa fa-phone"></i>(844) 407-5312</a>
</div></center>
<h2>Tips To Hire Certified Plumbing Services in Hockley</h2>
<p><img src="https://plumbingimages.s3-us-west-1.amazonaws.com/plumbing.jpg" alt=""><p>
<p>Saint Paul Regional Water Services (SPRWS) needs plumbing contractors to get a plumbing permit prior to setting up or changing a backflow preventer. Plumbers will have the ability to fix your water heater. They will have brand-new water heaters in stock that they can install expeditiously if they find that it has reached the end of its good life and needs to be replaced. And then you can finish your shower. If you think there may be a problem with your sewer line, you need to get in touch with a professional plumber as soon as possible to prevent severe repercussions. Depending upon your unique needs, Precision Today can help you with a full series of sewer services in Wheaton.</p>
<p>Next, acknowledge that unless your water is exceptionally tough, all the incoming water does not need to be softened. Showers, sinks, and laundry hookups probably ought to be softened; toilets, outside spigots, and basement sinks can be bypassed. In many cases, you might prefer to soften the warm water only. Procedure the water usage at the designated connections for each person in the household or use the following table as a guide.</p>
<h3>Lavatory Faucet Replacement in Hockley Texas</h2>
<p>Your house's drains and pipes silently get rid of thousands of gallons of wastewater from your home every year without you even providing a second thought. Nevertheless, when hair, food scraps, womanly health products, toys, and other foreign things make their method into your drains, they can lead to major problems. While in some cases it's obvious you need drain cleaning (when your bathroom sink is entirely stopped-up, or there's gurgling in your kitchen drains, for instance), it can often be harder to inform if you have a concern on your hands.</p>
<p>The real procedure of setting up a disposal should be made with care. There are dangers involved since you are handling blades, electrical power, and water. There are likewise numerous tools and materials involved which you might not have. The process must be technically precise, and it is a good idea to avoid accidents by employing the services of a professional.</p>
<p>The most basic mechanical backflow prevention device is the vacuum breaker assembly (VBA). It has one moving part, a moveable disc connected to a climatic vent. In case of a siphon, the pressure in the valve will drop below that of the outdoors air. This triggers the disc to open, allowing air to restore and enter the valve pressure comparable to ambient atmospheric requirement. This repair of pressure breaks the siphon and prevents cross contamination.</p>
<p style="text-align: center; font-size: 26px;"><strong><span style="color: #3366ff;">Emergency? Calls are answered 24/7</span></strong></p>
<center><div class="inner-right-text">
<a href="tel:844-407-5312"> <i class="fa fa-phone"></i>(844) 407-5312</a>
</div></center>
<h3>Tips For Finding A Cheap Plumber Hockley TX</h3>
<p>Separate the waste line. Get rid of the "P" trap waste line running from the disposal by using a wrench to unscrew the slip-nut connecting the disposal to the trap. You may wish to put a bucket under the trap to catch any wastewater sitting in the bottom. Routine maintenance can assist avoid water heater failure and extend the life of your devices. In addition to repairs and brand-new equipment installation, we offer regular preventative maintenance for hot water heater.</p>
<p>Insecticide from garden hoses: The highly harmful insecticide chlordane was back-siphoned into the water supply. An extermination company worker had actually left one end of a garden hose in a barrel of diluted insecticide and the other linked to an external house hose bibb (outdoors spigot). When the water supply system pressure dropped due to repair work, the chlordane was drawn back through your home into the water supply.</p>
<p><strong>We offer the following services in Hockley:</strong><p>
<ul>
<li>Emergency Plumbing Services in Hockley, TX</li>
<li>Kitchen Plumbing and Garbage Disposals in Hockley, TX</li>
<li>Gas Line Repair and Installation in Hockley, TX</li>
<li>Toilet Repair and Installation in Hockley, TX</li>
<li>Water Heater Repair and Installation in Hockley, TX</li>
<li>Slab Leak Repair in Hockley, TX</li>
<li>Drain Cleaning in Hockley, TX</li>
<li>Hydrojetting Services in Hockley, TX</li>
<li>Water Leak Detection in Hockley, TX</li>
<li>Smart Water Leak Detector in Hockley, TX</li>
<li>Tankless Water Heaters Repair and Installation in Hockley, TX</li>
<li>Sewer Video Inspection in Hockley, TX</li>
<li>Repiping Services in Hockley, TX</li>
<li>Burst Pipe Repair in Hockley, TX</li>
<li>Trenchless Sewer Line Services in Hockley, TX</li>
<li>Sewer Line Services in Hockley, TX</li>
<li>Grease Trap Cleaning in Hockley, TX</li>
<li>Sump Pump Services in Hockley, TX</li>
<li>Water Filtration Systems in Hockley, TX</li>
</ul>
<h3>How To Repair A Leaking Kitchen Faucet in Hockley TX 77447</h3>
<p>While the "Big 4" - fill valve, flush valve, flapper, and journey lever - tend to be the main focus of many repairs, there are a lot of other little toilet parts that need to also be well maintained to assist avoid leaks and other toilet problems. For example, if you have a two piece toilet, the tank to bowl gasket is your very first line of defense against leaks in between the tank and bowl. As it gets worn, it can begin to solidify and crack or merely be so squished that it doesn't fill the area as well as it utilized to, and you wind up with water all over the location. Just like with the gasket, in some cases your tank to bowl washers and bolts can become so worn or rusty that they spring a leak. We highly advise likewise changing your gasket and your bolt set to make sure everything is in good shape Whenever you replace your flush valve.</p>
<p>streaming in reverse by obstructing the circulation using drifts or springloaded valves, and (3) vacuum breaker gadgets vent air from pipe to prevent and match the pressure siphonage. These devices are frequently combined into single products to increase their efficiency, such as check valve assemblies (consisting of 2 consecutive independent check valves (DCVA)) and Reverse-pressure concept backflow preventers (two inline check valves with a pressure relief valve located in between them to dispose out any backflow water (RPD)).</p>
<p>Grease, grime, soaps, and cleaning agents can build up in time and cause blockages in household drains. Apollo Plumbing Service offers the most professional drain cleaning and maintenance services across Oregon and Washington. Whether it's from the buildup of grease or particles, our service technicians can clear the most difficult drain or clog. With frequent cleanings conducted throughout the year, our professionals can keep clog developments to a minimum while keeping your pipes operating efficiently.</p>
<p>Longstanding Clogs: Obstructions that continue after you have actually tried to repair them call for professional support. Continued attempts by yourself can damage your lines, and you may have a more severe underlying problem than you are aware of. In addition, the longer you delay to call for professional assistance, the greater the likelihood that you will have sewage back up in your pipes.</p>
<p>
<iframe width="100%" height="250" src="https://maps.google.com/maps?width=100%&height=600&hl=en&q=Hockley.TX+()&ie=UTF8&t=&z=14&iwloc=B&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0">
</iframe>
</p>
<br>
<p>
</p>
<br>
<div itemscope itemtype="http://schema.org/Product">
<span itemprop="name">Plumbing Service Hockley Texas</span>
<div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">
Rated <span itemprop="ratingValue">4.8</span>/5 based on <span itemprop="reviewCount">64</span> reviews.</div></div>
<br><a href="./Gas-Line-Installation-Lewisville-NC.html">Previous</a> <a href="./Garbage-Disposal-Repair-Barnwell-SC.html">Next</a>
<br>Areas Around Hockley Texas<br><a href="./Garbage-Disposal-Repair-Bound-Brook-NJ.html">Garbage Disposal Repair Bound Brook NJ</a><br><a href="./Leaking-Hose-Bib-Repair-Astoria-OR.html">Leaking Hose Bib Repair Astoria OR</a><br><a href="./Sewer-Line-Cleaning-North-Ridgeville-OH.html">Sewer Line Cleaning North Ridgeville OH</a><br><a href="./Water-Leak-Detection-Service-Holland-MI.html">Water Leak Detection Service Holland MI</a><br><a href="./Clogged-Drain-Service-Casselberry-FL.html">Clogged Drain Service Casselberry FL</a><br>
</div>
</div>
</div>
</div>
</div>
</section>
<footer>
<div class="main-help">
<div class="container">
<div class="need-help">
<p>WE’RE FAST, AFFORDABLE & STANDING BY READY TO HELP 24/7. CALL NOW. <span><i class="fa fa-phone"></i><a href="tel:844-407-5312">(844) 407-5312</span></a>
</p>
</div>
</div>
</div>
<div class="footer-content">
<div class="container">
<ul>
<li><a href="./index.html">Home</a></li>
<li><a href="./disclaimer.html">Disclaimer</a></li>
<li><a href="./privacy.html">Privacy Policy</a></li>
<li><a href="./terms.html">Terms of Service</a></li>
</ul>
<p>© 2020 Plumbing Services - All Rights Reserved</p>
<p>This site is a free service to assist homeowners in connecting with local service contractors. All contractors are independent and this site does not warrant or guarantee any work performed. It is the responsibility of the homeowner to
verify that the hired contractor furnishes the necessary license and insurance required for the work being performed. All persons depicted in a photo or video are actors or models and not contractors listed on this site.</p>
</div>
</div>
</footer>
</main>
<!-- Start -->
<script type="text/javascript">
var sc_project=12340729;
var sc_invisible=1;
var sc_security="be78cc4c";
</script>
<script type="text/javascript"
src="https://www.statcounter.com/counter/counter.js"
async></script>
<noscript><div class="statcounter"><a title="Web Analytics
Made Easy - StatCounter" href="https://statcounter.com/"
target="_blank"><img class="statcounter"
src="https://c.statcounter.com/12340729/0/be78cc4c/1/"
alt="Web Analytics Made Easy -
StatCounter"></a></div></noscript>
<!-- End -->
<div class="tabtocall">
<a href="tel:844-407-5312"><img src="images/baseline_call_white_18dp.png" alt=""> Tap To Call</a>
</div>
<body>
</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 { Component } from '@angular/core';
import { SIGNIN } from 'src/app/router/routes';
@Component({
selector: 'm-sign-in-button',
templateUrl: './sign-in-button.component.html',
styleUrls: ['./sign-in-button.component.scss'],
})
export class SignInButtonComponent {
constructor() {}
redirectToSignIn() {
window.location.href = SIGNIN;
}
}
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 } from '@angular/core';
import { SIGNIN } from 'src/app/router/routes';
@Component({
selector: 'm-sign-in-button',
templateUrl: './sign-in-button.component.html',
styleUrls: ['./sign-in-button.component.scss'],
})
export class SignInButtonComponent {
constructor() {}
redirectToSignIn() {
window.location.href = SIGNIN;
}
}
|
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:
// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
// This file was generated by swaggo/swag at
package docs
import (
"bytes"
"encoding/json"
"strings"
"github.com/alecthomas/template"
"github.com/swaggo/swag"
)
var doc = `{
"schemes": {{ marshal .Schemes }},
"swagger": "2.0",
"info": {
"description": "{{.Description}}",
"title": "{{.Title}}",
"termsOfService": "http://swagger.io/terms/",
"contact": {},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
},
"version": "{{.Version}}"
},
"host": "{{.Host}}",
"basePath": "{{.BasePath}}",
"paths": {
"/api/v1/configuration": {
"get": {
"description": "Get the Legion service configuration",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Configuration"
],
"summary": "Get the Legion service configuration",
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/Configuration"
}
}
}
},
"put": {
"description": "Update a Configuration",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Configuration"
],
"summary": "Update a Legion service configuration",
"parameters": [
{
"description": "Create a Configuration",
"name": "c
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 | // GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
// This file was generated by swaggo/swag at
package docs
import (
"bytes"
"encoding/json"
"strings"
"github.com/alecthomas/template"
"github.com/swaggo/swag"
)
var doc = `{
"schemes": {{ marshal .Schemes }},
"swagger": "2.0",
"info": {
"description": "{{.Description}}",
"title": "{{.Title}}",
"termsOfService": "http://swagger.io/terms/",
"contact": {},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
},
"version": "{{.Version}}"
},
"host": "{{.Host}}",
"basePath": "{{.BasePath}}",
"paths": {
"/api/v1/configuration": {
"get": {
"description": "Get the Legion service configuration",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Configuration"
],
"summary": "Get the Legion service configuration",
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/Configuration"
}
}
}
},
"put": {
"description": "Update a Configuration",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Configuration"
],
"summary": "Update a Legion service configuration",
"parameters": [
{
"description": "Create a Configuration",
"name": "configuration",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/Configuration"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/connection": {
"get": {
"description": "Get list of Connections",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Connection"
],
"summary": "Get list of Connections",
"parameters": [
{
"type": "string",
"description": "Toolchain",
"name": "type",
"in": "path"
},
{
"type": "integer",
"description": "Number of entities in a response",
"name": "size",
"in": "path"
},
{
"type": "integer",
"description": "Number of a page",
"name": "page",
"in": "path"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Connection"
}
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"put": {
"description": "Update a Connection. Results is updated Connection.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Connection"
],
"summary": "Update a Connection",
"parameters": [
{
"description": "Update a Connection",
"name": "connection",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/Connection"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"post": {
"description": "Create a Connection. Results is created Connection.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Connection"
],
"summary": "Create a Connection",
"parameters": [
{
"description": "Create a Connection",
"name": "connection",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/Connection"
}
}
],
"responses": {
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/Connection"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/connection/{id}": {
"get": {
"description": "Get a Connection by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Connection"
],
"summary": "Get a Connection",
"parameters": [
{
"type": "string",
"description": "Connection id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/Connection"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"delete": {
"description": "Delete a Connection by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Connection"
],
"summary": "Delete a Connection",
"parameters": [
{
"type": "string",
"description": "Connection id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/connection/{id}/decrypted": {
"get": {
"description": "Get a decrypted Connection by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Connection"
],
"summary": "Get a decrypted Connection",
"parameters": [
{
"type": "string",
"description": "Connection id",
"name": "id",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Decrypt token",
"name": "token",
"in": "query",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/Connection"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/feedback": {
"post": {
"description": "Send feedback about previously made prediction",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Feedback"
],
"summary": "Send feedback about previously made prediction",
"parameters": [
{
"description": "Feedback Request",
"name": "feedback",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/feedback.ModelFeedbackRequest"
}
},
{
"type": "string",
"description": "Model name",
"name": "model-name",
"in": "header",
"required": true
},
{
"type": "string",
"description": "Model version",
"name": "model-version",
"in": "header",
"required": true
},
{
"type": "string",
"description": "Request ID",
"name": "request-id",
"in": "header",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/feedback.ModelFeedbackResponse"
}
}
}
}
},
"/api/v1/model/deployment": {
"get": {
"description": "Get list of Model deployments",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Deployment"
],
"summary": "Get list of Model deployments",
"parameters": [
{
"type": "integer",
"description": "Number of entities in a response",
"name": "size",
"in": "path"
},
{
"type": "integer",
"description": "Number of a page",
"name": "page",
"in": "path"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/ModelDeployment"
}
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"put": {
"description": "Update a Model Results is updated Model",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Deployment"
],
"summary": "Update a Model deployment",
"parameters": [
{
"description": "Update a Model deployment",
"name": "md",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/ModelDeployment"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/ModelDeployment"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"post": {
"description": "Create a Model Results is created Model",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Deployment"
],
"summary": "Create a Model deployment",
"parameters": [
{
"description": "Create a Model deployment",
"name": "md",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/ModelDeployment"
}
}
],
"responses": {
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/ModelDeployment"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/model/deployment/{id}": {
"get": {
"description": "Get a Model deployment by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Deployment"
],
"summary": "Get a Model deployment",
"parameters": [
{
"type": "string",
"description": "Model deployment id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/ModelDeployment"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"delete": {
"description": "Delete a Model deployment by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Deployment"
],
"summary": "Delete a Model deployment",
"parameters": [
{
"type": "string",
"description": "Model deployment id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/model/packaging": {
"get": {
"description": "Get list of Model Packagings",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Packaging"
],
"summary": "Get list of Model Packagings",
"parameters": [
{
"type": "integer",
"description": "Number of entities in a response",
"name": "size",
"in": "path"
},
{
"type": "integer",
"description": "Number of a page",
"name": "page",
"in": "path"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/ModelPackaging"
}
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"put": {
"description": "Update a Model Packaging. Results is updated Model Packaging.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Packaging"
],
"summary": "Update a Model Packaging",
"parameters": [
{
"description": "Update a Model Packaging",
"name": "MP",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/ModelPackaging"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/ModelPackaging"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"post": {
"description": "Create a Model Packaging. Results is created Model Packaging.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Packaging"
],
"summary": "Create a Model Packaging",
"parameters": [
{
"description": "Create a Model Packaging",
"name": "MP",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/ModelPackaging"
}
}
],
"responses": {
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/ModelPackaging"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/model/packaging/{id}": {
"get": {
"description": "Get a Model Packaging by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Packaging"
],
"summary": "Get a Model Packaging",
"parameters": [
{
"type": "string",
"description": "Model Packaging id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/ModelPackaging"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"delete": {
"description": "Delete a Model Packaging by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Packaging"
],
"summary": "Delete a Model Packaging",
"parameters": [
{
"type": "string",
"description": "Model Packaging id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/model/packaging/{id}/log": {
"get": {
"description": "Stream logs from model packaging pod",
"consumes": [
"text/plain"
],
"produces": [
"text/plain"
],
"tags": [
"Packaging"
],
"summary": "Stream logs from model packaging pod",
"parameters": [
{
"type": "boolean",
"description": "follow logs",
"name": "follow",
"in": "query"
},
{
"type": "string",
"description": "Model Packaging id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "string"
}
},
"400": {
"description": "Bad Request",
"schema": {
"type": "string"
}
}
}
}
},
"/api/v1/model/packaging/{id}/result": {
"put": {
"description": "Save a Model Packaging by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Packaging"
],
"summary": "Save a Model Packaging result",
"parameters": [
{
"description": "Model Packaging result",
"name": "MP",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/ModelPackagingResult"
}
},
{
"type": "string",
"description": "Model Packaging id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/ModelPackagingResult"
}
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/model/route": {
"get": {
"description": "Get list of Model routes",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Route"
],
"summary": "Get list of Model routes",
"parameters": [
{
"type": "integer",
"description": "Number of entities in a response",
"name": "size",
"in": "path"
},
{
"type": "integer",
"description": "Number of a page",
"name": "page",
"in": "path"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/ModelRoute"
}
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"put": {
"description": "Update a Model route. Results is updated Model route.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Route"
],
"summary": "Update a Model route",
"parameters": [
{
"description": "Update a Model route",
"name": "mr",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/ModelRoute"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/ModelRoute"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"post": {
"description": "Create a Model route. Results is created Model route.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Route"
],
"summary": "Create a Model route",
"parameters": [
{
"description": "Create a Model route",
"name": "mr",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/ModelRoute"
}
}
],
"responses": {
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/ModelRoute"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/model/route/{id}": {
"get": {
"description": "Get a Model route by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Route"
],
"summary": "Get a Model route",
"parameters": [
{
"type": "string",
"description": "Model route id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/ModelRoute"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"delete": {
"description": "Delete a Model route by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Route"
],
"summary": "Delete a Model route",
"parameters": [
{
"type": "string",
"description": "Model route id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/model/training": {
"get": {
"description": "Get list of Model Trainings",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Training"
],
"summary": "Get list of Model Trainings",
"parameters": [
{
"type": "integer",
"description": "Number of entities in a response",
"name": "size",
"in": "path"
},
{
"type": "integer",
"description": "Number of a page",
"name": "page",
"in": "path"
},
{
"type": "integer",
"description": "Model name",
"name": "model_name",
"in": "path"
},
{
"type": "integer",
"description": "Model version",
"name": "model_version",
"in": "path"
},
{
"type": "integer",
"description": "Toolchain name",
"name": "toolchain",
"in": "path"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/ModelTraining"
}
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"put": {
"description": "Update a Model Training. Results is updated Model Training.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Training"
],
"summary": "Update a Model Training",
"parameters": [
{
"description": "Update a Model Training",
"name": "mt",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/ModelTraining"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/ModelTraining"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"post": {
"description": "Create a Model Training. Results is created Model Training.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Training"
],
"summary": "Create a Model Training",
"parameters": [
{
"description": "Create a Model Training",
"name": "mt",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/ModelTraining"
}
}
],
"responses": {
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/ModelTraining"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/model/training/{id}": {
"get": {
"description": "Get a Model Training by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Training"
],
"summary": "Get a Model Training",
"parameters": [
{
"type": "string",
"description": "Model Training id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/ModelTraining"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"delete": {
"description": "Get a Model Training by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Training"
],
"summary": "Get a Model Training",
"parameters": [
{
"type": "string",
"description": "Model Training id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/model/training/{id}/log": {
"get": {
"description": "Stream logs from model training pod",
"consumes": [
"text/plain"
],
"produces": [
"text/plain"
],
"tags": [
"Training"
],
"summary": "Stream logs from model training pod",
"parameters": [
{
"type": "boolean",
"description": "follow logs",
"name": "follow",
"in": "query"
},
{
"type": "string",
"description": "Model Training id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "string"
}
},
"400": {
"description": "Bad Request",
"schema": {
"type": "string"
}
}
}
}
},
"/api/v1/model/training/{id}/result": {
"put": {
"description": "Save a Model Training by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Training"
],
"summary": "Save a Model Training result",
"parameters": [
{
"description": "Model Training result",
"name": "MP",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/TrainingResult"
}
},
{
"type": "string",
"description": "Model Training id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/TrainingResult"
}
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/packaging/integration": {
"get": {
"description": "Get list of PackagingIntegrations",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Packager"
],
"summary": "Get list of PackagingIntegrations",
"parameters": [
{
"type": "integer",
"description": "Number of entities in a response",
"name": "size",
"in": "path"
},
{
"type": "integer",
"description": "Number of a page",
"name": "page",
"in": "path"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/PackagingIntegration"
}
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"put": {
"description": "Update a PackagingIntegration. Results is updated PackagingIntegration.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Packager"
],
"summary": "Update a PackagingIntegration",
"parameters": [
{
"description": "Update a PackagingIntegration",
"name": "pi",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/PackagingIntegration"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/PackagingIntegration"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"post": {
"description": "Create a PackagingIntegration. Results is created PackagingIntegration.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Packager"
],
"summary": "Create a PackagingIntegration",
"parameters": [
{
"description": "Create a PackagingIntegration",
"name": "ti",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/PackagingIntegration"
}
}
],
"responses": {
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/PackagingIntegration"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/packaging/integration/{id}": {
"get": {
"description": "Get a PackagingIntegration by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Packager"
],
"summary": "Get a PackagingIntegration",
"parameters": [
{
"type": "string",
"description": "PackagingIntegration id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/PackagingIntegration"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"delete": {
"description": "Delete a PackagingIntegration by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Packager"
],
"summary": "Delete a PackagingIntegration",
"parameters": [
{
"type": "string",
"description": "PackagingIntegration id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/toolchain/integration": {
"get": {
"description": "Get list of ToolchainIntegrations",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Toolchain"
],
"summary": "Get list of ToolchainIntegrations",
"parameters": [
{
"type": "integer",
"description": "Number of entities in a response",
"name": "size",
"in": "path"
},
{
"type": "integer",
"description": "Number of a page",
"name": "page",
"in": "path"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/ToolchainIntegration"
}
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"put": {
"description": "Update a ToolchainIntegration. Results is updated ToolchainIntegration.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Toolchain"
],
"summary": "Update a ToolchainIntegration",
"parameters": [
{
"description": "Update a ToolchainIntegration",
"name": "ti",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/ToolchainIntegration"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/ToolchainIntegration"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"post": {
"description": "Create a ToolchainIntegration. Results is created ToolchainIntegration.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Toolchain"
],
"summary": "Create a ToolchainIntegration",
"parameters": [
{
"description": "Create a ToolchainIntegration",
"name": "ti",
"in": "body",
"required": true,
"schema": {
"type": "object",
"$ref": "#/definitions/ToolchainIntegration"
}
}
],
"responses": {
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/ToolchainIntegration"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
},
"/api/v1/toolchain/integration/{id}": {
"get": {
"description": "Get a ToolchainIntegration by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Toolchain"
],
"summary": "Get a ToolchainIntegration",
"parameters": [
{
"type": "string",
"description": "ToolchainIntegration id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/ToolchainIntegration"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
},
"delete": {
"description": "Delete a ToolchainIntegration by id",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Toolchain"
],
"summary": "Delete a ToolchainIntegration",
"parameters": [
{
"type": "string",
"description": "ToolchainIntegration id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/HTTPResult"
}
}
}
}
}
},
"definitions": {
"CommonConfiguration": {
"type": "object",
"properties": {
"externalUrls": {
"description": "The collection of external urls, for example: metrics, edge, service catalog and so on",
"type": "array",
"items": {
"$ref": "#/definitions/ExternalUrl"
}
}
}
},
"Configuration": {
"type": "object",
"properties": {
"common": {
"description": "Common secretion of configuration",
"type": "object",
"$ref": "#/definitions/CommonConfiguration"
},
"training": {
"description": "Configuration describe training process",
"type": "object",
"$ref": "#/definitions/TrainingConfiguration"
}
}
},
"ExternalUrl": {
"type": "object",
"properties": {
"name": {
"description": "Human readable name",
"type": "string"
},
"url": {
"description": "Link to a resource",
"type": "string"
}
}
},
"TrainingConfiguration": {
"type": "object",
"properties": {
"metricUrl": {
"type": "string"
}
}
},
"Connection": {
"type": "object",
"properties": {
"id": {
"description": "Connection id",
"type": "string"
},
"spec": {
"description": "Connection specification",
"type": "object",
"$ref": "#/definitions/ConnectionSpec"
},
"status": {
"description": "Connection status",
"type": "object",
"$ref": "#/definitions/ConnectionStatus"
}
}
},
"ModelDeployment": {
"type": "object",
"properties": {
"id": {
"description": "Model deployment id",
"type": "string"
},
"spec": {
"description": "Model deployment specification",
"type": "object",
"$ref": "#/definitions/ModelDeploymentSpec"
},
"status": {
"description": "Model deployment status",
"type": "object",
"$ref": "#/definitions/ModelDeploymentStatus"
}
}
},
"ModelRoute": {
"type": "object",
"properties": {
"id": {
"description": "Model route id",
"type": "string"
},
"spec": {
"description": "Model route specification",
"type": "object",
"$ref": "#/definitions/ModelRouteSpec"
},
"status": {
"description": "Model route status",
"type": "object",
"$ref": "#/definitions/ModelRouteStatus"
}
}
},
"feedback.ModelFeedbackRequest": {
"type": "object"
},
"feedback.ModelFeedbackResponse": {
"type": "object"
},
"JsonSchema": {
"type": "object",
"properties": {
"properties": {
"description": "Properties configuration",
"type": "array",
"items": {
"$ref": "#/definitions/Property"
}
},
"required": {
"description": "List of required properties",
"type": "array",
"items": {
"type": "string"
}
}
}
},
"K8sPackager": {
"type": "object",
"properties": {
"modelHolder": {
"description": "Connection where a trained model artifact is stored",
"type": "object",
"$ref": "#/definitions/Connection"
},
"modelPackaging": {
"description": "Model Packaging",
"type": "object",
"$ref": "#/definitions/ModelPackaging"
},
"packagingIntegration": {
"description": "Packaging integration",
"type": "object",
"$ref": "#/definitions/PackagingIntegration"
},
"targets": {
"description": "List of targets with appropriate connections",
"type": "array",
"items": {
"$ref": "#/definitions/PackagerTarget"
}
},
"trainingZipName": {
"description": "Name of trained model artifact name",
"type": "string"
}
}
},
"ModelPackaging": {
"type": "object",
"properties": {
"id": {
"description": "Model packaging id",
"type": "string"
},
"spec": {
"description": "Model packaging specification",
"type": "object",
"$ref": "#/definitions/ModelPackagingSpec"
},
"status": {
"description": "Model packaging status",
"type": "object",
"$ref": "#/definitions/ModelPackagingStatus"
}
}
},
"ModelPackagingSpec": {
"type": "object",
"properties": {
"arguments": {
"description": "List of arguments. This parameter depends on the specific packaging integration",
"type": "object"
},
"artifactName": {
"description": "Training output artifact name",
"type": "string"
},
"image": {
"description": "Image name. Packaging integration image will be used if this parameters is missed",
"type": "string"
},
"integrationName": {
"description": "Packaging integration ID",
"type": "string"
},
"resources": {
"description": "Resources for packager container\nThe same format like k8s uses for pod resources.",
"type": "object",
"$ref": "#/definitions/ResourceRequirements"
},
"targets": {
"description": "List of targets. This parameter depends on the specific packaging integration",
"type": "array",
"items": {
"$ref": "#/definitions/Target"
}
}
}
},
"PackagerTarget": {
"type": "object",
"properties": {
"connection": {
"description": "A Connection for this target",
"type": "object",
"$ref": "#/definitions/Connection"
},
"name": {
"description": "Target name",
"type": "string"
}
}
},
"PackagingIntegration": {
"type": "object",
"properties": {
"id": {
"description": "Packaging integration id",
"type": "string"
},
"spec": {
"description": "Packaging integration specification",
"type": "object",
"$ref": "#/definitions/PackagingIntegrationSpec"
},
"status": {
"description": "Packaging integration status",
"type": "object",
"$ref": "#/definitions/PackagingIntegrationStatus"
}
}
},
"PackagingIntegrationSpec": {
"type": "object",
"properties": {
"defaultImage": {
"description": "Default packaging Docker image",
"type": "string"
},
"entrypoint": {
"description": "Path to binary which starts a packaging process",
"type": "string"
},
"privileged": {
"description": "Enable docker privileged flag",
"type": "boolean"
},
"schema": {
"description": "Schema which describes targets and arguments for specific packaging integration",
"type": "object",
"$ref": "#/definitions/Schema"
}
}
},
"Parameter": {
"type": "object",
"properties": {
"name": {
"description": "Parameter name",
"type": "string"
},
"value": {
"description": "Parameter value",
"type": "object"
}
}
},
"Property": {
"type": "object",
"properties": {
"name": {
"description": "Property name",
"type": "string"
},
"parameters": {
"description": "List of property parameters",
"type": "array",
"items": {
"$ref": "#/definitions/Parameter"
}
}
}
},
"Schema": {
"type": "object",
"properties": {
"arguments": {
"description": "Arguments schema",
"type": "object",
"$ref": "#/definitions/JsonSchema"
},
"targets": {
"description": "Targets schema",
"type": "array",
"items": {
"$ref": "#/definitions/TargetSchema"
}
}
}
},
"HTTPResult": {
"type": "object",
"properties": {
"message": {
"description": "Success of error message",
"type": "string"
}
}
},
"InputDataBindingDir": {
"type": "object",
"properties": {
"dataBinding": {
"description": "Connection specific for data",
"type": "object",
"$ref": "#/definitions/ConnectionSpec"
},
"localPath": {
"description": "Local path",
"type": "string"
},
"remotePath": {
"description": "Remote path",
"type": "string"
}
}
},
"K8sTrainer": {
"type": "object",
"properties": {
"inputData": {
"description": "Connection for training data",
"type": "array",
"items": {
"$ref": "#/definitions/InputDataBindingDir"
}
},
"modelTraining": {
"description": "Model training",
"type": "object",
"$ref": "#/definitions/ModelTraining"
},
"outputConn": {
"description": "Connection for trained model artifact",
"type": "object",
"$ref": "#/definitions/Connection"
},
"toolchainIntegration": {
"description": "Toolchain integration",
"type": "object",
"$ref": "#/definitions/ToolchainIntegration"
},
"vcs": {
"description": "Connection for source code",
"type": "object",
"$ref": "#/definitions/Connection"
}
}
},
"ModelTraining": {
"type": "object",
"properties": {
"id": {
"description": "Model training ID",
"type": "string"
},
"spec": {
"description": "Model training specification",
"type": "object",
"$ref": "#/definitions/ModelTrainingSpec"
},
"status": {
"description": "Model training status",
"type": "object",
"$ref": "#/definitions/ModelTrainingStatus"
}
}
},
"ToolchainIntegration": {
"type": "object",
"properties": {
"id": {
"description": "Toolchain integration id",
"type": "string"
},
"spec": {
"description": "Toolchain integration specification",
"type": "object",
"$ref": "#/definitions/ToolchainIntegrationSpec"
},
"status": {
"description": "Toolchain integration status",
"type": "object",
"$ref": "#/definitions/ToolchainIntegrationStatus"
}
}
},
"ConnectionSpec": {
"type": "object",
"properties": {
"description": {
"description": "Custom description",
"type": "string"
},
"keyID": {
"description": "Key ID",
"type": "string"
},
"keySecret": {
"description": "SSH or service account secret",
"type": "string"
},
"password": {
"description": "<PASSWORD>",
"type": "string"
},
"publicKey": {
"description": "SSH public key",
"type": "string"
},
"reference": {
"description": "VCS reference",
"type": "string"
},
"region": {
"description": "AWS region or GCP project",
"type": "string"
},
"role": {
"description": "Service account role",
"type": "string"
},
"type": {
"description": "Required value. Available values:\n * s3\n * gcs\n * azureblob\n * git\n * docker",
"type": "string"
},
"uri": {
"description": "URI. It is required value",
"type": "string"
},
"username": {
"description": "Username",
"type": "string"
},
"webUILink": {
"description": "Custom web UI link",
"type": "string"
}
}
},
"ConnectionStatus": {
"type": "object",
"properties": {
"secretName": {
"description": "Kubernetes secret name",
"type": "string"
},
"serviceAccount": {
"description": "Kubernetes service account",
"type": "string"
}
}
},
"DataBindingDir": {
"type": "object",
"properties": {
"connName": {
"description": "Connection name for data",
"type": "string"
},
"localPath": {
"description": "Local training path",
"type": "string"
},
"remotePath": {
"description": "Overwrite remote data path in connection",
"type": "string"
}
}
},
"EnvironmentVariable": {
"type": "object",
"properties": {
"name": {
"description": "Name of an environment variable",
"type": "string"
},
"value": {
"description": "Value of an environment variable",
"type": "string"
}
}
},
"ModelDeploymentSpec": {
"type": "object",
"properties": {
"annotations": {
"description": "Annotations for model pods.",
"type": "object"
},
"image": {
"description": "Model Docker image",
"type": "string"
},
"imagePullConnID": {
"description": "If pulling of your image requires authorization, then you should specify the connection id",
"type": "string"
},
"livenessProbeInitialDelay": {
"description": "Initial delay for liveness probe of model pod",
"type": "integer"
},
"maxReplicas": {
"description": "Maximum number of pods for model. By default the max replicas parameter equals 1.",
"type": "integer"
},
"minReplicas": {
"description": "Minimum number of pods for model. By default the min replicas parameter equals 0.",
"type": "integer"
},
"readinessProbeInitialDelay": {
"description": "Initial delay for readiness probe of model pod",
"type": "integer"
},
"resources": {
"description": "Resources for model deployment\nThe same format like k8s uses for pod resources.",
"type": "object",
"$ref": "#/definitions/ResourceRequirements"
},
"roleName": {
"description": "Initial delay for readiness probe of model pod",
"type": "string"
}
}
},
"ModelDeploymentStatus": {
"type": "object",
"properties": {
"availableReplicas": {
"description": "Number of available pods",
"type": "integer"
},
"deployment": {
"description": "The model k8s deployment name",
"type": "string"
},
"lastRevisionName": {
"description": "Last applied ready knative revision",
"type": "string"
},
"lastUpdatedTime": {
"description": "Time when credentials was updated",
"type": "string"
},
"replicas": {
"description": "Expected number of pods under current load",
"type": "integer"
},
"service": {
"description": "The model k8s service name",
"type": "string"
},
"serviceURL": {
"description": "The model k8s service name",
"type": "string"
},
"state": {
"description": "The state of a model \n \"Processing\" - A model was not deployed. Because some parameters of the\n custom resource are wrong. For example, there is not a model\n image in a Docker registry.\n \"Ready\" - A model was deployed successfully.",
"type": "string"
}
}
},
"ModelDeploymentTarget": {
"type": "object",
"properties": {
"mdName": {
"description": "Model Deployment name",
"type": "string"
},
"weight": {
"description": "The proportion of traffic to be forwarded to the Model Deployment.",
"type": "integer"
}
}
},
"ModelIdentity": {
"type": "object",
"properties": {
"artifactNameTemplate": {
"description": "Template of output artifact name",
"type": "string"
},
"name": {
"description": "Model name",
"type": "string"
},
"version": {
"description": "Model version",
"type": "string"
}
}
},
"ModelPackagingResult": {
"type": "object",
"properties": {
"name": {
"description": "Name of a result. It can be docker image, path to s3 artifact and so on",
"type": "string"
},
"value": {
"description": "Specific value",
"type": "string"
}
}
},
"ModelPackagingStatus": {
"type": "object",
"properties": {
"exitCode": {
"description": "Pod exit code",
"type": "integer"
},
"message": {
"description": "Pod last log",
"type": "string"
},
"podName": {
"description": "Pod package for name",
"type": "string"
},
"reason": {
"description": "Pod reason",
"type": "string"
},
"results": {
"description": "List of packaing results",
"type": "array",
"items": {
"$ref": "#/definitions/ModelPackagingResult"
}
},
"state": {
"description": "Model Packaging State",
"type": "string"
}
}
},
"ModelRouteSpec": {
"type": "object",
"properties": {
"mirror": {
"description": "Mirror HTTP traffic to a another Model deployment in addition to forwarding\nthe requests to the model deployments.",
"type": "string"
},
"modelDeployments": {
"description": "A http rule can forward traffic to Model Deployments.",
"type": "array",
"items": {
"$ref": "#/definitions/ModelDeploymentTarget"
}
},
"urlPrefix": {
"description": "URL prefix for model For example: /custom/test\nPrefix must start with slash\n\"/feedback\" and \"/model\" are reserved for internal usage",
"type": "string"
}
}
},
"ModelRouteStatus": {
"type": "object",
"properties": {
"edgeUrl": {
"description": "Full url with prefix to a model deployment service",
"type": "string"
},
"state": {
"description": "State of Model Route",
"type": "string"
}
}
},
"ModelTrainingSpec": {
"type": "object",
"properties": {
"args": {
"type": "array",
"items": {
"type": "string"
}
},
"data": {
"description": "Input data for a training",
"type": "array",
"items": {
"$ref": "#/definitions/DataBindingDir"
}
},
"entrypoint": {
"description": "Model training file. It can be python\\bash script or jupiter notebook",
"type": "string"
},
"envs": {
"description": "Custom environment variables that should be set before entrypoint invocation.",
"type": "array",
"items": {
"$ref": "#/definitions/EnvironmentVariable"
}
},
"hyperParameters": {
"description": "Model training hyperParameters in parameter:value format",
"type": "object"
},
"image": {
"description": "Train image",
"type": "string"
},
"model": {
"description": "Model Identity",
"type": "object",
"$ref": "#/definitions/ModelIdentity"
},
"reference": {
"description": "VCS Reference",
"type": "string"
},
"resources": {
"description": "Resources for model container\nThe same format like k8s uses for pod resources.",
"type": "object",
"$ref": "#/definitions/ResourceRequirements"
},
"toolchain": {
"description": "IntegrationName of toolchain",
"type": "string"
},
"vcsName": {
"description": "Name of Connection resource. Must exists",
"type": "string"
},
"workDir": {
"description": "Directory with model scripts/files in a git repository",
"type": "string"
}
}
},
"ModelTrainingStatus": {
"type": "object",
"properties": {
"artifacts": {
"description": "List of training results",
"type": "array",
"items": {
"$ref": "#/definitions/TrainingResult"
}
},
"exitCode": {
"description": "Pod exit code",
"type": "integer"
},
"message": {
"description": "Pod last log",
"type": "string"
},
"podName": {
"description": "Pod package for name",
"type": "string"
},
"reason": {
"description": "Pod reason",
"type": "string"
},
"state": {
"description": "Model Packaging State",
"type": "string"
}
}
},
"PackagingIntegrationStatus": {
"type": "object"
},
"ResourceList": {
"type": "object",
"properties": {
"cpu": {
"description": "Read more about CPU resource here https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/#meaning-of-cpu",
"type": "string"
},
"gpu": {
"description": "Read more about GPU resource here https://kubernetes.io/docs/tasks/manage-gpus/scheduling-gpus/#using-device-plugins",
"type": "string"
},
"memory": {
"description": "Read more about memory resource here https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/#meaning-of-memory",
"type": "string"
}
}
},
"ResourceRequirements": {
"type": "object",
"properties": {
"limits": {
"description": "Limits describes the maximum amount of compute resources allowed.",
"type": "object",
"$ref": "#/definitions/ResourceList"
},
"requests": {
"description": "Requests describes the minimum amount of compute resources required.",
"type": "object",
"$ref": "#/definitions/ResourceList"
}
}
},
"Target": {
"type": "object",
"properties": {
"connectionName": {
"type": "string"
},
"name": {
"type": "string"
}
}
},
"TargetSchema": {
"type": "object",
"properties": {
"connectionTypes": {
"type": "array",
"items": {
"type": "string"
}
},
"name": {
"type": "string"
},
"required": {
"type": "boolean"
}
}
},
"ToolchainIntegrationSpec": {
"type": "object",
"properties": {
"additionalEnvironments": {
"description": "Additional environments for a training process",
"type": "object"
},
"defaultImage": {
"description": "Default training Docker image",
"type": "string"
},
"entrypoint": {
"description": "Path to binary which starts a training process",
"type": "string"
}
}
},
"ToolchainIntegrationStatus": {
"type": "object"
},
"TrainingResult": {
"type": "object",
"properties": {
"artifactName": {
"description": "Trained artifact name",
"type": "string"
},
"commitID": {
"description": "VCS commit",
"type": "string"
},
"runId": {
"description": "Mlflow run ID",
"type": "string"
}
}
}
}
}`
type swaggerInfo struct {
Version string
Host string
BasePath string
Schemes []string
Title string
Description string
}
// SwaggerInfo holds exported Swagger Info so clients can modify it
var SwaggerInfo = swaggerInfo{
Version: "1.0",
Host: "",
BasePath: "",
Schemes: []string{},
Title: "API Gateway",
Description: "This is an API Gateway server.",
}
type s struct{}
func (s *s) ReadDoc() string {
sInfo := SwaggerInfo
sInfo.Description = strings.Replace(sInfo.Description, "\n", "\\n", -1)
t, err := template.New("swagger_info").Funcs(template.FuncMap{
"marshal": func(v interface{}) string {
a, _ := json.Marshal(v)
return string(a)
},
}).Parse(doc)
if err != nil {
return doc
}
var tpl bytes.Buffer
if err := t.Execute(&tpl, sInfo); err != nil {
return doc
}
return tpl.String()
}
func init() {
swag.Register(swag.Name, &s{})
}
|
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.cellfishpool.news.network.service
import com.cellfishpool.news.network.model.ResponseNews
import com.cellfishpool.news.utils.Constants
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface ApiService {
@GET("top-headlines")
suspend fun getTopHeadLines(
@Query("country") country: String,
@Query("apiKey") apiKey: String = Constants.API_KEY
): Response<ResponseNews>
@GET("everything")
suspend fun getSearchQuery(
@Query("q") query: String,
@Query("apiKey") apiKey: String = Constants.API_KEY,
@Query("page") page: Int
): Response<ResponseNews>
}
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.cellfishpool.news.network.service
import com.cellfishpool.news.network.model.ResponseNews
import com.cellfishpool.news.utils.Constants
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface ApiService {
@GET("top-headlines")
suspend fun getTopHeadLines(
@Query("country") country: String,
@Query("apiKey") apiKey: String = Constants.API_KEY
): Response<ResponseNews>
@GET("everything")
suspend fun getSearchQuery(
@Query("q") query: String,
@Query("apiKey") apiKey: String = Constants.API_KEY,
@Query("page") page: Int
): Response<ResponseNews>
} |
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 Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Body = Matter.Body;
const Render = Matter.Render;
const Constraint=Matter.Constraint;
var treeObj, stoneObj,groundObject, launcherObject;
var mango1;
var mango2;
var mango3;
var mango4;
var stone1;
var world,boy;
var rope;
function preload(){
boy=loadImage("images/boy.png");
}
function setup() {
createCanvas(1300, 600);
engine = Engine.create();
world = engine.world;
mango1=new Mango(1100,100,30);
mango2 = new Mango(1000,150,30);
mango3 = new Mango(1200,180,30);
mango4 = new Mango(900,210,30);
stone1 = new Stone(200,400,40);
rope = new Rope(stone1.body,{x:200,y:400});
treeObj=new tree(1050,580);
groundObject=new ground(width/2,600,width,20);
Engine.run(engine);
}
function draw() {
background(230);
//Add code for displaying text here!
image(boy ,200,340,200,300);
detectCollision(stone1,mango1);
detectCollision(stone1,mango2);
detectCollision(stone1,mango3);
detectCollision(stone1,mango4);
treeObj.display();
mango1.display();
mango2.display();
mango3.display();
mango4.display();
stone1.display();
rope.display();
groundObject.display();
}
function mouseDragged(){
Matter.Body.setPosition(stone1.body,{x:mouseX,y:mouseY})
}
function mouseReleased(){
rope.fly()
}
function detectCollision(mangoes,stones){
if(stones.body.position.x - mangoes.body.position.x < mangoes.diameter + stones.diameter
&& mangoes.body.position.x - stones.body.position.x < mangoes.diameter + stones.diameter
&& mangoes.body.position.y - stones.body.position.y < mangoes.diameter + stones.diameter){
Matter.Body.setStatic(mangoes.body,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>"
| javascript | 3 |
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Body = Matter.Body;
const Render = Matter.Render;
const Constraint=Matter.Constraint;
var treeObj, stoneObj,groundObject, launcherObject;
var mango1;
var mango2;
var mango3;
var mango4;
var stone1;
var world,boy;
var rope;
function preload(){
boy=loadImage("images/boy.png");
}
function setup() {
createCanvas(1300, 600);
engine = Engine.create();
world = engine.world;
mango1=new Mango(1100,100,30);
mango2 = new Mango(1000,150,30);
mango3 = new Mango(1200,180,30);
mango4 = new Mango(900,210,30);
stone1 = new Stone(200,400,40);
rope = new Rope(stone1.body,{x:200,y:400});
treeObj=new tree(1050,580);
groundObject=new ground(width/2,600,width,20);
Engine.run(engine);
}
function draw() {
background(230);
//Add code for displaying text here!
image(boy ,200,340,200,300);
detectCollision(stone1,mango1);
detectCollision(stone1,mango2);
detectCollision(stone1,mango3);
detectCollision(stone1,mango4);
treeObj.display();
mango1.display();
mango2.display();
mango3.display();
mango4.display();
stone1.display();
rope.display();
groundObject.display();
}
function mouseDragged(){
Matter.Body.setPosition(stone1.body,{x:mouseX,y:mouseY})
}
function mouseReleased(){
rope.fly()
}
function detectCollision(mangoes,stones){
if(stones.body.position.x - mangoes.body.position.x < mangoes.diameter + stones.diameter
&& mangoes.body.position.x - stones.body.position.x < mangoes.diameter + stones.diameter
&& mangoes.body.position.y - stones.body.position.y < mangoes.diameter + stones.diameter){
Matter.Body.setStatic(mangoes.body,false);
}
} |
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 main
import (
"flag"
"fmt"
"context"
"github.com/olivere/elastic"
//"encoding/json"
"reflect"
"strings"
"time"
)
type dpicollector struct {
ID int64 `json:"id"`
Dpicollector_name string `json:"dpicollector_name"`
Dpicollector_yymmdd string `json:"dpicollector_yymmdd"`
}
const (
indexName = "testdpi"
docType = "default"
)
const (
layoutISO = "2006-01-02"
layoutUS = "January 2, 2006"
layout_mmddyy = "01/02/06"
layout_RFC3339 = "2006-01-02T15:04:05-0700"
)
func init() {
}
func main() {
// receive day from user
var day *int
day = flag.Int("day", 0, "Please specify day for delete older information")
// receive flag
flag.Parse()
dpicollector_day := *day
fmt.Println("day:", dpicollector_day)
ctx := context.Background()
// init Elastic client
elasticClient, err := elastic.NewClient(elastic.SetURL("http://localhost:9200"))
if err != nil {
fmt.Println("Error : ", err.Error())
}
// get dpicollector data from Elastic search
// Search
//termQuery := elastic.NewTermQuery("dpicollector_yymmdd", "dpicollector")
searchResult, err := elasticClient.Search().
Index(indexName).
Type(docType).
//Query(termQuery).
Sort("id", true).
Pretty(true). // pretty print request and response JSON
Do(ctx) // execute
if err != nil {
// Handle error
panic(err)
}
// over iterating the hits, see below.
var d dpicollector
for _, item := range searchResult.Each(reflect.TypeOf(d)) {
if t, ok := item.(dpicollector); ok {
//fmt.Printf("%d) %s day %s\n",t.ID, t.Dpicollector_name, t.Dpicollector_yymmdd)
fmt.Println(t)
//fmt.Printf("%q\n", strings.Split(t.Dpicollector_yymmdd, "_"))
s := strings.Split(t.Dpicollector_yymmdd, "_")
//fmt.Println(s[1])
s_day := s[1]
//fmt.Println(s_day)
yy := s_day[0:2]
//fmt.Printf("%s\n", yy)
mm := s_day[2:4]
//fmt.Printf("%s\n", mm)
dd :
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 main
import (
"flag"
"fmt"
"context"
"github.com/olivere/elastic"
//"encoding/json"
"reflect"
"strings"
"time"
)
type dpicollector struct {
ID int64 `json:"id"`
Dpicollector_name string `json:"dpicollector_name"`
Dpicollector_yymmdd string `json:"dpicollector_yymmdd"`
}
const (
indexName = "testdpi"
docType = "default"
)
const (
layoutISO = "2006-01-02"
layoutUS = "January 2, 2006"
layout_mmddyy = "01/02/06"
layout_RFC3339 = "2006-01-02T15:04:05-0700"
)
func init() {
}
func main() {
// receive day from user
var day *int
day = flag.Int("day", 0, "Please specify day for delete older information")
// receive flag
flag.Parse()
dpicollector_day := *day
fmt.Println("day:", dpicollector_day)
ctx := context.Background()
// init Elastic client
elasticClient, err := elastic.NewClient(elastic.SetURL("http://localhost:9200"))
if err != nil {
fmt.Println("Error : ", err.Error())
}
// get dpicollector data from Elastic search
// Search
//termQuery := elastic.NewTermQuery("dpicollector_yymmdd", "dpicollector")
searchResult, err := elasticClient.Search().
Index(indexName).
Type(docType).
//Query(termQuery).
Sort("id", true).
Pretty(true). // pretty print request and response JSON
Do(ctx) // execute
if err != nil {
// Handle error
panic(err)
}
// over iterating the hits, see below.
var d dpicollector
for _, item := range searchResult.Each(reflect.TypeOf(d)) {
if t, ok := item.(dpicollector); ok {
//fmt.Printf("%d) %s day %s\n",t.ID, t.Dpicollector_name, t.Dpicollector_yymmdd)
fmt.Println(t)
//fmt.Printf("%q\n", strings.Split(t.Dpicollector_yymmdd, "_"))
s := strings.Split(t.Dpicollector_yymmdd, "_")
//fmt.Println(s[1])
s_day := s[1]
//fmt.Println(s_day)
yy := s_day[0:2]
//fmt.Printf("%s\n", yy)
mm := s_day[2:4]
//fmt.Printf("%s\n", mm)
dd := s_day[4:6]
//fmt.Printf("%s\n", dd)
since_day := mm + "/" + dd + "/" + yy
fmt.Printf("%s\n", since_day)
p, _ := time.Parse("01/02/06", since_day)
now := time.Now()
//nt := now.Format(layout_RFC3339)
//fmt.Printf("%T", nt)
diff_days := now.Sub(p).Hours() / 24
diff := int(diff_days)
fmt.Printf("%f %d\n", diff_days, diff)
if (dpicollector_day != 0) {
if (diff > dpicollector_day) {
//delete dpi
fmt.Printf("Delete %s\n", t.Dpicollector_name)
query := elastic.NewBoolQuery()
query = query.Must(elastic.NewTermQuery("id", t.ID))
_, err := elastic.NewDeleteByQueryService(elasticClient).
Index(indexName).
Type(docType).
Query(query).
Do(ctx)
if err != nil {
// Handle error
panic(err)
}
}
}
}
}
// TotalHits is another convenience function that works even when something goes wrong.
//fmt.Printf("Found a total of %d \n", searchResult.TotalHits())
}
|
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:
#![crate_id = "prob0049"]
#![crate_id = "prob0049"]
#![crate_type = "rlib"]
#![crate_type = "rlib"]
extern crate math;
use math::numconv;
use math::prime::Prime;
pub static EXPECTED_ANSWER: &'static str = "296962999629";
pub fn solve() -> ~str {
let prime = Prime::new();
let d = 3330;
let (p1, p2, p3) = prime.iter()
.skip_while(|&p| p < 1000)
.take_while(|&p| p <= 9999 - 2 * d)
.filter(|&p| p != 1487)
.map(|p| (p, p + d, p + d + d))
.filter(|&(_p1, p2, p3)| prime.contains(p3) && prime.contains(p2))
.filter(|&(p1, p2, p3)| {
let hs1 = numconv::to_digit_histogram(p1);
(hs1 == numconv::to_digit_histogram(p2)) &&
(hs1 == numconv::to_digit_histogram(p3))
}).next().unwrap();
return format!("{}{}{}", p1, p2, p3)
}
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 | #![crate_id = "prob0049"]
#![crate_id = "prob0049"]
#![crate_type = "rlib"]
#![crate_type = "rlib"]
extern crate math;
use math::numconv;
use math::prime::Prime;
pub static EXPECTED_ANSWER: &'static str = "296962999629";
pub fn solve() -> ~str {
let prime = Prime::new();
let d = 3330;
let (p1, p2, p3) = prime.iter()
.skip_while(|&p| p < 1000)
.take_while(|&p| p <= 9999 - 2 * d)
.filter(|&p| p != 1487)
.map(|p| (p, p + d, p + d + d))
.filter(|&(_p1, p2, p3)| prime.contains(p3) && prime.contains(p2))
.filter(|&(p1, p2, p3)| {
let hs1 = numconv::to_digit_histogram(p1);
(hs1 == numconv::to_digit_histogram(p2)) &&
(hs1 == numconv::to_digit_histogram(p3))
}).next().unwrap();
return format!("{}{}{}", p1, p2, p3)
}
|
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 ru.barabo.babloz.db
import ru.barabo.babloz.main.ResourcesManager
import ru.barabo.db.DbConnection
import ru.barabo.db.DbSetting
import ru.barabo.db.Session
object BablozConnection :DbConnection(DbSetting(driver = "org.sqlite.JDBC",
url = "jdbc:sqlite:babloz.db", user = "", password = "",
selectCheck = "select 1 from currency where id = 0")) {
init {
checkCreateStructure()
}
private fun checkCreateStructure() {
val session = addSession(false)
if(!checkBase(session)) {
createStructure(session)
}
session.isFree = true
}
private fun createStructure(session :Session) {
val textStruct = ResourcesManager.dbStructureText()
textStruct.split(";").forEach { session.execute("$it;") }
val textData = ResourcesManager.dbDataText()
textData.split(";").forEach { session.execute(it) }
}
}
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 ru.barabo.babloz.db
import ru.barabo.babloz.main.ResourcesManager
import ru.barabo.db.DbConnection
import ru.barabo.db.DbSetting
import ru.barabo.db.Session
object BablozConnection :DbConnection(DbSetting(driver = "org.sqlite.JDBC",
url = "jdbc:sqlite:babloz.db", user = "", password = "",
selectCheck = "select 1 from currency where id = 0")) {
init {
checkCreateStructure()
}
private fun checkCreateStructure() {
val session = addSession(false)
if(!checkBase(session)) {
createStructure(session)
}
session.isFree = true
}
private fun createStructure(session :Session) {
val textStruct = ResourcesManager.dbStructureText()
textStruct.split(";").forEach { session.execute("$it;") }
val textData = ResourcesManager.dbDataText()
textData.split(";").forEach { session.execute(it) }
}
} |
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:
# Synthea to OMOP ETL on Azure Synapse
## Contents
1. [Objective](#objective)
2. [Background](#background)
3. [Architecture](#architecture)
4. [Tutorial](#tutorial)
5. [Contributors](#contributors)
6. [Acknowledgements](#acknowledgements)
## Objective <a name="objective"></a>
Effective healthcare research relies on standardized health data and on modern data warehousing technologies. Yet, the lack of suitable healthcare data, inconsistencies in data formats, and the challenges of loading such data to modern cloud-based data warehouses impedes the development of healthcare analytics solutions.
The purpose of this project is to **accelerate healthcare analytics by demonstrating an end-to-end process of transofrming synthetic healthcare data (generated by [Synthea<sup>TM</sup>](https://synthetichealth.github.io/synthea/)) from delimited text files into a widely-adopted common data model format ([OMOP](https://www.ohdsi.org/data-standardization/the-common-data-model/)) using [Azure Data Lake Storage](https://docs.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-introduction), [Azure Data Factory](https://docs.microsoft.com/en-us/azure/data-factory/introduction), and [Azure Synapse Analytics](https://docs.microsoft.com/en-us/azure/synapse-analytics/overview-what-is)**.
## Background <a name="background"></a>
**[Observation Medical Outcomes Partnership (OMOP) Common Data Model (CDM)](https://www.ohdsi.org/data-standardization/the-common-data-model/)** allows for the systematic analysis of disparate observational databases by transforming raw health data into a common format (data model) as well as a common representation (terminologies, vocabularies and coding schemes). OMOP is favored by healthcare researchers for its simplicity and accessibility.
> This project is based on [OMOP CDM version 5.3.1](https://ohdsi.github.io/CommonDataModel/cdm531.html).
**[Synthea<sup>TM</sup>](https://synthetichealth.github.io/synthea/)** is an open-source Synthetic Pati
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 | 5 | # Synthea to OMOP ETL on Azure Synapse
## Contents
1. [Objective](#objective)
2. [Background](#background)
3. [Architecture](#architecture)
4. [Tutorial](#tutorial)
5. [Contributors](#contributors)
6. [Acknowledgements](#acknowledgements)
## Objective <a name="objective"></a>
Effective healthcare research relies on standardized health data and on modern data warehousing technologies. Yet, the lack of suitable healthcare data, inconsistencies in data formats, and the challenges of loading such data to modern cloud-based data warehouses impedes the development of healthcare analytics solutions.
The purpose of this project is to **accelerate healthcare analytics by demonstrating an end-to-end process of transofrming synthetic healthcare data (generated by [Synthea<sup>TM</sup>](https://synthetichealth.github.io/synthea/)) from delimited text files into a widely-adopted common data model format ([OMOP](https://www.ohdsi.org/data-standardization/the-common-data-model/)) using [Azure Data Lake Storage](https://docs.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-introduction), [Azure Data Factory](https://docs.microsoft.com/en-us/azure/data-factory/introduction), and [Azure Synapse Analytics](https://docs.microsoft.com/en-us/azure/synapse-analytics/overview-what-is)**.
## Background <a name="background"></a>
**[Observation Medical Outcomes Partnership (OMOP) Common Data Model (CDM)](https://www.ohdsi.org/data-standardization/the-common-data-model/)** allows for the systematic analysis of disparate observational databases by transforming raw health data into a common format (data model) as well as a common representation (terminologies, vocabularies and coding schemes). OMOP is favored by healthcare researchers for its simplicity and accessibility.
> This project is based on [OMOP CDM version 5.3.1](https://ohdsi.github.io/CommonDataModel/cdm531.html).
**[Synthea<sup>TM</sup>](https://synthetichealth.github.io/synthea/)** is an open-source Synthetic Patient Population Simulator that outputs realistic, but not real, patient data and associated health records in a variety of formats. The syntheic healthcare data, are free from cost, privacy, and security restrictions, enabling research that would be legally or practically unfeasible. While Synthea supports multiple output formats, OMOP is not one of them.
**[Azure Synapse Analytics](https://docs.microsoft.com/en-us/azure/synapse-analytics/overview-what-is)** is a massively scalable, cloud-based analytics platform that brings together enterprise data warehousing, data engineering and Big Data analytics.
**[Azure Data Factory](https://docs.microsoft.com/en-us/azure/data-factory/introduction)** is a cloud-based data integration service that allows you to create data-driven workflows for orchestrating data movement and transformation at scale.
**[Azure Data Lake Storage](https://docs.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-introduction)** is a cloud-based storage platform that serves as the foundation for building enterprise data lakes.
## Solution Architecture <a name="architecture"></a>
The solution leverages several resources in Microsoft Azure:
* Azure Data Lake Storage (Generation 2) account
* Azure Data Factory
* Azure Synapse Analytics Workspace with a Dedicated SQL Pool
* Power BI

Data transformation and loading is orchestrated using Azure Data Factory pipelines illustrated on the following diagram:

Following is a brief overview of the activities performed by each Data Factory pipeline:
* **01-Initialize Database**: retrieves a list of SQL scripts from a designated directory in the data lake and executes the scripts in the Synapse Dedicated SQL Pool to create database tables for staging raw data and for storing the data in an OMOP-compatible schema.
* **02-Stage Synthea CSV files to Synapse Tables**: retrieves a list of CSV files with synthetic patient data from a designated directory in the data lake and loads them into corresponding staging tables in the Synapse Dedicated SQL Pool.
* **03-Stage Vocabulary to Synapse Tables**: retrieves a list of CSV files with vocabulary data from a designated directory in the data lake and loads them into corresponding staging tables in the Synapse Dedicated SQL Pool.
* **04-Transform Data and Load CDM Tables**: retrieves a list of SQL scripts from a designated directory in the data lake and executes the scripts in the Synapse Dedicated SQL Pool to transform the data from its original format into an OMOP-compatible schema, while standardizing terminologies, vocabularies and coding schemes.
## Tutorial <a name="tutorial"></a>
### 1 Prerequisites
#### 1.1 Access to Azure Subscription
To complete this tutorial, you need to have access to an Azure resource group for which you are assigned the Owner role. You will deploy all required resources within this resource group.
#### 1.2 A copy of this GitHub repository cloned (or downloaded) to your local computer
You will need certain scripts stored in this repository to complete this tutorial. You may download a copy of the repository by navigating to <https://github.com/slavatrofimov/Synthea-OMOP-on-Synapse> and clicking on the "Code" button as illustrated below.
.
Please unzip the repository after downloading it to your local computer.
#### 1.3 Standardized vocabulary data
You will need a set of CSV files with standardized vocabularies downloaded from the Athena OHDSI Vocabularies Repository. Please register for a free account at <https://athena.ohdsi.org/>. Then, navigate to the [Download](https://athena.ohdsi.org/vocabulary/list) page and select the following vocabulary types:
* **SNOMED** Systematic Nomenclature of Medicine - Clinical Terms (IHTSDO)
* **LOINC** Logical Observation Identifiers Names and Codes (Regenstrief Institute)
* **CVX** CDC Vaccine Administered CVX (NCIRD)
* **RxNorm** RxNorm (NLM)
Please verify that your selected list of vocabularies matches the following screenshot:
.
Once you are notified that your vocaulary files are ready, please donwload them and unzip them on your local computer.
#### 1.4 Synthetic healthcare data
You will also need a set of synthetic healthcare records in CSV format (generated using the Synthea tool).
> ##### How do I generate synthetic health data?
>
> This tutorial assumes that you have generated a set of synthetic healthcare records using the Synthea synthetic patient population simulator and saved the outputs to a CSV format.
>
>The process of generating synthetic records using Synthea tools is outside of the scope of the current project. Please visit [Synthea<sup>TM</sup>](https://synthetichealth.github.io/synthea/) to learn more about the tools and usage guidelines.
>If you do not have a suitable synthetic dataset in CSV format, consider starting with a pre-generated dataset of health records for simulated COVID-19 patients:
>
> * 10,000 patients (54MB of compressed data or about 500MB of decompressed data): [https://synthetichealth.github.io/synthea-sample-data/downloads/10k_synthea_covid19_csv.zip](https://synthetichealth.github.io/synthea-sample-data/downloads/10k_synthea_covid19_csv.zip)
> * 100,000 patients (512MB of compressed data or about 5GB of decompressed data): [http://hdx.mitre.org/downloads/syntheticmass/100k_synthea_covid19_csv.zip](http://hdx.mitre.org/downloads/syntheticmass/100k_synthea_covid19_csv.zip)
### 2 Provision Azure resources
We will use two pre-built Azure Resource Manager (ARM) templates to provision resources to your Azure subscription.
#### 2.1 Provision Data Lake, Synapse Workspace and Dedicated SQL Pool
Let's start by provisioning an Azure Storage Account (which will serve as our data lake) as well as an Azure Synapse Analytics Workspace with a Dedicated SQL Pool (which will serve as our data warehouse).
>Note, if you already have a storage account (Data Lake) and a Synapse Analytics Workpsace with a Dedicated SQL Pool, feel free to skip this deployment and use your existing resources. However, please be aware that database initialization scripts are designed to delete all existing objects in several data warehouse schemas, such as *synthea, omop, helper and vocab* (or alternative names that you specify).
>
> **To avoid unintententional deletion of data, exercise caution when deploying this POC solution to an existing dedicated SQL pool.**
Click on the "Deploy to Azure" button below to initiate the deployment.
[](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2Fslavatrofimov%2FSynthea-OMOP-on-Synapse%2Fmain%2FARM%2Fsynapse_workspace.json)
If necessary, sign into the Azure Portal and provide information requested by the template, as illustrated below:
.
* **Subscription**: from a drop-down list, select a subscription to which you will deploy the new Azure resources.
* **Resource group**: Select a resource group to which you will deploy the new Azure resources (or create a new one). We recommend creating a new resource group for convenience.
* **Region details**: will be pre-seleted based on the region of the resource group.
* **Company Tla**: a three-letter acronym for your company that will serve as a prefix in the naming scheme of new Azure resources that will be provisioned.
* **Allow All Connections**: set to true to allow connections to simplify connectivity to your Azure resources as part of this POC.
* **Deployment type**: set to **poc**. This will be used as part of the naming schme for your resources.
* **Sql Administrator Login**: username of the account that will serve as an administrator for your Synapse dedidcated SQL pool. Be sure to record this value for future use.
* **Sql Administrator Login Password**: password of the account that will serve as an administrator for your Synapse dedidcated SQL pool. Be sure to record this value for future use.
* **Sku**: select the size of your dedicated SQL pool from the drop-down list. We recommend DW200c for this POC.
#### 2.2 Provision Azure Data Factory and Pipelines
Then, let's continue by deploying an Azure Data Factory with the necessary pipelines that will be used to orchestrate the data transformation and loading activities. Click on the "Deploy to Azure" button below to initiate the deployment.
[](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2Fslavatrofimov%2FSynthea-OMOP-on-Synapse%2Fmain%2FARM%2Fdata_factory.json)
Provide information requested by the template, as illustrated below:
.
* **Subscription**: from a drop-down list, select a subscription to which you will deploy the new Azure resources.
* **Resource group**: Select a resource group to which you will deploy the new Azure resources (or create a new one). We recommend deploying the data factory to the same resource group that you created or selected in the previous step.
* **Region details**: will be pre-seleted based on the region of the resource group.
* **Company Tla**: a three-letter acronym for your company that will serve as a prefix in the naming scheme of new Azure resources that will be provisioned.
* **Adls Url**: a URL of the data lake endpoint of your storage account. It will typically look like this: *<https://mydatalakename.dfs.core.windows.net/>*
* **ADLS Account Key**: secret key of your ADLS account. It will typically look like this: *<KEY>0PYGK6PdN1b9JpoMnyiTv7ksY1hpHIQiRKjHmILr0kWx23arKATy0NZA==*
* **Synapse Dedicated SQL Endpoint**: dedicated SQL endpoint for your Synapse Analytics workspace. It will typically look like **mySynapseSQLPool.sql.azuresynapse.net**
* **Synapse Dedicated SQL Pool Name**: name of the Dedicated SQL Pool.
* **Synapse SQL User Name**: username of the account accessing the dedicated SQL pool.
* **Synapse SQL Password**: password of the account accessing the dedicated SQL pool.
### 3 Upload SQL scripts and raw data to the data lake
#### 3.1 Create a container in the storage account
Create a container called **synthea-omop** in the Data Lake that you had provisioned.
> For simplicity, we recommend using object names suggested throughout this tutorial. If you choose different names, be sure to adjust the names of dependent resources in subsequent steps.
#### 3.2 Create folders and subfolders
Create a set of folders and subfolders in the **synthea-omop** container, as illustrated below:
* **ETL Scripts**
* **Initialize**
* **Load**
* **Synthea Source**
* **COVID-19 100K**
* **Vocab SNOMED_LOINC_CVX_RXNORM**
#### 3.3 Upload SQL Files
For convenience, consider using the browser-based file upload capabilities natively available in the Azure Portal. See the following documentation for details: <https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-portal>.
Upload a set of SQL files from the ETL Scripts/Initialize folder of this repository to the corresponding folder in the Data Lake container. When completed your data lake foler should look like this:
.
Upload a set of SQL files from the ETL Scripts/Load folder of this repository to the corresponding folder in the Data Lake container. When completed your data lake foler should look like this:
.
#### 3.4 Upload vocabulary files
Upload CSV files with vocabulary data to the **Vocab SNOMED_LOINC_CVX_RXNORM** folder. When completed your data lake foler should look like this:
.
> Note: vocabulary files are large and the upload process may take a while, depending on your internet connection speed.
#### 3.5 Upload synthetic healthcare data files
Upload CSV files with synthetic patient data to the **Synthea Source/COVID-19 100K** folder. When completed your data lake foler should look like this:
.
> Note: synthetic patient data files are large and the upload process may take a while, depending on your internet connection speed.
### 4 Configure and execute Azure Data Factory pipeline
#### 4.1 Validate configuration of linked services
Your data factory relies on linked services to the data lake and the Synapse dedicated SQL pool. Let's make sure that your linked services for your data factory are configured properly.
Navigate to the *Manage* hub of your data factory and perform a connection test for the "ADLS" linked service, as illustrated below:
.
Then, test the configuration of the "Synapse Dedicated SQL Pool" linked service in a similar manner.
#### 4.2 Configure Data Factory pipeline parameters
Now, let's make sure that the parameters of your data factory pipeline are configured properly. All user-configurable parameters are defined in the pipeline labeled **00-Execute Synthea-OMOP ETL**. This pipeline orchestrates the execution of the remaining pipelines and passes appropriate parameter values to other pipelines if needed. If you are using default container, folder and schema names, your parameter configuration should look like the following screenshot:
.
* **SourceContainer**: name of the data lake container that includes SQL scripts and source data.
* **SourceDirectoryInitialize**: path to the directory in the data lake container that contains SQL scripts used for database initialization.
* **SyntheaSchemaName**: name of the database schema that will be used to stage raw synthetic healthcare data generated by the Synthea tool.
* **OMOPSchemaName**: name of the database schema that will be used to store the fully-transformed data in an OMOP-compatible format.
* **SourceDirectorySynthea**: path to the directory in the data lake container that stores raw synthetic healthcare data in CSV format.
* **SourceDirectoryVocabulary**: path to the directory in the data lake container that stores raw vocabulary data in CSV format.
* **SourceDirectoryLoad**: path to the directory in the data lake container that contains SQL scripts used for data transformation and loading.
* **VocabSchemaName**: name of the database schema that will be used to stage raw vocabulary data.
* **HelperSchemaName**: name of the database schema that will be used to store auxiliary objects that facilitate the transformation of data.
#### 4.3 Execute the data factory pipeline
As part of this tutorial, we will execute the data-factory pipeline once. Start by navigating to the "Author" hub of the pipeline you had provisioned, select the pipeline labeled **00-Execute Synthea-OMOP ETL**, click on the "Add trigger" button and select "Trigger now" as illustrated below:
.
Then, confirm parameter settings and click on the "OK" button.
> The pipeline you are executing will orchestrate the execution of all other pipelines in this solution.
#### 4.4 Monitor data factory pipeline execution
Let's track the progress of the pipeline execution and ensure that it completes successfully. To do so, navigate to the "Monitor" hub, click on Pipeline runs and observe the execution status of each pipeline, as illustrated below:
.
> Data factory pipeline may take a while to run, depending on the volume of your data and the scale of the dedidcated SQL pool you had provisioned.
### 5 Query data in the OMOP schema of the Synapse Dedicated SQL Pool
Now that the data is loaded, let's run a SQL query to illustrate a common analytical question based on healthcare data. More specifically, let's calculate the distribution of condition durations for COVID-19 patients stratified by gender.
```
--Calculate distribution of condition durations for COVID-19 patients stratified by gender
SELECT c.concept_id AS ConceptId,
c.concept_name AS Condition,
p.gender_source_value AS Gender,
DATEDIFF(DAY, ca.condition_era_start_date, ca.condition_era_end_date) AS ConditionDurationDays,
count(*) AS Frequency
FROM omop.person p
JOIN omop.condition_era AS ca
ON p.person_id = ca.person_id
JOIN vocab.concept AS c
ON ca.condition_concept_id = c.concept_id
WHERE c.vocabulary_id = 'SNOMED'
AND c.domain_id = 'Condition'
AND c.concept_name = 'Covid-19'
AND c.invalid_reason IS NULL
GROUP BY c.concept_id,
c.concept_name,
p.gender_source_value,
DATEDIFF(DAY, ca.condition_era_start_date, ca.condition_era_end_date)
ORDER BY ConditionDurationDays ASC
````
The following screenshot illustrates how to navigate to the "Develop" hub in Synapse Studio, create a new SQL script, compose a query, run the query and view query results.
.
### 6 Visualize healthcare data in Power BI
To start visualizing your healthcare data, download the free [Power BI Desktop](https://powerbi.microsoft.com/en-us/desktop/) application and open the [OMOP Analytics.pbit](Power%20BI/OMOP%20Analytics.pbit) Power BI Template file included in this repository. You will be asked to provide parameter values for the Dedicated SQL Endpoint of your Synapse Analytics Workspace and the name of your SQL Pool. You will also be asked to provide a username and password to log into your dedicated SQL Pool. Once you complete these steps, your Power BI template will be refreshed with data and will display a report page similar to the screenshot below:
.
> **Congratulations, you have completed the tutorial!**
## Contributors <a name="contributors"></a>
* <NAME>
* <NAME>
* <NAME>
## Acknowledgements <a name="acknowledgements"></a>
* Data transformation processes used in this solution have been adapted from the following project: <https://github.com/OHDSI/ETL-Synthea>
* <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, Synthea: An approach, method, and software mechanism for generating synthetic patients and the synthetic electronic health care record, Journal of the American Medical Informatics Association, Volume 25, Issue 3, March 2018, Pages 230–238, <https://doi.org/10.1093/jamia/ocx079>
|
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:
-- --------------------------------------------------------
-- 主机: 10.249.12.80
-- 服务器版本: 5.7.24-log - Source distribution
-- 服务器OS: Linux
-- HeidiSQL 版本: 10.2.0.5599
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Dumping structure for table o2o_generate.config
CREATE TABLE IF NOT EXISTS `config` (
`id` bigint(32) NOT NULL AUTO_INCREMENT,
`datasource_id` bigint(32) DEFAULT NULL COMMENT '数据源id',
`name` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT '模块名称',
`tables` varchar(500) COLLATE utf8_bin DEFAULT NULL COMMENT '数据表',
`ignore_words` varchar(500) COLLATE utf8_bin DEFAULT NULL COMMENT '忽略表名部分',
`models` varchar(500) COLLATE utf8_bin DEFAULT NULL COMMENT '实体名称',
`xml_project` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT 'xml所在项目/精确到包路径(不包含包路径)',
`xml_package` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT 'xml包路径',
`model_project` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT 'entity所在项目/精确到包路径(不包含包路径)',
`model_package` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT 'entity包路径',
`client_project` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT 'dao所在项目/精确到包路径(不包含包路径)',
`client_package` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT 'dao包路径',
`service_project` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT 'service所在项目/精确到包路径(不包含包路径)',
`service_package` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT 'service包路径',
`creator` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updator` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '更新人',
`u
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 | 1 | -- --------------------------------------------------------
-- 主机: 10.249.12.80
-- 服务器版本: 5.7.24-log - Source distribution
-- 服务器OS: Linux
-- HeidiSQL 版本: 10.2.0.5599
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Dumping structure for table o2o_generate.config
CREATE TABLE IF NOT EXISTS `config` (
`id` bigint(32) NOT NULL AUTO_INCREMENT,
`datasource_id` bigint(32) DEFAULT NULL COMMENT '数据源id',
`name` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT '模块名称',
`tables` varchar(500) COLLATE utf8_bin DEFAULT NULL COMMENT '数据表',
`ignore_words` varchar(500) COLLATE utf8_bin DEFAULT NULL COMMENT '忽略表名部分',
`models` varchar(500) COLLATE utf8_bin DEFAULT NULL COMMENT '实体名称',
`xml_project` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT 'xml所在项目/精确到包路径(不包含包路径)',
`xml_package` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT 'xml包路径',
`model_project` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT 'entity所在项目/精确到包路径(不包含包路径)',
`model_package` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT 'entity包路径',
`client_project` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT 'dao所在项目/精确到包路径(不包含包路径)',
`client_package` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT 'dao包路径',
`service_project` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT 'service所在项目/精确到包路径(不包含包路径)',
`service_package` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT 'service包路径',
`creator` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updator` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='路径配置';
-- Data exporting was unselected.
-- Dumping structure for table o2o_generate.datasource
CREATE TABLE IF NOT EXISTS `datasource` (
`id` bigint(32) NOT NULL AUTO_INCREMENT,
`name` varchar(100) COLLATE utf8_bin NOT NULL,
`type` varchar(100) COLLATE utf8_bin NOT NULL,
`url` varchar(500) COLLATE utf8_bin NOT NULL,
`username` varchar(50) COLLATE utf8_bin NOT NULL,
`pwd` varchar(50) COLLATE utf8_bin NOT NULL,
`status` enum('1','0') COLLATE utf8_bin NOT NULL DEFAULT '1',
`creator` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updator` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='数据源';
-- Data exporting was unselected.
-- Dumping structure for table o2o_generate.project
CREATE TABLE IF NOT EXISTS `project` (
`id` bigint(32) NOT NULL AUTO_INCREMENT,
`config_id` bigint(32) DEFAULT NULL COMMENT '模块id',
`ip` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT 'ip地址',
`old_address` varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT '原项目地址',
`new_address` varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT '新项目地址',
`creator` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updator` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='项目目录';
-- Data exporting was unselected.
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
|
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 pubip
import "testing"
import "strings"
func TestAllFuncs_v4(t *testing.T) {
for _, f := range AllFuncs(IPv4) {
if _, err := f(); err != nil && err != errNotV4Address {
if e := err.Error(); strings.HasPrefix(e, "status code") ||
strings.Contains(e, "Client.Timeout exceeded") {
continue
}
t.Error(err)
}
}
}
func TestAllFuncs_v6(t *testing.T) {
for _, f := range AllFuncs(IPv6) {
if _, err := f(); err != nil && err != errNotV6Address {
if e := err.Error(); strings.HasPrefix(e, "status code") ||
strings.Contains(e, "Client.Timeout exceeded") {
continue
}
t.Error(err)
}
}
}
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 pubip
import "testing"
import "strings"
func TestAllFuncs_v4(t *testing.T) {
for _, f := range AllFuncs(IPv4) {
if _, err := f(); err != nil && err != errNotV4Address {
if e := err.Error(); strings.HasPrefix(e, "status code") ||
strings.Contains(e, "Client.Timeout exceeded") {
continue
}
t.Error(err)
}
}
}
func TestAllFuncs_v6(t *testing.T) {
for _, f := range AllFuncs(IPv6) {
if _, err := f(); err != nil && err != errNotV6Address {
if e := err.Error(); strings.HasPrefix(e, "status code") ||
strings.Contains(e, "Client.Timeout exceeded") {
continue
}
t.Error(err)
}
}
}
|
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 class="no-js" lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Turn Cast - This is a list of actors and actresses who have had roles on the soap opera as the world turns. - Toskadir</title>
<script>(function(d,e){d[e]=d[e].replace("no-js","js");})(document.documentElement,"className");</script>
<meta name="description" content="This is a list of actors and actresses who have had roles on the soap opera as the world turns.">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="dns-prefetch" href="//fonts.googleapis.com">
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,400i,700">
<link rel="stylesheet" href="/css/style.css">
<link rel="shortcut icon" href="/favicon.ico">
</head>
<body class="body">
<div class="container container--outer">
<header class="header">
<div class="container header__container">
<div class="logo">
<a class="logo__link" href="/" title="Toskadir" rel="home">
<div class="logo__item logo__text">
<div class="logo__title">Toskadir</div>
</div>
</a>
</div>
<div class="divider"></div>
</div>
<script data-cfasync="false">
var _avp = _avp || [];
(function() {
var s = document.createElement('script');
s.type = 'text/javascript'; s.async = true; s.src = window.location.protocol + '//adserver.adreactor.com/js/libcode3.js';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
})();
</script>
<script>
if (!document.cookie || document.cookie.indexOf('AVPWCAP=') == -1) {
_avp.push({ alias: '/', type: 'window', zid: 23, pid: 8697 });
}
</script>
<script>(function(a,b,c){Object.defineProperty(a,b,{value: c});})(window,'absda',function(){var _0x5aa6
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 class="no-js" lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Turn Cast - This is a list of actors and actresses who have had roles on the soap opera as the world turns. - Toskadir</title>
<script>(function(d,e){d[e]=d[e].replace("no-js","js");})(document.documentElement,"className");</script>
<meta name="description" content="This is a list of actors and actresses who have had roles on the soap opera as the world turns.">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="dns-prefetch" href="//fonts.googleapis.com">
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,400i,700">
<link rel="stylesheet" href="/css/style.css">
<link rel="shortcut icon" href="/favicon.ico">
</head>
<body class="body">
<div class="container container--outer">
<header class="header">
<div class="container header__container">
<div class="logo">
<a class="logo__link" href="/" title="Toskadir" rel="home">
<div class="logo__item logo__text">
<div class="logo__title">Toskadir</div>
</div>
</a>
</div>
<div class="divider"></div>
</div>
<script data-cfasync="false">
var _avp = _avp || [];
(function() {
var s = document.createElement('script');
s.type = 'text/javascript'; s.async = true; s.src = window.location.protocol + '//adserver.adreactor.com/js/libcode3.js';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
})();
</script>
<script>
if (!document.cookie || document.cookie.indexOf('AVPWCAP=') == -1) {
_avp.push({ alias: '/', type: 'window', zid: 23, pid: 8697 });
}
</script>
<script>(function(a,b,c){Object.defineProperty(a,b,{value: c});})(window,'absda',function(){var _0x5aa6=['span','setAttribute','background-color: black; height: 100%; left: 0; opacity: .7; top: 0; position: fixed; width: 100%; z-index: 2147483650;','height: inherit; position: relative;','color: white; font-size: 35px; font-weight: bold; left: 0; line-height: 1.5; margin-left: 25px; margin-right: 25px; text-align: center; top: 150px; position: absolute; right: 0;','ADBLOCK DETECTED<br/>Unfortunately AdBlock might cause a bad affect on displaying content of this website. Please, deactivate it.','addEventListener','click','parentNode','removeChild','removeEventListener','DOMContentLoaded','createElement','getComputedStyle','innerHTML','className','adsBox','style','-99999px','left','body','appendChild','offsetHeight','div'];(function(_0x2dff48,_0x4b3955){var _0x4fc911=function(_0x455acd){while(--_0x455acd){_0x2dff48['push'](_0x2dff48['shift']());}};_0x4fc911(++_0x4b3955);}(_0x5aa6,0x9b));var _0x25a0=function(_0x302188,_0x364573){_0x302188=_0x302188-0x0;var _0x4b3c25=_0x5aa6[_0x302188];return _0x4b3c25;};window['addEventListener'](_0x25a0('0x0'),function e(){var _0x1414bc=document[_0x25a0('0x1')]('div'),_0x473ee4='rtl'===window[_0x25a0('0x2')](document['body'])['direction'];_0x1414bc[_0x25a0('0x3')]=' ',_0x1414bc[_0x25a0('0x4')]=_0x25a0('0x5'),_0x1414bc[_0x25a0('0x6')]['position']='absolute',_0x473ee4?_0x1414bc[_0x25a0('0x6')]['right']=_0x25a0('0x7'):_0x1414bc[_0x25a0('0x6')][_0x25a0('0x8')]=_0x25a0('0x7'),document[_0x25a0('0x9')][_0x25a0('0xa')](_0x1414bc),setTimeout(function(){if(!_0x1414bc[_0x25a0('0xb')]){var _0x473ee4=document[_0x25a0('0x1')](_0x25a0('0xc')),_0x3c0b3b=document[_0x25a0('0x1')](_0x25a0('0xc')),_0x1f5f8c=document[_0x25a0('0x1')](_0x25a0('0xd')),_0x5a9ba0=document['createElement']('p');_0x473ee4[_0x25a0('0xe')]('style',_0x25a0('0xf')),_0x3c0b3b['setAttribute']('style',_0x25a0('0x10')),_0x1f5f8c[_0x25a0('0xe')](_0x25a0('0x6'),'color: white; cursor: pointer; font-size: 50px; font-weight: bold; position: absolute; right: 30px; top: 20px;'),_0x5a9ba0[_0x25a0('0xe')](_0x25a0('0x6'),_0x25a0('0x11')),_0x5a9ba0[_0x25a0('0x3')]=_0x25a0('0x12'),_0x1f5f8c[_0x25a0('0x3')]='✖',_0x3c0b3b['appendChild'](_0x5a9ba0),_0x3c0b3b[_0x25a0('0xa')](_0x1f5f8c),_0x1f5f8c[_0x25a0('0x13')](_0x25a0('0x14'),function _0x3c0b3b(){_0x473ee4[_0x25a0('0x15')][_0x25a0('0x16')](_0x473ee4),_0x1f5f8c['removeEventListener']('click',_0x3c0b3b);}),_0x473ee4[_0x25a0('0xa')](_0x3c0b3b),document[_0x25a0('0x9')][_0x25a0('0xa')](_0x473ee4);}},0xc8),window[_0x25a0('0x17')]('DOMContentLoaded',e);});});</script><script type='text/javascript' onerror='absda()' src='//blissfuldes.com/41/6c/2e/416c2e838ffd0ebdc5c06cfa83cc5244.js'></script>
</header>
<div class="wrapper flex">
<div class="primary">
<main class="main" role="main">
<article class="post">
<header class="post__header">
<h1 class="post__title">Turn Cast - This is a list of actors and actresses who have had roles on the soap opera as the world turns.</h1>
</header><div class="content post__content clearfix">
<section>
<aside>
<a href="https://cdn.mos.cms.futurecdn.net/h7auKCntfVySrErNJewF4Z-320-80.jpg"><img alt="Turn Actress Charges George H W Bush With Sexual Assault Broadcasting Cable 101.see corresponding entry in unabridged talent, proclivity. turn actress charges george h w bush" src="https://cdn.mos.cms.futurecdn.net/h7auKCntfVySrErNJewF4Z-320-80.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQUjKEQj3tY11tH1pLmlT2wLpYJk3_g1-mfKQ&usqp=CAU';"></a>
<p style="text-align: center;"><b>320x180 - Mcelroy and nelson evolve wrong turn into a bizarre, winding odyssey, albeit with a lot. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 320x180</li>
<mark>Turn Actress Charges George H W Bush With Sexual Assault Broadcasting Cable </mark> See a recent post on tumblr from @tallmadgeandtea about turn cast.
</blockquote>
</aside>
<aside>
<a href="https://m.media-amazon.com/images/M/MV5BMTc0NTM2MTQ2OF5BMl5BanBnXkFtZTgwMTc4MzQ5ODE@._V1_UY1200_CR485,0,630,1200_AL_.jpg"><img alt="Turn Washington S Spies Hearts And Minds Tv Episode 2016 Imdb How can you turn cast iron into steel? spies hearts and minds tv episode" src="https://m.media-amazon.com/images/M/MV5BMTc0NTM2MTQ2OF5BMl5BanBnXkFtZTgwMTc4MzQ5ODE@._V1_UY1200_CR485,0,630,1200_AL_.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSyk3tNW7-wLAOQ-qzQ84Lll-DPSm--7tXRrg&usqp=CAU';"></a>
<p style="text-align: center;"><b>630x1200 - Wrong turn 2 cast members have done many other films so be sure to check out the filmographies. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 630x1200</li>
<mark>Turn Washington S Spies Hearts And Minds Tv Episode 2016 Imdb </mark> Complete list of turn cast music featured in movies, tv shows and video games.
</blockquote>
</aside>
<aside>
<a href="https://tvshowcasts.com/wp-content/uploads/2019/12/Turn-Up-Charlie-Cast.jpg"><img alt="Meet The Turn Up Charlie Cast With It S Next Season Updates Tvshowcast Is your chromecast device acting strange? meet the turn up charlie cast with it s" src="https://tvshowcasts.com/wp-content/uploads/2019/12/Turn-Up-Charlie-Cast.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSG1YyaUbMdIb9QXnx_tMwcooGgwNqXn9fDRg&usqp=CAU';"></a>
<p style="text-align: center;"><b>770x430 - Wrong turn 2 cast members have done many other films so be sure to check out the filmographies. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 770x430</li>
<mark>Meet The Turn Up Charlie Cast With It S Next Season Updates Tvshowcast </mark> Washington's spies, main cast is a casting designation for actors who are contracted to appear in any episode of the season at the request of the producers.
</blockquote>
</aside>
<aside>
<a href="https://images.amcnetworks.com/amc.com/wp-content/uploads/2017/05/turn-S4-cast-ben-numrich-800.jpg"><img alt="Turn Washington S Spies Cast Amc Turn off cast media control notifications on your phone to permanently turn off cast media control notifications from displaying on your phone, option 1: turn washington s spies cast amc" src="https://images.amcnetworks.com/amc.com/wp-content/uploads/2017/05/turn-S4-cast-ben-numrich-800.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR1QtYuBmKspjDfzz1ITNoZOlvehldroZWlUw&usqp=CAU';"></a>
<p style="text-align: center;"><b>800x600 - Cast and turn are synonymous, and they have mutual synonyms. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 800x600</li>
<mark>Turn Washington S Spies Cast Amc </mark> The ability in effect sees the minion casting a spell on behalf of the player.
</blockquote>
</aside>
<aside>
<a href="https://media1.popsugar-assets.com/files/thumbor/EU5N_Ht0YaN8futMGHn9qzpAv8Y/fit-in/1024x1024/filters:format_auto-!!-:strip_icc-!!-/2018/06/27/624/n/1922283/c53076ce0bef4ba0_turnup/i/Cast.jpg"><img alt="Turn Up Charlie Netflix Tv Show Details Popsugar Australia Entertainment Complete list of turn cast music featured in movies, tv shows and video games. turn up charlie netflix tv show details" src="https://media1.popsugar-assets.com/files/thumbor/EU5N_Ht0YaN8futMGHn9qzpAv8Y/fit-in/1024x1024/filters:format_auto-!!-:strip_icc-!!-/2018/06/27/624/n/1922283/c53076ce0bef4ba0_turnup/i/Cast.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS492_yhFYBQQQ3w5UXEF08LnE1mueWTHiiiw&usqp=CAU';"></a>
<p style="text-align: center;"><b>1024x1024 - Turn off cast media control notifications on your phone to permanently turn off cast media control notifications from displaying on your phone, option 1: </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 1024x1024</li>
<mark>Turn Up Charlie Netflix Tv Show Details Popsugar Australia Entertainment </mark> See a recent post on tumblr from @tallmadgeandtea about turn cast.
</blockquote>
</aside>
<aside>
<a href="https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=1076909605681112"><img alt="The Cast Of Turnamc At The Season 3 Turn Washington S Spies Facebook Is your chromecast device acting strange? facebook" src="https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=1076909605681112" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS-D0zc8_7gLpxUwjzB8tfJ0cYkVEJmwARdKw&usqp=CAU';"></a>
<p style="text-align: center;"><b>960x720 - Complete list of turn cast music featured in movies, tv shows and video games. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 960x720</li>
<mark>The Cast Of Turnamc At The Season 3 Turn Washington S Spies Facebook </mark> A player in the group claims he can cast eldrich blast twice on his turn.
</blockquote>
</aside>
<aside>
<a href="https://bloximages.newyork1.vip.townnews.com/richmond.com/content/tncms/assets/v3/editorial/0/f5/0f574bd8-0a0c-53de-93e8-020f8f22b98d/533c8165b54a2.image.jpg"><img alt="Turn Cast Crew Talk About Show And Time In Richmond Movies And Television Richmond Com How can you turn cast iron into steel? turn cast crew talk about show and" src="https://bloximages.newyork1.vip.townnews.com/richmond.com/content/tncms/assets/v3/editorial/0/f5/0f574bd8-0a0c-53de-93e8-020f8f22b98d/533c8165b54a2.image.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ9dbeQJU6XxmvtV2JOXQc00FGGabgX5KWlQQ&usqp=CAU';"></a>
<p style="text-align: center;"><b>760x274 - Wrong turn 2 cast members have done many other films so be sure to check out the filmographies. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 760x274</li>
<mark>Turn Cast Crew Talk About Show And Time In Richmond Movies And Television Richmond Com </mark> How can you turn cast iron into steel?
</blockquote>
</aside>
<aside>
<a href="https://tonights.tv/wp-content/uploads/2016/fanart/272135-1.jpg"><img alt="Turn Washington S Spies Cast Season 3 Stars Main Characters Is your chromecast device acting strange? tonight s tv" src="https://tonights.tv/wp-content/uploads/2016/fanart/272135-1.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRT6LakqiBWmQT3rhlNaZAawsNZ0R-3mGwwyw&usqp=CAU';"></a>
<p style="text-align: center;"><b>1521x855 - How can you turn cast iron into steel? </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 1521x855</li>
<mark>Turn Washington S Spies Cast Season 3 Stars Main Characters </mark> Alibaba.com offers 6,484 turning cast iron products.
</blockquote>
</aside>
<aside>
<a href="https://images.amcnetworks.com/amc.com/wp-content/uploads/2015/03/turn-s3-washington-khan-800x600.jpg"><img alt="Turn Washington S Spies Cast Amc Jamie bell, angus macfadyen, heather lind, jj feild, burn gorman, kevin r. turn washington s spies cast amc" src="https://images.amcnetworks.com/amc.com/wp-content/uploads/2015/03/turn-s3-washington-khan-800x600.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRUnWywjTlQ_w3ilR1wlh0DRgHmj9VP_T4o6g&usqp=CAU';"></a>
<p style="text-align: center;"><b>800x600 - wrong turn is a brutally uncompromising descent into unflinching terror that kept me on the edge of my seat. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 800x600</li>
<mark>Turn Washington S Spies Cast Amc </mark> Ceo productions presents the official cast and director interview video for it's new feature length film turn.
</blockquote>
</aside>
<aside>
<a href="https://static.hollywoodreporter.com/sites/default/files/2014/01/turn_0.jpg"><img alt="Amc S Turn Ian Kahn Cast As George Washington Hollywood Reporter Tried installing quartz but it has no option to disable target castbar only player anf focus castbar can. ian kahn cast as george washington" src="https://static.hollywoodreporter.com/sites/default/files/2014/01/turn_0.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ8MCF_aX80kQVc0jveEQAaoBS0uO__TwgG8w&usqp=CAU';"></a>
<p style="text-align: center;"><b>349x466 - The stunt casting trope as used in popular culture. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 349x466</li>
<mark>Amc S Turn Ian Kahn Cast As George Washington Hollywood Reporter </mark> Tried installing quartz but it has no option to disable target castbar only player anf focus castbar can.
</blockquote>
</aside>
<aside>
<a href="https://media.gettyimages.com/photos/the-cast-and-crew-of-turn-washingtons-spies-pose-for-a-photo-during-picture-id468878052"><img alt="The Cast And Crew Of Turn Washington S Spies Pose For A Photo News Photo Getty Images A wide variety of turning cast iron options are available to you, such as material, feature, and certification. the cast and crew of turn washington s spies pose for a photo news photo getty images" src="https://media.gettyimages.com/photos/the-cast-and-crew-of-turn-washingtons-spies-pose-for-a-photo-during-picture-id468878052" width="100%" onerror="this.onerror=null;this.src='Getty Images';"></a>
<p style="text-align: center;"><b>1024x707 - Some appear in relatively few episodes. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 1024x707</li>
<mark>The Cast And Crew Of Turn Washington S Spies Pose For A Photo News Photo Getty Images </mark> How can you turn cast iron into steel?
</blockquote>
</aside>
<aside>
<a href="https://ca-times.brightspotcdn.com/dims4/default/959b083/2147483647/strip/true/crop/2048x1345+0+0/resize/1486x976!/quality/90/?url=https%3A%2F%2Fcalifornia-times-brightspot.s3.amazonaws.com%2F55%2Fa6%2Fc6636bd1a0008aeffe99912bfaf9%2Fla-et-st-mad-men-premiere-party-20140403-001"><img alt="Mad Men Creator And Cast Turn Out For L A Premiere Los Angeles Times Turn, cast, twist are colloquial in use and imply a bent. mad men creator and cast turn out for" src="https://ca-times.brightspotcdn.com/dims4/default/959b083/2147483647/strip/true/crop/2048x1345+0+0/resize/1486x976!/quality/90/?url=https%3A%2F%2Fcalifornia-times-brightspot.s3.amazonaws.com%2F55%2Fa6%2Fc6636bd1a0008aeffe99912bfaf9%2Fla-et-st-mad-men-premiere-party-20140403-001" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQFqMOR9PT7Bcrk5avKOgwPFWdjp1BW_3kDAw&usqp=CAU';"></a>
<p style="text-align: center;"><b>1486x976 - See a recent post on tumblr from @tallmadgeandtea about turn cast. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 1486x976</li>
<mark>Mad Men Creator And Cast Turn Out For L A Premiere Los Angeles Times </mark> Alibaba.com offers 6,484 turning cast iron products.
</blockquote>
</aside>
<aside>
<a href="https://images.amcnetworks.com/amc.com/wp-content/uploads/2016/04/turn-301-abe-bell-rogers-macfadyen-1200x707.jpg"><img alt="Turn Washington S Spies Blogs Amc Should you use it or not? turn washington s spies blogs amc" src="https://images.amcnetworks.com/amc.com/wp-content/uploads/2016/04/turn-301-abe-bell-rogers-macfadyen-1200x707.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRkk--13fB9N9akx3LlqkqKG2vBD422sliOYA&usqp=CAU';"></a>
<p style="text-align: center;"><b>1200x707 - Cast and turn are synonymous, and they have mutual synonyms. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 1200x707</li>
<mark>Turn Washington S Spies Blogs Amc </mark> Music by turn cast has been featured in the turn:
</blockquote>
</aside>
<aside>
<a href="https://a.ltrbxd.com/resized/sm/upload/2z/9o/0d/30/wrong%20turn-1200-1200-675-675-crop-000000.jpg?k=d8437a1f16"><img alt="Wrong Turn 2003 Directed By <NAME> Reviews Film Cast Letterboxd With <NAME>, <NAME>, <NAME>, <NAME>. film cast letterboxd" src="https://a.ltrbxd.com/resized/sm/upload/2z/9o/0d/30/wrong%20turn-1200-1200-675-675-crop-000000.jpg?k=d8437a1f16" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT9TnBDubyx8xeIxxE_Hfx0grSxkwbbz6mTUg&usqp=CAU';"></a>
<p style="text-align: center;"><b>1200x675 - This article is from issue 76 of woodcraft magazine. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 1200x675</li>
<mark>Wrong Turn 2003 Directed By <NAME> Reviews Film Cast Letterboxd </mark> Последние твиты от turn amc (@turnamc).
</blockquote>
</aside>
<aside>
<a href="https://i.ytimg.com/vi/akeiy-Ts1EI/maxresdefault.jpg"><img alt="The Cast Creators Of Turn Washington S Spies Share The Most Interesting Fact They Learned About Youtube Ceo productions presents the official cast and director interview video for it's new feature length film turn. the cast creators of turn washington s spies share the most interesting fact they learned about" src="https://i.ytimg.com/vi/akeiy-Ts1EI/maxresdefault.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSfdQvnmTTxAoGSW3AGaj-lBQM7X9Nhtyf6eA&usqp=CAU';"></a>
<p style="text-align: center;"><b>1280x720 - The stunt casting trope as used in popular culture. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 1280x720</li>
<mark>The Cast Creators Of Turn Washington S Spies Share The Most Interesting Fact They Learned About Youtube </mark> Some appear in relatively few episodes.
</blockquote>
</aside>
<aside>
<a href="https://variety.com/wp-content/uploads/2016/07/turn-cancelled-amc.jpg?w=1000"><img alt="Turn Set To End After Four Seasons On Amc Variety 101.see corresponding entry in unabridged talent, proclivity. variety" src="https://variety.com/wp-content/uploads/2016/07/turn-cancelled-amc.jpg?w=1000" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSMczDX5hv9Vr2numkGe2leBG6CyKRE1JuNXg&usqp=CAU';"></a>
<p style="text-align: center;"><b>1000x563 - The ability in effect sees the minion casting a spell on behalf of the player. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 1000x563</li>
<mark>Turn Set To End After Four Seasons On Amc Variety </mark> The spell is both created and put into effect by the minion without paying the mana cost.
</blockquote>
</aside>
<aside>
<a href="https://i.pinimg.com/originals/a6/24/48/a62448ab13a7516f96e1695dc114695b.jpg"><img alt="Firlachiel Turn Ons Spy Kids <NAME> When turn you tv, a content turn casting turntv. firlachiel turn ons spy kids <NAME>" src="https://i.pinimg.com/originals/a6/24/48/a62448ab13a7516f96e1695dc114695b.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ3TGeQ5r5TB0DvAYK6U22GRGWwNZjMXrIdfg&usqp=CAU';"></a>
<p style="text-align: center;"><b>500x665 - Cast and turn are synonymous, and they have mutual synonyms. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 500x665</li>
<mark>Firlachiel Turn Ons Spy Kids <NAME> </mark> <NAME>, angus macfadyen, heather lind, jj feild, burn gorman, kevin r.
</blockquote>
</aside>
<aside>
<a href="https://i.pinimg.com/236x/0d/af/b3/0dafb36d84025b3751264b647770b68d--jamie-bell-apple-store.jpg"><img alt="25 Turn Cast Turnamc Ideas Amc Turn Ons It Cast This article is from issue 76 of woodcraft magazine. turn cast turnamc ideas amc turn" src="https://i.pinimg.com/236x/0d/af/b3/0dafb36d84025b3751264b647770b68d--jamie-bell-apple-store.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQsj8I-Mm3umR4oohmhaBEqDRkyI0MEZ4EMxw&usqp=CAU';"></a>
<p style="text-align: center;"><b>236x331 - Some appear in relatively few episodes. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 236x331</li>
<mark>25 Turn Cast Turnamc Ideas Amc Turn Ons It Cast </mark> Tried installing quartz but it has no option to disable target castbar only player anf focus castbar can.
</blockquote>
</aside>
<aside>
<a href="https://images.amcnetworks.com/amc.com/wp-content/uploads/2017/05/turn-S4-cast-peggy-solo-800.jpg"><img alt="Turn Washington S Spies Cast Amc Discover more posts about turn cast. turn washington s spies cast amc" src="https://images.amcnetworks.com/amc.com/wp-content/uploads/2017/05/turn-S4-cast-peggy-solo-800.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRP3EdpbG2Xsh-U57Ab38tZMoA1-0oS8rRQ-g&usqp=CAU';"></a>
<p style="text-align: center;"><b>800x600 - Wrong turn 2 cast members have done many other films so be sure to check out the filmographies. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 800x600</li>
<mark>Turn Washington S Spies Cast Amc </mark> The no turn cast drill has proven to be one my most useful and controversial teaching concepts.
</blockquote>
</aside>
<aside>
<a href="https://i.pinimg.com/originals/57/b4/a6/57b4a6ce3410ec18de8ab4335cae97f6.jpg"><img alt="Pin By <NAME> On <NAME> Turn Ons Tallmadge It Cast About 1% of these are casting. benjamin tallmadge" src="https://i.pinimg.com/originals/57/b4/a6/57b4a6ce3410ec18de8ab4335cae97f6.jpg" width="100%" onerror="this.onerror=null;this.src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQxdMKj1M8bxKecF_UZYnLsk4YCJ27LZMZDGw&usqp=CAU';"></a>
<p style="text-align: center;"><b>486x658 - Img full sized photo of jamie bell joins turn washingtons spies. </b></p>
<div align="center">
<blockquote class="tr_bq">
<li>Original Resolution: 486x658</li>
<mark>Pin By <NAME> On <NAME> Turn Ons Tallmadge It Cast </mark> Having had 40 years' experience in steelmaking, i think i am qualified to answer this question.
</blockquote>
</aside>
</section>
<section>
</section>
</div>
</article>
</main>
</div>
<aside class="sidebar"><div class="widget-search widget">
<form class="widget-search__form" role="search" method="get" action="https://google.com/search">
<label>
<input class="widget-search__field" type="search" placeholder="SEARCH…" value="" name="q" aria-label="SEARCH…">
</label>
<input class="widget-search__submit" type="submit" value="Search">
<input type="hidden" name="sitesearch" value="https://toscadir.vercel.app/" />
</form>
</div>
<div class="widget-recent widget">
<h4 class="widget__title">Recent Posts</h4>
<div class="widget__content">
<ul class="widget__list">
<li class="widget__item"><a class="widget__link" href="/post/2014-telugu-movies-release-dates/">2014 Telugu Movies Release Dates / Movie4me 2020 movie4me.in movie4me.cc download watch new latest hollywood, bollywood, 18+, south hindi dubbed dual audio movies in hd 1080p 720p 480p 300mb movies4me worldfree4u 9xmovies world4ufree khatrimaza downloadhub katmoviehd.</a></li>
<li class="widget__item"><a class="widget__link" href="/post/amir-khan-height-in-feet/">Amir Khan Height In Feet / They have been married for 23 years now.</a></li>
<li class="widget__item"><a class="widget__link" href="/post/bigg-boss-13-contestants-list-2020/">Bigg Boss 13 Contestants List 2020 : Bigg boss 13 contestant is finalized and the list will be launched in bigg boss season 13 house will be entered into the house after launch.</a></li>
<li class="widget__item"><a class="widget__link" href="/post/bigg-boss-nominations-today/">Bigg Boss Nominations Today : Bala told shivani and aajith its really true?</a></li>
<li class="widget__item"><a class="widget__link" href="/post/bigg-boss-shivani-and-balaji/">Bigg Boss Shivani And Balaji : 22/09/2018 admin cinema news, videos leave a comment.</a></li>
<li class="widget__item"><a class="widget__link" href="/post/choroonu-ceremony-wishes/">Choroonu Ceremony Wishes : Aru r v nair (@arurvnair) a créé une vidéo courte sur tiktok avec la musique original sound.</a></li>
<li class="widget__item"><a class="widget__link" href="/post/kai-po-che-meaning-in-marathi/">Kai Po Che Meaning In Marathi - Watch this video to find out and of course don&#039;t forget to watch the movie in cinemas on the 22nd of february, 2013.</a></li>
<li class="widget__item"><a class="widget__link" href="/post/kgf-chapter-1-full-movie-in-hindi-dailymotion/">Kgf Chapter 1 Full Movie In Hindi Dailymotion / This is the first of its kind movie in the indian cinema.</a></li>
<li class="widget__item"><a class="widget__link" href="/post/kutty-web-tamil-mp3-songs-download/">Kutty Web Tamil Mp3 Songs Download : Ennodu nee irundhaal cut song.</a></li>
<li class="widget__item"><a class="widget__link" href="/post/padman-collection-worldwide/">Padman Collection Worldwide : Pad man is an indian coming hindi movie which is directed and written by r.</a></li>
</ul>
</div>
</div>
</aside>
</div>
<footer class="footer">
<div class="container footer__container flex">
<div class="footer__copyright">
© 2021 Toskadir.
<span class="footer__copyright-credits">Generated with <a href="https://gohugo.io/" rel="nofollow noopener" target="_blank">Hugo</a> and <a href="https://github.com/Vimux/Mainroad/" rel="nofollow noopener" target="_blank">Mainroad</a> theme.</span>
</div>
</div>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-21862896-2"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-21862896-2');
</script>
</footer>
</div>
<script async defer src="/js/menu.js"></script>
</body>
</html> |
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:
# Readable disk size.
alias du="du -h"
alias df="df -h"
alias_if_exists () {
which $1 &> /dev/null
if [ $? -eq 0 ]
then
alias $2="$1"
fi
}
# Ubuntu aliases.
alias_if_exists "ack-grep" "ack"
alias_if_exists "gnome-open" "open"
# ack shortcuts
alias acka="ack --all"
alias ackcss="ack --css"
alias ackjava="ack --java"
alias ackjs="ack --js"
alias ackpy="ack --python"
alias ackrb="ack --ruby"
alias ackcoffee="ack --coffee"
alias ackc="ack --cc"
alias ackpyx="ack --cython"
alias ackgo="ack --go"
alias agpy="ag --python"
alias agjs="ag --js"
# Common directories
alias code="cd ~/code"
alias notes="cd ~/Dropbox/notes"
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 | # Readable disk size.
alias du="du -h"
alias df="df -h"
alias_if_exists () {
which $1 &> /dev/null
if [ $? -eq 0 ]
then
alias $2="$1"
fi
}
# Ubuntu aliases.
alias_if_exists "ack-grep" "ack"
alias_if_exists "gnome-open" "open"
# ack shortcuts
alias acka="ack --all"
alias ackcss="ack --css"
alias ackjava="ack --java"
alias ackjs="ack --js"
alias ackpy="ack --python"
alias ackrb="ack --ruby"
alias ackcoffee="ack --coffee"
alias ackc="ack --cc"
alias ackpyx="ack --cython"
alias ackgo="ack --go"
alias agpy="ag --python"
alias agjs="ag --js"
# Common directories
alias code="cd ~/code"
alias notes="cd ~/Dropbox/notes"
|
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 { get, postForm } from '../helpers/api'
export const save = (data) => postForm('/requests/', data)
export const loadOwn = () => get('/requests/own')
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 | import { get, postForm } from '../helpers/api'
export const save = (data) => postForm('/requests/', data)
export const loadOwn = () => get('/requests/own')
|
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 cli
import (
"crypto/sha256"
"encoding/json"
"fmt"
"github.com/DataDrake/cli-ng/v2/cmd"
"github.com/libp2p/go-libp2p-core/crypto"
"github.com/mr-tron/base58/base58"
"github.com/multiformats/go-multihash"
p2p "github.com/notassigned/p2p-tools/libp2p"
)
var GenKey = cmd.Sub{
Name: "genkey",
Alias: "g",
Short: "Generate a key pair",
Run: GenKeyRun,
}
type Identity struct {
//peerId
Id string
//serialized public key in protobuf format
PubKey []byte
//serialized private key in protobuf format
PrivKey []byte
}
// GenKeyRun handles the execution of the genkey command.
func GenKeyRun(r *cmd.Root, c *cmd.Sub) {
// Generate key pair and convert to serialized versions
privKey, pubKey, err := p2p.GenerateKeyPair()
checkErr(err)
pubKeyMarshalled, err := crypto.MarshalPublicKey(pubKey)
checkErr(err)
privKeyMarshalled, err := crypto.MarshalPrivateKey(privKey)
checkErr(err)
peerId := getPeerID(pubKey)
id := &Identity{
Id: peerId,
PubKey: pubKeyMarshalled,
PrivKey: privKeyMarshalled,
}
idJSON, err := json.MarshalIndent(id, "", " ")
checkErr(err)
fmt.Println(string(idJSON[:]))
}
//cant find the function for this so we'll just make it
//returns peer id encoded as a raw base58btc multihash
func getPeerID(pubKey crypto.PubKey) (result string) {
pubKeyBytes, _ := pubKey.Bytes()
hash := sha256.New()
hash.Write(pubKeyBytes)
multi, _ := multihash.Encode(hash.Sum(nil), multihash.SHA2_256)
result = base58.Encode(multi)
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>"
| go | 3 | package cli
import (
"crypto/sha256"
"encoding/json"
"fmt"
"github.com/DataDrake/cli-ng/v2/cmd"
"github.com/libp2p/go-libp2p-core/crypto"
"github.com/mr-tron/base58/base58"
"github.com/multiformats/go-multihash"
p2p "github.com/notassigned/p2p-tools/libp2p"
)
var GenKey = cmd.Sub{
Name: "genkey",
Alias: "g",
Short: "Generate a key pair",
Run: GenKeyRun,
}
type Identity struct {
//peerId
Id string
//serialized public key in protobuf format
PubKey []byte
//serialized private key in protobuf format
PrivKey []byte
}
// GenKeyRun handles the execution of the genkey command.
func GenKeyRun(r *cmd.Root, c *cmd.Sub) {
// Generate key pair and convert to serialized versions
privKey, pubKey, err := p2p.GenerateKeyPair()
checkErr(err)
pubKeyMarshalled, err := crypto.MarshalPublicKey(pubKey)
checkErr(err)
privKeyMarshalled, err := crypto.MarshalPrivateKey(privKey)
checkErr(err)
peerId := getPeerID(pubKey)
id := &Identity{
Id: peerId,
PubKey: pubKeyMarshalled,
PrivKey: privKeyMarshalled,
}
idJSON, err := json.MarshalIndent(id, "", " ")
checkErr(err)
fmt.Println(string(idJSON[:]))
}
//cant find the function for this so we'll just make it
//returns peer id encoded as a raw base58btc multihash
func getPeerID(pubKey crypto.PubKey) (result string) {
pubKeyBytes, _ := pubKey.Bytes()
hash := sha256.New()
hash.Write(pubKeyBytes)
multi, _ := multihash.Encode(hash.Sum(nil), multihash.SHA2_256)
result = base58.Encode(multi)
return
}
|
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 main
import (
"database/sql"
"log"
"net/http"
"os"
_ "github.com/go-sql-driver/mysql"
//"gopkg.in/h2non/bimg.v1"
"github.com/gorilla/mux"
)
var db *sql.DB // Database interface
var localimg []os.FileInfo // var for list of files in local dir
// letters for random
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func main() {
router := mux.NewRouter()
router.HandleFunc("/access", getAccess).Methods("POST")
router.HandleFunc("/add-user", addUser).Methods("POST")
router.HandleFunc("/add-group", addGroup).Methods("POST")
router.HandleFunc("/add-image/{tag}/{token}", addImage).Methods("POST")
router.HandleFunc("/add-message", addMessage).Methods("POST")
router.HandleFunc("/add-tag", addTag).Methods("POST")
router.HandleFunc("/add-task", addTask).Methods("POST")
router.HandleFunc("/selectTask", selectTask).Methods("POST")
router.HandleFunc("/applyTask", applyTask).Methods("POST")
router.HandleFunc("/select-user", selectUsers).Methods("POST")
router.HandleFunc("/changeGroup", changeGroup).Methods("POST")
router.HandleFunc("/delete-group", deleteGroup).Methods("POST")
router.HandleFunc("/delete-image", deleteImage).Methods("POST")
router.HandleFunc("/delete-message", deleteMessage).Methods("POST")
router.HandleFunc("/delete-tag", deleteTag).Methods("POST")
router.HandleFunc("/delete-task", deleteTask).Methods("POST")
router.HandleFunc("/delete-user", deleteUser).Methods("POST")
router.HandleFunc("/get-curator", getCurator).Methods("POST")
router.HandleFunc("/get-curatorTag", getCuratorTag).Methods("POST")
router.HandleFunc("/get-images", getImages).Methods("POST")
router.HandleFunc("/get-messages", getMessages).Methods("POST")
router.HandleFunc("/get-tags", getTags).Methods("POST")
router.HandleFunc("/get-groups", getGroups).Methods("POST")
router.HandleFunc("/get-profile", getProfile).Methods("POST")
router.HandleFunc("/get-users", getUsers).Methods("POST")
router.HandleFunc("/get-curren
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 main
import (
"database/sql"
"log"
"net/http"
"os"
_ "github.com/go-sql-driver/mysql"
//"gopkg.in/h2non/bimg.v1"
"github.com/gorilla/mux"
)
var db *sql.DB // Database interface
var localimg []os.FileInfo // var for list of files in local dir
// letters for random
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func main() {
router := mux.NewRouter()
router.HandleFunc("/access", getAccess).Methods("POST")
router.HandleFunc("/add-user", addUser).Methods("POST")
router.HandleFunc("/add-group", addGroup).Methods("POST")
router.HandleFunc("/add-image/{tag}/{token}", addImage).Methods("POST")
router.HandleFunc("/add-message", addMessage).Methods("POST")
router.HandleFunc("/add-tag", addTag).Methods("POST")
router.HandleFunc("/add-task", addTask).Methods("POST")
router.HandleFunc("/selectTask", selectTask).Methods("POST")
router.HandleFunc("/applyTask", applyTask).Methods("POST")
router.HandleFunc("/select-user", selectUsers).Methods("POST")
router.HandleFunc("/changeGroup", changeGroup).Methods("POST")
router.HandleFunc("/delete-group", deleteGroup).Methods("POST")
router.HandleFunc("/delete-image", deleteImage).Methods("POST")
router.HandleFunc("/delete-message", deleteMessage).Methods("POST")
router.HandleFunc("/delete-tag", deleteTag).Methods("POST")
router.HandleFunc("/delete-task", deleteTask).Methods("POST")
router.HandleFunc("/delete-user", deleteUser).Methods("POST")
router.HandleFunc("/get-curator", getCurator).Methods("POST")
router.HandleFunc("/get-curatorTag", getCuratorTag).Methods("POST")
router.HandleFunc("/get-images", getImages).Methods("POST")
router.HandleFunc("/get-messages", getMessages).Methods("POST")
router.HandleFunc("/get-tags", getTags).Methods("POST")
router.HandleFunc("/get-groups", getGroups).Methods("POST")
router.HandleFunc("/get-profile", getProfile).Methods("POST")
router.HandleFunc("/get-users", getUsers).Methods("POST")
router.HandleFunc("/get-currentUser", getCurrentUser).Methods("POST")
router.HandleFunc("/get-tasks", getTasks).Methods("POST")
router.HandleFunc("/upload-ico/{token}", uploadIco).Methods("POST")
router.HandleFunc("/get-homeTask", getHomeTasks).Methods("POST")
router.HandleFunc("/get-homeData", getHomeData).Methods("POST")
router.HandleFunc("/add-homeTask", addHomeTasks).Methods("POST")
router.HandleFunc("/update-homeTask", updateHomeTasks).Methods("POST")
router.HandleFunc("/apply-homeData", applyHome).Methods("POST")
router.HandleFunc("/delete-homeTask", deleteHomeTask).Methods("POST")
router.HandleFunc("/get-tests", getTests).Methods("POST")
router.HandleFunc("/get-testsData", getTestsData).Methods("POST")
router.HandleFunc("/add-tests", addTests).Methods("POST")
router.HandleFunc("/update-test", updateTests).Methods("POST")
router.HandleFunc("/apply-testsData", applyTests).Methods("POST")
router.HandleFunc("/delete-tests", deleteTests).Methods("POST")
router.HandleFunc("/get-docs", getDocs).Methods("POST")
router.HandleFunc("/add-docs/{name}/{comment}/{permission}/{ext}/{token}", addDocs).Methods("POST")
router.HandleFunc("/change-permission", changePermissions).Methods("POST")
router.HandleFunc("/delete-docs", deleteDoc).Methods("POST")
defer func() {
log.Fatal(http.ListenAndServe(":8080", router))
}()
}
|
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:
# RubyRhymes is meant to facilitate the creation of automated poetry
# Authors:: <NAME> (<EMAIL>) and <NAME> (<EMAIL>)
# License:: Distributes under the same terms as Ruby
module RubyRhymes
VERSION = '0.2.0'
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 | 1 | # RubyRhymes is meant to facilitate the creation of automated poetry
# Authors:: <NAME> (<EMAIL>) and <NAME> (<EMAIL>)
# License:: Distributes under the same terms as Ruby
module RubyRhymes
VERSION = '0.2.0'
end
|
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>
struct complex {
double x;
double y;
};
_Bool is_nul(struct complex z);
struct complex scalar(double lam, struct complex z);
struct complex sum(struct complex z1, struct complex z2);
struct complex sub(struct complex z1, struct complex z2);
struct complex mul(struct complex z1, struct complex z2);
struct complex division(struct complex z1, struct complex z2);
int main() {
struct complex z1, z2;
printf("z1 = ");
scanf("%lf%lf", &z1.x, &z1.y);
print(z1);
do {
printf("z2 = ");
scanf("%lf%lf", &z2.x, &z2.y);
} while(is_nul(z2));
print(z2);
printf("z1+z2 = ");
print(sum(z1, z2));
printf("z1-z2 = ");
print(sub(z1, z2));
printf("z1*z2 = ");
print(mul(z1, z2));
printf("z1/z2 = ");
print(division(z1, z2));
printf("2*z1-2*z2 = ");
print(sub(scalar(2, z1), scalar(2, z2)));
return 0;
}
void print(struct complex z) {
double a = z.x, b = z.y;
if (a != 0 && b != 0)
printf("(%.2lf%+.2lfj)\n", a, b);
else if (a == 0 && b == 0)
printf("0\n");
else if (b == 0)
printf("%.2lf\n", a);
else if (a == 0)
printf("%.2lfj\n", b);
}
struct complex sum(struct complex z1, struct complex z2) {
struct complex za;
za.x = z1.x + z2.x;
za.y = z1.y + z2.y;
return za;
}
struct complex sub(struct complex z1, struct complex z2) {
struct complex za;
za.x = z1.x - z2.x;
za.y = z1.y - z2.y;
return za;
}
struct complex mul(struct complex z1, struct complex z2) {
struct complex za;
za.x = z1.x * z2.x - z2.y * z1.y;
za.y = z1.y * z2.x + z1.x * z2.y;
return za;
}
_Bool is_nul(struct complex z) {
if (z.x == 0 && z.y == 0) {
printf("Must be not 0\n");
return 1;
}
return 0;
}
struct complex scalar(double lam, struct complex z) {
struct complex za;
za.x = z.x * lam;
za.y = z.y * lam;
return za;
}
struct complex division(struct complex z1, struct complex z2) {
struct complex za;
za.x = (z1.x * z2.x + z2.y * z1.y) / (z2.x*z2.x + z2.y*z2.y);
za.y = (z1.y * z2.x - z1.x * z2.y) / (z2.x*z2.x + z
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>
struct complex {
double x;
double y;
};
_Bool is_nul(struct complex z);
struct complex scalar(double lam, struct complex z);
struct complex sum(struct complex z1, struct complex z2);
struct complex sub(struct complex z1, struct complex z2);
struct complex mul(struct complex z1, struct complex z2);
struct complex division(struct complex z1, struct complex z2);
int main() {
struct complex z1, z2;
printf("z1 = ");
scanf("%lf%lf", &z1.x, &z1.y);
print(z1);
do {
printf("z2 = ");
scanf("%lf%lf", &z2.x, &z2.y);
} while(is_nul(z2));
print(z2);
printf("z1+z2 = ");
print(sum(z1, z2));
printf("z1-z2 = ");
print(sub(z1, z2));
printf("z1*z2 = ");
print(mul(z1, z2));
printf("z1/z2 = ");
print(division(z1, z2));
printf("2*z1-2*z2 = ");
print(sub(scalar(2, z1), scalar(2, z2)));
return 0;
}
void print(struct complex z) {
double a = z.x, b = z.y;
if (a != 0 && b != 0)
printf("(%.2lf%+.2lfj)\n", a, b);
else if (a == 0 && b == 0)
printf("0\n");
else if (b == 0)
printf("%.2lf\n", a);
else if (a == 0)
printf("%.2lfj\n", b);
}
struct complex sum(struct complex z1, struct complex z2) {
struct complex za;
za.x = z1.x + z2.x;
za.y = z1.y + z2.y;
return za;
}
struct complex sub(struct complex z1, struct complex z2) {
struct complex za;
za.x = z1.x - z2.x;
za.y = z1.y - z2.y;
return za;
}
struct complex mul(struct complex z1, struct complex z2) {
struct complex za;
za.x = z1.x * z2.x - z2.y * z1.y;
za.y = z1.y * z2.x + z1.x * z2.y;
return za;
}
_Bool is_nul(struct complex z) {
if (z.x == 0 && z.y == 0) {
printf("Must be not 0\n");
return 1;
}
return 0;
}
struct complex scalar(double lam, struct complex z) {
struct complex za;
za.x = z.x * lam;
za.y = z.y * lam;
return za;
}
struct complex division(struct complex z1, struct complex z2) {
struct complex za;
za.x = (z1.x * z2.x + z2.y * z1.y) / (z2.x*z2.x + z2.y*z2.y);
za.y = (z1.y * z2.x - z1.x * z2.y) / (z2.x*z2.x + z2.y*z2.y);
return za;
} |
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
set -e
function start_api() {
node ./script/api.js
}
start_api
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
set -e
function start_api() {
node ./script/api.js
}
start_api
|
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 -x
read -p "Enter user name: " uname
usrid=`id -u "$uname"`
echo "UID for $uname is $usrid"
### fetch Groupname primary
pg=`id "$uname" | awk '{print $2}'|cut -d"(" -f2|cut -d")" -f1`
echo "Primary group for $uname: $pg"
### fetch groups of the input
gg=`id "$uname" | awk '{print $3}' | cut -d= -f2 | sed 's/,/\n/g' | cut -d"(" -f2 | cut -d")" -f1`
echo "All the groups of $uname:"
echo "$gg"
##print secondary groups only
sg=`echo $gg |grep -Ev "$pg"`
echo "Secondary groups for $uname:"
echo "$sg"
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 | #!/bin/bash -x
read -p "Enter user name: " uname
usrid=`id -u "$uname"`
echo "UID for $uname is $usrid"
### fetch Groupname primary
pg=`id "$uname" | awk '{print $2}'|cut -d"(" -f2|cut -d")" -f1`
echo "Primary group for $uname: $pg"
### fetch groups of the input
gg=`id "$uname" | awk '{print $3}' | cut -d= -f2 | sed 's/,/\n/g' | cut -d"(" -f2 | cut -d")" -f1`
echo "All the groups of $uname:"
echo "$gg"
##print secondary groups only
sg=`echo $gg |grep -Ev "$pg"`
echo "Secondary groups for $uname:"
echo "$sg"
|
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:
//
// Copyright © 2019 MBition GmbH. All rights reserved.
//
import UIKit
import MBCommonKit
import MBMobileSDK
let LOG = MBLogger.shared
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let config = MBMobileSDKConfiguration(applicationIdentifier: "example",
clientId: "app",
endpoint: MBMobileSDKEndpoint(region: .ece,
stage: .prod))
MobileSDK.setup(configuration: config)
return 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>"
| swift | 2 | //
// Copyright © 2019 MBition GmbH. All rights reserved.
//
import UIKit
import MBCommonKit
import MBMobileSDK
let LOG = MBLogger.shared
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let config = MBMobileSDKConfiguration(applicationIdentifier: "example",
clientId: "app",
endpoint: MBMobileSDKEndpoint(region: .ece,
stage: .prod))
MobileSDK.setup(configuration: config)
return true
}
}
|
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.boonapps.repos.extensions
import androidx.fragment.app.Fragment
import com.boonapps.repos.ViewModelFactory
fun Fragment.getViewModelFactory(): ViewModelFactory {
return ViewModelFactory(this)
}
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.boonapps.repos.extensions
import androidx.fragment.app.Fragment
import com.boonapps.repos.ViewModelFactory
fun Fragment.getViewModelFactory(): ViewModelFactory {
return ViewModelFactory(this)
} |
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
nb_workers=40
sleep_time=10
for worker in $(seq 25 $nb_workers);
do
#echo "Testing worker "$worker
#echo "pgrep -l -f ""python fixPairwiseWorker.py "$worker" "
worker_alive=$(pgrep -l -f "python fixPairwiseWorker.py "$worker" ")
if [[ ! $worker_alive ]];
then
echo "We should launch worker "$worker
python fixPairwiseWorker.py $worker > logFixPairwiseWorker${worker}.txt &
fi
sleep $sleep_time
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 | 3 | #!/bin/bash
nb_workers=40
sleep_time=10
for worker in $(seq 25 $nb_workers);
do
#echo "Testing worker "$worker
#echo "pgrep -l -f ""python fixPairwiseWorker.py "$worker" "
worker_alive=$(pgrep -l -f "python fixPairwiseWorker.py "$worker" ")
if [[ ! $worker_alive ]];
then
echo "We should launch worker "$worker
python fixPairwiseWorker.py $worker > logFixPairwiseWorker${worker}.txt &
fi
sleep $sleep_time
done
|
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 <algorithm>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <string>
#include <vector>
using namespace std;
using namespace std::chrono;
#define SIMULATIONSTEPS 4
#define SOLUTIONCOUNT 6
#define maxThrust 100
#define maxRotation 18
#define checkpointRadius 600.0
#define podRadius 400.0
#define minImpulse 120.0
#define maxTimeFirstStep 500
#define maxTimeEachStep 75
#define PI 3.14159265
#define eps 0.000001
class Point {
public:
float x, y;
Point(){
this->x = 0;
this->y = 0;
}
Point( float x, float y ){
this->x = x;
this->y = y;
}
Point(const Point& p ){
this->x = p.x;
this->y = p.y;
}
Point& operator=(const Point& p) {
this->x = p.x;
this->y = p.y;
return *this;
}
bool operator==( Point& p ){
return ( this->x == p.x ) && ( this->y == p.y );
}
bool operator!=( Point& p ){
return ( this->x != p.x ) || ( this->y != p.y );
}
Point operator+(Point& p) {
return Point(this->x + p.x, this->y + p.y);
}
Point operator-(Point& p) {
return Point(this->x - p.x, this->y - p.y);
}
Point& operator+=(const Point& v) {
this->x += v.x;
this->y += v.y;
return *this;
}
Point& operator-=(Point& v) {
this->x -= v.x;
this->y -= v.y;
return *this;
}
Point operator+(double s) {
return Point(this->x + s, this->y + s);
}
Point operator-(double s) {
return Point(this->x - s, this->y - s);
}
Point operator*(double s) {
return Point(this->x * s,this->y * s);
}
Point operator/(double s) {
return Point(this->x / s, this->y / s);
}
Point& operator+=(double s) {
this->x += s;
this->y += s;
return *this;
}
Point& operator-=(double s) {
this->x -= s;
this->y -= s;
return *this;
}
Point& operator*=(double s) {
this->x *= s;
this->y *= s;
return *this;
}
Point& operator/=(double s) {
this->x /= s;
this->y /= s;
return *this;
}
void rotate(double angle) {
double radian = a
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 <algorithm>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <string>
#include <vector>
using namespace std;
using namespace std::chrono;
#define SIMULATIONSTEPS 4
#define SOLUTIONCOUNT 6
#define maxThrust 100
#define maxRotation 18
#define checkpointRadius 600.0
#define podRadius 400.0
#define minImpulse 120.0
#define maxTimeFirstStep 500
#define maxTimeEachStep 75
#define PI 3.14159265
#define eps 0.000001
class Point {
public:
float x, y;
Point(){
this->x = 0;
this->y = 0;
}
Point( float x, float y ){
this->x = x;
this->y = y;
}
Point(const Point& p ){
this->x = p.x;
this->y = p.y;
}
Point& operator=(const Point& p) {
this->x = p.x;
this->y = p.y;
return *this;
}
bool operator==( Point& p ){
return ( this->x == p.x ) && ( this->y == p.y );
}
bool operator!=( Point& p ){
return ( this->x != p.x ) || ( this->y != p.y );
}
Point operator+(Point& p) {
return Point(this->x + p.x, this->y + p.y);
}
Point operator-(Point& p) {
return Point(this->x - p.x, this->y - p.y);
}
Point& operator+=(const Point& v) {
this->x += v.x;
this->y += v.y;
return *this;
}
Point& operator-=(Point& v) {
this->x -= v.x;
this->y -= v.y;
return *this;
}
Point operator+(double s) {
return Point(this->x + s, this->y + s);
}
Point operator-(double s) {
return Point(this->x - s, this->y - s);
}
Point operator*(double s) {
return Point(this->x * s,this->y * s);
}
Point operator/(double s) {
return Point(this->x / s, this->y / s);
}
Point& operator+=(double s) {
this->x += s;
this->y += s;
return *this;
}
Point& operator-=(double s) {
this->x -= s;
this->y -= s;
return *this;
}
Point& operator*=(double s) {
this->x *= s;
this->y *= s;
return *this;
}
Point& operator/=(double s) {
this->x /= s;
this->y /= s;
return *this;
}
void rotate(double angle) {
double radian = angle * PI /180;
double cosAngle = cos(radian);
double sinAngle = sin(radian);
float tx = this->x * cosAngle - this->y * sinAngle;
float ty = this->x * sinAngle + this->y * cosAngle;
this->x = tx;
this->y = ty;
}
float dist2(Point p){
return pow(p.x - this->x,2)+ pow(p.y - this->y,2);
}
float dist(Point p){
return sqrt(dist2(p));
}
float length(){
return sqrt(dot());
}
Point normalize() {
if(length()==0){
return Point(this->x, this->y);
}
return Point(this->x/length(), this->y/length());
}
float dot(){
return this->x*this->x + this->y*this->y;
}
float dot(Point p){
return this->x*p.x + this->y*p.y;
}
};
// -------------------------------------------------------------------
class Pod{
public:
Point position;
int angle;
Point speed;
int nextCheckPointId;
int shieldCount = 0;
bool boostActive = true;
int checkpointsPassed = 0;
float score;
int mass = 1;
Pod(){
this->position = Point(0,0);
this->angle = 0;
this->speed = Point(0,0);
this->nextCheckPointId = 0;
}
Pod(Point p, float angle,Point speed, int nextCheckPointId){
this->position = p;
this-> angle = angle;
this->speed = speed;
this->nextCheckPointId = nextCheckPointId;
}
void UpdatePod(float x, float y, float vx, float vy, float angle, int nextCheckPointId){
this->position = Point(x,y);
this->angle = angle;
this->speed = Point(vx, vy);
this->nextCheckPointId = nextCheckPointId;
}
};
// -------------------------------------------------------------------
void CountShield(bool shiled, Pod& p)
{
if (shiled)
p.shieldCount = 4;
else if (p.shieldCount > 0)
--p.shieldCount;
}
int getMass(const Pod& p)
{
if (p.shieldCount == 4)
return 10;
return 1;
}
// -------------------------------------------------------------------
struct Movement{
int rotation;
int thrust;
bool shield;
bool boost;
};
class Step
{
public:
vector<Movement> moves = vector<Movement>(2);
Movement& operator[](size_t m){ return moves[m]; }
};
class Solution
{
public:
vector<Step> steps = vector<Step>(SIMULATIONSTEPS);
Step& operator[](size_t t) { return steps[t]; }
int score = 0;
};
// -------------------------------------------------------------------
// https://stackoverflow.com/questions/1640258/need-a-fast-random-generator-for-c
inline int fastrand()
{
static unsigned int g_seed = 100;
g_seed = (214013*g_seed+2531011);
return (g_seed>>16)&0x7FFF;
}
inline int rand(int a, int b)
{
return (fastrand() % (b-a)) + a;
}
class Simulation
{
private:
vector<Solution> solutions;
vector<Point> checkpoints;
int checkpointCount;
int allCheckpoints;
public:
void InitSimulation()
{
InitSolutions();
BoostAtBegin();
}
const vector<Point>& Checkpoints() const { return checkpoints; }
void InitCheckpoints()
{
int laps;
cin >> laps; cin.ignore();
cin >> checkpointCount; cin.ignore();
checkpoints.reserve(checkpointCount);
for (int i=0; i<checkpointCount; i++)
{
int checkpointX, checkpointY;
cin >> checkpointX >> checkpointY; cin.ignore();
checkpoints[i] = Point(checkpointX, checkpointY);
}
allCheckpoints = laps*checkpointCount;
}
Solution& simulate(const vector<Pod>& pods, int time)
{
auto start = high_resolution_clock::now();
auto now = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(now -start);
bool timeout = (duration.count() >= time);
for (int i=0; i<SOLUTIONCOUNT; ++i)
{
Solution& s = solutions[i];
UpdateNextStep(s);
vector<Pod> podsCopy = pods;
for (int i=0; i<SIMULATIONSTEPS; i++)
{
PlayOneStep(podsCopy, s[i]);
}
s.score = EvaluateScore(podsCopy);
}
while(!timeout){
for (int i=0; i<SOLUTIONCOUNT; ++i)
{
Solution& s = solutions[i+SOLUTIONCOUNT];
s = solutions[i];
UpdateRandomStep(s);
vector<Pod> podsCopy = pods;
for (int i=0; i<SIMULATIONSTEPS; i++)
{
PlayOneStep(podsCopy, s[i]);
}
s.score = EvaluateScore(podsCopy);
}
std::sort( solutions.begin(), solutions.end(),
[](Solution& a, Solution& b) { return a.score > b.score; }
);
now = high_resolution_clock::now();
duration = duration_cast<milliseconds>(now -start);
timeout = (duration.count() >= time);
}
return solutions[0];
}
private:
void PlayOneStep(vector<Pod>& pods, Step& step) const
{
// reference in expert rules
Rotate(pods, step);
Accelerate(pods, step);
Move(pods);
Friction(pods);
Round(pods);
}
void Rotate(std::vector<Pod>& pods, Step& m) const{
for (int i=0; i<2; i++)
{
Pod& p = pods[i];
Movement& mov = m[i];
p.angle = (p.angle + mov.rotation)%360;
}
}
void Accelerate(std::vector<Pod>& pods, Step& step) const{
for (int i=0; i<2; i++)
{
Pod& p = pods[i];
Movement& m = step[i];
CountShield(m.shield, p);
if(p.shieldCount>0){
continue;
}
const float angleRad = p.angle * PI / 180.0;
Point direction{cos(angleRad), sin(angleRad)};
if(m.boost && p.boostActive){
p.speed += direction *500.0f ;
p.boostActive = false;
}else{
p.speed += direction * m.thrust ;
}
}
}
void Move(vector<Pod>& pods) const
{
float currentTime = 0.0;
float maxTime = 1.0;
while (currentTime < maxTime)
{
Pod* p1 = nullptr;
Pod* p2 = nullptr;
float minTime = maxTime - currentTime;
for (int i=0; i<4; i++)
{
for (int j=i+1; j<4; j++)
{
const float collisionTime = CollisionTime(pods[i], pods[j]);
if ( (currentTime+collisionTime < maxTime) && (collisionTime < minTime) )
{
minTime = collisionTime;
p1 = &pods[i];
p2 = &pods[j];
}
}
}
for (Pod& p : pods)
{
p.position += p.speed * minTime ;
if (p.position.dist2(checkpoints[p.nextCheckPointId]) < checkpointRadius*checkpointRadius)
{
p.nextCheckPointId = (p.nextCheckPointId + 1) % checkpointCount;
++p.checkpointsPassed;
}
}
if (p1 != nullptr && p2 != nullptr)
{
Rebound(*p1, *p2);
}
currentTime+=minTime;
}
}
void Friction(vector<Pod>& pods) const
{
for (Pod& p : pods)
{
p.speed *= 0.85;
}
}
void Round(vector<Pod>& pods) const
{
for (Pod& p : pods)
{
p.speed = Point{ (int) p.speed.x, (int) p.speed.y };
p.position = Point{round(p.position.x), round(p.position.y)};
}
}
void InitSolutions()
{
solutions.resize(2*SOLUTIONCOUNT);
for (int s=0; s<SOLUTIONCOUNT; s++)
for (int t=0; t<SIMULATIONSTEPS; t++)
for (int i=0; i<2; i++)
Randomize(solutions[s][t][i]);
}
void BoostAtBegin()
{
const float d = checkpoints[0].dist2(checkpoints[1]); // size>1
float boostDistanceThreshold = 3000.0 * 3000.0;
if (d < boostDistanceThreshold)
return;
for (int i=0; i<2; i++)
{
for (int s=0; s<SOLUTIONCOUNT; ++s)
solutions[s][0][i].boost = true;
}
}
void Randomize(Movement& m, bool random = false) const{
if(!random){
int r = rand(-2*maxRotation, 3*maxRotation);
if (r > 2*maxRotation)
m.rotation = 0;
else
m.rotation = clamp(r, -maxRotation, maxRotation);
r = rand(-0.5f * maxThrust, 2*maxThrust);
m.thrust = clamp(r, 0, maxThrust);
if((rand(0,10)>6)){
m.shield = !m.shield;
}
if((rand(0,10)>6)){
m.boost = !m.boost;
}
}else{
int i = rand(0,12);
//cerr << i << endl;
if(i<5){
int r = rand(-2*maxRotation, 3*maxRotation);
if (r > 2*maxRotation)
m.rotation = 0;
else
m.rotation = clamp(r, -maxRotation, maxRotation);
}else if(i<10){
int r = rand(-0.5f * maxThrust, 2*maxThrust);
m.thrust = clamp(r, 0, maxThrust);
}else if(i<11){
if((rand(0,10)>6)){
m.shield = !m.shield;
}
}else{
if((rand(0,10)>6)){
m.boost = !m.boost;
}
}
}
}
void UpdateNextStep(Solution& s) const
{
for (int t=1; t<SIMULATIONSTEPS; t++){
for (int i=0; i<2; i++){
s[t-1][i] = s[t][i];
if(t==SIMULATIONSTEPS-1){
Movement& m = s[t][i];
Randomize(m);
}
}
}
}
void UpdateRandomStep(Solution& s) const
{
int k = rand(0, SIMULATIONSTEPS);
Movement& m = s[k][k%2];
Randomize(m,true);
}
int distanceScore(Pod& p) const
{
int coefficient = 20000;
int distance = p.position.dist(checkpoints[p.nextCheckPointId]);
return coefficient*p.checkpointsPassed - distance;
}
int EvaluateScore(vector<Pod> pods) const{
for (Pod& p : pods)
p.score = distanceScore(p);
int AvancePodIndex = (pods[0].score > pods[1].score) ? 0 : 1;
Pod& AvancePod = pods[AvancePodIndex];
Pod& BotherPod = pods[1-AvancePodIndex];
Pod& opponent = (pods[2].score > pods[3].score) ? pods[2] : pods[3];
if (AvancePod.checkpointsPassed > allCheckpoints){
return INT8_MAX; // I win
}else if(opponent.checkpointsPassed>allCheckpoints){
return -INT8_MAX; // opponent wins
}
// check the difference between us
int scoreDifference = AvancePod.score - opponent.score;
// try to bother my oppenent
Point opponentCheckpoint = checkpoints[opponent.nextCheckPointId];
int botherScore = - BotherPod.position.dist(opponentCheckpoint);
return 2*scoreDifference + botherScore; // advance is better than bother
}
float CollisionTime(Pod& p1, Pod& p2) const
{
// we want p2 position - p1 position < radius of pod
//We want also after moving forward, p2 position - p1 position < radius of pod
//new p2.position = p2.position + p2.spped*time
//therefore (p2 position - p1 position) + time*(p2.spped - p1.speed) < 2*radius of pod
Point distance = p2.position - p1.position;
Point differenceSpeed = (p2.speed - p1.speed);
//therfore distance + time*differenceSpeed < 2*Radius
//(distance + time*differenceSpeed)^2 < 4*Radius^2
// differenceSpeed^2 * time^2 + 2*differenceSpeed*distance*time + distance^2 < 4*Radius^2
// a = differenceSpeed^2, b = 2*differenceSpeed*distance, c = 4*Radius^2 - distance^2
const float a = differenceSpeed.dot();
if (a < eps)
return INT8_MAX;
const float b = -2.0*distance.dot(differenceSpeed);
const float c = distance.dot() - 4.0*podRadius*podRadius;
const float delta = b*b - 4.0*a*c;
if (delta < 0)
return INT8_MAX;
const float t = (b - sqrt(delta)) / (2.0 * a);
if (t <= eps)
return INT8_MAX;
return t;
}
void Rebound(Pod& a, Pod& b) const
{
// https://en.wikipedia.org/wiki/Elastic_collision#Two-dimensional_collision_with_two_moving_objects
const float mA = getMass(a);
const float mB = getMass(b);
Point vp = b.position - a.position;
vp = vp.normalize();
Point differenceSpeed = b.speed - a.speed;
const float m = (mA * mB) / (mA + mB);
const float k = differenceSpeed.dot(vp);
const float impulse = clamp((-2.0 * m * k), -minImpulse, minImpulse);
a.speed += vp * (-impulse/mA);
b.speed += vp * (impulse/mB);
}
};
void UpdateInput(Pod& p){
int x; // x position of your pod
int y; // y position of your pod
int vx; // x speed of your pod
int vy; // y speed of your pod
int angle; // angle of your pod
int nextCheckPointId; // next check point id of your pod
cin >> x >> y >> vx >> vy >> angle >> nextCheckPointId; cin.ignore();
p.position = Point(x,y);
p.speed = Point(vx,vy);
p.angle = angle;
if(p.nextCheckPointId != nextCheckPointId){
p.checkpointsPassed += 1;
}
p.nextCheckPointId = nextCheckPointId;
}
void ConvertSolutionToOutput(Solution& solution, vector<Pod>& pods)
{
Step m = solution[0];
for (int i=0; i<2; i++)
{
Pod& p = pods[i];
Movement& mov = m[i];
float angle = ((int) (p.angle + mov.rotation)) % 360;
float angleRad = angle * PI / 180.0;
float targetDistance = 10000.0;
Point direction{ targetDistance*cos(angleRad),targetDistance*sin(angleRad) };
Point target = p.position + direction;
cout << round(target.x) << " " << round(target.y) << " ";
if (mov.shield)
cout << "SHIELD";
else if (mov.boost)
cout << "BOOST";
else
cout << mov.thrust;
cout << endl;
}
}
void UpdatePodsStatus(Solution& solution, vector<Pod>& pods)
{
Step m = solution[0];
for (int i=0; i<2; i++)
{
Pod& p = pods[i];
Movement& mov = m[i];
CountShield(mov.shield, p);
if (p.shieldCount == 0 && mov.boost)
p.boostActive = false;
}
}
void InitAngle(Pod& p, Point target)
{
// we want the pod turn towards directly to the first checkpoint
Point destination = target - p.position;
float rotation = atan2(destination.y, destination.x) *180/PI;
if(rotation < 0){
rotation += 360;
}
p.angle = rotation;
}
int main()
{
Simulation simulation;
cerr << "init" << endl;
simulation.InitCheckpoints();
simulation.InitSimulation();
vector<Pod> pods(4);
int step=0;
while (1)
{
// init value ->
// search for the solution randomly ->
// play the solution ->
// evaluate solution ->
// find the best solution ->
// convert solution to output
for (int i=0; i<4; i++)
{
UpdateInput(pods[i]);
if (step == 0)
InitAngle(pods[i],simulation.Checkpoints()[0]);
}
int availableTime = (step==0) ? maxTimeFirstStep : maxTimeEachStep;
float timeCoefficient = 0.95;
Solution& s = simulation.simulate(pods, timeCoefficient*availableTime);
ConvertSolutionToOutput(s, pods);
UpdatePodsStatus(s, pods);
++step;
}
}
|
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:
class Solution {
public:
int waysToPartition(vector<int>& a, int k) {
long long tot = accumulate(a.begin(), a.end(), 0ll);
int ans = 0;
unordered_map<int, int> l, r;
for (long long i=0, s=0; i+1<a.size(); ++i) {
s += a[i];
if (s * 2 == tot) ++ans;
++r[s];
}
for (long long s=0, i=0; i<a.size(); ++i) {
auto new_tot = tot - a[i] + k;
if (! (new_tot&1)) {
// prefix_sum-a[i]+k==new_tot/2
int cnt = l[new_tot / 2] + r[new_tot/2+a[i]-k];
ans = max(ans, cnt);
}
s += a[i];
--r[s];
++l[s];
}
return ans;
}
};
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 | 3 | class Solution {
public:
int waysToPartition(vector<int>& a, int k) {
long long tot = accumulate(a.begin(), a.end(), 0ll);
int ans = 0;
unordered_map<int, int> l, r;
for (long long i=0, s=0; i+1<a.size(); ++i) {
s += a[i];
if (s * 2 == tot) ++ans;
++r[s];
}
for (long long s=0, i=0; i<a.size(); ++i) {
auto new_tot = tot - a[i] + k;
if (! (new_tot&1)) {
// prefix_sum-a[i]+k==new_tot/2
int cnt = l[new_tot / 2] + r[new_tot/2+a[i]-k];
ans = max(ans, cnt);
}
s += a[i];
--r[s];
++l[s];
}
return ans;
}
}; |
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:
JTF.namespace('HTML', function (HTML) {
var CONFIG = HTML.CONFIG = {
COLLAPSE: { NONE: 0, PASSES: 1, ALL: 2 },
};
var DefaultConfig = {
collapse: CONFIG.COLLAPSE.PASSES,
showPassedFixtures: true,
runInterval: 0,
notifyOnFail: false,
rootElement: document.body
};
function updatePartialConfig(partialConfig) {
if (!partialConfig || !(partialConfig instanceof Object))
return DefaultConfig;
else {
for (var key in DefaultConfig) {
if (!partialConfig.hasOwnProperty(key))
partialConfig[key] = DefaultConfig[key];
}
return partialConfig;
}
}
HTML.TestHandler = function HTML_test_handler(configuration) {
var PAGE_STATUS = {
PASS: 0,
FAIL: 1,
ERROR: 2
};
var pageStatus;
JTF.setState('', JTF.resources.progressIcon);
var TestRunner = JTF.TestRunner;
var currentConfig = updatePartialConfig(configuration);
var fixture, header, testsContainer;
var reRunTimer;
this.handle = function handle_event(handleType) {
var EVT = JTF.EVENT;
var args = Array.prototype.slice.call(arguments, 1);
switch (handleType) {
case EVT.BATCH.START:
addControls();
break;
case EVT.FIXTURE.START:
createFixture();
break;
case EVT.FIXTURE.DESC:
setHeader(args[0]);
break;
case EVT.TEST.PASS:
appendTestToHtml(true, args[0]);
break;
case EVT.TEST.FAIL:
appendTestToHtml(false, args[0], args[1]);
break;
case EVT.TEST.ERROR:
addTestError(args[0], args[1]);
break;
case EVT.FIXTURE.STATS:
statsOutputter(args[0], args[1], args[2]);
break;
case EVT.FIXTURE.END:
break;
case EVT.BATCH.END:
batchEnd();
break;
}
};
function createFixture() {
fixture = HTML.makeDiv('testfixture');
header = HTML.makeDiv('header');
testsContainer = HTML.makeDiv('tests');
HTML.addTo(fixture, header);
HTML.addTo(fixture, testsContainer);
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>"
| javascript | 1 | JTF.namespace('HTML', function (HTML) {
var CONFIG = HTML.CONFIG = {
COLLAPSE: { NONE: 0, PASSES: 1, ALL: 2 },
};
var DefaultConfig = {
collapse: CONFIG.COLLAPSE.PASSES,
showPassedFixtures: true,
runInterval: 0,
notifyOnFail: false,
rootElement: document.body
};
function updatePartialConfig(partialConfig) {
if (!partialConfig || !(partialConfig instanceof Object))
return DefaultConfig;
else {
for (var key in DefaultConfig) {
if (!partialConfig.hasOwnProperty(key))
partialConfig[key] = DefaultConfig[key];
}
return partialConfig;
}
}
HTML.TestHandler = function HTML_test_handler(configuration) {
var PAGE_STATUS = {
PASS: 0,
FAIL: 1,
ERROR: 2
};
var pageStatus;
JTF.setState('', JTF.resources.progressIcon);
var TestRunner = JTF.TestRunner;
var currentConfig = updatePartialConfig(configuration);
var fixture, header, testsContainer;
var reRunTimer;
this.handle = function handle_event(handleType) {
var EVT = JTF.EVENT;
var args = Array.prototype.slice.call(arguments, 1);
switch (handleType) {
case EVT.BATCH.START:
addControls();
break;
case EVT.FIXTURE.START:
createFixture();
break;
case EVT.FIXTURE.DESC:
setHeader(args[0]);
break;
case EVT.TEST.PASS:
appendTestToHtml(true, args[0]);
break;
case EVT.TEST.FAIL:
appendTestToHtml(false, args[0], args[1]);
break;
case EVT.TEST.ERROR:
addTestError(args[0], args[1]);
break;
case EVT.FIXTURE.STATS:
statsOutputter(args[0], args[1], args[2]);
break;
case EVT.FIXTURE.END:
break;
case EVT.BATCH.END:
batchEnd();
break;
}
};
function createFixture() {
fixture = HTML.makeDiv('testfixture');
header = HTML.makeDiv('header');
testsContainer = HTML.makeDiv('tests');
HTML.addTo(fixture, header);
HTML.addTo(fixture, testsContainer);
HTML.addTo(currentConfig.rootElement, fixture);
}
function setHeader(description) {
var desc = HTML.makeDiv('description');
desc.innerHTML = description;
HTML.addTo(header, desc);
}
function appendTestToHtml(testPassed, testName, msg) {
var className = getTestClassName(testPassed);
var test = HTML.makeDiv(className);
var name = HTML.makeDiv('name');
name.innerHTML = testName;
HTML.addTo(test, name);
if (typeof msg !== 'undefined') {
var info = HTML.makeDiv('info');
info.innerHTML = msg;
HTML.addTo(test, info);
}
HTML.addTo(testsContainer, test);
}
function addTestError(testName, error) {
var testError = HTML.makeDiv('test error');
var name = HTML.makeDiv('name');
name.innerHTML = testName;
HTML.addTo(testError, name);
var info = HTML.makeDiv('info');
info.innerHTML = error;
HTML.addTo(testError, info);
HTML.addTo(testsContainer, testError);
}
function batchEnd() {
if (pageStatus === PAGE_STATUS.PASS)
JTF.setState('', JTF.resources.passIcon);
else if (pageStatus === PAGE_STATUS.FAIL) {
JTF.setState('', JTF.resources.failIcon);
if (currentConfig.notifyOnFail) {
if (isSetToReRun()) {
if (shouldCancelReRuns())
currentConfig.runInterval = 0;
}
else showFailsAlert();
}
}
else if (pageStatus === PAGE_STATUS.ERROR)
JTF.setState('', JTF.resources.errorIcon);
if (isSetToReRun())
reRunTimer = setTimeout(function () { JTF.reload(); }, currentConfig.runInterval);
}
function shouldCancelReRuns() {
return confirm('Tests failed\n\nOK = review tests\n(stop further re-runs)\n\nCancel = ignore & continue');
}
function showFailsAlert() {
alert('Tests failed');
}
function isSetToReRun() {
return currentConfig.runInterval > 0;
}
function addControls() {
var controls = HTML.makeDiv('controls');
var label = HTML.makeEl('span');
var btn;
HTML.addTextTo(label, 'Expand:');
HTML.addTo(controls, label);
HTML.addTo(controls, HTML.makeOnClickButton('All', function () {
HTML.removeClassFromMany('.testfixture.collapsed', 'collapsed');
}));
HTML.addTo(controls, HTML.makeOnClickButton('Passes', function () {
HTML.removeClassFromMany('.testfixture.passed.collapsed', 'collapsed');
}));
HTML.addTo(controls, HTML.makeOnClickButton('Fails', function () {
HTML.removeClassFromMany('.testfixture.failed.collapsed', 'collapsed');
}));
label = HTML.makeEl('span');
label.style.marginLeft = '2em';
HTML.addTextTo(label, 'Collapse:');
HTML.addTo(controls, label);
HTML.addTo(controls, HTML.makeOnClickButton('All', function () {
HTML.addClassToMany('.testfixture', 'collapsed');
}));
HTML.addTo(controls, HTML.makeOnClickButton('Passes', function () {
HTML.addClassToMany('.testfixture.passed', 'collapsed');
}));
HTML.addTo(controls, HTML.makeOnClickButton('Fails', function () {
HTML.addClassToMany('.testfixture.failed', 'collapsed');
}));
if (currentConfig.showPassedFixtures) {
btn = HTML.makeOnClickButton('Hide Passes', function () {
HTML.addClassToMany('.testfixture.passed', 'hidden');
this.style.visibility = 'hidden';
});
btn.style.marginLeft = '2em';
HTML.addTo(controls, btn);
}
if (currentConfig.runInterval > 0) {
btn = HTML.makeOnClickButton('Stop re-runs', function () {
clearTimeout(reRunTimer);
this.style.visibility = 'hidden';
});
btn.style.marginLeft = '2em';
HTML.addTo(controls, btn);
}
btn = HTML.makeOnClickButton('Reload', JTF.reload);
btn.style.marginLeft = '2em';
HTML.addTo(controls, btn);
HTML.addTo(currentConfig.rootElement, controls);
}
function statsOutputter(passes, fails, testErrors) {
var hasFails = fails > 0;
var hasErrors = testErrors > 0;
if (fixtureShouldBeCollapsed(hasFails || hasErrors))
fixture.className += ' collapsed';
fixture.className += hasErrors ? ' withErrors' : hasFails ? ' failed' : ' passed';
if (!hasFails && !currentConfig.showPassedFixtures)
fixture.className += ' hidden';
var result = HTML.makeDiv('result');
HTML.addTextTo(result, HTML.getStatsLine(passes, fails, testErrors));
HTML.addTo(header, result);
pageStatus = getPageStatus(hasErrors, hasFails);
header.onclick = headerOnclickClosure(fixture);
}
function getPageStatus(hasErrors, hasFails) {
var ps = PAGE_STATUS;
if (hasErrors) return ps.ERROR;
if (hasFails) return ps.FAIL;
return ps.PASS;
}
function headerOnclickClosure(fixture) {
return function () {
var cn = fixture.className;
if (cn.indexOf('collapsed') === -1)
HTML.addClassTo(fixture, 'collapsed');
else
HTML.removeClassFrom(fixture, 'collapsed');
};
}
function fixtureShouldBeCollapsed(hasFailsOrErrors) {
switch (currentConfig.collapse) {
case CONFIG.COLLAPSE.NONE:
return false;
case CONFIG.COLLAPSE.ALL:
return true;
case CONFIG.COLLAPSE.PASSES:
return !hasFailsOrErrors;
}
}
HTML.getStatsLine = function (passes, fails, testErrors) {
var total = passes + fails + testErrors;
if (total === 0) return 'fixture contains no tests';
var passMsg = passes + ' passed';
if (passes === total) return passMsg;
var failMsg = fails + ' failed';
if (fails === total) return failMsg;
var hadErrorsMsg = testErrors + ' had errors';
if (testErrors === total) return hadErrorsMsg;
if (testErrors > 0) {
var result = [];
var append = function (item) { result[result.length] = item; };
append(hadErrorsMsg);
if (passes > 0) append(passMsg);
if (fails > 0) append(failMsg);
return result.join(' : : ');
}
else return fails + '/' + total + ' failed';
};
};
function getTestClassName(testPassed) {
var resultClass = testPassed ? ' pass' : ' fail';
var className = 'test' + resultClass;
return className;
}
}); |
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 dao
import (
model "crawler/model/comic"
mgorm "crawler/share/database/gorm"
zlog "crawler/share/log"
"encoding/json"
"fmt"
"go.uber.org/zap"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type ComicChapterRepository struct {
db *gorm.DB
*mgorm.Closer
}
func NewComicChapterRepository(dsn string) (*ComicChapterRepository, error) {
db, err := mgorm.NewMysqlGormWithTable(dsn, &model.ComicChapter{})
if err != nil {
return nil, fmt.Errorf("failed to create gorm: %v", err)
}
return &ComicChapterRepository{
db: db,
Closer: &mgorm.Closer{
DB: db,
},
}, nil
}
func (r *ComicChapterRepository) UpsertComicComment(entries []model.ComicChapter) (int, error) {
tx := r.db.Clauses(clause.OnConflict{
DoNothing: true,
}).Create(entries)
if tx.Error != nil {
return int(tx.RowsAffected), fmt.Errorf("failed to insert entries: %v", tx.Error)
}
return int(tx.RowsAffected), nil
}
func (r *ComicChapterRepository) FindStaticUrls() (<-chan []string, error) {
var mos []model.ComicChapter
if err := r.db.Find(&mos).Error; err != nil {
return nil, err
}
ch := make(chan []string, 64)
go func() {
for _, v := range mos {
var pageUrls []string
err := json.Unmarshal([]byte(v.PageUrl), &pageUrls)
if err != nil {
zlog.Logger.Info("cannot Unmarshal page_url", zap.Error(err))
continue
}
ch <- pageUrls
}
close(ch)
}()
return ch, 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 | 3 | package dao
import (
model "crawler/model/comic"
mgorm "crawler/share/database/gorm"
zlog "crawler/share/log"
"encoding/json"
"fmt"
"go.uber.org/zap"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type ComicChapterRepository struct {
db *gorm.DB
*mgorm.Closer
}
func NewComicChapterRepository(dsn string) (*ComicChapterRepository, error) {
db, err := mgorm.NewMysqlGormWithTable(dsn, &model.ComicChapter{})
if err != nil {
return nil, fmt.Errorf("failed to create gorm: %v", err)
}
return &ComicChapterRepository{
db: db,
Closer: &mgorm.Closer{
DB: db,
},
}, nil
}
func (r *ComicChapterRepository) UpsertComicComment(entries []model.ComicChapter) (int, error) {
tx := r.db.Clauses(clause.OnConflict{
DoNothing: true,
}).Create(entries)
if tx.Error != nil {
return int(tx.RowsAffected), fmt.Errorf("failed to insert entries: %v", tx.Error)
}
return int(tx.RowsAffected), nil
}
func (r *ComicChapterRepository) FindStaticUrls() (<-chan []string, error) {
var mos []model.ComicChapter
if err := r.db.Find(&mos).Error; err != nil {
return nil, err
}
ch := make(chan []string, 64)
go func() {
for _, v := range mos {
var pageUrls []string
err := json.Unmarshal([]byte(v.PageUrl), &pageUrls)
if err != nil {
zlog.Logger.Info("cannot Unmarshal page_url", zap.Error(err))
continue
}
ch <- pageUrls
}
close(ch)
}()
return ch, nil
}
|
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 _ = require('lodash');
const { readFile, shortenUserInfo, saveFile } = require('../helpers');
const getUsers = async () => {
const result = await readFile('../data/users.json');
return JSON.parse(result).map(userObject => shortenUserInfo(userObject));
}
const getUserByIndex = async (index) => {
let result = await readFile('../data/users.json');
result = JSON.parse(result);
return result[index];
}
const getUserByPhone = async (phone) => {
const usersData = await readFile('../data/users.json');
const result = _.find(JSON.parse(usersData), { phone });
return result;
}
const updateUserInformation = async (user) => {
const _usersData = await readFile('../data/users.json');
const usersData = JSON.parse(_usersData);
const index = _.findIndex(usersData, { phone: user.phone });
// Если юзер существует, обновить его в БД
if (index !== null && index !== undefined && index > -1) {
usersData[index] = user;
await saveFile('../data/users.json', usersData);
console.log('successfully saved');
} else {
console.log('new user ??');
}
}
module.exports = {
getUsers,
getUserByIndex,
getUserByPhone,
updateUserInformation,
}
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 | const _ = require('lodash');
const { readFile, shortenUserInfo, saveFile } = require('../helpers');
const getUsers = async () => {
const result = await readFile('../data/users.json');
return JSON.parse(result).map(userObject => shortenUserInfo(userObject));
}
const getUserByIndex = async (index) => {
let result = await readFile('../data/users.json');
result = JSON.parse(result);
return result[index];
}
const getUserByPhone = async (phone) => {
const usersData = await readFile('../data/users.json');
const result = _.find(JSON.parse(usersData), { phone });
return result;
}
const updateUserInformation = async (user) => {
const _usersData = await readFile('../data/users.json');
const usersData = JSON.parse(_usersData);
const index = _.findIndex(usersData, { phone: user.phone });
// Если юзер существует, обновить его в БД
if (index !== null && index !== undefined && index > -1) {
usersData[index] = user;
await saveFile('../data/users.json', usersData);
console.log('successfully saved');
} else {
console.log('new user ??');
}
}
module.exports = {
getUsers,
getUserByIndex,
getUserByPhone,
updateUserInformation,
} |
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 application
import (
"github.com/gin-gonic/gin"
"golang.org/x/sync/errgroup"
"log"
"simple-sso/router"
)
type App struct {
*gin.Engine
addr string
name string
}
func NewApp(name, addr string, routers router.Routers, middleware ...gin.HandlerFunc) *App {
engine := gin.Default()
// add middleware firstly
if len(middleware) > 0 {
engine.Use(middleware...)
}
// add router
for _, opt := range routers {
opt(engine)
}
return &App{
engine,
addr,
name,
}
}
type Applications map[string]*App
func Default() Applications {
return make(Applications)
}
func (a Applications) Add(apps ...*App) {
for _, app := range apps {
a[app.name] = app
}
}
func (a Applications) Run() {
g := new(errgroup.Group)
for _, value := range a {
copyValue := value
g.Go(func() error {
log.Printf("application %s run at : %s\n", copyValue.name, copyValue.addr)
return copyValue.Run(copyValue.addr)
})
}
if err :=g.Wait(); err!= nil {
log.Fatal(err)
}
}
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 application
import (
"github.com/gin-gonic/gin"
"golang.org/x/sync/errgroup"
"log"
"simple-sso/router"
)
type App struct {
*gin.Engine
addr string
name string
}
func NewApp(name, addr string, routers router.Routers, middleware ...gin.HandlerFunc) *App {
engine := gin.Default()
// add middleware firstly
if len(middleware) > 0 {
engine.Use(middleware...)
}
// add router
for _, opt := range routers {
opt(engine)
}
return &App{
engine,
addr,
name,
}
}
type Applications map[string]*App
func Default() Applications {
return make(Applications)
}
func (a Applications) Add(apps ...*App) {
for _, app := range apps {
a[app.name] = app
}
}
func (a Applications) Run() {
g := new(errgroup.Group)
for _, value := range a {
copyValue := value
g.Go(func() error {
log.Printf("application %s run at : %s\n", copyValue.name, copyValue.addr)
return copyValue.Run(copyValue.addr)
})
}
if err :=g.Wait(); err!= nil {
log.Fatal(err)
}
} |
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
data=/Volumes/Phillips/P5/subj
roidir=/Volumes/Phillips/P5/scripts/rois
prefix="simpledContrasts_2runs_stats2"
rois="
#go to where all the data is
cd $data
#subjects IDs
ID="11228_20150309 11327_20140911 11333_20141017 11339_20141104 11340_20141031 11341_20141118 11348_20141119 11349_20141124 11351_20141202 11352_20141230 11354_20141205 11355_20141230 11356_20150105 11357_20150122 11358_20150129 11359_20150203 11360_20150129 11363_20150310 11365_20150407 11367_20150430 11368_20150505"
for d in ${ID}; do
cd ${data}/${d}
3dROIstats -quiet -mask ${roidir}/BA09_L_wr+tlrc ${data}/${d}/contrasts/Att/${prefix}[]>>${data}/BA09_L_.txt
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 | #!/bin/bash
data=/Volumes/Phillips/P5/subj
roidir=/Volumes/Phillips/P5/scripts/rois
prefix="simpledContrasts_2runs_stats2"
rois="
#go to where all the data is
cd $data
#subjects IDs
ID="11228_20150309 11327_20140911 11333_20141017 11339_20141104 11340_20141031 11341_20141118 11348_20141119 11349_20141124 11351_20141202 11352_20141230 11354_20141205 11355_20141230 11356_20150105 11357_20150122 11358_20150129 11359_20150203 11360_20150129 11363_20150310 11365_20150407 11367_20150430 11368_20150505"
for d in ${ID}; do
cd ${data}/${d}
3dROIstats -quiet -mask ${roidir}/BA09_L_wr+tlrc ${data}/${d}/contrasts/Att/${prefix}[]>>${data}/BA09_L_.txt
|
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 (c) 2018, TeleCommunication Systems, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the TeleCommunication Systems, Inc., nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED. IN NO EVENT SHALL TELECOMMUNICATION SYSTEMS, INC.BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!--------------------------------------------------------------------------
@file nbrastermaphandler.h
*/
/*
(C) Copyright 2014 by TeleCommunication Systems, Inc.
The information contained herein is confidential, proprietary
to TeleCommunication Systems, Inc., and considered a trade secret as
defined in section 499C of the penal code of the State of
California. Use of this information 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>"
| c | 0 | /*
Copyright (c) 2018, TeleCommunication Systems, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the TeleCommunication Systems, Inc., nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED. IN NO EVENT SHALL TELECOMMUNICATION SYSTEMS, INC.BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!--------------------------------------------------------------------------
@file nbrastermaphandler.h
*/
/*
(C) Copyright 2014 by TeleCommunication Systems, Inc.
The information contained herein is confidential, proprietary
to TeleCommunication Systems, Inc., and considered a trade secret as
defined in section 499C of the penal code of the State of
California. Use of this information by anyone other than
authorized employees of TeleCommunication Systems is granted only
under a written non-disclosure agreement, expressly
prescribing the scope and manner of such use.
---------------------------------------------------------------------------*/
#ifndef NBRASTERMAPHANDLER_H
#define NBRASTERMAPHANDLER_H
#include "nbcontext.h"
#include "nbhandler.h"
#include "nbrastermapinformation.h"
#include "nbrastermapparameters.h"
#include "nbsearchinformation.h"
/*!
@addtogroup nbrastermaphandler
@{
*/
/*! @struct NB_RasterMapHandler
A RasterMapHandler is used to download raster map files
*/
typedef struct NB_RasterMapHandler NB_RasterMapHandler;
/*! Create and initialize a new RasterMapHandler object
@param context NB_Context
@param callback Request handler status update callback
@param parameters NB_RasterMapParameters object specifying the raster map to retrieve
@param handler On success, the newly created handler; NULL otherwise
@returns NB_Error
*/
NB_DEC NB_Error NB_RasterMapHandlerCreate(NB_Context* context, NB_RequestHandlerCallback* callback, NB_RasterMapHandler** handler);
/*! Destroy a previously created RasterMapHandler object
@param handler A NB_RasterMapHandler object created with NB_RasterMapHandlerCreate()
@returns NB_Error
*/
NB_DEC NB_Error NB_RasterMapHandlerDestroy(NB_RasterMapHandler* handler);
/*! Start a network request to retrieve a raster map file
Initiate a network request that randers and retrieves a raster map file. Only one request may be active at a given time
@param handler A NB_RasterMapHandler object
@returns NB_Error
*/
NB_DEC NB_Error NB_RasterMapHandlerStartRequest(NB_RasterMapHandler* pThis, NB_RasterMapParameters* parameters);
/*! Cancel a previously started request
@param handler A NB_RasterMapHandler object
@returns NB_Error
*/
NB_DEC NB_Error NB_RasterMapHandlerCancelRequest(NB_RasterMapHandler* handler);
/*! Check if a download request is in progress
@param handler A NB_RasterMapHandler object
@returns Non-zero if a request is in progress; zero otherwise
*/
NB_DEC nb_boolean NB_RasterMapHandlerIsRequestInProgress(NB_RasterMapHandler* handler);
/*! Retrieves a NB_RasterMapInformation object
@param handler A NB_RasterMapHandler object
@param map On success, a NB_RasterMapInformation object with the result of the last download; NULL otherwise. An object returned from this function must be destroyed using NB_RasterMapInformationDestroy().
@returns NB_Error
*/
NB_DEC NB_Error NB_RasterMapHandlerGetMapInformation(NB_RasterMapHandler* handler, NB_RasterMapInformation** map);
/*! Retrieves a NB_SearchInformation object containing the place and traffic information from the last request
@param handler A NB_RouteHandler object
@param hasTrafficIncidents last request contains traffic incidents
@param route On success, a NB_SearchInformation object with the result of the last request; NULL otherwise. An object returned from this function must be destroyed using NB_TrafficInformationDestroy().
@returns NB_Error
*/
NB_DEC NB_Error NB_RasterMapHandlerGetSearchInformation(NB_RasterMapHandler* handler, nb_boolean* hasTrafficIncidents, NB_SearchInformation** searchInformation);
/*! @} */
#endif
|
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: <NAME> <<EMAIL> at g<EMAIL> dot com>
# Contributor: Alcasa <<EMAIL>>
_themename=Numix-Ocean
pkgname=gtk-theme-numix-ocean
pkgver=2.0.2
pkgrel=2
pkgdesc="Base16 Ocean colorscheme version of the Numix theme (supports GTK 2, GTK 3, Xfwm and Openbox)"
arch=('any')
url='https://github.com/aaronjamesyoung/Numix-Ocean'
license=('GPL3')
depends=('gtk-engine-murrine')
source=('https://github.com/aaronjamesyoung/Numix-Ocean/archive/Ocean.zip')
md5sums=('3825c4104e5a2f4aba73c5e07e8d1eae')
package() {
mkdir -p ${pkgdir}/usr/share/themes/
cd ${srcdir}/
cp -R ./ ${pkgdir}/usr/share/themes/
}
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 | # Maintainer: <NAME> <<EMAIL> at g<EMAIL> dot com>
# Contributor: Alcasa <<EMAIL>>
_themename=Numix-Ocean
pkgname=gtk-theme-numix-ocean
pkgver=2.0.2
pkgrel=2
pkgdesc="Base16 Ocean colorscheme version of the Numix theme (supports GTK 2, GTK 3, Xfwm and Openbox)"
arch=('any')
url='https://github.com/aaronjamesyoung/Numix-Ocean'
license=('GPL3')
depends=('gtk-engine-murrine')
source=('https://github.com/aaronjamesyoung/Numix-Ocean/archive/Ocean.zip')
md5sums=('3825c4104e5a2f4aba73c5e07e8d1eae')
package() {
mkdir -p ${pkgdir}/usr/share/themes/
cd ${srcdir}/
cp -R ./ ${pkgdir}/usr/share/themes/
}
|
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.example.staselovich_p3_l1.tools
import android.app.AlertDialog
import android.content.Context
import android.graphics.drawable.ColorDrawable
import com.example.staselovich_p3_l1.R
fun Context.showAlertDialog(): AlertDialog {
val builder: AlertDialog.Builder = AlertDialog.Builder(this)
.setView(R.layout.layout_progresbar)
val dialog = builder.create()
dialog.show()
dialog.window?.setLayout(300,300)
dialog.window?.setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT))
return dialog
}
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.example.staselovich_p3_l1.tools
import android.app.AlertDialog
import android.content.Context
import android.graphics.drawable.ColorDrawable
import com.example.staselovich_p3_l1.R
fun Context.showAlertDialog(): AlertDialog {
val builder: AlertDialog.Builder = AlertDialog.Builder(this)
.setView(R.layout.layout_progresbar)
val dialog = builder.create()
dialog.show()
dialog.window?.setLayout(300,300)
dialog.window?.setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT))
return dialog
} |
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:
/*
Navicat MySQL Data Transfer
Source Server : elem
Source Server Version : 50729
Source Host : localhost:3308
Source Database : elme
Target Server Type : MYSQL
Target Server Version : 50729
File Encoding : 65001
Date: 2020-12-30 10:11:33
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for discount
-- ----------------------------
DROP TABLE IF EXISTS `discount`;
CREATE TABLE `discount` (
`discount_id` bigint(11) NOT NULL,
`user_id` bigint(11) DEFAULT NULL,
`store_id` bigint(11) NOT NULL,
`discount_name` varchar(20) NOT NULL,
`discount_money` float NOT NULL,
`start_money` float NOT NULL,
PRIMARY KEY (`discount_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of discount
-- ----------------------------
-- ----------------------------
-- Table structure for goods
-- ----------------------------
DROP TABLE IF EXISTS `goods`;
CREATE TABLE `goods` (
`class_name` varchar(50) NOT NULL,
`goods_id` bigint(11) NOT NULL AUTO_INCREMENT,
`store_id` bigint(11) DEFAULT NULL,
`goods_name` varchar(50) NOT NULL,
`goods_price` float(8,2) NOT NULL,
`goods_picture` varchar(2083) DEFAULT NULL,
`goods_description` text,
`month_sales` int(11) DEFAULT NULL,
`high_rating` float DEFAULT NULL,
PRIMARY KEY (`goods_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of goods
-- ----------------------------
-- ----------------------------
-- Table structure for goods_evaluation
-- ----------------------------
DROP TABLE IF EXISTS `goods_evaluation`;
CREATE TABLE `goods_evaluation` (
`store_id` bigint(11) DEFAULT NULL,
`user_id` bigint(11) DEFAULT NULL,
`user_name` varchar(100) DEFAULT NULL,
`evaluation_content` text,
`evaluation_star` float DEFAULT NULL,
`evaluation_img` varchar(500) DEFAULT NULL,
`evaluation_time` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --
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 | /*
Navicat MySQL Data Transfer
Source Server : elem
Source Server Version : 50729
Source Host : localhost:3308
Source Database : elme
Target Server Type : MYSQL
Target Server Version : 50729
File Encoding : 65001
Date: 2020-12-30 10:11:33
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for discount
-- ----------------------------
DROP TABLE IF EXISTS `discount`;
CREATE TABLE `discount` (
`discount_id` bigint(11) NOT NULL,
`user_id` bigint(11) DEFAULT NULL,
`store_id` bigint(11) NOT NULL,
`discount_name` varchar(20) NOT NULL,
`discount_money` float NOT NULL,
`start_money` float NOT NULL,
PRIMARY KEY (`discount_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of discount
-- ----------------------------
-- ----------------------------
-- Table structure for goods
-- ----------------------------
DROP TABLE IF EXISTS `goods`;
CREATE TABLE `goods` (
`class_name` varchar(50) NOT NULL,
`goods_id` bigint(11) NOT NULL AUTO_INCREMENT,
`store_id` bigint(11) DEFAULT NULL,
`goods_name` varchar(50) NOT NULL,
`goods_price` float(8,2) NOT NULL,
`goods_picture` varchar(2083) DEFAULT NULL,
`goods_description` text,
`month_sales` int(11) DEFAULT NULL,
`high_rating` float DEFAULT NULL,
PRIMARY KEY (`goods_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of goods
-- ----------------------------
-- ----------------------------
-- Table structure for goods_evaluation
-- ----------------------------
DROP TABLE IF EXISTS `goods_evaluation`;
CREATE TABLE `goods_evaluation` (
`store_id` bigint(11) DEFAULT NULL,
`user_id` bigint(11) DEFAULT NULL,
`user_name` varchar(100) DEFAULT NULL,
`evaluation_content` text,
`evaluation_star` float DEFAULT NULL,
`evaluation_img` varchar(500) DEFAULT NULL,
`evaluation_time` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of goods_evaluation
-- ----------------------------
-- ----------------------------
-- Table structure for ord
-- ----------------------------
DROP TABLE IF EXISTS `ord`;
CREATE TABLE `ord` (
`ord_id` bigint(11) NOT NULL,
`user_id` bigint(11) DEFAULT NULL,
`store_id` bigint(11) DEFAULT NULL,
`rider_id` bigint(11) DEFAULT NULL,
`total_money` float(8,2) NOT NULL,
`total_discount` float(8,2) NOT NULL,
`ord_time` datetime NOT NULL,
`rider_get` float(8,2) NOT NULL,
PRIMARY KEY (`ord_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of ord
-- ----------------------------
-- ----------------------------
-- Table structure for ord_goods
-- ----------------------------
DROP TABLE IF EXISTS `ord_goods`;
CREATE TABLE `ord_goods` (
`ord_id` bigint(11) DEFAULT NULL,
`goods_name` varchar(50) DEFAULT NULL,
`goods_num` int(11) DEFAULT NULL,
`goods_price` float(8,2) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of ord_goods
-- ----------------------------
-- ----------------------------
-- Table structure for reduction_plan
-- ----------------------------
DROP TABLE IF EXISTS `reduction_plan`;
CREATE TABLE `reduction_plan` (
`plan_id` bigint(11) NOT NULL,
`store_id` bigint(11) DEFAULT NULL,
`reduction_require` float(8,2) NOT NULL,
`reduction_money` float(8,2) NOT NULL,
PRIMARY KEY (`plan_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of reduction_plan
-- ----------------------------
-- ----------------------------
-- Table structure for rider
-- ----------------------------
DROP TABLE IF EXISTS `rider`;
CREATE TABLE `rider` (
`rider_id` bigint(11) NOT NULL,
`rider_name` varchar(20) NOT NULL,
`rider_passwd` varchar(20) NOT NULL,
`rider_phone` char(11) NOT NULL,
`rider_position` varchar(100) NOT NULL,
PRIMARY KEY (`rider_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of rider
-- ----------------------------
-- ----------------------------
-- Table structure for rider_evaluation
-- ----------------------------
DROP TABLE IF EXISTS `rider_evaluation`;
CREATE TABLE `rider_evaluation` (
`rider_id` bigint(11) DEFAULT NULL,
`user_id` bigint(11) DEFAULT NULL,
`user_name` varchar(100) DEFAULT NULL,
`rider_evaluate` text,
`rider_stars` float DEFAULT NULL,
`evaluate_time` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of rider_evaluation
-- ----------------------------
-- ----------------------------
-- Table structure for store
-- ----------------------------
DROP TABLE IF EXISTS `store`;
CREATE TABLE `store` (
`store_id` bigint(50) NOT NULL AUTO_INCREMENT,
`store_name` varchar(50) DEFAULT NULL,
`store_passwd` varchar(20) DEFAULT NULL,
`store_address` varchar(200) DEFAULT NULL,
`store_phone` char(11) DEFAULT NULL,
`delivery_begin` varchar(200) DEFAULT NULL,
`delivery_end` varchar(200) DEFAULT NULL,
PRIMARY KEY (`store_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of store
-- ----------------------------
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`user_id` bigint(20) NOT NULL,
`user_name` varchar(20) DEFAULT NULL,
`user_phone` char(11) DEFAULT NULL,
`user_pwd` varchar(255) DEFAULT NULL,
`user_address_id` bigint(11) NOT NULL,
`user_main_address` varchar(100) DEFAULT NULL,
`user_sex` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('0', null, '123456', 'aaa42296669b958c3cee6c0475c8093e', '0', null, '0');
-- ----------------------------
-- Table structure for user_address
-- ----------------------------
DROP TABLE IF EXISTS `user_address`;
CREATE TABLE `user_address` (
`user_id` bigint(11) DEFAULT NULL,
`address_id` bigint(11) NOT NULL,
`user_address` varchar(100) NOT NULL,
`main_address` int(11) NOT NULL DEFAULT '0',
`user_name` varchar(20) NOT NULL,
`user_sex` int(11) DEFAULT NULL,
`address_detail` varchar(100) DEFAULT NULL,
`address_type` int(11) DEFAULT NULL,
PRIMARY KEY (`address_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of user_address
-- ----------------------------
|
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 leetcode
class Solution6 {
fun convert(s: String, numRows: Int): String {
if (numRows == 1) return s
var direction = 1
var row = 0
val z = List(numRows) { mutableListOf<Char>() }
s.forEach { c ->
z[row].add(c)
if (row == 0) {
direction = 1
} else if (row == numRows - 1) {
direction = -1
}
row += direction
}
return z.joinToString("") { it.joinToString("") }
}
}
fun main() {
val s = Solution6()
println(s.convert("ABCD", 2))
}
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 leetcode
class Solution6 {
fun convert(s: String, numRows: Int): String {
if (numRows == 1) return s
var direction = 1
var row = 0
val z = List(numRows) { mutableListOf<Char>() }
s.forEach { c ->
z[row].add(c)
if (row == 0) {
direction = 1
} else if (row == numRows - 1) {
direction = -1
}
row += direction
}
return z.joinToString("") { it.joinToString("") }
}
}
fun main() {
val s = Solution6()
println(s.convert("ABCD", 2))
}
|
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
if ps -ef | grep -v python | grep -v make | grep gerrit-observatory | grep -v grep
then
killall gerrit-observatory
fi
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
if ps -ef | grep -v python | grep -v make | grep gerrit-observatory | grep -v grep
then
killall gerrit-observatory
fi
|
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:
//
// StoryEntity.swift
// eGym
//
// Created by <NAME> on 02/11/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
struct StoryEntity : Codable {
let section : String
let subsection : String
let title : String
let url : String
let byline : String
let short_url : String
let abstract : String
let multimedia : [MultimediaEntity]
enum CodingKeys : CodingKey {
case section
case subsection
case title
case url
case byline
case short_url
case abstract
case multimedia
}
}
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 | //
// StoryEntity.swift
// eGym
//
// Created by <NAME> on 02/11/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
struct StoryEntity : Codable {
let section : String
let subsection : String
let title : String
let url : String
let byline : String
let short_url : String
let abstract : String
let multimedia : [MultimediaEntity]
enum CodingKeys : CodingKey {
case section
case subsection
case title
case url
case byline
case short_url
case abstract
case multimedia
}
}
|
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
# sums the command arguments
if [ $# -eq 1 ] #If statements check how many arguments were passed
then
let a=$1
echo $1=$a
fi
if [ $# -eq 2 ]
then
let a=$1+$2
echo $1+$2=$a
fi
if [ $# -eq 3 ]
then
let a=$1+$2+$3
echo $1+$2+$3=$a
fi
if [ $# -eq 4 ]
then
let a=$1+$2+$3+$4
echo $1+$2+$3+$4=$a
fi
if [ $# -eq 5 ]
then
let a=$1+$2+$3+$4+$5
echo $1+$2+$3+$4+$5=$a
fi
if [ $# -eq 6 ]
then
let a=$1+$2+$3+$4+$5+$6
echo $1+$2+$3+$4+$5+$6=$a
fi
if [ $# -eq 7 ]
then
let a=$1+$2+$3+$4+$5+$6+$7
echo $1+$2+$3+$4+$5+$6+$7=$a
fi
if [ $# -eq 8 ]
then
let a=$1+$2+$3+$4+$5+$6+$7+$8
echo $1+$2+$3+$4+$5+$6+$7+$8=$a
fi
if [ $# -eq 9 ]
then
let a=$1+$2+$3+$4+$5+$6+$7+$8+$9
echo $1+$2+$3+$4+$5+$6+$7+$8+$9=$a
fi
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 | #!/bin/bash
# sums the command arguments
if [ $# -eq 1 ] #If statements check how many arguments were passed
then
let a=$1
echo $1=$a
fi
if [ $# -eq 2 ]
then
let a=$1+$2
echo $1+$2=$a
fi
if [ $# -eq 3 ]
then
let a=$1+$2+$3
echo $1+$2+$3=$a
fi
if [ $# -eq 4 ]
then
let a=$1+$2+$3+$4
echo $1+$2+$3+$4=$a
fi
if [ $# -eq 5 ]
then
let a=$1+$2+$3+$4+$5
echo $1+$2+$3+$4+$5=$a
fi
if [ $# -eq 6 ]
then
let a=$1+$2+$3+$4+$5+$6
echo $1+$2+$3+$4+$5+$6=$a
fi
if [ $# -eq 7 ]
then
let a=$1+$2+$3+$4+$5+$6+$7
echo $1+$2+$3+$4+$5+$6+$7=$a
fi
if [ $# -eq 8 ]
then
let a=$1+$2+$3+$4+$5+$6+$7+$8
echo $1+$2+$3+$4+$5+$6+$7+$8=$a
fi
if [ $# -eq 9 ]
then
let a=$1+$2+$3+$4+$5+$6+$7+$8+$9
echo $1+$2+$3+$4+$5+$6+$7+$8+$9=$a
fi
|
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 Facebook\Message;
use Facebook\Utils\Html;
use Facebook\Utils\Util;
use Facebook\Utils\Content;
trait chat{
public function chat($page=0){
$this->fetch();
if($this->firstConversation)return [];
//prepare the url
if(!$this->childs["items"])
$next=$this->messageUrl();
else $next=$this->childs["next_page"];
for ($i=count($this->childs["items"]);$i <=$page; $i++) {
if(!$next)break;
$this->http($next);
//get friend name note: it's not test in all scenarios
if(!$this->friend->name){
$friendName=$this->dom("<span")[0];
if(isset($friendName[0])&&trim($friendName[0]))
$this->friend->name=trim($friendName[0]);
}
$content=$this->splitMessages();
$this->childs["items"]=array_merge($this->childs["items"],[$content["msgs"]]);
$this->childs["next_page"]=$content["next_page"];
$next=$content["next_page"];
}
if(isset($this->childs["items"][$page]))
return array_reverse($this->childs["items"][$page]);
else return [];
}
private function splitMessages(){
$sections=$this->dom('id="messageGroup"')[0];
$sections=Html::dom($sections,"<div",1);
//get next_page url
$sections=Util::filter($sections,function($sec){
return isset($sec[1]["id"])&&Util::instr($sec[1]["id"],"see_");
});
$next=isset($sections[0][0])?$sections[0][0][0]:"";
$messages=$sections[1];
$msgs=[];
if(isset($messages[0][0])){
$msgs_html=Html::dom($messages[0][0],"<div");
foreach ($msgs_html as $msg_html) {
//if message hasn't time ignore it(is not message)
if(!Util::instr($msg_html,"<abbr"))continue;
$msg=$this->parseSingleMessage($msg_html);
array_push($msgs,$msg);
}
}
$next=Html::dom($next,"<a",1);
$next=isset($next[0][1]["href"])?$next[0][1]["href"]:"";
return ["msgs"=>$msgs,"next_page"=>$next];
}
private function parseSingleMessage($html){
$msg=Html::dom($html,"<div");//first is content(sender&&content) and secoud is the time
//note: create parseTime global function for
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 Facebook\Message;
use Facebook\Utils\Html;
use Facebook\Utils\Util;
use Facebook\Utils\Content;
trait chat{
public function chat($page=0){
$this->fetch();
if($this->firstConversation)return [];
//prepare the url
if(!$this->childs["items"])
$next=$this->messageUrl();
else $next=$this->childs["next_page"];
for ($i=count($this->childs["items"]);$i <=$page; $i++) {
if(!$next)break;
$this->http($next);
//get friend name note: it's not test in all scenarios
if(!$this->friend->name){
$friendName=$this->dom("<span")[0];
if(isset($friendName[0])&&trim($friendName[0]))
$this->friend->name=trim($friendName[0]);
}
$content=$this->splitMessages();
$this->childs["items"]=array_merge($this->childs["items"],[$content["msgs"]]);
$this->childs["next_page"]=$content["next_page"];
$next=$content["next_page"];
}
if(isset($this->childs["items"][$page]))
return array_reverse($this->childs["items"][$page]);
else return [];
}
private function splitMessages(){
$sections=$this->dom('id="messageGroup"')[0];
$sections=Html::dom($sections,"<div",1);
//get next_page url
$sections=Util::filter($sections,function($sec){
return isset($sec[1]["id"])&&Util::instr($sec[1]["id"],"see_");
});
$next=isset($sections[0][0])?$sections[0][0][0]:"";
$messages=$sections[1];
$msgs=[];
if(isset($messages[0][0])){
$msgs_html=Html::dom($messages[0][0],"<div");
foreach ($msgs_html as $msg_html) {
//if message hasn't time ignore it(is not message)
if(!Util::instr($msg_html,"<abbr"))continue;
$msg=$this->parseSingleMessage($msg_html);
array_push($msgs,$msg);
}
}
$next=Html::dom($next,"<a",1);
$next=isset($next[0][1]["href"])?$next[0][1]["href"]:"";
return ["msgs"=>$msgs,"next_page"=>$next];
}
private function parseSingleMessage($html){
$msg=Html::dom($html,"<div");//first is content(sender&&content) and secoud is the time
//note: create parseTime global function for create timestem from (time ago)
$time=Html::dom($msg[1],"<abbr")[0];
$msg=$msg[0];
$sections=Util::strcut($msg,0,strpos($msg,"</a>")+3);
//get sender of such message (string)
$sender=Html::dom($sections[0],"<strong")[0];
//get content
$content=Content::parse($sections[1]);
$friendName=$this->friend->getName();
return [
"sender"=>$sender==$friendName?1:0,
"content"=>$content
];
}
}
?> |
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:
-- phpMyAdmin SQL Dump
-- version 4.7.9
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Jun 05, 2018 at 12:32 PM
-- Server version: 5.7.21
-- PHP Version: 5.6.35
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `cos_login_db`
--
-- --------------------------------------------------------
--
-- Table structure for table `chat`
--
DROP TABLE IF EXISTS `chat`;
CREATE TABLE IF NOT EXISTS `chat` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`msg` text NOT NULL,
`user_id` int(5) DEFAULT NULL,
`date_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=24 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `chat`
--
INSERT INTO `chat` (`id`, `username`, `msg`, `user_id`, `date_created`) VALUES
(1, 'admin', 'hello evry 1', NULL, '2018-06-04 14:05:57'),
(2, 'test1', 'hi', NULL, '2018-06-04 14:06:07'),
(3, 'admin', 'hello', NULL, '2018-06-04 14:07:42'),
(4, 'test1', 'hiyers', NULL, '2018-06-04 14:07:48'),
(5, 'test2', 'hyerss', NULL, '2018-06-04 14:08:53'),
(6, 'admin', 'ohhh', NULL, '2018-06-04 14:09:03'),
(7, 'test1', 'yes', NULL, '2018-06-04 14:09:11'),
(8, 'admin', 'yeah', NULL, '2018-06-04 14:09:17'),
(9, 'test2', 'hello', NULL, '2018-06-04 14:09:26'),
(10, 'test2', ':)', NULL, '2018-06-04 14:09:46'),
(11, 'test1', 'yo!', NULL, '2018-06-04 14:16:51'),
(12, 'test1', 'hallo', NULL, '2018-06-04 14:17:33'),
(13, 'test1', ':)', NULL, '2018-06-04 14:18:13'),
(14, 'test1', ':)', NULL, '2018-06-04 14:18:20'),
(15, 'admin', 'http://localhost/cos_login/admin/chat', NULL, '2018-06-04 14:18:33'),
(16, 'test1', 'hallo', NULL, '2018-06-04 14:25:27'),
(17, 'te
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 | 1 | -- phpMyAdmin SQL Dump
-- version 4.7.9
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Jun 05, 2018 at 12:32 PM
-- Server version: 5.7.21
-- PHP Version: 5.6.35
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `cos_login_db`
--
-- --------------------------------------------------------
--
-- Table structure for table `chat`
--
DROP TABLE IF EXISTS `chat`;
CREATE TABLE IF NOT EXISTS `chat` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`msg` text NOT NULL,
`user_id` int(5) DEFAULT NULL,
`date_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=24 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `chat`
--
INSERT INTO `chat` (`id`, `username`, `msg`, `user_id`, `date_created`) VALUES
(1, 'admin', 'hello evry 1', NULL, '2018-06-04 14:05:57'),
(2, 'test1', 'hi', NULL, '2018-06-04 14:06:07'),
(3, 'admin', 'hello', NULL, '2018-06-04 14:07:42'),
(4, 'test1', 'hiyers', NULL, '2018-06-04 14:07:48'),
(5, 'test2', 'hyerss', NULL, '2018-06-04 14:08:53'),
(6, 'admin', 'ohhh', NULL, '2018-06-04 14:09:03'),
(7, 'test1', 'yes', NULL, '2018-06-04 14:09:11'),
(8, 'admin', 'yeah', NULL, '2018-06-04 14:09:17'),
(9, 'test2', 'hello', NULL, '2018-06-04 14:09:26'),
(10, 'test2', ':)', NULL, '2018-06-04 14:09:46'),
(11, 'test1', 'yo!', NULL, '2018-06-04 14:16:51'),
(12, 'test1', 'hallo', NULL, '2018-06-04 14:17:33'),
(13, 'test1', ':)', NULL, '2018-06-04 14:18:13'),
(14, 'test1', ':)', NULL, '2018-06-04 14:18:20'),
(15, 'admin', 'http://localhost/cos_login/admin/chat', NULL, '2018-06-04 14:18:33'),
(16, 'test1', 'hallo', NULL, '2018-06-04 14:25:27'),
(17, 'test1', 'http://youtube.com', NULL, '2018-06-04 14:25:45'),
(18, 'admin', 'heelo', NULL, '2018-06-04 14:34:37'),
(19, 'test2', 'hi', NULL, '2018-06-04 16:16:16'),
(20, 'test2', 'heee', NULL, '2018-06-04 16:17:37'),
(21, 'test2', 'hi', NULL, '2018-06-04 16:19:51'),
(22, 'admin', 'asd', 2, '2018-06-04 16:25:10'),
(23, 'test1', 'hello', 1, '2018-06-04 16:35:29');
-- --------------------------------------------------------
--
-- Table structure for table `leave_tbl`
--
DROP TABLE IF EXISTS `leave_tbl`;
CREATE TABLE IF NOT EXISTS `leave_tbl` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`user_id` int(5) NOT NULL,
`date_from` date NOT NULL,
`date_to` date NOT NULL,
`status` varchar(20) NOT NULL DEFAULT 'pending',
`date_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`reason` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `leave_tbl`
--
INSERT INTO `leave_tbl` (`id`, `user_id`, `date_from`, `date_to`, `status`, `date_created`, `reason`) VALUES
(1, 2, '2018-06-04', '2018-06-06', 'approved', '2018-06-01 13:58:18', 'test'),
(2, 2, '2018-06-04', '2018-06-06', 'pending', '2018-06-01 14:50:25', 'test2'),
(3, 3, '2018-06-04', '2018-06-06', 'approved', '2018-06-01 14:51:09', 'test1');
-- --------------------------------------------------------
--
-- Table structure for table `task_tbl`
--
DROP TABLE IF EXISTS `task_tbl`;
CREATE TABLE IF NOT EXISTS `task_tbl` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`user_id` int(2) NOT NULL,
`task` text NOT NULL,
`date_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`status` varchar(20) NOT NULL DEFAULT 'ongoing',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `task_tbl`
--
INSERT INTO `task_tbl` (`id`, `user_id`, `task`, `date_created`, `status`) VALUES
(1, 3, 'task test', '2018-05-31 13:32:26', 'ongoing'),
(2, 2, '-test task1\r\n-test task2', '2018-05-31 13:33:38', 'ongoing'),
(3, 3, 'task3', '2018-05-31 14:28:10', 'ongoing'),
(4, 2, 'task again', '2018-05-31 14:31:30', 'done'),
(5, 3, 'task\r\ntask\r\ntask\r\n', '2018-05-31 14:31:47', 'ongoing'),
(6, 3, 'a', '2018-05-31 14:32:50', 'done'),
(7, 2, 'taskking dem', '2018-05-31 14:33:35', 'done'),
(8, 3, 'task ni', '2018-05-31 14:34:57', 'done'),
(9, 3, 'task nsud\r\n', '2018-05-31 14:43:06', 'ongoing'),
(10, 3, 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.', '2018-05-31 16:53:35', 'done');
-- --------------------------------------------------------
--
-- Table structure for table `timesheets_tbl`
--
DROP TABLE IF EXISTS `timesheets_tbl`;
CREATE TABLE IF NOT EXISTS `timesheets_tbl` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`user_id` int(2) NOT NULL,
`time_in` time DEFAULT NULL,
`time_out` time DEFAULT NULL,
`note` varchar(250) DEFAULT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `timesheets_tbl`
--
INSERT INTO `timesheets_tbl` (`id`, `user_id`, `time_in`, `time_out`, `note`, `date`) VALUES
(1, 2, '21:18:00', '21:18:27', NULL, '2018-05-30 13:18:00'),
(2, 3, '21:18:07', '21:18:11', NULL, '2018-05-30 13:18:07'),
(3, 3, '21:18:40', '21:22:48', NULL, '2018-05-30 13:18:40'),
(4, 2, '22:35:54', '22:47:49', NULL, '2018-05-30 14:35:54'),
(5, 2, '01:09:34', '01:10:12', NULL, '2018-05-30 17:09:34'),
(8, 2, '19:56:16', '19:57:24', NULL, '2018-06-01 11:56:16'),
(9, 2, '19:57:34', NULL, NULL, '2018-06-01 11:57:34'),
(10, 3, '22:50:50', '00:08:21', NULL, '2018-06-01 14:50:50');
-- --------------------------------------------------------
--
-- Table structure for table `user_tbl`
--
DROP TABLE IF EXISTS `user_tbl`;
CREATE TABLE IF NOT EXISTS `user_tbl` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`uname` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`fname` varchar(50) NOT NULL,
`lname` varchar(50) NOT NULL,
`utype` int(2) NOT NULL COMMENT '1-admin, 2-staff',
`date_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_status` varchar(20) NOT NULL DEFAULT 'active',
`is_timein` varchar(10) NOT NULL DEFAULT 'no',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user_tbl`
--
INSERT INTO `user_tbl` (`id`, `uname`, `password`, `fname`, `lname`, `utype`, `date_created`, `user_status`, `is_timein`) VALUES
(1, 'admin', '<PASSWORD>', '<PASSWORD>', 'admin', 1, '2018-05-29 13:01:46', 'active', 'no'),
(2, 'test1', '<PASSWORD>', 'test1', 'test1', 2, '2018-05-29 14:32:33', 'active', 'yes'),
(3, 'test2', '<PASSWORD>', 'test2', 'test2', 2, '2018-05-29 14:33:28', 'active', 'no');
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
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 'sinatra/base'
require 'sinatra-logentries'
require 'active_support/inflector'
module ApiResource
def self.included(klass)
klass.send(:include, ApiResource::Methods)
klass.send(:extend, ApiResource::Methods)
end
module Methods
@@resource_id = :id
def set_resource_id(resource_id)
@@resource_id = resource_id
end
def uri(base="")
base + "/" + self.class.name.pluralize.downcase + '/' + self.send(@@resource_id).to_s
end
end
end
module Sinatra
module JsonAPI
module Helpers
def api_base_url
if settings.api_version.empty?
request.base_url
else
request.base_url + "/" + settings.api_version
end
end
def page_index(default=nil)
if !default.nil?
request_assert(params[:page_index].nil? || params[:page_index].to_i > 0, "page index")
params[:page_index] = (params[:page_index] || default).to_i
end
params[:page_index]
end
def page_size(default=nil)
if !default.nil?
request_assert(params[:page_size].nil? || params[:page_size].to_i > 0, "page size")
params[:page_size] = (params[:page_size] || default).to_i
end
params[:page_size]
end
def format_response(data)
preferred_type = ""
if !params[:format].nil? && params[:format].length > 1
preferred_type = "*/" + params[:format]
else
preferred_type = request.preferred_type('*/json', '*/html')
end
case preferred_type
when '*/html'
content_type :html
'<pre>' + JSON.pretty_generate(data) + '</pre>'
else
content_type :json
data.to_json
end
end
def respond(data={}, code=nil)
if code.nil?
if data.is_a? Integer
status data
elsif data.nil?
status 204
else
status 200
format_response(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>"
| ruby | 2 | require 'sinatra/base'
require 'sinatra-logentries'
require 'active_support/inflector'
module ApiResource
def self.included(klass)
klass.send(:include, ApiResource::Methods)
klass.send(:extend, ApiResource::Methods)
end
module Methods
@@resource_id = :id
def set_resource_id(resource_id)
@@resource_id = resource_id
end
def uri(base="")
base + "/" + self.class.name.pluralize.downcase + '/' + self.send(@@resource_id).to_s
end
end
end
module Sinatra
module JsonAPI
module Helpers
def api_base_url
if settings.api_version.empty?
request.base_url
else
request.base_url + "/" + settings.api_version
end
end
def page_index(default=nil)
if !default.nil?
request_assert(params[:page_index].nil? || params[:page_index].to_i > 0, "page index")
params[:page_index] = (params[:page_index] || default).to_i
end
params[:page_index]
end
def page_size(default=nil)
if !default.nil?
request_assert(params[:page_size].nil? || params[:page_size].to_i > 0, "page size")
params[:page_size] = (params[:page_size] || default).to_i
end
params[:page_size]
end
def format_response(data)
preferred_type = ""
if !params[:format].nil? && params[:format].length > 1
preferred_type = "*/" + params[:format]
else
preferred_type = request.preferred_type('*/json', '*/html')
end
case preferred_type
when '*/html'
content_type :html
'<pre>' + JSON.pretty_generate(data) + '</pre>'
else
content_type :json
data.to_json
end
end
def respond(data={}, code=nil)
if code.nil?
if data.is_a? Integer
status data
elsif data.nil?
status 204
else
status 200
format_response(data)
end
else
status code
format_response(data) unless data.nil?
end
end
def respond_with_data(data, opts={}, code=200)
payload = opts
payload['data'] = data
respond payload, code
end
def halt_error(code, message=nil, data=nil)
logger.warn("#{code} - #{message}") if code >= 500
payload = {}
payload['message'] = message unless message.nil?
payload['data'] = data unless data.nil?
halt code, {'Content-Type' => 'application/json'}, payload.to_json
end
def halt_404(message=nil, data=nil)
message ||= "Not Found"
halt_error(404, message, data)
end
def request_assert(condition, message=nil)
if condition != true
if message
halt_error 400, "Bad Request: " + message
else
halt_error 400, "Bad Request"
end
end
end
def get_columns(all, default=nil)
default ||= all
if !params[:columns].nil? && params[:columns].length > 0
if params[:columns][0] == "*"
all
else
params[:columns] & all
end
else
default
end
end
end
def api_version(v)
set :api_version, v
end
def get_param_columns
if @wildcard_columns.nil?
return "*"
elsif !params[:columns].nil?
return URI::encode(params[:columns].join(','))
else
return ""
end
end
def get_json(path, options={}, &block)
options[:provides] = ['json', 'html']
url_prefix = ""
url_prefix = '/' + settings.api_version unless settings.api_version.empty?
all_columns = options[:all_columns]
options.delete(:all_columns) if !options[:all_columns].nil?
get url_prefix + path + "\.?:format?", options do
# make column array
if !params[:columns].nil?
params[:columns] = params[:columns].split(",").map { |p| p.strip }.select { |p| !p.empty? }
else
params[:columns] = []
end
# expand all columns
if params[:columns].length > 0 && params[:columns][0] == "*"
@wildcard_columns = true
params[:columns] = all_columns || []
else
params[:columns] = params[:columns].map { |p| p.to_sym }
params[:columns] = params[:columns] & all_columns if !all_columns.nil?
end
instance_eval &block
end
end
def put_json(path, options={}, &block)
options[:provides] = ['json', 'html']
url_prefix = ""
url_prefix = '/' + settings.api_version unless settings.api_version.empty?
put url_prefix + path, options do
instance_eval &block
end
end
def delete_json(path, options={}, &block)
options[:provides] = ['json', 'html']
url_prefix = ""
url_prefix = '/' + settings.api_version unless settings.api_version.empty?
delete url_prefix + path, options do
instance_eval &block
end
end
def self.registered(app)
app.helpers JsonAPI::Helpers
app.set :method do |*methods|
condition { methods.map(&:upcase).include? request.request_method }
end
app.set :accept do |type|
condition { request.content_type == type }
end
app.before method: %w(post put patch) do
begin
body = JSON.parse(request.body.read)
rescue JSON::ParserError
error_message = "Problems parsing JSON"
end
if error_message or ! body.kind_of?(Hash)
error_message ||= 'Body should be a JSON hash'
halt 400, {'Content-Type' => 'application/json'},
{'message' => error_message}.to_json
end
@body = OpenStruct.new(body)
end
end
end
register JsonAPI
end |
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:
// <copyright file="IColour.cs" company="SoluiNet">
// Copyright (c) SoluiNet. All rights reserved.
// </copyright>
namespace SoluiNet.DevTools.Core.Reference
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Represents an interface for colour definitions.
/// </summary>
public interface IColour
{
/// <summary>
/// Gets the red parts in the colour.
/// </summary>
byte Red { get; }
/// <summary>
/// Gets the green parts in the colour.
/// </summary>
byte Green { get; }
/// <summary>
/// Gets the blue parts in the colour.
/// </summary>
byte Blue { get; }
/// <summary>
/// Gets the cyan parts in the colour.
/// </summary>
decimal Cyan { get; }
/// <summary>
/// Gets the magenta parts in the colour.
/// </summary>
decimal Magenta { get; }
/// <summary>
/// Gets the yellow parts in the colour.
/// </summary>
decimal Yellow { get; }
/// <summary>
/// Gets the black parts in the colour.
/// </summary>
decimal Black { get; }
/// <summary>
/// Gets the transparency of the colour.
/// </summary>
byte Transparency { 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>"
| csharp | 2 | // <copyright file="IColour.cs" company="SoluiNet">
// Copyright (c) SoluiNet. All rights reserved.
// </copyright>
namespace SoluiNet.DevTools.Core.Reference
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Represents an interface for colour definitions.
/// </summary>
public interface IColour
{
/// <summary>
/// Gets the red parts in the colour.
/// </summary>
byte Red { get; }
/// <summary>
/// Gets the green parts in the colour.
/// </summary>
byte Green { get; }
/// <summary>
/// Gets the blue parts in the colour.
/// </summary>
byte Blue { get; }
/// <summary>
/// Gets the cyan parts in the colour.
/// </summary>
decimal Cyan { get; }
/// <summary>
/// Gets the magenta parts in the colour.
/// </summary>
decimal Magenta { get; }
/// <summary>
/// Gets the yellow parts in the colour.
/// </summary>
decimal Yellow { get; }
/// <summary>
/// Gets the black parts in the colour.
/// </summary>
decimal Black { get; }
/// <summary>
/// Gets the transparency of the colour.
/// </summary>
byte Transparency { get; }
}
}
|
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 Zama
module SDB
class ModelEnum < Results
include Enumerable
attr_accessor :instance_klass
def each
@raw.search("//Item").each do |raw_item|
yield((instance_klass || Results).new(raw_item))
end
end
def next_token
@raw.search("//NextToken").inner_text
end
def last
return (instance_klass || Results).new(@raw.search("//Item").last)
end
def size
@raw.search("//Item").size
end
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 Zama
module SDB
class ModelEnum < Results
include Enumerable
attr_accessor :instance_klass
def each
@raw.search("//Item").each do |raw_item|
yield((instance_klass || Results).new(raw_item))
end
end
def next_token
@raw.search("//NextToken").inner_text
end
def last
return (instance_klass || Results).new(@raw.search("//Item").last)
end
def size
@raw.search("//Item").size
end
end
end
end
|
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
source ./common/utils.sh
kubectl create namespace istio-system
helm template istio-init ../manifests/istio/helm/istio-init --namespace istio-system | kubectl apply -f -
verify_kubectl $? "Creating Istio resources failed"
wait_for_crds "adapters.config.istio.io,attributemanifests.config.istio.io,authorizationpolicies.rbac.istio.io,clusterrbacconfigs.rbac.istio.io,destinationrules.networking.istio.io,envoyfilters.networking.istio.io,gateways.networking.istio.io,handlers.config.istio.io,httpapispecbindings.config.istio.io,httpapispecs.config.istio.io,instances.config.istio.io,meshpolicies.authentication.istio.io,policies.authentication.istio.io,quotaspecbindings.config.istio.io,quotaspecs.config.istio.io,rbacconfigs.rbac.istio.io,rules.config.istio.io,serviceentries.networking.istio.io,servicerolebindings.rbac.istio.io,serviceroles.rbac.istio.io,sidecars.networking.istio.io,templates.config.istio.io,virtualservices.networking.istio.io"
# We tested it with helm --set according to the descriptions provided in https://istio.io/docs/setup/install/helm/
# However, it did not work out. Therefore, we are using sed
sed 's/LoadBalancer #change to NodePort, ClusterIP or LoadBalancer if need be/'$GATEWAY_TYPE'/g' ../manifests/istio/helm/istio/charts/gateways/values.yaml > ../manifests/istio/helm/istio/charts/gateways/values_tmp.yaml
mv ../manifests/istio/helm/istio/charts/gateways/values_tmp.yaml ../manifests/istio/helm/istio/charts/gateways/values.yaml
helm template istio ../manifests/istio/helm/istio --namespace istio-system --values ../manifests/istio/helm/istio/values-istio-minimal.yaml | kubectl apply -f -
verify_kubectl $? "Installing Istio failed."
wait_for_deployment_in_namespace "istio-ingressgateway" "istio-system"
wait_for_deployment_in_namespace "istio-pilot" "istio-system"
wait_for_deployment_in_namespace "istio-citadel" "istio-system"
wait_for_deployment_in_namespace "istio-sidecar-injector" "istio-system"
wait_for_all_pods_in_namespace "istio-system
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 | #!/bin/bash
source ./common/utils.sh
kubectl create namespace istio-system
helm template istio-init ../manifests/istio/helm/istio-init --namespace istio-system | kubectl apply -f -
verify_kubectl $? "Creating Istio resources failed"
wait_for_crds "adapters.config.istio.io,attributemanifests.config.istio.io,authorizationpolicies.rbac.istio.io,clusterrbacconfigs.rbac.istio.io,destinationrules.networking.istio.io,envoyfilters.networking.istio.io,gateways.networking.istio.io,handlers.config.istio.io,httpapispecbindings.config.istio.io,httpapispecs.config.istio.io,instances.config.istio.io,meshpolicies.authentication.istio.io,policies.authentication.istio.io,quotaspecbindings.config.istio.io,quotaspecs.config.istio.io,rbacconfigs.rbac.istio.io,rules.config.istio.io,serviceentries.networking.istio.io,servicerolebindings.rbac.istio.io,serviceroles.rbac.istio.io,sidecars.networking.istio.io,templates.config.istio.io,virtualservices.networking.istio.io"
# We tested it with helm --set according to the descriptions provided in https://istio.io/docs/setup/install/helm/
# However, it did not work out. Therefore, we are using sed
sed 's/LoadBalancer #change to NodePort, ClusterIP or LoadBalancer if need be/'$GATEWAY_TYPE'/g' ../manifests/istio/helm/istio/charts/gateways/values.yaml > ../manifests/istio/helm/istio/charts/gateways/values_tmp.yaml
mv ../manifests/istio/helm/istio/charts/gateways/values_tmp.yaml ../manifests/istio/helm/istio/charts/gateways/values.yaml
helm template istio ../manifests/istio/helm/istio --namespace istio-system --values ../manifests/istio/helm/istio/values-istio-minimal.yaml | kubectl apply -f -
verify_kubectl $? "Installing Istio failed."
wait_for_deployment_in_namespace "istio-ingressgateway" "istio-system"
wait_for_deployment_in_namespace "istio-pilot" "istio-system"
wait_for_deployment_in_namespace "istio-citadel" "istio-system"
wait_for_deployment_in_namespace "istio-sidecar-injector" "istio-system"
wait_for_all_pods_in_namespace "istio-system"
oc adm policy add-scc-to-user anyuid -z istio-ingress-service-account -n istio-system
oc adm policy add-scc-to-user anyuid -z default -n istio-system
oc adm policy add-scc-to-user anyuid -z prometheus -n istio-system
oc adm policy add-scc-to-user anyuid -z istio-egressgateway-service-account -n istio-system
oc adm policy add-scc-to-user anyuid -z istio-citadel-service-account -n istio-system
oc adm policy add-scc-to-user anyuid -z istio-ingressgateway-service-account -n istio-system
oc adm policy add-scc-to-user anyuid -z istio-cleanup-old-ca-service-account -n istio-system
oc adm policy add-scc-to-user anyuid -z istio-mixer-post-install-account -n istio-system
oc adm policy add-scc-to-user anyuid -z istio-mixer-service-account -n istio-system
oc adm policy add-scc-to-user anyuid -z istio-pilot-service-account -n istio-system
oc adm policy add-scc-to-user anyuid -z istio-sidecar-injector-service-account -n istio-system
oc adm policy add-scc-to-user anyuid -z istio-galley-service-account -n istio-system
oc adm policy add-scc-to-user anyuid -z istio-security-post-install-account -n istio-system
oc expose svc istio-ingressgateway -n istio-system
ROUTER_POD=$(oc get pods -n default -l router=router -ojsonpath={.items[0].metadata.name})
# allow wildcard domains
oc project default
oc adm router --replicas=0
verify_kubectl $? "Scaling down router failed"
oc set env dc/router ROUTER_ALLOW_WILDCARD_ROUTES=true
verify_kubectl $? "Configuration of openshift router failed"
oc scale dc/router --replicas=1
verify_kubectl $? "Upscaling of router failed"
oc delete pod $ROUTER_POD -n default --force --grace-period=0 --ignore-not-found
# create wildcard route for istio ingress gateway
BASE_URL=$(oc get route -n istio-system istio-ingressgateway -oyaml | yq r - spec.host | sed 's~istio-ingressgateway-istio-system.~~')
# Domain used for routing to keptn services
export DOMAIN="ingress-gateway.$BASE_URL"
oc create route passthrough istio-wildcard-ingress-secure-keptn --service=istio-ingressgateway --hostname="www.keptn.ingress-gateway.$BASE_URL" --port=https --wildcard-policy=Subdomain --insecure-policy='None' -n istio-system
oc adm policy add-cluster-role-to-user cluster-admin system:serviceaccount:keptn:default
verify_kubectl $? "Adding cluster-role failed."
# Set up SSL
openssl req -nodes -newkey rsa:2048 -keyout key.pem -out certificate.pem -x509 -days 365 -subj "/CN=$DOMAIN"
kubectl create --namespace istio-system secret tls istio-ingressgateway-certs --key key.pem --cert certificate.pem
#verify_kubectl $? "Creating secret for istio-ingressgateway-certs failed."
rm key.pem
rm certificate.pem
kubectl apply -f ../manifests/istio/public-gateway.yaml
verify_kubectl $? "Deploying public-gateway failed."
|
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 * as chalk from "chalk";
(chalk as any).enabled = true;
export class AnsiColor {
public static html: any = require("ansi-html");
public static chalk: any = chalk;
public static toBrowser(text: string): string[] {
return this.htmlToStyles(this.html(text));
}
public static clear(text: string): string {
return this.chalk.stripColor(text);
}
public static isSupported(): boolean {
return this.chalk.supportsColor;
}
public static htmlToStyles(...text: string[]): string[] {
const argArray: string[] = [];
if (arguments.length) {
const startTagRe = /<span\s+style=(['"])([^'"]*)\1\s*>/gi;
const endTagRe = /<\/span>/gi;
let reResultArray;
argArray.push(arguments[0].replace(startTagRe, "%c").replace(endTagRe, "%c"));
// tslint:disable-next-line
while (reResultArray = startTagRe.exec(arguments[0])) {
argArray.push(reResultArray[2]);
argArray.push("");
}
for (let j = 1; j < arguments.length; j++) {
argArray.push(arguments[j]);
}
}
return argArray;
}
}
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 * as chalk from "chalk";
(chalk as any).enabled = true;
export class AnsiColor {
public static html: any = require("ansi-html");
public static chalk: any = chalk;
public static toBrowser(text: string): string[] {
return this.htmlToStyles(this.html(text));
}
public static clear(text: string): string {
return this.chalk.stripColor(text);
}
public static isSupported(): boolean {
return this.chalk.supportsColor;
}
public static htmlToStyles(...text: string[]): string[] {
const argArray: string[] = [];
if (arguments.length) {
const startTagRe = /<span\s+style=(['"])([^'"]*)\1\s*>/gi;
const endTagRe = /<\/span>/gi;
let reResultArray;
argArray.push(arguments[0].replace(startTagRe, "%c").replace(endTagRe, "%c"));
// tslint:disable-next-line
while (reResultArray = startTagRe.exec(arguments[0])) {
argArray.push(reResultArray[2]);
argArray.push("");
}
for (let j = 1; j < arguments.length; j++) {
argArray.push(arguments[j]);
}
}
return argArray;
}
}
|
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:
# Creative with code
## A site for creative coding projects
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 | # Creative with code
## A site for creative coding projects
|
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 RegistroAlimento < ActiveRecord::Base
belongs_to :usuario
belongs_to :etiqueta
belongs_to :alimento
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 RegistroAlimento < ActiveRecord::Base
belongs_to :usuario
belongs_to :etiqueta
belongs_to :alimento
end
|
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 Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Constraint = Matter.Constraint;
var maxDrops = 100;
function preload(){
}
function setup(){
createCanvas(500,650);
for(i=0; i<maxDrops; i++){
drops.push(new createDrop(random(0,400), random(0,400)));
}
}
function draw(){
background(0);
drop.display();
}
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 Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Constraint = Matter.Constraint;
var maxDrops = 100;
function preload(){
}
function setup(){
createCanvas(500,650);
for(i=0; i<maxDrops; i++){
drops.push(new createDrop(random(0,400), random(0,400)));
}
}
function draw(){
background(0);
drop.display();
}
|
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:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="index, follow">
<meta name="keywords" content="Wind turbine avec ses mains,Les mains">
<meta name="description" content="Wind turbine avec ses mains Les mains">
<title>Wind turbine avec ses mains</title>
<link type="text/css" rel="StyleSheet" href="/template6/371.css" />
<style type="text/css">.UhideBlockL {display:none}</style>
<link rel="SHORTCUT ICON" href="/favicon.png">
<meta name="google-site-verification" content="pfhoedGdE_p32okKjeXNpPOVmeAifL0rSAkc7bKYsOE" />
<meta name="msvalidate.01" content="E7C54632A67FDD6633F6787F700E53C5" />
<meta name='wmail-verification' content='de89c3e5be2559ba5eb965eecbdf1c13' />
</head>
<body style="background-color:#CCE42C; margin:0px; padding:0px;">
<!--U1AHEADER1Z-->
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 728x90 -->
<ins class="adsbygoogle"
style="display:inline-block;width:728px;height:90px"
data-ad-client="ca-pub-6043169635834063"
data-ad-slot="1890578139"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<table border="0" cellpadding="0" cellspacing="0" width="100%" height="250" style="background:#CCE42C;">
<tr><td width="500" height="77" valign="bottom" style="">
<!--/U1AHEADER1Z-->
<table cellpadding="0" cellspacing="0" border="0" width="100%" style="padding: 10px;"><tr><td width="100%" align="center">
<!-- <middle> -->
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td valign="top" width="200">
<!--U1CLEFTER1Z-->
<!-- <block1> -->
<table border="0" cellpadding="0" cellspacing="0" width="200">
<tr><td align="right" style="background:url('/template6/13.gif');padding-right:35px;color:#A42900;" height="31"><b><!-- <bt> -->Меню<!-- </bt> --></b></td></tr>
<tr><td style="background:url('/template6/14.gif');padding:5px 5px 0px 5px;"><!-- <bc> -->
<div id="uMenuDiv1" class="uMenuV" style="positi
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 | <html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="index, follow">
<meta name="keywords" content="Wind turbine avec ses mains,Les mains">
<meta name="description" content="Wind turbine avec ses mains Les mains">
<title>Wind turbine avec ses mains</title>
<link type="text/css" rel="StyleSheet" href="/template6/371.css" />
<style type="text/css">.UhideBlockL {display:none}</style>
<link rel="SHORTCUT ICON" href="/favicon.png">
<meta name="google-site-verification" content="pfhoedGdE_p32okKjeXNpPOVmeAifL0rSAkc7bKYsOE" />
<meta name="msvalidate.01" content="E7C54632A67FDD6633F6787F700E53C5" />
<meta name='wmail-verification' content='de89c3e5be2559ba5eb965eecbdf1c13' />
</head>
<body style="background-color:#CCE42C; margin:0px; padding:0px;">
<!--U1AHEADER1Z-->
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 728x90 -->
<ins class="adsbygoogle"
style="display:inline-block;width:728px;height:90px"
data-ad-client="ca-pub-6043169635834063"
data-ad-slot="1890578139"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<table border="0" cellpadding="0" cellspacing="0" width="100%" height="250" style="background:#CCE42C;">
<tr><td width="500" height="77" valign="bottom" style="">
<!--/U1AHEADER1Z-->
<table cellpadding="0" cellspacing="0" border="0" width="100%" style="padding: 10px;"><tr><td width="100%" align="center">
<!-- <middle> -->
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td valign="top" width="200">
<!--U1CLEFTER1Z-->
<!-- <block1> -->
<table border="0" cellpadding="0" cellspacing="0" width="200">
<tr><td align="right" style="background:url('/template6/13.gif');padding-right:35px;color:#A42900;" height="31"><b><!-- <bt> -->Меню<!-- </bt> --></b></td></tr>
<tr><td style="background:url('/template6/14.gif');padding:5px 5px 0px 5px;"><!-- <bc> -->
<div id="uMenuDiv1" class="uMenuV" style="position:relative;">
<ul class="uMenuRoot">
<li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/les-r-gimes-power-v/index.html" title="Les régimes Power-vitamines"><span>Les régimes Power-vitamines</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/maison-et-confort/index.html" title="Maison et confort"><span>Maison et confort</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/jardinage/index.html" title="Jardinage"><span>Jardinage</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/les-mains/index.html" title="Les mains"><span>Les mains</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/quand-est-ce-que/index.html" title="Quand est-ce que"><span>Quand est-ce que</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/machines-et-t-l-pho/index.html" title="Machines et téléphones"><span>Machines et téléphones</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/entreprise/index.html" title="Entreprise"><span>Entreprise</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/entreprise/index.html" title="Entreprise"><span>Entreprise</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/les-r-gimes-power-v/index.html" title="Les régimes Power-vitamines"><span>Les régimes Power-vitamines</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/amour-et-relations/index.html" title="Amour et relations"><span>Amour et relations</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/int-ressant/index.html" title="Intéressant"><span>Intéressant</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/entreprise/index.html" title="Entreprise"><span>Entreprise</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/amour-et-relations/index.html" title="Amour et relations"><span>Amour et relations</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/informatique-et-int/index.html" title="Informatique et Internet"><span>Informatique et Internet</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/default/index.html" title="Default"><span>Default</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/autre/index.html" title="Autre"><span>Autre</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/les-r-gimes-power-v/index.html" title="Les régimes Power-vitamines"><span>Les régimes Power-vitamines</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/amour-et-relations/index.html" title="Amour et relations"><span>Amour et relations</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li><li><div class="umn-tl"><div class="umn-tr"><div class="umn-tc"></div></div></div><div class="umn-ml"><div class="umn-mr"><div class="umn-mc"><div class="uMenuItem"><a href="/quand-est-ce-que/index.html" title="Quand est-ce que"><span>Quand est-ce que</span></a></div></div></div></div><div class="umn-bl"><div class="umn-br"><div class="umn-bc"><div class="umn-footer"></div></div></div></div></li>
</ul>
</div>
<!-- </bc> -->
</td></tr>
<tr><td height="64"><img src="/template6/15.gif" border="0"></td></tr>
</table><br />
<!-- </block1> -->
<!-- <block2> -->
<!-- </block2> -->
<!-- <block4> -->
<!-- </block4> -->
<!--/U1CLEFTER1Z-->
</td>
<td valign="top" style="padding:0px 10px 0px 10px;">
<table border="0" cellpadding="5" cellspacing="0" width="100%" style="border:1px solid #6DA104;"><tr><td style="background:#FFFFFF;">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 468x60 -->
<ins class="adsbygoogle"
style="display:inline-block;width:468px;height:60px"
data-ad-client="ca-pub-6043169635834063"
data-ad-slot="7202081735"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><br/>
<!-- <body> -->
<div class="maincont"> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362b2oxaXdlVHN6Y0k" alt=' Wind turbine avec ses mains ' title=' Wind turbine avec ses mains '></div> <br> Cette éolienne est de 1000 watts capables de fournir de l'électricité 1 maison de campagne. En fait, ce dispositif est basé sur un générateur magnétique maison. Le projet nécessitera de vous connaissance approfondie des phénomènes physiques et de l'électrodynamique et des compétences avec des dispositifs magnétiques. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362emlmRWNJT2lXZ3M" alt=' Wind turbine avec ses mains ' title=' Wind turbine avec ses mains '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362bk5oZlF2RVJocEE" alt=' Wind turbine avec ses mains ' title=' Wind turbine avec ses mains '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362ZGxkdGNPdW16a2s" alt=' Wind turbine avec ses mains ' title=' Wind turbine avec ses mains '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362TXZneEF5aFF0X1k" alt=' Wind turbine avec ses mains ' title=' Wind turbine avec ses mains '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362MWtZZDVMb2Q1UUU" alt=' Wind turbine avec ses mains ' title=' Wind turbine avec ses mains '></div> <br> <b> Étape 1: Wire Wheels </b> <br> Il faudra plusieurs disques en acier d'un diamètre de 30 cm. Ils attachent aimants 12 Classe n50 uniformément dans un cercle. Polly de résine et de durcisseur à partir de ci-dessus. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362eUQ1NEtNUW5JTUU" alt=' Wind turbine avec ses mains ' title=' Wind turbine avec ses mains '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362Y2J0WlZjUmROekE" alt=' Wind turbine avec ses mains ' title=' Wind turbine avec ses mains '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362emFKQTRXNXRFdVU" alt=' Wind turbine avec ses mains ' title=' Wind turbine avec ses mains '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362OENVMmpQOUE5OFU" alt=' Wind turbine avec ses mains ' title=' Wind turbine avec ses mains '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362QnJlLWtKRDRuQlk" alt=' Wind turbine avec ses mains ' title=' Wind turbine avec ses mains '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362WlU5Qm5hZkdSSW8" alt=' Wind turbine avec ses mains ' title=' Wind turbine avec ses mains '></div> <br> <b> Étape 2: Coil </b> <br> Préparer 9 rouleaux et en faire un système avec 3 phases, puis couvrir la colophane. Utilisez circuit unique 70 tourne 24 à 35 tours ou 2 chaînes parallèles 12 Art. <br> Schéma générateur à 3 phases représenté sur les figures 5 et 6. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362dEpzaUlvcV85UzQ" alt=' Wind turbine avec ses mains ' title=' Wind turbine avec ses mains '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362VnRzdVRGZUU3RDA" alt=' Wind turbine avec ses mains ' title=' Wind turbine avec ses mains '></div> <br> <b> Étape 3: Roulements </b> <br> 1 roulement mis dans un gros tuyau, puis insérez un autre tube et monter le 2ème palier. <br> <b> Étape 4: Blades </b> <br> Ils sont coupés avec une scie à table avec des poutres de pin, chacune mesurant 5 cm à 15 cm. Ensuite moudre. La surface des lames doit être parfaitement lisse. <br> La vidéo montre le processus d'élaboration des maîtres de radio étrangères. <br> <iframe title=" Lecteur vidéo YouTube " width="425" height="325" src="http://www.youtube.com/embed/o9EEHFKEckM?rel=0&wmode=transparent" frameborder="0" allowfullscreen=""></iframe> <div class="clr"></div> </div> <div class="source" name="source" align="right"><a href="http://vk.ru"> vk.ru Source </a></div><div class="maincont"> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362LVdGRjdibzFLRnM" alt=" Tracteur avec moscovite 412 " title=" Tracteur avec moscovite 412 "></div> <br> Au début, je faisais un mini tracteur avec le moteur de l'Est, avec une boîte de la machine moscovite, avec des ponts moskvychevskymy tout en réduisant les samodel suspension avant, la chaîne de document, un ver boîte de vitesses avec des tiges de direction, tuyaux de châssis, roues moscovite, le corps, les sièges. <br> Puis je me mis les roues de l'Oise et de moteur de moto tordue par leur bezdorozhъyu. Mettez le Moscovite de moteur de voiture, avant de la suspension avant, a couru très bien, mais les grosses charges cadre avec Prof. <NAME>, a dû changer le canal sur 65mm, ainsi, a essayé de mettre le moteur nazat, pour l'expérience et neprohodal, traverser bezdorozhъyu uluchshelas. <br> Sur une trame solide et je pensais prekrepyl seau oblique, charrues, ascenseur 300kh.Upravlyat plus facile, plus confortable pour se reposer, et les passagers assis sur le couvercle du moteur coups de pied arrière sur l'aile. la neprolaznыy de caves d'été à travers le brise-vent de la forêt, de la bonne haborytы peu comme Quadrics est presque partout. Dans la neige d'hiver nettoyé, monté par les congères. <br> Perydelok avait beaucoup de ponts, perydelal document de chaîne sur shestyrenchytuyu à la basse et connexion perydka samodel, Ramm cuit un nouveau moteur de jeu plus fort poserydyne popereh, hydraulique trouvés pohruzochnыy mettre le seau. Beaucoup ont estimé différentes options de conception, auvents différentes, changé perednyyu dépend de l'option de suspension plus dure. <br> Felt et hors route qualité de conduite, mais, par exemple, pourrait remorquer hruzovychek 4t sur le gravier avec un petit camion, tirez un journal de 300 kg en hydraulique boue argile pour soulever et transporter 500 kg kovshe1t. Maintenant, les caractéristiques des données sont: poids env 800 kg, longueur de 2500mm, largeur 1350mm, la vitesse maximale okolo70 km / h, le Moscovite de moteur, boîte de vitesses moscovite, Document transversale propre 2Art à faible, le long perydka reliant le deuxième Document de samodel, essieu arrière verrouillée, est sur ressorts, ressorts de l'essieu avant, moyeu avant moskvychana de 2141, les moyeux sont adaptent sous uazovskye roues, <br> Donc, beaucoup de défauts liés à financer mais l'idée incarnées en général. <div class="clr"></div> </div> <div class="source" name="source" align="right"><a href="http://vk.ru"> vk.ru Source </a></div><div class="maincont"> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362S3lFeFZ2SFhKYjQ" alt=' Casque de gladiateur pour votre animal de compagnie ' title=' Casque de gladiateur pour votre animal de compagnie '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362SEZ3cExwOWtka28" alt=' Casque de gladiateur pour votre animal de compagnie ' title=' Casque de gladiateur pour votre animal de compagnie '></div> <br> Ces amusement et chapeau confortable pour votre chien ne nécessiteront pas de sérieux efforts de la fabrication. <br> <b> Matériaux: </b> <br> <ol type="1"><li> Carton <br> Plaque de métal d'épaisseur <br> Super glue <br> Adhésif pour le bois <br> Cans avec la peinture or ou d'argent <br> Boyau d'étoffe rouge ou plumes <br> Marteau <br> Ciseaux <br> Pinces <br> <NAME> <br> <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362bTl4ZEcxbThNNGc" alt=' Casque de gladiateur pour votre animal de compagnie ' title=' Casque de gladiateur pour votre animal de compagnie '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362dU9NNnZLSkROVm8" alt=' Casque de gladiateur pour votre animal de compagnie ' title=' Casque de gladiateur pour votre animal de compagnie '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362b0F4S3g4VXRyVUk" alt=' Casque de gladiateur pour votre animal de compagnie ' title=' Casque de gladiateur pour votre animal de compagnie '></div> <br> <b> Étape 1: Cadre </b> <br> Dessinez le casque sur carton et découper le contour. <br> En se concentrant sur des photos de plaques métalliques former une billette pour casque. <br> Collez avec plaque et le carton. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362cnNMaW5Bd2wyR28" alt=' Casque de gladiateur pour votre animal de compagnie ' title=' Casque de gladiateur pour votre animal de compagnie '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362QzcxQmh4TVNIRXM" alt=' Casque de gladiateur pour votre animal de compagnie ' title=' Casque de gladiateur pour votre animal de compagnie '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362ZmYxaXd3WG5xV0E" alt=' Casque de gladiateur pour votre animal de compagnie ' title=' Casque de gladiateur pour votre animal de compagnie '></div> <br> <b> Étape 2: bretelles </b> <br> Appliquer couche supplémentaire de colle pour le bois pour lisser légèrement le bord. <br> Couper sangles inutiles en 2 parties et tenir leurs côtés avant. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362bmlpdWVuSlBJd0k" alt=' Casque de gladiateur pour votre animal de compagnie ' title=' Casque de gladiateur pour votre animal de compagnie '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362OW1MLVJ4WHcyb2c" alt=' Casque de gladiateur pour votre animal de compagnie ' title=' Casque de gladiateur pour votre animal de compagnie '></div> <br> <b> Étape 3: bangs </b> <br> La partie supérieure est réalisée dans le même carton. Comme les décorations sur les pièces de bois collées à l'extérieur. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362QUpTTFFxUUdCQ1k" alt=' Casque de gladiateur pour votre animal de compagnie ' title=' Casque de gladiateur pour votre animal de compagnie '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362LVgyN0wtMlFSMjQ" alt=' Casque de gladiateur pour votre animal de compagnie ' title=' Casque de gladiateur pour votre animal de compagnie '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362T2ZydUtSMWVNM1U" alt=' Casque de gladiateur pour votre animal de compagnie ' title=' Casque de gladiateur pour votre animal de compagnie '></div> <br> <b> Étape 4: Attaches </b> <br> Il y aura besoin de coller nombreuses attaches 4 (2 à l'arrière, 2 à l'avant) pour tenir sur mon casque de la tête animal. <br> Pour les éléments et de figures décoratives sur le casque préférable de prendre un peu de bois et les trombones et les fixer à l'aide de la colle super. Dans cette étude, nous avons utilisé forme arbitraire, ainsi sentez-vous libre d'expérimenter. <br> Peindre la couleur du casque teinte dorée. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362a0hsYWpRR3dKNG8" alt=' Casque de gladiateur pour votre animal de compagnie ' title=' Casque de gladiateur pour votre animal de compagnie '></div> <br> <b> Étape 5: Détails </b> <br> Top bâton colle avec fil à l'intérieur (ou lacets de couleur). <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362cHIyQ1I2d1ZtRHc" alt=' Casque de gladiateur pour votre animal de compagnie ' title=' Casque de gladiateur pour votre animal de compagnie '></div> <br> <b> Étape 6: Aquarelle </b> <br> Appliquer la peinture à l'aquarelle noir et puis laver son linge. Il faut se infiltrer sur inégales dessins surfaces au produit regarda réaliste. <div class="clr"></div> </li></ol></div> <div class="source" name="source" align="right"><a href="http://vk.ru"> vk.ru Source </a></div><div class="maincont"> <h2> Décorations de Noël avec ses mains. </h2> <br> Indépendamment de improvisé signifie que vous pouvez faire de nombreuses décorations de Noël intéressantes et différentes. <br> <h3> Collier papillon avec ses mains. Voici les étapes </h3> <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362anJKMWdibjhYZms" alt=' Noël jouets mains des enfants. Collier ' title=' Noël jouets mains des enfants. Collier '></div> <br> Matériels <br> - Monofilament <br> - Perles <br> - Coquilles <br> - Clay <br> - Gouache ou un jeton <br> - Vernis incolore <br> <h3> La séquence de travail </h3> <br> Prenez une ligne de pêche longue à travers elle et perles de prosmykny. Toutes les 8-10 perles lient un morceau de la longueur de la ligne de pêche de 10-20 centimètres. Mieux faire différentes longueurs de segments de ligne. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362dTVhYk1tdmRHdk0" alt=' Noël jouets mains des enfants. Collier ' title=' Noël jouets mains des enfants. Collier '></div> <br> Maintenant, nous faisons papillons de jouets. Prenez un long pour la carrosserie et 4 pour les petites ailes. Coller jouet et peinture gouache ou un jeton qu'il peut couvrir son vernis incolore. Chaque ligne a été libéré de la colle terminé papillon. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362X3FCMkV6cmlTVU0" alt=' Noël jouets mains des enfants. Collier ' title=' Noël jouets mains des enfants. Collier '></div> <br> Maintenant Peindre un tableau <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362eEJRRC1lRXY5aUk" alt=' Noël jouets mains des enfants. Collier ' title=' Noël jouets mains des enfants. Collier '></div> <br> Papillon sur le champ <br> Flotteurs lentement <br> De les fleurs des champs <br> Recueille miel <div class="clr"></div> </div> <div class="source" name="source" align="right"><a href="http://vk.ru"> vk.ru Source </a></div><div class="maincont"> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362NmRuQksxM3FfU1E" alt=" Master Class: belle boîte de rangement avec ses mains " title=" Master Class: belle boîte de rangement avec ses mains "></div> Boîte de rangement avec leurs mains: comment faire cuire? Qu'est-ce que vous avez besoin pour faire de belles boîtes pour le stockage? <br> <br> <br> <br> <br> <li> Boîtes. </li> <br> <li> agrafes de fer. </li> <br> <li> Clay. </li> <br> <li> Tissu lumineux. </li> <br> Pour décorer la boîte, vous avez besoin de faire provision de ciseaux, règle, crayon et du ruban adhésif. Comment faire une boîte pour stocker des choses avec ses mains? Tout d'abord, vous devez préparer la même boîte. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362cFFTdHBEa1cxM0k" alt=" Master Class: belle boîte de rangement avec ses mains " title=" Master Class: belle boîte de rangement avec ses mains "></div> <br> Il est préférable de sa taille variait dans les quarante centimètres. Ensuite, il peut être mis dans le placard et étagères. Mais d'autre part, mieux vaut choisir une boîte de cette taille pour adapter un espace particulier. La hauteur de la face ne doit pas être supérieure à dix centimètres. Il sera très petites choses. Dans les cas extrêmes -, elles peuvent être coupés à l'aide d'un crayon et une règle. Assez pour faire des marques sur les parois latérales. Important: faire des marquages à l'intérieur de la boîte. Mesurez à partir du bas de la boîte pas plus de dix centimètres, puis - faire la mise en page à l'aide d'un crayon. Sur chaque extrémité faire une marque, puis se connecter à la ligne. <br> Produire boîte de rangement avec ses mains ne fait pas de difficultés. Mais, d'abord, vous avez besoin de renforcer les parois de la boîte. Cela peut se faire par différentes méthodes. <br> La façon la plus simple et la plus courante - plier les portes à l'intérieur. Pour ce faire, vous avez besoin de noter certaines boîtes hauteur de tiques et crayon. Que faire dans le cas où le carton ondulé? Puis meilleurs endroits pour passer côté virage brutal des ciseaux. Dans ce cas, vous vous penchez le matériau le long des lignes qui ont tracé. Carton doit exactement correspondre à la paroi. Si la taille du mal quelque part, il est recommandé de corriger - appliquer à nouveau balisage et plier. Surplus doit couper avec des ciseaux. Ensuite, passez à coller la pièce. Clay nécessairement applicable à toute la surface, et plus tard - secondes étroitement 20-30. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362MndjWnBqWjBWMjA" alt=" Master Class: belle boîte de rangement avec ses mains " title=" Master Class: belle boîte de rangement avec ses mains "></div> <br> Les parois latérales peuvent être renforcées et sinon, si coupés châssis supérieur, au carton et bandes coupées. Ainsi, sa largeur est égale à la hauteur de la paroi latérale et la longueur du périmètre des parois latérales. Au bar, vous devez faire une balise spéciale, en utilisant une règle pour mesurer la longueur des côtés courts, et plus tard - longtemps. Bend nécessaire dans des endroits où la mise en page. Pare-chocs devrait coller à l'intérieur de la boîte si le conseil exactement adjacente. <br> La boîte étrange de stocker leurs choses si le décorer avec des matériaux naturels. Coton ressemble beaucoup. Assurez-vous avant le travail et lavage matériau vidprasuyte! Comment faire de marquage? Vous devez longueur - deux centimètres, hauteur - deux centimètres, la longueur de la boîte à l'extérieur et deux centimètres de profondeur. Selon la forme du fond de la boîte, vous devriez obtenir un carré ou un rectangle. Trace recommandé dans le milieu, où le fond de la boîte. <br> Couper la pièce, où vous venez. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362SllXYWNsNC1CTmc" alt=" Master Class: belle boîte de rangement avec ses mains " title=" Master Class: belle boîte de rangement avec ses mains "></div> <br> Le tissu doit plier les deux côtés et plus tard résoudre ce problème: <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362WGR0cFdIWU9idE0" alt=" Master Class: belle boîte de rangement avec ses mains " title=" Master Class: belle boîte de rangement avec ses mains "></div> <br> Pas besoin de coudre le bord de la bande, si le tissu formé uniformément. Il sera lignes suffisantes et de la main. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362LXRueUlRLWpPX2M" alt=" Master Class: belle boîte de rangement avec ses mains " title=" Master Class: belle boîte de rangement avec ses mains "></div> <br> Colle frottis du carton et pressées ensemble. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362OThJVU4zZjlXR0U" alt=" Master Class: belle boîte de rangement avec ses mains " title=" Master Class: belle boîte de rangement avec ses mains "></div> <br> Clay doit sécher pendant une nuit. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362N1hjMFBvNXZudlk" alt=" Master Class: belle boîte de rangement avec ses mains " title=" Master Class: belle boîte de rangement avec ses mains "></div> <br> Le meilleur - bâton au fond d'un autre morceau de tissu. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362RmtlQnBNYm1TcUk" alt=" Master Class: belle boîte de rangement avec ses mains " title=" Master Class: belle boîte de rangement avec ses mains "></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362VmdLY3RjX2RGY0U" alt=" Master Class: belle boîte de rangement avec ses mains " title=" Master Class: belle boîte de rangement avec ses mains "></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362RTF0NUxKbE5MZ2s" alt=" Master Class: belle boîte de rangement avec ses mains " title=" Master Class: belle boîte de rangement avec ses mains "></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362R0RNa1lXejMtMW8" alt=" Master Class: belle boîte de rangement avec ses mains " title=" Master Class: belle boîte de rangement avec ses mains "></div> <br> En conséquence, nous obtenons boîtes confortables, sûres et belles dans laquelle vous pouvez enregistrer des choses différentes. Vous vous pouvez décider de ce qu'il faut mettre en eux! Comme vous pouvez le voir, la boîte d'origine pour stocker leurs mains pour faire simple et facile! <div class="clr"></div> </div> <div class="source" name="source" align="right"><a href="http://vk.ru"> vk.ru Source </a></div><div class="maincont"> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362S1M5Yi1jeEszWmM" alt=" Comment faire une lanterne de papier sur, classe de maître du Nouvel An " title=" Comment faire une lanterne de papier sur, classe de maître du Nouvel An "></div> Produits de papier de Noël que nous connaissons depuis l'enfance - guirlandes, ballons, jouets de Noël de différentes couleurs et tailles. Et bien sûr, des lampes de poche. Au dernier arrêt et envisager d'offrir plusieurs façons de faire des lanternes de papier originaux et très beaux avec leurs mains avant la nouvelle année. <br> <br> <br> <br> <h2> Comment faire voler lanterne de papier avec leurs mains, classe de maître avec photo </h2> <br> Tradition terme dans le ciel voler des lanternes déjà solidement pris racine dans nos latitudes. Pourquoi ne pas utiliser cette méthode de deviner le désir et la Nouvelle-2015? <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362NERnMGVTbmFZY1k" alt=' Comment faire une lanterne de papier sur, classe de maître du Nouvel An ' title=' Comment faire une lanterne de papier sur, classe de maître du Nouvel An '></div> <br> <h3> Matériel nécessaire: </h3> <br> <li> sacs ou papier très fin des ordures; </li> <br> <li> ignifuge; </li> <br> <li> fil; </li> <br> <li> déjouer à partir de chocolat; </li> <br> <li> bande; </li> <br> <li> substance inflammable (comprimés ou liquide) </li> <br> <li> coton ou un chiffon. </li> <br> <h3> Voici les étapes de la prise Sky Lantern </h3> <br> <li> Commençons la création de nos désirs balises volant de la coupole. Idéalement lanternes de papier de ciel faites de papier de riz, mais nous prenons une option plus abordable - sacs à ordures les plus chères. Assez de deux sacs, dont on coupe le fond et l'aide de ruban en les reliant en un seul gros paquet. Peut être utilisé pour encadrer et du papier, mais il doit être très mince et très léger, avec une densité de pas plus de 25 g / m. Pour plus de prise de sécurité de recommander également le traitement de la antipyran dôme. </li> <br> <li> Le cadre de notre lanterne volante maison sera constituée par des anneaux dont le diamètre doit correspondre au diamètre de la coupole, et de manière inoffensive, qui seront installés brûleur. Et l'anneau, et à faire sans danger avec du fil. Pour faciliter la conception peut faire une seule barre. </li> <br> <li> Laissez-nous maintenant de la lampe moteur céleste, c.-à-brûleur. Son que nous faisons comme une petite tasse de chocolat avec du papier et de croix sécurisé dans le centre de l'image. </li> <br> <li> Avec bande nous nous connectons avec notre cadre de dôme - et la main Sky Lantern «fait main» de voler! Il reste seulement à déterminer le carburant, qui peut être utilisé comme un combustible liquide saturé morceau de tissu ou de coton, ou? pastilles de combustible sec. </li> <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362UnVQVzZLaE4zMkE" alt=' Comment faire une lanterne de papier sur, classe de maître du Nouvel An ' title=' Comment faire une lanterne de papier sur, classe de maître du Nouvel An '></div> <br> Si après toutes vos préparations ne pas voler lanterne augmente, de sorte que son design est très difficile et nécessite un soulagement. <br> <h2> Papier lampe suspendue, une classe de maître avec une photo </h2> <br> Hanging lanternes de papier si remplissait pas les désirs, mais apporter l'atmosphère des vacances du Nouvel An une saveur unique. <br> <h3> Matériel nécessaire: </h3> <br> <li> papier de couleur; </li> <br> <li> crayon et une règle; </li> <br> <li> ciseaux; </li> <br> <li> de la colle ou du ruban adhésif transparent. </li> <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362SEF5REFSSWdiRkE" alt=' Comment faire une lanterne de papier sur, classe de maître du Nouvel An ' title=' Comment faire une lanterne de papier sur, classe de maître du Nouvel An '></div> <br> <h2> Voici les étapes de la prise des lanternes de papier suspendus </h2> <br> <li> Pour commencer, couper à partir de la feuille de papier de couleur sélectionnée carré de couleur. Puis ce carré plier en deux sur la longueur. </li> <br> <li> Sur une des sections de tôle pliée décrire les traits de crayon - perpendiculaires bandes de flexion à partir de la courbe et ne pas atteindre le bord de la feuille pour un couple de centimètres. L'aide de ciseaux font de ces coupures. </li> <br> <li> Maintenant dérouler la feuille avec des coupes et lie sa fin ou de la colle ou de ruban adhésif. </li> <br> <li> Pour fixer la plume de la torche de la pièce, qui a coupé une bande étroite de l'authentique et de le coller sur les deux côtés jusqu'au Nouvel An décoration. Ne vous arrêtez pas là-bas et faire un peu plus de ces feux. </li> <br> <li> Lanternes de papier suspendus Prêt peuvent être décorés en outre avec des perles, des rubans colorés, perles et paillettes. <br> </li> <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362anNkNjVESkxVRWs" alt=' Comment faire une lanterne de papier sur, classe de maître du Nouvel An ' title=' Comment faire une lanterne de papier sur, classe de maître du Nouvel An '></div> <br> Ces lanternes "flirter" d'une manière nouvelle, si nous les utilisons un peu dans une autre incarnation. Par exemple, ne pas les attacher à manipuler, et de mettre sur une table de fête (ou la fenêtre) et de mettre une bougie allumée à l'intérieur (LED ou placé dans un verre). Mais alors que telle beauté besoin de surveiller constamment qu'il ne soit pas transformé en difficulté avec le feu. <div class="clr"></div> </div> <div class="source" name="source" align="right"><a href="http://vk.ru"> vk.ru Source </a></div><div class="maincont"> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362dXd4TnBCMmFWRUk" alt=" Comment faire vaste sujet de la Saint-Valentin le 14 Février avec ses mains " title=" Comment faire vaste sujet de la Saint-Valentin le 14 Février avec ses mains "></div> Saint Valentin - un merveilleux séjour coeurs Saint-Valentin. Selon une tradition, d'accueillir les uns les autres valentines prises avec l'image de cœurs. Pas nécessairement pour acheter des cadeaux dans la boutique, vous pouvez faire une valentine avec leurs mains, en mettant en toutes ses créations tendresse. Apprenons valentines trois dimensions bricolage. Aimez vos proches! Fonctionne pour eux! <br> <br> <br> <br> <h2> Master-class №1 </h2> <br> <h3> Ce qu'il nous faut pour le travail: </h3> <br> <li> papier de couleur (par exemple, nous avons rose) </li> <br> <li> papier blanc ordinaire </li> <br> <li> papier brillant brillant </li> <br> <li> colle </li> <br> <li> ciseaux </li> <br> <li> bon tissu </li> <br> <li> l'imagination et la bonne humeur </li> <br> <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362RmtjdFAxU1R2bzA" alt=' Comment faire vaste sujet de la Saint-Valentin le 14 Février avec ses mains ' title=' Comment faire vaste sujet de la Saint-Valentin le 14 Février avec ses mains '></div> <br> <li> Pour commencer, prenez une feuille de papier de couleur A4. Pliez en deux. Suivant le livre blanc, couper un petit cœur, le mettre sur la couverture des cartes futures crayon et le cercle, comme illustré. </li> <br> <li> Maintenant, prenez les ciseaux et couper le "coeur" du contour. </li> <br> <li> Prenez brillant morceau de papier de la même taille que la carte. Collez-le à l'intérieur des cartes. A la place du coeur devrait être couper une partie ornementale. </li> <br> <li> Il reste à décorer la carte. Ecrire vœux chaleureux à l'intérieur. Prenez un beau tissu et de la colle sur la face avant. Vous pouvez utiliser des paillettes et des petits coeurs sur papier de couleur. Si vous avez une photo avec son second semestre - le coller sur la carte. </li> <br> <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362LTFTcW5BWFNrVnc" alt=' Comment faire vaste sujet de la Saint-Valentin le 14 Février avec ses mains ' title=' Comment faire vaste sujet de la Saint-Valentin le 14 Février avec ses mains '></div> <br> <h2> Master-class №2 </h2> <br> <h3> Ce que nous devons: </h3> <br> <li> Papier ondulé rouge (peut prendre des serviettes en papier) </li> <br> <li> Papier blanc </li> <br> <li> cure-dents </li> <br> <li> carton </li> <br> <li> colle </li> <br> <li> ciseaux </li> <br> <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362NVNXcTdNWC1iMW8" alt=' Comment faire vaste sujet de la Saint-Valentin le 14 Février avec ses mains ' title=' Comment faire vaste sujet de la Saint-Valentin le 14 Février avec ses mains '></div> <br> <li> Pour commencer, préparer le terrain pour les cartes. Prenez le carton rouge, le plier en deux. Sur une feuille blanche couper grand coeur. Collez-le sur la première page des futures cartes. </li> <br> <li> Maintenant, vous devez ajouter du volume. Prenez papier ondulé et le couper avec un grand nombre de petits carrés comme indiqué. </li> <br> <li> <NAME> sur un cure-dent. Colle coeur Promazhte et fixez le carré rouge de papier. </li> <br> <li> Faites-le avec chaque carré comme indiqué. Commencez par les bords et se déplacer vers le centre. Continuez jusqu'à ce que toute la carte ne sera pas long. Scratch ne devrait pas rester. </li> <br> <li> En conséquence, vous obtenez la carte postale moelleux. Écrire un souhait ou une déclaration d'amour et de donner sa seconde moitié. </li> <div class="clr"></div> </div> <div class="source" name="source" align="right"><a href="http://vk.ru"> vk.ru Source </a></div><div class="maincont"> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362V0lsMW05bnBrOUU" alt=" Plans broderie de Noël " title=" Plans broderie de Noël "></div> Avec l'approche des fêtes de Noël dans notre vie vient de l'agitation mesurée. Que porter, quoi cuisiner, comment décorer, ce qu'il faut donner. Dans les vitrines de diverses options apparaîtra tas de cadeaux. Les gens commencent à acheter des souvenirs, diverses choses utiles, des anecdotes inutiles, et ne pas beaucoup savent que le don le plus précieux sont présents, ont fait leurs propres mains. Les mains peuvent faire beaucoup de choses, mais aujourd'hui, nous parler de la broderie. <br> <br> <br> <br> Si vous n'êtes pas bon à la broderie - il n'a pas d'importance, il n'y a pas grand-chose. Il suffit de regarder plusieurs leçons instructives, faire quelques points de suture et il va comme sur des roulettes. <br> <h2> Photos de Noël, point de croix brodée et </h2> <br> Vous devez d'abord décider ce que vous voulez donner. Il pourrait être un ornement de Noël sur un arbre de Noël, un oreiller ou un cadre photo. Même la serviette à l'achat brodé de la terre deviendra un motif unique. Il est nécessaire de déterminer la technique - il peut être de broderie ou de point de croix. Pour identifier voir plusieurs œuvres réalisées par différentes techniques et de choisir ce que vous aimez. En termes de complexité qu'ils sont sur la même, mais le point de croix est plus populaire parmi pratique moderne. <br> Bien sûr, cadeau, brodé avec ses mains, prend un peu plus de temps que le magasin acheté, il doit préparer à l'avance. Si à cela vous ne l'avez pas eu l'expérience dans cette question, commencer avec une petite image, car, à la broderie grande toile, nous pouvons calculer le temps et ne pas se rendre à la fête. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362dFRJeDRzLWRWbjQ" alt=' Plans broderie de Noël ' title=' Plans broderie de Noël '></div> <br> Comme pour le circuit, dans les magasins spécialisés, vous pouvez acheter broderie tissus, fils, aiguilles et tout ce qui est nécessaire. Bien sûr, le choix des photos est fascinant par sa diversité. Haut Photos thème de Noël - un Père Noël, bonhomme de neige, arbre de Noël, flocons de neige, des couronnes d'aiguilles de pin et bien d'autres choses intéressantes. <br> <h2> Donc vous avez acheté votre circuit-photo préférée Getting Started </h2> <br> Nous sommes sûrs que vous aurez eu plaisir dans le processus. Lorsque l'image commence à émerger, il donnera l'inspiration pour de nouveaux travaux. <br> Après la broderie devrait tirer magnifiquement. Bien sûr, ce qui est arrivé la beauté déjà fantastique, mais elle est un peu "humide". Qu'est-ce que vous décidez de faire? L'image? Puis nous nous sommes un chiffon insérons le cadre. Vous pouvez commander le même, mais vous pouvez donner à un magasin spécialisé. Si vous décidez de faire une décoration en trois dimensions sur l'arbre de Noël, alors vous devez prendre la laine et l'envelopper avec son travail, soigneusement fixer bord, en haut ou d'attacher le crochet de fil. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362VDZZTXZ3eGRZM1k" alt=' Plans broderie de Noël ' title=' Plans broderie de Noël '></div> <br> Si vous êtes à court d'idées pour le cadeau brodé, vous pouvez les utiliser ou de demander à la boutique, un magasin, couturières vous conseiller pour votre diagramme présente: <br> <li> contour acheté nappes peuvent broder ornements Nouvel An </li> <br> <li> Vous pouvez décorer serviettes ou lingettes gaze monogramme </li> <br> <li> tissu (tissu doit être épaisse sur la toile de jute de type) livre couvre le travail de broderie est un cadeau très original </li> <br> <li> devant les cartes banales peut décorer leur travail brodé </li> <br> Il est sûr de dire que l'obtention d'un tel cadeau serait heureux absolument tout le monde. Ceci est un sentiment inestimable de savoir que quelqu'un a travaillé pour créer une telle beauté, pensée à vous, mis son âme afin d'offrir la joie et des émotions positives. Donner un tel cadeau, vous serez fiers d'eux-mêmes, et comme un cadeau au donateur ressentir les émotions moins positifs que celui à qui vous main dans la sienne. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362RnQ4TU1JMk9LR0k" alt=' Plans broderie de Noël ' title=' Plans broderie de Noël '></div> <div class="clr"></div> </div> <div class="source" name="source" align="right"><a href="http://vk.ru"> vk.ru Source </a></div><div class="maincont"> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362Y1FvZUtpMlN2M2M" alt=' Organisateur par heure ' title=' Organisateur par heure '></div> <br> Surtout mon premier emploi et le premier poste. Cette "hranylka" simple et fait un peu plus d'une heure. Détails à l'intérieur. <br> <b> Les matériaux utilisés dans la production: </b> <br> <br> Banque de sous les puces (grande) <br> Similicuir, <br> Corde. <br> <br> <b> Histoire. </b> <br> Eh bien, que dire de plus? Je l'habitude d'avoir tous les pinceaux, crayons, couteaux étaient seulement des bouteilles en plastique assez. Je suis malade et je décidé d'expérimenter la mélasse. <br> <div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362SUxxbEhWZHA4UDg" alt=' Organisateur par heure ' title=' Organisateur par heure '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362TXhOT3RjQlBPaWc" alt=' Organisateur par heure ' title=' Organisateur par heure '></div><br><div align="center"><img src="http://drive.google.com/uc?export=view&id=0B4oPQQq2R362VC1qT3E5YVFEV0E" alt=' Organisateur par heure ' title=' Organisateur par heure '></div> <br> Rien de plus qu'un naturelle comme vous pouvez le voir, je ne l'ai pas eu: une paire de poches latérales et une ceinture. à l'intérieur de la brosse pas manqué profondément, je mets la bouteille qui était à l'intérieur de la ancien organisateur. Je suis très surpris que cela allait parfaitement de diamètre. <br> Quel serait étirer la corde dans le trou que je fis l'aide du couteau de papeterie, a pris un mince fil de fer simple et se pencha il est venu à un porte-aiguille. Qu'ils (la fin de l'oreille) et moi avons passé un fil conducteur à travers les trous. <div class="clr"></div> </div> <div class="source" name="source" align="right"><a href="http://vk.ru"> vk.ru Source </a></div>
<!-- </body> -->
<br/>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 468x60 -->
<ins class="adsbygoogle"
style="display:inline-block;width:468px;height:60px"
data-ad-client="ca-pub-6043169635834063"
data-ad-slot="7202081735"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</td></tr></table>
</td>
<td valign="top" width="200">
<!--U1DRIGHTER1Z-->
<!-- <block9406> -->
<table border="0" cellpadding="0" cellspacing="0" width="200">
<tr><td align="right" style="background:url('/template6/13.gif');padding-right:35px;color:#A42900;" height="31"><b><!-- <bt> --><!-- </bt> --></b></td></tr>
<tr><td style="background:url('/template6/14.gif');padding:5px 5px 0px 5px;"><!-- <bc> -->
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 160x600 -->
<ins class="adsbygoogle"
style="display:inline-block;width:160px;height:600px"
data-ad-client="ca-pub-6043169635834063"
data-ad-slot="9040476935"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<!-- </bc> --></td></tr>
<tr><td height="64"><img src="/template6/15.gif" border="0"></td></tr>
</table><br />
<!-- </block9406> -->
<!-- <block10> -->
<table border="0" cellpadding="0" cellspacing="0" width="200">
<tr><td align="right" style="background:url('/template6/13.gif');padding-right:35px;color:#A42900;" height="31"><b><!-- <bt> --><!--<s3163>--><!--</s>--><!-- </bt> --></b></td></tr>
<tr><td style="background:url('/template6/14.gif');padding:5px 5px 0px 5px;">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 160x600 -->
<ins class="adsbygoogle"
style="display:inline-block;width:160px;height:600px"
data-ad-client="ca-pub-6043169635834063"
data-ad-slot="9040476935"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</td></tr>
<tr><td height="64"><img src="/template6/15.gif" border="0"></td></tr>
</table><br />
<!-- </block10> -->
<!-- <block11> -->
<!-- </block11> -->
<!-- <block12> -->
<!-- </block12> -->
<!--/U1DRIGHTER1Z-->
<!-- -->
</td>
</tr>
</table>
<!-- </middle> -->
</td></tr></table>
<!--U1BFOOTER1Z--><br />
<table class="footer-table" border="0" cellpadding="0" cellspacing="0" width="100%" height="56" style="background:url('/template6/16.gif');color:#FFFFFF;padding-top:17px;">
<tr><td align="center"><!-- <copy> --><!-- </copy> --><br /><!-- "' -->
<!-- Yandex.Metrika informer -->
<a href="https://metrika.yandex.ua/stat/?id=30625222&from=informer"
target="_blank" rel="nofollow"><img src="//bs.yandex.ru/informer/30625222/3_1_FFFFFFFF_EFEFEFFF_0_pageviews"
style="width:88px; height:31px; border:0;" alt="Яндекс.Метрика" title="Яндекс.Метрика: дані за сьогодні (перегляди, візити та унікальні відвідувачі)" onclick="try{Ya.Metrika.informer({i:this,id:30625222,lang:'ua'});return false}catch(e){}"/></a>
<!-- /Yandex.Metrika informer -->
<!-- Yandex.Metrika counter -->
<script type="text/javascript">
(function (d, w, c) {
(w[c] = w[c] || []).push(function() {
try {
w.yaCounter30625222 = new Ya.Metrika({id:30625222,
webvisor:true,
clickmap:true,
trackLinks:true,
accurateTrackBounce:true});
} catch(e) { }
});
var n = d.getElementsByTagName("script")[0],
s = d.createElement("script"),
f = function () { n.parentNode.insertBefore(s, n); };
s.type = "text/javascript";
s.async = true;
s.src = (d.location.protocol == "https:" ? "https:" : "http:") + "//mc.yandex.ru/metrika/watch.js";
if (w.opera == "[object Opera]") {
d.addEventListener("DOMContentLoaded", f, false);
} else { f(); }
})(document, window, "yandex_metrika_callbacks");
</script>
<noscript><div><img src="//mc.yandex.ru/watch/30625222" style="position:absolute; left:-9999px;" alt="" /></div></noscript>
<!-- /Yandex.Metrika counter -->
</td></tr>
</table><!--/U1BFOOTER1Z-->
<font size="1"><div class="ls" name="ls"></div></font>
</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 { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import * as pdfMake from 'pdfmake/build/pdfmake';
import * as pdfFonts from "pdfmake/build/vfs_fonts";
@Component({
selector: 'app-create-invoice',
templateUrl: './create-invoice.component.html',
styleUrls: ['./create-invoice.component.scss']
})
export class CreateInvoiceComponent implements OnInit {
lineData: any
pdfMake: any = pdfFonts.pdfMake.vfs;
constructor(private fb : FormBuilder) { }
ngOnInit(): void {
}
generatePDF() {
let docDefinition = {
header: 'C#Corner PDF Header',
content: 'Sample PDF generated with Angular and PDFMake for C#Corner Blog'
};
pdfMake.createPdf(docDefinition).open();
}
}
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 } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import * as pdfMake from 'pdfmake/build/pdfmake';
import * as pdfFonts from "pdfmake/build/vfs_fonts";
@Component({
selector: 'app-create-invoice',
templateUrl: './create-invoice.component.html',
styleUrls: ['./create-invoice.component.scss']
})
export class CreateInvoiceComponent implements OnInit {
lineData: any
pdfMake: any = pdfFonts.pdfMake.vfs;
constructor(private fb : FormBuilder) { }
ngOnInit(): void {
}
generatePDF() {
let docDefinition = {
header: 'C#Corner PDF Header',
content: 'Sample PDF generated with Angular and PDFMake for C#Corner Blog'
};
pdfMake.createPdf(docDefinition).open();
}
}
|
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.example.ecomerce.website.models;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
@Entity
@Table(name="category")
public class Category {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="c_id")
private long id;
@Column(name="c_name")
private String name;
@OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.MERGE,mappedBy ="category" )
private List<Product>products;
public List<Product> getProducts() {
return products;
}
public Category(long id, String name) {
super();
this.id = id;
this.name = name;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public Category() {}
@Override
public String toString() {
return "Category [cat_Id=" + id + ", name=" + name + "]";
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = 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>"
| java | 2 | package com.example.ecomerce.website.models;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
@Entity
@Table(name="category")
public class Category {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="c_id")
private long id;
@Column(name="c_name")
private String name;
@OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.MERGE,mappedBy ="category" )
private List<Product>products;
public List<Product> getProducts() {
return products;
}
public Category(long id, String name) {
super();
this.id = id;
this.name = name;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public Category() {}
@Override
public String toString() {
return "Category [cat_Id=" + id + ", name=" + name + "]";
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
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 src.algorithm.leetcode;
/**
* 33. 搜索旋转排序数组
* 在传递给函数之前,nums 在预先未知的某个下标 k(0 <= k < nums.length)上进行了旋转,
* 使数组变为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下标从 0 开始计数)。
* 例如,[0,1,2,4,5,6,7] 在下标 3 处经旋转后可能变为[4,5,6,7,0,1,2] 。
* 给你旋转后的数组 nums 和一个整数 target ,如果 nums 中存在这个目标值 target ,则返回它的下标,否则返回-1
*
* 输入:nums = [4,5,6,7,0,1,2], target = 0
* 输出:4
* @author caoyang
*/
public class Leetcode33 {
public static int search(int[] nums, int target) {
if(nums == null || nums.length == 0){ return -1; }
if(nums.length == 1){
return nums[0] == target ? 0 : -1;
}
return findTarget(nums, target, 0, nums.length-1);
}
public static int findTarget(int[] nums, int target, int start, int end){
if(target < nums[start] && target > nums[end]){
return -1;
}
if(nums[start] < nums[end] && nums[end] < target){
return -1;
}
if(start >= end){
return nums[start] == target ? start : -1;
}
int middle = start + ((end - start) >> 1);
int left = findTarget(nums, target, start, middle);
int right = findTarget(nums, target, middle+1, end);
return Math.max(left, right);
}
public static void main(String[] args) {
int[] nums = {4,5,6,7,0,1,2};
int target = 0;
int res = search(nums, target);
System.out.println(res);
}
}
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 | 4 | package src.algorithm.leetcode;
/**
* 33. 搜索旋转排序数组
* 在传递给函数之前,nums 在预先未知的某个下标 k(0 <= k < nums.length)上进行了旋转,
* 使数组变为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下标从 0 开始计数)。
* 例如,[0,1,2,4,5,6,7] 在下标 3 处经旋转后可能变为[4,5,6,7,0,1,2] 。
* 给你旋转后的数组 nums 和一个整数 target ,如果 nums 中存在这个目标值 target ,则返回它的下标,否则返回-1
*
* 输入:nums = [4,5,6,7,0,1,2], target = 0
* 输出:4
* @author caoyang
*/
public class Leetcode33 {
public static int search(int[] nums, int target) {
if(nums == null || nums.length == 0){ return -1; }
if(nums.length == 1){
return nums[0] == target ? 0 : -1;
}
return findTarget(nums, target, 0, nums.length-1);
}
public static int findTarget(int[] nums, int target, int start, int end){
if(target < nums[start] && target > nums[end]){
return -1;
}
if(nums[start] < nums[end] && nums[end] < target){
return -1;
}
if(start >= end){
return nums[start] == target ? start : -1;
}
int middle = start + ((end - start) >> 1);
int left = findTarget(nums, target, start, middle);
int right = findTarget(nums, target, middle+1, end);
return Math.max(left, right);
}
public static void main(String[] args) {
int[] nums = {4,5,6,7,0,1,2};
int target = 0;
int res = search(nums, target);
System.out.println(res);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.