Urbi "switch" statement error - robotics

I'm working on a project in Urbi for the Aibo ERS-7. Since Urbi 2 is not available for Aibo, I'm using the following:
URBI Language specif 1.0 - Copyright (C) 2005-2008 Gostai SAS
URBI Kernel version 1.5 rev. 51997ef
I'm wondering why the following code is generating an error. It is intended to make a random action when a loud noise is heard. The code is below.
motor on;
robot.initial();
robot.stretch();
whenever (micro.volume >= 1000)
{
randomval = random(16);
switch (randomval)
{
case 0: //LF1
legLF1.val = (random(254) - 120);
case 1: //LF2
legLF2.val = (random(100) - 9);
case 2: //LF3
legLF3.val = (random(148) - 29);
case 3: //RF1
legRF1.val = (random(254) - 134);
case 4: //RF2
legRF2.val = (random(100) - 9);
case 5: //RF3
legRF3.val = (random(148) - 29);
case 6: //LH1
legLH1.val = (random(254) - 120);
case 7: //LH2
legLH2.val = (random(100) - 9);
case 8: //LH3
legLH3.val = (random(148) - 29);
case 9: //RH1
legRH1.val = (random(254) - 134);
case 10: //RH2
legRH2.val = (random(100) - 9);
case 11: //RH3
legRH1.val = (random(148) - 29);
case 12: //neck
neck.val = (random(80) - 2);
case 13: //headTilt
headTilt.val = (random(60) - 16);
case 14: //headPan
neck.val = (random(182) - 91);
case 15: //mouth
mouth.val = (random(55) - 58);
}
};
The error that is generated is as follows:
/MS/clap.u:50.10: syntax error, unexpected (
[0000037549]!!! 22.1-15: Error loading file: clap.u
[0000037549]!!! 22.1-15: Error with function eval: U596213128.load [nb param=1]
[0000037549]!!! 22.1-15: EXPR evaluation failed
From what I understand, it doesn't like the parenthesis at the "switch" line. I don't really see reference to "switch" in the version I'm using, and it is highlighted as if it exists in the Gostai Editor, but there is no mention of it in any changelogs up to the newest version. Does it even exists, and if so, what am I doing wrong. In the case that it does not exist, should I just use a bunch of if statements (please, no).

There is indeed no switch/case in urbi 1.0.
A better alternative to a bunch of ifs is to use arrays to store the device and parameters:
var devices = [legLF1, legLF2, ...];
var ranges = [254, 100, ...];
var offsets = [...];
devices[randomval].val = random(ranges[randomval]) + offsets[randomval];

Related

How best to convert old Dart code that triggers "The non-nullable variable must be assigned" error?

Take the following non-null safe Dart code:
static String appBarShiftTitleString(int fromEpochSeconds) {
String monthWord;
String dayWord;
DateTime dt = DateTime.fromMillisecondsSinceEpoch(fromEpochSeconds * 1000);
switch (dt.month) {
case 1:
monthWord = "Jan";
break;
case 2:
monthWord = "Feb";
break;
case 3:
monthWord = "Mar";
break;
case 4:
monthWord = "Apr";
break;
case 5:
monthWord = "May";
break;
case 6:
monthWord = "Jun";
break;
case 7:
monthWord = "Jul";
break;
case 8:
monthWord = "Aug";
break;
case 9:
monthWord = "Sep";
break;
case 10:
monthWord = "Oct";
break;
case 11:
monthWord = "Nov";
break;
case 12:
monthWord = "Dec";
break;
}
switch (dt.weekday) {
case 1:
dayWord = "Mon";
break;
case 2:
dayWord = "Tue";
break;
case 3:
dayWord = "Wed";
break;
case 4:
dayWord = "Thu";
break;
case 5:
dayWord = "Fri";
break;
case 6:
dayWord = "Sat";
break;
case 7:
dayWord = "Sun";
break;
}
return dayWord + ' ' + monthWord + ' ' + dt.day.toString();
}
Android Studio is saying, "The non-nullable local variable 'dayWord' must be assigned before it can be used."
I understand the error and have discovered that I can simply modify the first two lines of the method like this:
String monthWord = "error!";
String dayWord = "error!";
This way, I satisfy the language rules, and it will be plainly obvious if we reach what ought to be an impossible situation of the variable not having been assigned.
This seems hacky though... so in these types of scenarios, what is the elegant and proper way to convert this code to null safety, and if there are multiple ways, then what are the pros and cons?
In general, you have a few options:
1. Initialize the variable to some non-null sentinel value and assert later:
String monthWord = '';
// ...
switch (dt.month) {
// ...
}
assert(monthWord.isNotEmpty);
This will cause debug builds to throw AssertionError at runtime if you neglect to handle a case for it in the switch.
2. Make the variable nullable and use the null assertion operator:
String? monthWord;
// ...
switch (dt.month) {
// ...
}
monthWord!;
// Since `monthWord` is a local variable, it will now be promoted to a
// non-nullable `String` type.
This will throw a TypeError in all build types if you neglect to set the variable to a non-null value.
3. Make the variable late
Declaring variables as late states that you promise that the variables will be initialized before they are ever read. The compiler will generate runtime checks that verify that the variable is initialized when you try to access it. This will throw a LateInitializationError in all build types if you neglect to set the variable.
4. Add a default case that throws
If all of your cases set a local variable, adding a default case that throws allows the compiler to deduce that that variable must always be set if code after the switch statement is reached:
String monthWord; // No explicit initialization required!
// ...
switch (dt.month) {
case 1:
monthWord = "Jan";
break;
// ... etc. ...
default:
throw AssertionError('Unhandled case: ${dt.month}');
}
// The compiler now can deduce that `monthWord` is guaranteed to be
// initialized.
(Note that you should not add a default case for this purpose if you're using a switch statement on an enum type. For enums, the compiler and analyzer can determine if your cases are exhaustive and will generate analysis warnings if you accidentally omit any cases.)
As for which approach to use, it's mostly a matter of preference. They're all mostly equivalent in that they'll result in runtime errors. I personally would choose #1 (assert) or #4 (default case) to avoid unnecessary checks in release builds.
In your particular example, I also would just use DateTime.month and DateTime.day as indices into Lists of the month and day names respectively:
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
assert(months.length == 12);
assert(days.length == 7);
var monthWord = months[dt.month - 1];
var dayWord = days [dt.day - 1];

Thread 1 : EXC_BAD_ACCESS in Xcode with C code

I am using Xcode to code in C language. I am getting strange error.
If ranges(height2, width2) of for loops are around 500,600 code is working fine. BUT if I change ranges more than 800 then it gives me following error.
"Thread 1: EXE_BAD_ACCESS(CODE - 2, address = 07x33434...)"
for (int i = 0 ; i <height2 ; i++)
{
for (int j = 0 ; j< width2 ; j++)
{
float height_Frac_Idx = i*scale_h;
float width_Frac_Idx = j*scale_w;
int height_idx, width_idx;
height_idx = (int) height_Frac_Idx;
width_idx = (int) width_Frac_Idx;
float del_h = height_Frac_Idx - height_idx;
float del_w = width_Frac_Idx - width_idx;
img_op[i][j] = (img_IP[height_idx][width_idx])*(1 - del_h)*(1-del_w) + (img_IP[height_idx+1][width_idx])*(del_h)*(1-del_w) + (img_IP[height_idx][width_idx+1])*(1 - del_h)*(del_w) + (img_IP[height_idx+1][width_idx+1])*(del_h)*(del_w);
}
}
"Thread 1: EXE_BAD_ACCESS(CODE - 2, address = 07x33434...)"
This error come when when you accessing the unallocated or more that allocated memory in code.
Looking your code and explanation i can guess that you probably accessing some more memory in case of img_op[][] or img_IP[][] array.
Also try Enabling NSZombies
Very easy to enable:
Double click your executable in the “Executables” in XCode
Open “Arguments” tab
In “Variables to be set in the environment” (that’s the list at the
bottom, be careful which one you edit) click the “+” button and for
name of the variable enter “NSZombieEnabled” and for value “YES”

Switch statement in Swift

I'm learning syntax of Swift and wonder, why the following code isn't working as I expect it to:
for i in 1...100{
switch (i){
case 1:
Int(i%3) == 0
println("Fizz")
case 2:
Int(i%5) == 0
println("Buzz")
default:
println("\(i)")
}
}
I want to print Fizz every time number is divisible by 3 (3, 6, 9, 12, etc) and print Buzz every time it's divisible by 5. What piece of the puzzle is missing?
Note: I did solve it using the following:
for ( var i = 0; i < 101; i++){
if (Int(i%3) == 0){
println("Fizz")
} else if (Int(i%5) == 0){
println("Buzz")
} else {
println("\(i)")
}
}
I want to know how to solve this using Switch. Thank you.
The usual rules for the FizzBuzz game
are to replace every multiple of 3 by "Fizz", every multiple of 5 by "Buzz", and
every multiple of both 3 and 5 by "FizzBuzz".
This can be done with a switch statement on the tuple (i % 3, i % 5).
Note that _ means "any value":
for i in 1 ... 100 {
switch (i % 3, i % 5) {
case (0, 0):
print("FizzBuzz")
case (0, _):
print("Fizz")
case (_, 0):
print("Buzz")
default:
print(i)
}
}
Switch statements in Swift support value bindings.
This allows you to assign a value that matches a certain condition (evaluated via the where clause) to a temporary variable (x & y here):
for i in 1...100 {
switch (i){
case let x where x%3 == 0:
println("Fizz")
case let y where y%5 == 0:
println("Buzz")
default:
println("\(i)")
}
}
You could also use the assigned temp value in the case body.
Update:
Matt Gibson points out in the comments, that you can omit the assignment to a temp var if you are not going to use it in the case body.
So a more concise version of the above code would be:
for i in 1...100 {
switch (i){
case _ where i%3 == 0:
println("Fizz")
case _ where i%5 == 0:
println("Buzz")
default:
println("\(i)")
}
}
Side note: Your 2 code samples are slightly different (the first one uses the range 0-100 as input, while the second one operates on 1-100). My sample is based on your first code snippet.
This is a more general answer for people who come here just wanting to know how to use the switch statement in Swift.
General usage
switch someValue {
case valueOne:
// executable code
case valueTwo:
// executable code
default:
// executable code
}
Example
let someValue = "horse"
switch someValue {
case "horse":
print("eats grass")
case "wolf":
print("eats meat")
default:
print("no match")
}
Notes:
No break statement is necessary. It is the default behavior. Swift switch cases do not "fall through". If you want them to fall through to the code in the next case, you must explicitly use the fallthrough keyword.
Every case must include executable code. If you want to ignore a case, you can add a single break statement.
The cases must be exhaustive. That is, they must cover every possibly value. If it is not feasible to include enough case statements, a default statement can be included last to catch any other values.
The Swift switch statement is very flexible. The following sections include some other ways of using it.
Matching multiple values
You can match multiple values in a single case if you use separate the values with commas. This is called a compound case.
let someValue = "e"
switch someValue {
case "a", "b", "c":
// executable code
case "d", "e":
// executable code
default:
// executable code
}
You can also match whole intervals.
let someValue = 4
switch someValue {
case 0..<10:
// executable code
case 10...100:
// executable code
default:
// executable code
}
You can even use tuples. This example is adapted from the documentation.
let aPoint = (1, 1)
switch aPoint {
case (0, 0):
// only catches an exact match for first and second
case (_, 0):
// any first, exact second
case (-2...2, -2...2):
// range for first and second
default:
// catches anything else
}
Value Bindings
Sometimes you might want to create a temporary constant or variable from the switch value. You can do this right after the case statement. Anywhere that a value binding is used, it will match any value. This is similar to using _ in the tuple example above. The following two examples are modified from the documentation.
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
// can use x here
case (0, let y):
// can use y here
case let (x, y):
// can use x or y here, matches anything so no "default" case is necessary
}
You can further refine the matching by using the where keyword.
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
// executable code
case let (x, y) where x == -y:
// executable code
case let (x, y):
// executable code
}
Further study
This answer was meant to be a quick reference. Please read the full documentation for more. It isn't difficult to understand.
This is how it can be done
var i = 0
switch i {
case i where i % 5 == 0 && i % 3 == 0: print(" Fizz Buzz")
case i where i % 3 == 0 : print("Fizz")
case i where i % 5 == 0 : print("Buzz")
default: print(i)
}
The industry standard behaviour of switch can lead to bugs similar to "Go to Fail".
Basically the code doesn't always do exactly what it looks like the code will do when reading over it, which leads to code auditors skipping over critical bugs.
To counter that, Apple has decided switch statements should not work the same in Swift as the industry standard. In particular:
There is an automatic break at the end of every case. It's impossible for more than one case statement to execute.
If it's theoretically possible for one of the case statements to be missed, then the code will not compile at all. In swift one of the case statements will always execute, no matter what value is provided. If you provide an enum, every enum value must be handled. If a new value is added to an existing enum the code won't compile until new case statements are added. If you provide a 32 bit integer, you must handle every possible value of a 32 bit int.
Here are the two ways I use switch statement for this kind of problems .
1>> Using where keyword
func printNumberType(number : Int){
switch number {
case number where number % 3 == 0 && number % 5 == 0 :
print("foo bar")
case number where number % 3 == 0 :
print("foo")
case number where number % 5 == 0 :
print("bar")
default :
print("Number is not divisible by 3 and 5")
}
}
2>> Using values combination
func printNumberByMultipleValues(number : Int){
let combination = (number % 3,number % 5)
switch combination {
case (0,0):
print("foo bar")
case (0,_) :
print("foo")
case (_,0) :
print("bar")
default :
print("Number is not divisible by 3 and 5")
}
}
Here is closer example for multiple value type .
var printNumberByMultipleValues : (Int)->() = { number in
let combination = (number % 3,number % 5)
switch combination {
case (0,0):
print("foo bar")
case (0,_) :
print("foo")
case (_,0) :
print("bar")
default :
print("Number is not divisible by 3 and 5")
}
}
Use this code. Your logic is wrong. Your Switch Statement does not find the case accept 1 and 2
class TEST1{
func print() -> Void{
var i = 0
for i in 1...100{
if Int(i%3) == 0 {
println("Fizz")
}
else if Int(i%5) == 0{
println("Buzz")
}
else {
println("\(i)")
}
}
}
}
var x = TEST1()
x.print()

