keeping track of a series of simple multiple choice web form answers - actionscript

This is the code I'm trying to use, which seems logical. But doesn't seem to be working.
MyAsFileName.prototype.getTotalScore = function() {
var totalScore = 0;
for (var i = 0; i < allQuestions.length; i++) {
totalScore += allQuestions[i].getCalculatedScore();
if (currentModule.allQuestions[i].parent.questionCorrect == true) {
knowledgePoints++;
} else {
knowledgePoints--;
}
}
debugLog("Total score: " + totalScore);
debugLog(knowledgePoints);
return totalScore;
}
I have allQuestions defined as below:
var allQuestions = Array();
I have knowledgePoints defined as:
this.knowledgePoints = 10;
I have questionCorrect defined as:
this.questionCorrect = false;
Second fresh attempt made with new class as answer below suggested (commented out for now until I figure out how to get working):
// package
// {
/*public class Quiz {
//public
var knowledgePoints: int = 10;
//public
var allQuestions: Array = new Array;
//public
var questionCorrect: Boolean = false;
//public
function getTotalScore(): int {
var totalScore: int = 0;
for (var i = 0; i < allQuestions.length; i++) {
totalScore += allQuestions[i].getCalculatedScore();
if (currentModule.allQuestions[i].parent.questionCorrect) {
knowledgePoints++;
} else {
knowledgePoints--;
}
}
debugLog("Total score: " + totalScore);
debugLog(knowledgePoints);
return totalScore;
}
}*/
//}
This code above outputs two errors in flash console:
Error 1. Attribute used outside of class.
Error 2. 'Int' could not be loaded.

It's a weird (and actually non-AS3 way) way to do this. Instead of creating a unnamed closure which refers weird variables from who-knows where, you should make it a normal AS3 class, something like that (in a file named Quiz.as):
package
{
public class Quiz
{
public var knowledgePoints:int = 10;
public var allQuestions:Array = new Array;
public var questionCorrect:Boolean = false;
public function getTotalScore():int
{
var totalScore:int = 0;
// Your code does not explain how you will that Array.
// It is initially an empty Array of length 0.
for (var i = 0; i < allQuestions.length; i++)
{
totalScore += allQuestions[i].getCalculatedScore();
if (currentModule.allQuestions[i].parent.questionCorrect)
{
knowledgePoints++;
}
else
{
knowledgePoints--;
}
}
// Not sure what it is.
debugLog("Total score: " + totalScore);
debugLog(knowledgePoints);
return totalScore;
}
}
}

Related

How to return two value from a function in dart?

here is my code
import 'dart:io';
import 'dart:math';
void main() {
bool flag = false;
for (int i = 0; i < 100; i++) {
gameCode();
if (userNumber == computerNumber) {
flag = true;
break;
}
}
}
int randomNumber(number) {
Random randNumber = Random();
int random = randNumber.nextInt(number);
return random;
}
gameCode() {
int computerNumber = randomNumber(9);
print("start guessing the number : ");
int userNumber = int.parse(stdin.readLineSync()!);
if (userNumber == computerNumber) {
print("You got it");
}
}
in this code you can see gameCode function. in that function there is two value that i need to use in main function.so how do i return those two keyword from that function ?
//userNumber // computerNumber
this is the variable that i want to return from that code
Dart not support return multiple values in function, you can return it with array, map, or you can use third lib tuple
Dart does not support returning multiple values in the current latest version. I would in your case recommend creating a class for the specific purpose of define the result from gameCode(). So something like this:
class GameCodeResult {
int userNumber;
int computerNumber;
GameCodeResult({
required this.userNumber,
required this.computerNumber,
});
}
Which we can then use like this in your program:
import 'dart:io';
import 'dart:math';
void main() {
bool flag = false;
for (int i = 0; i < 100; i++) {
GameCodeResult result = gameCode();
if (result.userNumber == result.computerNumber) {
flag = true;
break;
}
}
}
final _random = Random();
int randomNumber(int maxNumber) => _random.nextInt(maxNumber);
GameCodeResult gameCode() {
int computerNumber = randomNumber(9);
print("start guessing the number : ");
int userNumber = int.parse(stdin.readLineSync()!);
if (userNumber == computerNumber) {
print("You got it");
}
return GameCodeResult(userNumber: userNumber, computerNumber: computerNumber);
}
Note, I also fixed your randomNumber() method since it is not recommended to generate a new Random() object for each new random number you want. We should instead reuse an instance of Random in our program.
Please refer to below code
import 'dart:io';
import 'dart:math';
void main() {
bool flag = false;
for (int i = 0; i < 100; i++) {
Map<String, dynamic> res = gameCode();
print(res);
if (res['user_number'] == res['computer_number']) {
flag = true;
break;
}
}
}
int randomNumber(number) {
Random randNumber = Random();
int random = randNumber.nextInt(number);
return random;
}
Map<String, dynamic> gameCode() {
int computerNumber = randomNumber(9);
print("start guessing the number : ");
int userNumber =
int.parse(stdin.readLineSync()!);
if (userNumber == computerNumber) {
print("You got it");
}
return {
"computer_number": computerNumber,
"user_number": userNumber,
};
}

