Scoping problem when trying to assign vector of strings in DOORS DXL - scoping

I want to be able to send a selector value to a function, and have the function create a string array of values for use in subsequent operations. The problem I'm running into is that the DXL rules don't "see" a declared variable inside an "if {} " block, even when I've guaranteed that in all cases my string array would get initialized. Example:
string tryme( int thechoice){
string outit
if (thechoice == 1){
outit = "you chose one"
}
else if (thechoice ==2){
outit = "you chose two"
}
else { outit = "bad choice"}
// do a bunch of stuff with "outit" values
return outit
}
// that works, but this doesn't
string trymore( int thechoice){
if (thechoice == 1){
string outit[] = {"you chose one","and one"}
}
else if (thechoice ==2){
string outit[] = {"you chose two","and two", "and three"}
}
else { string outit = "bad choice"}
// do a bunch of stuff with "outit" values
return outit
}
I could use dynamic arrays, thus allowing me to declare the array prior to the "if{}", but then I'm forced to write loops inside each case, using put to load the array.
I know DXL has a limited capability, but if anyone knows a better approach please let me know.
additional constraint
In the end, I want to be able to call the function repeatedly from a loop, changing "thechoice" each time. That is why I can't declare the string array in the parent script, because once declared ( string outit[] = {'a','b'} ) , DXL cannot delete or resize the array.

It's easier than that, tho' a bit counterintuitive . I need to declare a string vector with out assigning anything, then generate a temporary string vector, then set my desired variable equal to the temp. Like this:
string trymore( int thechoice){
string outit[]
string whatdone
if (thechoice == 1){
string foo[] = {"you chose one","and one"}
whatdone = "did one"
outit = foo
}
else if (thechoice ==2){
string foo[] = {"you chose two","and two", "and three"}
whatdone = "did two"
outit = foo
}
else {
string foo[] = "bad choice"
whatdone = "nogood"
outit = foo
}
print "outit " outit[0] "\n"
// do a bunch of stuff with "outit" values
return whatdone
}
DXL will not allow you to assign the values to outit , crying "length mismatch", but will allow you to set outit equal to the fully defined foo

Related

How to return a variable in a function in kotlin

I created a function that recieves input and compare it to a list, when find a match it return the match, in this case this match is the attribute of a class that i created.
I understand that the problem is with the return statement, so in the beginning of the function I declare the return as "Any", further more than that I'm kinda lost.
The error is this: A 'return' expression required in a function with a block body ('{...}')
class Class1(var self: String)
var test_class = Class1("")
fun giver(){
test_class.self = "Anything"
}
class Funciones(){
fun match_finder(texto: String): Any{
var lista = listOf<String>(test_class.self)
var lista_de_listas = listOf<String>("test_class.self")
var count = -1
for (i in lista_de_listas){
count = count + 1
if (texto == i){
lista_de_listas = lista
var variable = lista_de_listas[count]
return variable
}
}
}
}
fun main(){
giver()
var x = "test_class.self"
var funcion = Funciones()
var y = funcion.match_finder(x)
println(y)
}
To explain you what the problem is, let's consider the following code:
class MyClass {
fun doSomething(): String {
val numbers = listOf(1, 2, 3)
for (number in numbers) {
if (number % 2 == 0) {
return "There is at least one even number in the list"
}
}
}
}
If you try compiling it you'll get the same error message as in your question: A 'return' expression required in a function with a block body ('{...}'). Why is that?
Well, we defined a function doSomething returning a String (it could be any other type) but we're returning a result only if the list of numbers contains at least one even number. What should it return if there's no even number? The compiler doesn't know that (how could it know?), so it prompts us that message. We can fix the code by returning a value or by throwing an exception:
class MyClass {
fun doSomething(): String {
val numbers = listOf(1, 2, 3)
for (number in numbers) {
if (number % 2 == 0) {
return "There is at least one even number in the list"
}
}
// return something if the list doesn't contain any even number
return "There is no even number in the list"
}
}
The same logic applies to your original code: what should the function return if there is no i such that texto == i?
Please also note that the solution you proposed may be syntactically correct - meaning it compiles correctly - but will probably do something unexpected. The for loop is useless since the if/else statement will always cause the function to return during the first iteration, so the value "There is no match" could be returned even if a match actually exists later in the list.
I searched online, if someone has the same problem, the correct code is as follows:
class Funciones(){
fun match_finder(texto: String): Any{
var lista = listOf<String>(test_class.self)
var lista_de_listas = listOf<String>("test_class.self")
var count = -1
var variable = " "
for (i in lista_de_listas){
count = count + 1
if (texto == i){
lista_de_listas = lista
var variable = lista_de_listas[count]
return variable
} else {
return "There is no match"
}
}
return variable
}
}

