Multiple OR operators in a single IF - openedge

How to have multiple OR operators in a single if statement? I tried this way but there's an error of:
Incompatible data types in expression or assignment.
I looked at documentation of length function and it is LENGTH ( {string | raw-expression | blob-field } [ , type ] )?
Here's the code:
DEFINE VARIABLE cMonth AS CHARACTER.
DEFINE VARIABLE cDay AS CHARACTER.
DEFINE VARIABLE cYear AS CHARACTER.
UPDATE cDateFromUser.
cDay = (SUBSTRING(cDateFromUser,1,2)).
cMonth = (SUBSTRING(cDateFromUser,3,2)).
cYear = (SUBSTRING(cDateFromUser,5,4)).
IF (LENGTH(cDay <> 2)) OR (LENGTH(cMonth <> 2)) OR (LENGTH(cYear <> 4)) THEN DO:
/*Code*/
END.
ELSE DO:
/*Code*/
END.

The syntax is not right here. Use the following IF:
IF (LENGTH(cDay) <> 2) OR (LENGTH(cMonth) <> 2) OR (LENGTH(cYear) <> 4) THEN DO:

Related

How do you access name of a ProtoField after declaration?

How can I access the name property of a ProtoField after I declare it?
For example, something along the lines of:
myproto = Proto("myproto", "My Proto")
myproto.fields.foo = ProtoField.int8("myproto.foo", "Foo", base.DEC)
print(myproto.fields.foo.name)
Where I get the output:
Foo
An alternate method that's a bit more terse:
local fieldString = tostring(field)
local i, j = string.find(fieldString, ": .* myproto")
print(string.sub(fieldString, i + 2, j - (1 + string.len("myproto")))
EDIT: Or an even simpler solution that works for any protocol:
local fieldString = tostring(field)
local i, j = string.find(fieldString, ": .* ")
print(string.sub(fieldString, i + 2, j - 1))
Of course the 2nd method only works as long as there are no spaces in the field name. Since that's not necessarily always going to be the case, the 1st method is more robust. Here is the 1st method wrapped up in a function that ought to be usable by any dissector:
-- The field is the field whose name you want to print.
-- The proto is the name of the relevant protocol
function printFieldName(field, protoStr)
local fieldString = tostring(field)
local i, j = string.find(fieldString, ": .* " .. protoStr)
print(string.sub(fieldString, i + 2, j - (1 + string.len(protoStr)))
end
... and here it is in use:
printFieldName(myproto.fields.foo, "myproto")
printFieldName(someproto.fields.bar, "someproto")
Ok, this is janky, and certainly not the 'right' way to do it, but it seems to work.
I discovered this after looking at the output of
print(tostring(myproto.fields.foo))
This seems to spit out the value of each of the members of ProtoField, but I couldn't figure out the correct way to access them. So, instead, I decided to parse the string. This function will return 'Foo', but could be adapted to return the other fields as well.
function getname(field)
--First, convert the field into a string
--this is going to result in a long string with
--a bunch of info we dont need
local fieldString= tostring(field)
-- fieldString looks like:
-- ProtoField(188403): Foo myproto.foo base.DEC 0000000000000000 00000000 (null)
--Split the string on '.' characters
a,b=fieldString:match"([^.]*).(.*)"
--Split the first half of the previous result (a) on ':' characters
a,b=a:match"([^.]*):(.*)"
--At this point, b will equal " Foo myproto"
--and we want to strip out that abreviation "abvr" part
--Count the number of times spaces occur in the string
local spaceCount = select(2, string.gsub(b, " ", ""))
--Declare a counter
local counter = 0
--Declare the name we are going to return
local constructedName = ''
--Step though each word in (b) separated by spaces
for word in b:gmatch("%w+") do
--If we hav reached the last space, go ahead and return
if counter == spaceCount-1 then
return constructedName
end
--Add the current word to our name
constructedName = constructedName .. word .. " "
--Increment counter
counter = counter+1
end
end

convert `NULL` to string (empty or literally `NULL`)

I receive a list test that may contain or miss a certain name variable.
When I retrieve items by name, e.g. temp = test[[name]] in case name is missing I temp is NULL. In other cases, temp has inadequate value, so I want to throw a warning, something like name value XXX is invalid, where XXX is temp (I use sprintf for that purpose) and assign the default value.
However, I have a hard time converting it to string. Is there one-liner in R to do this?
as.character produces character(0) which turns the whole sprintf argument to character(0).
Workflow typically looks like:
for (name in name_list){
temp = test[[name]]
if(is.null(temp) || is_invalid(temp) {
warning(sprintf('%s is invalid parameter value for %s', as.character(temp), name))
result = assign_default(name)
} else {
result = temp
print(sprintf('parameter %s is OK', name)
}
}
PS.
is_invalid is function defined elsewhere. I need subsitute of as.character that would return '' or 'NULL'.
test = list(t1 = "a", t2 = NULL, t3 = "b")
foo = function(x){
ifelse(is.null(test[[x]]), paste(x, "is not valid"), test[[x]])
}
foo("t1")
#[1] "a"
foo("t2")
#[1] "t2 is not valid"
foo("r")
#[1] "r is not valid"
You can use format() to convert NULL to "NULL".
In your example it would be:
warning(sprintf('%s is invalid parameter value for %s', format(temp), name))
Well, as ultimately my goal was to join two strings, one of which might be empty (null), I realized, I just can use paste(temp, "name is empty or invalid") as my warning string. It doesn't exactly convert NULL to the string, but it's a solution.

Vb script string comparison error

I have tried all but its not working
I am getting a colum value form Data base as
substatus=rsprefobj("isnotificationactive");
after doing
Response.write substatus
It gives me --> n
and when i do
intcomaprestringval=StrComp(substatus,"n",vbTextCompare)
Response.write intcomaprestringval
It(intcomaprestringval) gives me --> 1 even though they are same
I want to take some decision based on database value if its "n" or "y"
If intcomaprestringval = 0 Then
some
Else
some
End If
But StrComp()always returns 1 in my case whether database value is "n" or "y" :(
I write a compare function that will return either "OK" if 2 values are a match or "No Match" if they do not. Here it is:
Function Compare(str1, str2, comp)
str = "OK"
If StrComp(str1, str2, comp) <> 0 Then str = "No Match"
Compare = str
End Function
str1 and str2 are the 2 values you wish to compare and comp is the method of comparison (0 = binary comparison and 1 = text comparison). I always use 0.
So you would use it like this:
If Compare(substatus, "n", 0) = "OK" Then
' Values match
Else
'Values do not match
End If
Hope it helps
Regarding your test:
intcomaprestringval=StrComp(substatus,"n",vbTextCompare)
Are you setting vbTextCompare to be 0 at some point earlier in your code?
I have used Trim() as suggested by #EntBark
Dim myvalue
myvalue=Trim(substatus)
intcomaprestringval=StrComp(myvalue,"n",vbTextCompare)

Check if palindrome while ignoring special characters

I'm failing the last test case, which is the one with the spaces and single quotation mark.
I used s.strip, but the error still persists.
Is there another way to go about this?
Thank you.
from test import testEqual
def removeWhite(s):
s.strip()
s.strip("'")
return s
def isPal(s):
if s == "" or len(s) == 1:
return True
if removeWhite(s[0]) != removeWhite(s[-1]):
return False
return isPal(removeWhite(s[1:-1]))
testEqual(isPal(removeWhite("x")),True)
testEqual(isPal(removeWhite("radar")),True)
testEqual(isPal(removeWhite("hello")),False)
testEqual(isPal(removeWhite("")),True)
testEqual(isPal(removeWhite("hannah")),True)
testEqual(isPal(removeWhite("madam i'm adam")),True)
At first your removeWhite function doesn't return all spaces because strip only removes from the end and the beginning of a string. See:
>>> " a ".strip()
'a'
>>> " a a ".strip()
'a a'
So i suggest this approach:
def removeWhite(s):
return ''.join(filter(lambda x: x not in " '", s))
Please note that I use join because filter returns an iterator which needs to be converted back to a string.
For finding the palindromes i would suggest this function:
def isPal(s):
if len(s) <= 1: # Special case to prevent KeyError later
return True
stripped = removeWhite(s) # Strip off all whitespaces
first = stripped[:len(stripped) // 2] # First half of the string
if len(stripped) % 2: # Length of string is even?
second = stripped[len(stripped) // 2 + 1:] # Drop the middle character
else:
second = stripped[len(stripped) // 2:] # Else keep it
secondrev = ''.join(reversed(second)) # Reverse the second half
return first == secondrev # And return wether they're equal.
This holds for all your examples. But it think your isPal function should work too if you fix your removeWhite function

Longest substring in alphabetical order [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print
Longest substring in alphabetical order is: abc
Here you go edx student i've been helped to finish the code :
from itertools import count
def long_sub(input_string):
maxsubstr = input_string[0:0] # empty slice (to accept subclasses of str)
for start in range(len(input_string)): # O(n)
for end in count(start + len(maxsubstr) + 1): # O(m)
substr = input_string[start:end] # O(m)
if len(substr) != (end - start): # found duplicates or EOS
break
if sorted(substr) == list(substr):
maxsubstr = substr
return maxsubstr
sub = (long_sub(s))
print "Longest substring in alphabetical order is: %s" %sub
These are all assuming you have a string (s) and are needing to find the longest substring in alphabetical order.
Option A
test = s[0] # seed with first letter in string s
best = '' # empty var for keeping track of longest sequence
for n in range(1, len(s)): # have s[0] so compare to s[1]
if len(test) > len(best):
best = test
if s[n] >= s[n-1]:
test = test + s[n] # add s[1] to s[0] if greater or equal
else: # if not, do one of these options
test = s[n]
print "Longest substring in alphabetical order is:", best
Option B
maxSub, currentSub, previousChar = '', '', ''
for char in s:
if char >= previousChar:
currentSub = currentSub + char
if len(currentSub) > len(maxSub):
maxSub = currentSub
else: currentSub = char
previousChar = char
print maxSub
Option C
matches = []
current = [s[0]]
for index, character in enumerate(s[1:]):
if character >= s[index]: current.append(character)
else:
matches.append(current)
current = [character]
print "".join(max(matches, key=len))
Option D
def longest_ascending(s):
matches = []
current = [s[0]]
for index, character in enumerate(s[1:]):
if character >= s[index]:
current.append(character)
else:
matches.append(current)
current = [character]
matches.append(current)
return "".join(max(matches, key=len))
print(longest_ascending(s))
The following code solves the problem using the reduce method:
solution = ''
def check(substr, char):
global solution
last_char = substr[-1]
substr = (substr + char) if char >= last_char else char
if len(substr) > len(solution):
solution = substr
return substr
def get_largest(s):
global solution
solution = ''
reduce(check, list(s))
return solution

Resources