How to add n- custom cells between two rows

So I am trying to visualize a curricilum as a table. It should look like this:
As you can see there are custom cells (+) which are not a lesson. They are buttons.
I have two classes:
public class Lesson {
private Room schoolRoom;
private Room teachingRoom;
private TeacherSpecialization teachingInfo;
private WeekDay weekDay;
private int schoolHour;
}
and
public class ClassHour {
Lesson[] dayLessons = new Lesson[18];
private int hour;
public ClassHour(int hour) {
this.hour = hour;
}
}
Using this code I convert my Lesson Object to ClassHour objects, because I use the ClassHour Object to save the lessons in the table:
public ObservableList<ClassHour> convertToClassHour(List<Lesson> lessons) {
ObservableList<ClassHour> classHours = FXCollections.observableArrayList();
// Converting Lessons to ClassHour objects.
lessons.forEach(lesson -> {
ClassHour classHour = classHours.stream().filter(ch -> ch.getHour() == lesson.getSchoolHour()).findFirst().orElse(null);
if (classHour == null) {
classHour = new ClassHour(lesson.getSchoolHour());
classHours.add(classHour);
}
classHour.getDayLessons()[lesson.getWeekDay().ordinal()] = lesson;
});
return classHours;
}
And the last step is to show the data in the table:
private void showLessons(String roomNr) throws Exception {
try {
// lessons.addListener((ListChangeListener) e -> repopulate(lessons, classHours));
ArrayList<Lesson> allLessonsByRoomNr = db.getAllLessonsByRoomNr(roomNr);
ObservableList<ClassHour> classHours = db.convertToClassHour(allLessonsByRoomNr);
for (int i = 0; i < 5; i++) {
int day = i;
TableColumn<ClassHour, Lesson> dayColumn = new TableColumn<>(WeekDay.values()[i].name());
dayColumn.setSortable(false);
dayColumn.setCellValueFactory(param -> new SimpleObjectProperty(param.getValue().getDayLessons()[day]));
dayColumn.setCellFactory((TableColumn<ClassHour, Lesson> param) -> new TableCell<ClassHour, Lesson>() {
#Override
protected void updateItem(Lesson item, boolean empty) {
super.updateItem(item, empty);
setText(null);
setGraphic(null);
if (!empty) {
if (item != null) {
setText(item.toString());
} else {
Button btn = new Button("+ ADD");
btn.setOnAction(e -> {
tableLessons.getSelectionModel().select((ClassHour) getTableRow().getItem());
showAdd(day, ((ClassHour) getTableRow().getItem()).getHour(), btn);
});
setGraphic(new StackPane(btn));
}
}
}
});
tableLessons.getColumns().addAll(dayColumn);
}
tableLessons.setItems(classHours);
} catch (Exception ex) {
showResultDialog("An error has occured:", ex.getMessage());
}
}
The problem I am struggling are the custom cells (+ buttons). For some reason I can't draw them between two lessons. In the case below there should be 5 cells/rows between classhour 10 and 16 (monday).
Note that your convertToClassHour creates a ClassHour instance if and only if there is a Lesson and if the Lessons are not ordered by hour, the order of ClassHours in the output is wrong.
Unless you've got a predetermined set of hours, you need to find the min and max hours to fix your issue:
public ObservableList<ClassHour> convertToClassHour(List<Lesson> lessons) {
ObservableList<ClassHour> classHours = FXCollections.observableArrayList();
if (!lessons.isEmpty()) {
// find required hour range
int minHour = lessons.mapToInt(Lesson::getSchoolHour).min().getAsInt();
int maxHour = lessons.mapToInt(Lesson::getSchoolHour).max().getAsInt();
// create ClassHours for range
for (int i = minHour; i <= maxHour; i++) {
classHours.add(new ClassHour(i));
}
// fill classHours with lessons
for (Lesson lesson : lessons) {
classHours.get(lesson.getSchoolHour() - minHour).getDayLessons()[lesson.getWeekDay().ordinal()] = lesson;
}
}
return classHours;
}

