How to display an inter object in the readline command in r? - r

I have declared an integer object called "teamStrength" and want to call it in the readline command. I know this is pretty much how to do it in Java but how do I display the object? "teamStrength" is supposed to change so I can't just display the actual number.
teamStrength <- mean(teams$Fifa.Rating, trim = 0.5)
CONTINUE <- readline(prompt = 'Your team strength is ' + teamStrength +
'Type yes if you want to continue. Type no if
you want to rechoose. ')

The prompt string should be concatenated with paste(), rather than plus signs. Your code should be something like this:
teamStrength <- mean(teams$Fifa.Rating, trim = 0.5)
CONTINUE <- readline(prompt = paste('Your team strength is ',
teamStrength, 'Type yes if you want to continue.
Type no if you want to rechoose. '))

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

compare foreign language strings in scilab

I am trying to compare the input string with the strings present in the doc. I am using strcmp for the purpose. These are non-English strings. When the input string is English language, the output is correct. But for any Kannada (non-English language) word the output is the same. I am trying to write a program to check if the word is present in the database. Please guide me in what could be the problem.
The calling function is as below:
str_kan = handles.InputBox.String;
res = strcmp('str_kan','s1.text')
if res == 1 then handles.InputBox.String = string( ' present')
abort
else
handles.InputBox.String = string( 'not present')
abort
end
The whole program is as below:
global s1
f=figure('figure_position',[400,50],'figure_size',[640,480],'auto_resize','on','background',[33],'figure_name','Graphic window number %d','dockable','off','infobar_visible','off','toolbar_visible','off','menubar_visible','off','default_axes','on','visible','off');
handles.dummy = 0;
handles.InputBox=uicontrol(f,'unit','normalized','BackgroundColor',[-1,-1,-1],'Enable','on','FontAngle','normal','FontName','Tunga','FontSize',[12],'FontUnits','points','FontWeight','normal','ForegroundColor',[-1,-1,-1],'HorizontalAlignment','left','ListboxTop',[],'Max',[1],'Min',[0],'Position',[0.0929487,0.6568182,0.4647436,0.1795455],'Relief','default','SliderStep',[0.01,0.1],'String','Enter a Kannada Word','Style','edit','Value',[0],'VerticalAlignment','middle','Visible','on','Tag','InputBox','Callback','')
handles.CheckDB=uicontrol(f,'unit','normalized','BackgroundColor',[-1,-1,-1],'Enable','on','FontAngle','normal','FontName','Tahoma','FontSize',[12],'FontUnits','points','FontWeight','normal','ForegroundColor',[-1,-1,-1],'HorizontalAlignment','center','ListboxTop',[],'Max',[1],'Min',[0],'Position',[0.1025641,0.4636364,0.4567308,0.1204545],'Relief','default','SliderStep',[0.01,0.1],'String','Check','Style','pushbutton','Value',[0],'VerticalAlignment','middle','Visible','on','Tag','CheckDB','Callback','CheckDB_callback(handles)')
f.visible = "on";
function CheckDB_callback(handles)
str_kan = handles.InputBox.String;
res = strcmp('str_kan','s1.text')
if res == 1 then handles.InputBox.String = string( ' present')
abort
else
handles.InputBox.String = string( 'not present')
abort
end
endfunction
Here is an example showing that, in Scilab, strcmp() does support UTF-8 extended characters:
--> strcmp(["aα" "aα" "aβ"], ["aα" "aβ" "aα"])
ans =
0. -1. 1.
The problem in the original posted code is the confusion between literal values as "Hello" and variables names as Hello="my text", as already noted by PTRK.

Build string with OS-specific newline characters (CRLF, LF, CR) to write it into a database table column

I want to write write a string that contains the usual new line character of R (\n) into a column of a database table.
How can I convert the new line into operating system specific representation (Windows = CR/LF, Linux = LF, Mac = CR...)?
I have learned that R does not provide the operating system specific representation so I have to find a work-around:
R equivalent for .NET's Environment.NewLine
Printing newlines with print() in R
Any trial to print/cat the string did fail:
msg <- "I want to have \n a new line"
cat(msg)
# I want to have
# a new line
out <- capture.output(cat(msg))
out
# a vector with two elements (one for each row but no new line characters anymore)
# [1] "I want to have " " a new line"
paste(out, collapse = "\n") # how could I inject the correct new line characters here?
# [1] "I want to have \n a new line"
# welcome endless-loop :-)
Is there any way to let R create the correct new line characters from \n in a string?
PS: I am playing around with the built-in tcltk package and puts but I always end with R "reconverting" the newline into \n...
Another "cheat" could be to enclose the \n with quotation marks to read it as if it were one line. I have no idea so far how this could work...
One way to correctly set the new line code in R is to query the operating system. Since both OS X and Linux behave the same way, it's a question of determining whether the operating system is Windows. One way to do this is to interrogate the OS environment variable as follows.
if(substr(Sys.getenv("OS"),1,7) == "Windows") {
# set Windows newline
newLine <- "\r\n"
}
else {
# set non-Windows newline
newLine <- "\n"
}
Next use paste() with the newLine object to generate the right characters for new line by operating system.
paste("my text string on a line",newline,sep="")
regards,
Len
Here you find my final implementation as a possible alternative to the accepted answer:
# Returns the operating system specific new line character(s):
# CR LF on Windows, else only LF...
# Simlar to Microsofts .Net "Environment.NewLine"
platform.NewLine <- function() {
is.windows <- grepl(tolower(.Platform$OS.type), "windows", fixed = TRUE)
if (is.windows) {
newline <- "\r\n"
} else {
newline <- "\n"
}
sys.name <- Sys.info()["sysname"]
is.windows.2nd.opinion <- grepl(tolower(sys.name), "windows", fixed = TRUE)
if (is.windows != is.windows.2nd.opinion)
warning("R seems to run on Windows OS but this could not be recognized for sure")
return(newline)
}
# Usage (examples) ------------------------------------------------------------------------------------------------
newline <- platform.NewLine()
# "print" shows the "symbolic" names (escape codes)
print(paste("Line1", "Line2", sep = newline))
# [1] "Line1\r\nLine2"
# uses "\n" or "\r\n" depending on your OS
# "cat" applies the newline escape codes to the output
cat(paste("Line1", "Line2", sep = newline))
# Line1
# Line2

nginx string.match non posix

I got a string (str1) and I want to extract anything after pattern "mycode=",
local str1 = "ServerName/codebase/?mycode=ABC123";
local tmp1 = string.match(str1, "mycode=%w+");
local tmp2 = string.gsub(tmp1,"mycode=", "");
From the logs,
tmp1 => mycode=ABC123
tmp2 => ABC123
Is there a better/more efficient way to do this? I do belive lua strings do not follow the POSIX standard (due to the size of the code base).
Yes, use a capture in your pattern to control what you get back from string.match.
From the lua reference manual (emphasis mine):
Looks for the first match of pattern in the string s. If it finds one, then match returns the captures from the pattern; otherwise it returns nil. If pattern specifies no captures, then the whole match is returned. A third, optional numerical argument init specifies where to start the search; its default value is 1 and can be negative.
It works like this:
> local str1 = "ServerName/codebase/?mycode=ABC123"
> local tmp1 = string.match(str1, "mycode=%w+")
> print(tmp1)
mycode=ABC123
> local tmp2 = string.match(str1, "mycode=(%w+)")
> print(tmp2)
ABC123

Python 3.4 help - using slicing to replace characters in a string

Say I have a string.
"poop"
I want to change "poop" to "peep".
In fact, I also want all of the o's in poop to change to e's for any word I put in.
Here's my attempt to do the above.
def getword():
x = (input("Please enter a word."))
return x
def main():
y = getword()
for i in range (len(y)):
if y[i] == "o":
y = y[:i] + "e"
print (y)
main()
As you can see, when you run it, it doesn't amount to what I want. Here is my expected output.
Enter a word.
>>> brother
brether
Something like this. I need to do it using slicing. I just don't know how.
Please keep your answer simple, since I'm somewhat new to Python. Thanks!
This uses slicing (but keep in mind that slicing is not the best way to do it):
def f(s):
for x in range(len(s)):
if s[x] == 'o':
s = s[:x]+'e'+s[x+1:]
return s
Strings in python are non-mutable, which means that you can't just swap out letters in a string, you would need to create a whole new string and concatenate letters on one-by-one
def getword():
x = (input("Please enter a word."))
return x
def main():
y = getword()
output = ''
for i in range(len(y)):
if y[i] == "o":
output = output + 'e'
else:
output = output + y[i]
print(output)
main()
I'll help you this once, but you should know that stack overflow is not a homework help site. You should be figuring these things out on your own to get the full educational experience.
EDIT
Using slicing, I suppose you could do:
def getword():
x = (input("Please enter a word."))
return x
def main():
y = getword()
output = '' # String variable to hold the output string. Starts empty
slice_start = 0 # Keeps track of what we have already added to the output. Starts at 0
for i in range(len(y) - 1): # Scan through all but the last character
if y[i] == "o": # If character is 'o'
output = output + y[slice_start:i] + 'e' # then add all the previous characters to the output string, and an e character to replace the o
slice_start = i + 1 # Increment the index to start the slice at to be the letter immediately after the 'o'
output = output + y[slice_start:-1] # Add the rest of the characters to output string from the last occurrence of an 'o' to the end of the string
if y[-1] == 'o': # We still haven't checked the last character, so check if its an 'o'
output = output + 'e' # If it is, add an 'e' instead to output
else:
output = output + y[-1] # Otherwise just add the character as-is
print(output)
main()
Comments should explain what is going on. I'm not sure if this is the most efficient or best way to do it (which really shouldn't matter, since slicing is a terribly inefficient way to do this anyways), just the first thing I hacked together that uses slicing.
EDIT Yeah... Ourous's solution is much more elegant
Can slicing even be used in this situation??
The only probable solution I think would work, as MirekE stated, is y.replace("o","e").

Resources