know the Datatype in Swift

i am new to swift i just started with the basics. In one of the Blog i saw a simple task which goes like this read a line from the stdin and check whether it is a integer,float,String.
I tried with the following code
let input = readLine()
var result = test(input)
print (result)
func test (obj:Any) -> String {
if obj is Int { return "This input is of type Intger." }
else if obj is String { return "This input is of type String." }
else { return "This input is something else. " }
}
when the input of 3245 is given it stores in the string format. and returns output as string.
how to overcome it..?
The readLine function returns a value of type String?. So your input variable can only be a String. It will never be Int or anything else.
If you want to see if the entered value is a valid number, you can try to convert the string to an Int.
if let input = readLine() {
if let num = Int(input) {
// the user entered a valid integer
} else {
// the user entered something other than an integer
}
}
As others have pointed out, readline() always returns a String?. It's up to you to parse that into whatever format you use it.
This is how I would do this:
let line = readLine()
switch line {
case let s? where Int(s) != nil:
print("This input is of type Intger.")
case let s? where Float(s) != nil:
print("This input is of type Float.")
case let s? where s.hasPrefix("\"") && s.hasSuffix("\""):
print("This input is of type String.")
default: print("This input is something else. ")
}
It exploits the ability of Int and Float's initializers to test the validity of a String, which almost entirely defeats the purpose of this exercise. But hey, it works, right? 😄
You can find of the type of object as
if let intt = obj as? Int {
// obj is a String. Do something with intt
}
else if let str = obj as? String {
// obj is a String. Do something with str
}
else {
//obj is something else
}

Autohotkey iterate through loop, but only return value if key matches input

Suppose I have the following
^!r::
InputBox, input, Enter the string
if (input = "trip")
{
TripFunction()
}
else if (input = "leave")
{
LeaveFunction()
}
else
{
Msgbox, That word isnt defined.
}
Return
But, anticipating having to add a lot of different cases to test for, I figure the best idea is to put this into an array, and iterate through the array, looking for the matching key, returning the value (the function), and no longer iterating through the dictionary. So now, I have something like this:
^!r::
InputBox, input, Enter the string
dict = { "trip": TripFunction(), "leave": LeaveFunction() }
for k, v in dict
{
...
see if k = "trip", if so, return TripFunction(), if not, go to next
item in array
...
}
Return
The trouble I'm having is once it successfully matches akey in the dictionary, it will return all of the associated values. What should I put in the brackets to do what I intend?
You're using the wrong equal sign operator (use := for non-literal assignments instead of =)
Also, in the line dict = { "trip": TripFunction(), "leave": LeaveFunction() }, tripfunction aind leavefunction are executed, which you probably do not want.
Try:
^!r::
InputBox, input, Enter the string
dict := { "trip": "TripFunction", "leave": "LeaveFunction" }
for k, v in dict
{
if(k==input) {
%v%() ; documentation: https://autohotkey.com/docs/Functions.htm#DynCall
break
}
}
Return
TripFunction() {
msgbox trip
}
LeaveFunction() {
msgbox leave
}

Binary operator '~=' cannot be applied to two UmRet operands