AngularDart How to Create Component

I just started to learning from this tutorial:
https://github.com/angular/angular.dart.tutorial/wiki/Creating-a-Custom-Component
I'm just stucked with a problem, and looking for some help. The rating component does not show for me, none of the methods called (at least not at any breakpoint). Here you can see the code:
https://www.dropbox.com/s/oizzl9k6nclgoqd/SecondAngularDart.zip
Please help me with some guidence, how can I debug a situation like this? Or what the problem is?
#NgComponent(
selector:'rating',
templateUrl:'rating_component.html',
cssUrl:'rating_component.css',
publishAs:'cmp'
)
class RatingComponent {
static const String _starOnChar = "\u2605";
static const String _starOffChar = "\u2606";
static const String _starOnClass = "star-on";
static const String _starOffClass = "star-off";
List<int> stars = [];
#NgTwoWay('rating')
int rating;
#NgAttr('max-rating')
int maxRating(String max) {
stars = [];
var count = max == null ? 5 : int.parse(max);
for(var i=1; i <= count; i++) {
stars.add(i);
}
}
String starClass(int star) {
return star > rating ? _starOffClass : _starOnClass;
}
String starChar(int star) {
return star > rating ? _starOffChar : _starOnChar;
}
void handleClick(int star) {
if (star == 1 && rating == 1) {
rating = 0;
} else {
rating = star;
}
}
}
You have annotated a function with #NgAttr('max-rating'). Those data-binding annotations only work with fields or setters:
#NgAttr('max-rating')
set maxRating(String max) {
stars = [];
var count = max == null ? 5 : int.parse(max);
for(var i=1; i <= count; i++) {
stars.add(i);
}
}
Also, in starClass and starChar you access rating, which could be null:
String starClass(int star) {
if (rating != null) {
return star > rating ? _starOffClass : _starOnClass;
}
}
Okay, it was a beginner mistake, but I used the component this way:
<rating max-rating="5" rating="{{ctrl.selectedRecipe.ratings}}"></rating>
But should be used this way:
<rating max-rating="5" rating="ctrl.selectedRecipe.ratings"></rating>

Sorting an array of String in BlackBerry