Get Call logs Blackberry

What i want
Hi, I am new to BB development and want to know how can i get all call logs list with attributes like time, number etc programmatically ??
What i Read
i have read this Link but not getting the way to implement.
Also there is not good support like android or iOS for blackberry.
Kindly suggest me with some code snippet.
Thanks
I assume you really do want Java (BBOS) code.
In my opinion, the link you referenced provides sufficient information to code something, but since you seem to need more, I hope this helps:
PhoneLogs _logs = PhoneLogs.getInstance();
int numberOfCalls = _logs.numberOfCalls(PhoneLogs.FOLDER_NORMAL_CALLS);
System.out.println("Number of calls: " + Integer.toString(numberOfCalls));
for ( int i = 0; i < numberOfCalls; i++ ) {
PhoneCallLog phoneLog = (PhoneCallLog)_logs.callAt(i,PhoneLogs.FOLDER_NORMAL_CALLS);
int callType = phoneLog.getType();
String callTypeString = "";
switch (callType) {
case PhoneCallLog.TYPE_MISSED_CALL_OPENED:
case PhoneCallLog.TYPE_MISSED_CALL_UNOPENED:
callTypeString = "Missed";
break;
case PhoneCallLog.TYPE_PLACED_CALL:
callTypeString = "Placed";
break;
case PhoneCallLog.TYPE_RECEIVED_CALL:
callTypeString = "Received";
break;
default:
callTypeString = "Unknown";
break;
}
PhoneCallLogID participant = phoneLog.getParticipant();
System.out.println("Call: " + Integer.toString(i) + " " + callTypeString + " " + participant.getAddressBookFormattedNumber());
}
Sample output (from debug log):
Number of calls: 1
Call: 0 Placed 1 (234) 534-5343 5555