I'm working on integrating an IDTech swiper into my app and I've gotten pretty far along, added the library, registered notifications, unregistered them, and now I'm working on a function that connects the reader. I can't seem to figure out what I'm doing wrong here when I'm attempting to switch cases based on a return value.. could someone please help me?
func displayUmRet(operation: String, returnValue: UmRet) {
var string = ""
do {
switch returnValue {
case UMRET_SUCCESS: string = ""
case UMRET_NO_READER: string="No reader attached"
case UMRET_SDK_BUSY: string="Communication with reader in progress"
case UMRET_MONO_AUDIO: string="Mono audio enabled"
case UMRET_ALREADY_CONNECTED: string="Already connected"
case UMRET_LOW_VOLUME: string="Low volume"
case UMRET_NOT_CONNECTED: string="Not connected"
case UMRET_NOT_APPLICABLE: string="Not applicable to reader type"
case UMRET_INVALID_ARG: string="Invalid argument"
case UMRET_UF_INVALID_STR: string="Invalid firmware update string"
case UMRET_UF_NO_FILE: string="Firmware file not found"
case UMRET_UF_INVALID_FILE: string="Invalid firmware file"
default: string="<unknown code>"
}
} while (0)
// var retStatus = UMRET_SUCCESS==ret
//self.textResponse.text = "\(operation), \(retStatus), \(string)"
self.hexResponse.text = "";
}
You need to put a . before your cases:
enum UmRet {
case UMRET_SUCCESS, UMRET_FAILURE
}
var string = " "
let returnValue = UmRet.UMRET_SUCCESS
switch returnValue {
case .UMRET_SUCCESS: string = "y"
case .UMRET_FAILURE: string = "n"
}
Also, 0 isn't the same as false in Swift, so:
do {
...
} while (0)
Shouldn't work either.
And you don't need semicolons at the end of a line, so this:
self.hexResponse.text = "";
can be this:
self.hexResponse.text = ""
And finally, if your switch statement has every case for every case in your enum, you don't need a default case. (that's why mine didn't have one in the example)
By the way, ~= is just the operator for the pattern-matching function, which is what Swift does in a switch statement. It works kind of like the == function, for instance, Int ~= Int is the same as Int == Int. But it's a bit more versatile: for instance Range ~= Int, eg 0...3 ~= 2 returns whether or not the Int is in the range. (So true in this case) For enums, it matches cases to cases. In my example, it'll match UMRET_SUCCESS, and string will be set to y.

Interpolate String Loaded From File

I can't figure out how to load a string from a file and have variables referenced in that string be interpolated.
Let's say a text file at filePath that has these contents:
Hello there, \(name)!
I can load this file into a string with:
let string = String.stringWithContentsOfFile(filePath, encoding: NSUTF8StringEncoding, error: nil)!
In my class, I have loaded a name in: let name = "George"
I'd like this new string to interpolate the \(name) using my constant, so that its value is Hello there, George!. (In reality the text file is a much larger template with lots of strings that need to be swapped in.)
I see String has a convertFromStringInterpolation method but I can't figure out if that's the right way to do this. Does anyone have any ideas?
This cannot be done as you intend, because it goes against type safety at compile time (the compiler cannot check type safety on the variables that you are trying to refer to on the string file).
As a workaround, you can manually define a replacement table, as follows:
// Extend String to conform to the Printable protocol
extension String: Printable
{
public var description: String { return self }
}
var string = "Hello there, [firstName] [lastName]. You are [height]cm tall and [age] years old!"
let firstName = "John"
let lastName = "Appleseed"
let age = 33
let height = 1.74
let tokenTable: [String: Printable] = [
"[firstName]": firstName,
"[lastName]": lastName,
"[age]": age,
"[height]": height]
for (token, value) in tokenTable
{
string = string.stringByReplacingOccurrencesOfString(token, withString: value.description)
}
println(string)
// Prints: "Hello there, John Appleseed. You are 1.74cm tall and 33 years old!"
You can store entities of any type as the values of tokenTable, as long as they conform to the Printable protocol.
To automate things further, you could define the tokenTable constant in a separate Swift file, and auto-generate that file by using a separate script to extract the tokens from your string-containing file.
Note that this approach will probably be quite inefficient with very large string files (but not much more inefficient than reading the whole string into memory on the first place). If that is a problem, consider processing the string file in a buffered way.
There is no built in mechanism for doing this, you will have to create your own.
Here is an example of a VERY rudimentary version:
var values = [
"name": "George"
]
var textFromFile = "Hello there, <name>!"
var parts = split(textFromFile, {$0 == "<" || $0 == ">"}, maxSplit: 10, allowEmptySlices: true)
var output = ""
for index in 0 ..< parts.count {
if index % 2 == 0 {
// If it is even, it is not a variable
output += parts[index]
}
else {
// If it is odd, it is a variable so look it up
if let value = values[parts[index]] {
output += value
}
else {
output += "NOT_FOUND"
}
}
}
println(output) // "Hello there, George!"
Depending on your use case, you will probably have to make this much more robust.