I need to sort an array of String like the following, in ascending order.
String str[] = {"ASE", "LSM", "BSE", "LKCSE", "DFM"};
How to do that? I need help.
This answer is based on Signare and HeartBeat's suggestion. Explore this link for details. Also this link, Sorting using java.util.Array might be helpful.
// Initialization of String array
String strs[] = {"One", "Two", "Threee", "Four", "Five", "Six", "Seven"};
// implementation of Comparator
Comparator strComparator = new Comparator() {
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
}
};
// Sort
Arrays.sort(strs, strComparator);
Try this -
import java.util.*;
import java.io.*;
public class TestSort1 {
String [] words = { "RĂ©al", "Real", "Raoul", "Rico" };
public static void main(String args[]) throws Exception {
try {
Writer w = getWriter();
w.write("Before :\n");
for (String s : words) {
w.write(s + " ");
}
java.util.Arrays.sort(words);
w.write("\nAfter :\n");
for (String s : words) {
w.write(s + " ");
}
w.flush();
w.close();
}
catch(Exception e){
e.printStackTrace();
}
}
// useful to output accentued characters to the console
public static Writer getWriter() throws UnsupportedEncodingException {
if (System.console() == null) {
Writer w =
new BufferedWriter
(new OutputStreamWriter(System.out, "Cp850"));
return w;
}
else {
return System.console().writer();
}
}
}
Here is my solution:-
String str[]={"ASE","LSM","BSE","LKCSE","DFM"};
for(int j = 0; j < str.length; j++){
for(int i = j + 1; i < str.length; i++) {
if(str[i].compareTo(str[j]) < 0) {
String t = str[j];
str[j] = str[i];
str[i] = t;
}
}
}

Custom container not drawing

I've been reading about Vala over the past couple of days and decided to dive into it and make some Clutter widgets along the way. I'm currently trying to draw a private actor from my custom actor subclass. Here is a simplified version of what I've got so far.
public class MyContainer : Clutter.Actor, Clutter.Container {
private Clutter.Group group;
public MyContainer() {
group = new Clutter.Group();
group.set_parent(this);
}
public void add_actor(Clutter.Actor actor) {
group.add_actor(actor);
actor.show();
set_size(group.width, group.height);
actor_added(actor);
queue_redraw();
}
public void foreach(Clutter.Callback callback) {
group.foreach(callback);
queue_redraw();
}
public override void get_preferred_height(
float for_width,
out float min_height_p,
out float natural_height_p) {
group.get_preferred_height(
for_width,
out min_height_p,
out natural_height_p);
}
public override void get_preferred_width(
float for_height,
out float min_width_p,
out float natural_width_p) {
group.get_preferred_width(
for_height,
out min_width_p,
out natural_width_p);
}
public override void paint() {
group.paint();
}
public void remove_actor(Clutter.Actor actor) {
group.remove_actor(actor);
set_size(group.width, group.height);
actor_removed(actor);
queue_redraw();
}
public void sort_depth_order() {
group.sort_depth_order();
queue_redraw();
}
}
int main(string [] args) {
// Start clutter.
var result = Clutter.init(ref args);
if (result != Clutter.InitError.SUCCESS) {
stderr.printf("Error: %s\n", result.to_string());
return 1;
}
var stage = Clutter.Stage.get_default();
// Build a MyCollection object.
var myc = new MyContainer();
myc.x = 100;
myc.y = 100;
var r1 = new Clutter.Rectangle();
r1.width = 50;
r1.height = 50;
r1.color = Clutter.Color.from_string("rgb(255, 0, 0)");
var t1 = new Clutter.Text();
t1.text = "The red square.";
t1.y = r1.height;
// Build a Group object similar to the previous.
var group = new Clutter.Group();
group.x = 300;
group.y = 100;
var r2 = new Clutter.Rectangle();
r2.width = 50;
r2.height = 50;
r2.color = Clutter.Color.from_string("rgb(255, 0, 0)");
var t2 = new Clutter.Text();
t2.text = "The red square.";
t2.y = r2.height;
// Display.
myc.add_actor(r1);
myc.add_actor(t1);
group.add_actor(r2);
group.add_actor(t2);
stage.add_actor(myc);
stage.add_actor(group);
stage.show_all();
Clutter.main();
return 0;
}
The example paints the group added directly to the stage, but not the group wrapped by the custom collection that is added to the stage. How can I get this to work and what is wrong with the above?
I've been working on ubuntu 11.10 with valac --pkg clutter-1.0 above_code_example.vala.
This answer is from buz on gnome.irc's #clutter room.
The problem is a missing override for the allocate function.

Resources