How to I18N PrimeFaces Editor

I cannot work out how to add internationalization to the PrimeFaces Editor (Version 3.2).
I need to translate tooltips, texts in comboboxes and change icons of the toolbar.
In an old users guide http://www.scribd.com/doc/49595285/46/Editor I found an attribute called "language" but this seems to be kind of disabled or removed for the actual version.
My project setup is JSF 2 with PrimeFaces 3.2 and GlassFish 3.1.2
I'd be very glad if you could show me how I can solve this problem.
Thanks and Kind regards,
Pedro
JMelnik is right. There is a workaround though!
You can do that by downloading the editor.js file from the primefaces subversion repository: 3_3_1/src/main/resources/META-INF/resources/primefaces/editor/editor.js and place it inside your project's META-INF/resources/primefaces/editor folder.
Now you can edit the file and change it according to you locale. I did it for some of the buttons in pt_BR:
buttons: {
// name,title,command,popupName (""=use name)
init:
"bold,Negrito,|" +
"italic,Itálico,|" +
"underline,Sublinhado,|" +
"strikethrough,Tachado,|" +
"subscript,Subscrito,|" +
"superscript,Sobrescrito,|" +
"font,Fonte,fontname,|" +
"size,Tamanho da Fonte,fontsize,|" +
"style,Estilo,formatblock,|" +
"color,Cor da fonte,forecolor,|" +
"highlight,Cor de Destaque do Texto,hilitecolor,color|" +
"removeformat,Remove Formatting,|" +
"bullets,Marcadores,insertunorderedlist|" +
"numbering,Numeração,insertorderedlist|" +
"outdent,Diminuir Recuo,|" +
"indent,Aumentar Recuo,|" +
"alignleft,Alinhar à Esquerda,justifyleft|" +
"center,Centralizar,justifycenter|" +
"alignright,Alinhar à Direita,justifyright|" +
"justify,Justificar,justifyfull|" +
"undo,,|" +
"redo,,|" +
"rule,Insert Horizontal Rule,inserthorizontalrule|" +
"image,Insert Image,insertimage,url|" +
"link,Insert Hyperlink,createlink,url|" +
"unlink,Remove Hyperlink,|" +
"cut,,|" +
"copy,,|" +
"paste,,|" +
"pastetext,Paste as Text,inserthtml,|" +
"print,,|" +
"source,Mostrar Código Fonte"
},
A i18n solution for that would be great since this approach won't support multiple locales and make you code depend on specific encoding (as it may use special characters).
Analysis
If we look at the PrimeFaces 3.2 documentation, there is no such attribute as language for Editor component and there is nothing mentioned in localization chapter.
PrimeFaces do not provide a way to localize Editor as they do provide for Calendar. And obviously they do provide it for calendar, because it is out of box feature for jQuery datePicker, which caledar is based on.
Outcome
Look for editor.js in PrimeFaces 3.2 sources. There is a section, where all editor buttons are initialized:
buttons: {
// name,title,command,popupName (""=use name)
init:
.....
"font,,fontname,|" +
"size,Font Size,fontsize,|" +
.....
}
There is provided format for separate button setup: name,title,command,popupName. The title part is the one you can make use of.
What you can do, you can build primefaces sources with your own titles provided, or override them in other way I cannot think of.
Help
If you are using maven, you can install customized primefaces in local or centralized repository of your own and use it instead of original dependency.
Lesson
You shouldn't look for old documentation, when you are using newer version. Look for the documentation of the version you are using.
Since JSF2 and Primefaces have jQuery, you can simply run this code on your page:
$(function(){
$(".ui-editor-group>.ui-editor-button").each(function(){
var title = $(this).attr("title").toLowerCase();
switch(title){
case "bold": title = "Negrito"; break;
case "italic": title = "Itálico"; break;
case "underline": title = "Sublinhado"; break;
case "align text left": title = "Alinhado à esquerda"; break;
case "center": title = "Centralizado"; break;
case "align text right": title = "Alinhado à direita"; break;
case "justify": title = "Justificado"; break;
case "insert hyperlink": title = "Inserir link"; break;
case "remove hyperlink": title = "Remover link"; break;
}
$(this).attr("title", title);
})
})
This little jQuery code can change Primefaces Editor's strings to wherever you want. I made it only for a few editor's components because I didn't used all of them.
If you need to translate the other options, simply add them inside the switch command. Don't forget that all titles inside switch command are in lowercase, due to ".toLowerCase()" method on line three. I've done this to simplify string management.
You can put it inside a function inside an external JavaScript file to get it cached, too.
This is a working example I made for Greek language (el_GR locale), all buttons:
$(".ui-editor-group>.ui-editor-button").each(function () {
var title = $(this).attr("title").toLowerCase();
switch (title) {
case "bold":
title = "Έντονα";
break;
case "italic":
title = "Πλάγια";
break;
case "underline":
title = "Υπογραμμισμένα";
break;
case "align text left":
title = "Στοίχιση αριστερά";
break;
case "center":
title = "Στοίχιση στο κέντρο";
break;
case "align text right":
title = "Στοίχiση δεξιά";
break;
case "justify":
title = "Στοίχιση";
break;
case "insert hyperlink":
title = "Εισαγωγή συνδέσμου";
break;
case "remove hyperlink":
title = "Αφαίρεση συνδέσμου";
break;
case "strikethrough":
title = "Διεγραμμένα";
break;
case "subscript":
title = "Δείκτης";
break;
case "superscript":
title = "Εκθέτης";
break;
case "font":
title = "Γραμματοσειρά";
break;
case "font size":
title = "Μέγεθος γραμματοσειράς";
break;
case "style":
title = "Στυλ";
break;
case "font color":
title = "Χρώμα γραμματοσειράς";
break;
case "text highlight color":
title = "Χρώμα επισήμανσης κειμένου";
break;
case "remove formatting":
title = "Κατάργηση μορφοποίησης";
break;
case "bullets":
title = "Λίστα με κουκκίδες";
break;
case "numbering":
title = "Αριθμητική λίστα";
break;
case "outdent":
title = "Προεξοχή";
break;
case "indent":
title = "Εσοχή";
break;
case "undo":
title = "Αναίρέση";
case "redo":
title = "Επαναφορά";
break;
case "insert horizontal rule":
title = "Eισαγωγή οριζόντιας γραμμής";
break;
case "insert image":
title = "Εισαγωγή εικόνας";
break;
case "cut":
title = "Κόψιμο";
break;
case "copy":
title = "Αντιγραφή";
break;
case "paste":
title = "Επικόλληση";
break;
case "paste as text":
title = "Επικόλληση ως απλό κείμενο";
break;
case "print":
title = "Εκτύπωση";
break;
case "show source":
title = "Εμφάνιση κώδικα";
break;
case "Show Rich Text":
title = "Εμφάνιση εύκολης επεξεργασίας άρθρου";
break;
}
$(this).attr("title", title);
});

Resources