Recursive method to revert text - pascal

Can someone please explain me how this code reverts the users input(it's a recursion):
Procedure revert;
Var text:char;
Begin
Read (text)
If (text <> '.') Then revert;
Write(text);
End;

Let's do it by an example.
Imagine the user types 'Hello.'
He types the letter 'H'.
As text equals 'H' the condition (text <> '.') is true.
So revert is called once again.
Now there is a second text variable on the stack and it is going to
be filled with the second letter the user enters. In this case it's
'e'.
The condition (text <> '.') is true again. So revert is called
once again.
Now there is a third text variable on the stack and it is going to
be filled with the third letter the user enters. In this case it's
'l'.
The condition (text <> '.') is true again. So revert is called
once again.
Now there is a fourth text variable on the stack and it is going to
be filled with the third letter the user enters. In this case it's
'l'.
The condition (text <> '.') is true again. So revert is called
once again.
Now there is a fifth text variable on the stack and it is going to
be filled with the fifth letter the user enters. In this case it's
'o'.
The condition (text <> '.') is true again. So revert is called
once again.
Now there is a sixth text variable on the stack and it is going to
be filled with the sixth letter the user enters. In this case it's
'.'.
Now the condition (text <> '.') is false! revert is not going to
be called.
The value of the topmost text variable will be written to the
console. In this case it's '.'.
The sixth call to revert is done now. It's cleaning the stack so
the sixth text variable will be removed from it. The program is
going back to the position where it has come from: The fifth call to
revert.
The value of the topmost text variable will be written to the
console. In this case it's 'o'.
The fifth call to revert is done now. It's cleaning the stack so
the fifth text variable will be removed from it. The program is
going back to the position where it has come from: The fourth call to
revert.
The value of the topmost text variable will be written to the
console. In this case it's 'l'.
The fourth call to revert is done now. It's cleaning the stack so
the fourth text variable will be removed from it. The program is
going back to the position where it has come from: The third call to
revert.
The value of the topmost text variable will be written to the
console. In this case it's 'l'.
The third call to revert is done now. It's cleaning the stack so
the third text variable will be removed from it. The program is
going back to the position where it has come from: The second call to
revert.
The value of the topmost text variable will be written to the
console. In this case it's 'e'.
The second call to revert is done now. It's cleaning the stack so
the second text variable will be removed from it. The program is
going back to the position where it has come from: The initial call
to revert.
The value of the topmost text variable will be written to the
console. In this case it's 'H'.
The initial call to revert is done now. It's cleaning the stack so
the first text variable will be removed from it. The program is
going back to the position where it has come from: We don't know it.
Maybe the program ends
The string '.olleH' appeared on the screen.

import java.io.*;
class revstr
{
static String ans="";
static String rev (String str)
{
if(str.length()==0)
return ans;
else
{
ans+=str.charAt(str.length()-1);
return rev(str.substring(0,str.length()-1));
}
}
}

Related

Is there something I'm doing wrong to pick up this error?

I am new to Ti-basic, and I am trying to code it. I'm trying to make this 'special type of input' program. It is kind of like input, but it will show the word as it is being pressed (and there is no need to put in alpha)
Here is the code so far that I believe is pertaining to the error
:{41,42,43,51,52,53,54,55,61,62,63,64,65,71,72,73,74,75,81,82,83,84,85,91,92,93,94,102,103,103}→∟KEYS
:"ABCDEFGHIJKLMNOPQRSTUVWXYZθ :?"→Str7
:0→K
:""→Str1
:
:Repeat K=105
:getKey→K
:If max(∟KEYS-K)
:prgmFINDIND
:.........
:End
Inside prgmFINDIND, This is the code
:1+sum(not(cumSum(∟KEYS=K)))→I
://I is used later on in the code. It isn't pertaining to the problem.
I have done some testing with pause on this already, and I found the problem was in the if statement. It returns an 'INVALID DIM' error.
Anybody know what's wrong?
In this part (edited a bit)
Repeat K=105
getKey->K
If max(|LKEYS=K
prgmFINDIND
Str1+sub(Str7,I,1->Str1
End
prgmFINDIND is only called if the key that was pressed is in the list, otherwise the index I is not changed (and possibly implicitly zero, or whatever other value that was left there).
Pressing GOTO on the INVALID DIM actually goes to Str1+sub(Str7,I,1->Str1, indicating that a bad index was used to index into Str7.
It could be fixed by using an If/Then block, which can cover more than one statement:
Repeat K=105
getKey->K
If max(|LKEYS=K
Then
prgmFINDIND
Str1+sub(Str7,I,1)->Str1
End
End

Viewing Swift optional values in debugger

Trying to get my feet wet in writing and debugging Swift code, I wrote the following. This is on OS X 10.10.2, Xcode 6.2.
let text : String? = "This is some text.\nJust for fun."
let lines : [String]? =
text?.componentsSeparatedByCharactersInSet(
NSCharacterSet.newlineCharacterSet())
println("\(lines)")
Breaking on the println ... line, the debugger's variable view shows Some as the value of lines. In my understanding, this indicates that lines is of an optional type and contains a value wrapped in Some, as opposed to being None.
Knowing that, how can I use the debugger to inspect what that value actually is? I tried:
clicking the small "i" button, which produces the output "Some" in the debugger console.
entering po lines and po lines! in the debugger console, which yields EXC_BAD_ACCESS. Update: Following a fresh installation of Xcode, po lines seems to have no effect, i.e. no output.
The final line prints Optional(["This is some text.", "Just for fun."]), which is exactly what I'd like the debugger to show.
How can I get at the unwrapped string array value of lines, and what is the difference between the optional variable lines, whose unwrapped value the debugger doesn't show, and the optional variable text, whose value it does show? Will I actually have to introduce an auxiliary variable every time I want to debug an optional value, or use printf-debugging?
Maybe I am misunderstanding, but you made "lines" an optional value. Because of that, you would need to unwrap it in your println statement or not make it an optional value. Take off the "?" after your "lines" declaration first and see if that works for you.
let lines : [String] =
To print an optional value use:
if let unwrappedLines = lines { // only executes if lines is not nil
println("\(unwrappedLines)") // prints the unwrapped variable
}

Import Subtitles in Processing

I am working on this sketch on Processing which gets the videofeed from my webcam/smartphone and shows it when running. I want to import an .srt converted to txt subtitles file from a film to it. I can see that the text file has all these numbers that stand for the start and end subtitle frame before the actual text.
Here's an example:
{9232}{9331}Those swings are dangerous.|Stay off there. I haven't fixed them yet.
{9333}{9374}I think you're gonna live.
What I would like to do is to figure outa code that will
use the numbers and set them as start/end frames to run at the right time as in the film
display the subtitles
figure out how the '|'sign can be used as a symbol to trigger in the script the change of line.
I guess that might already be quite complicated but I just wanted to check whether someone has done anything similar in the past..
I guess what I want to do is save me from doing the whole
if ((current_frame > 9232) && ((current_frame < 9331)) {
text("Those swings are dangerous.", 200, 500/2);
text("Stay off there. I haven't fixed them yet..", 200, (500/2 + 35));
}
thing for each subtitle...
I am quite new to processing so not that familiar with many commands apart from 'for' and 'if', a newbie at importing .txt files and an ignoramus in working with arrays. But I really want to find a nice way in the last two bits..
Any help in any form will be greatly appreciated :)
Cheers,
George
For displaying the appropriate subtitle, you could do something like the following (explanation below, sorry in advance for the wall of text):
String[] subtitles = loadStrings("subtitles.txt");
int currentFrame = 0;
int subtitleIndex = -1;
int startFrame = -1, endFrame = -1;
int fontSize = 10; //change to suit your taste
String[] currentSubtitle;
...
//draw loop start:
//video drawing code goes here
if(currentFrame > endFrame){ //update which subtitle is now/next
subtitleIndex++;
startFrame = int(subtitles[subtitleIndex].split("\\}\\{")[0].substring(1));
endFrame = int(subtitles[subtitleIndex].split("\\}\\{")[1].split("\\}")[0]);
currentSubtitle = subtitles[subtitleIndex].split("\\}")[2].split("\\|");
}
if(currentFrame >= startFrame && currentFrame <= endFrame){
for(int i = 0; i < currentSubtitle.length; i++){
text(currentSubtitle[i], width/2, height - fontSize * (currentSubtitle.length - i));
}
}
currentFrame++;
//draw loop end
Probably that looks pretty intimidating to you, so here's some walk-through commentary. Your program will be a type of state machine. It will either be in the state of displaying a subtitle, or not. We'll keep this in mind later when we're designing the code. First, you need to declare and initialize your variables.
The first line uses the loadStrings() function, which reads through a text file and returns a String array where each element in the array is a line in the file. Of course, you'll need to change the filename to fit your file.
Your code uses a variable called current_frame, which is a very good idea, but I've renamed it to currentFrame to fit the java coding convention. We'll start at zero, and later on our code will increment it on every frame display. This variable will tell us where we are in the subtitle sequence and which message should be displayed (if any).
Because the information for what frame each subtitle starts and ends on is encoded in a string, it's a bit tricky to incorporate it into the code. For now, let's just create some variables that represent when the "current" subtitle-- the subtitle that we're either currently displaying or will be displaying next-- starts and ends. We'll also create an index to keep track of which element in the subtitles array is the "current" subtitle. These variables all start at -1, which may seem a bit odd. Whereas we initialized currentFrame to 0, these don't really have a real "initial" value, at least not for now. If we chose 0, then that's not really true, because the first subtitle may not (probably doesn't) begin and end at frame 0, and any other positive number doesn't make much sense. -1 is often used as a dummy index that will be replaced before the variable actually gets used, so we'll do that here, too.
Now for the final variable: currentSubtitle. The immediate thought would be to have this be a plain String, not a String array. However, because each subtitle may need to be split on the pipe (|) symbols, each subtitle may actually represent several lines of text, so we'll create an array just to be safe. It's possible that some subtitles may be a single-element array, but that's fine.
Now for the hard part!
Presumably, your code will have some sort of loop in it, where on each iteration the pertinent video frame is drawn to the screen and (if the conditions are met), the subtitle is drawn over top of it. I've left out the video portion, as that's not part of your question.
Before we do anything else, we need to remember that some of our variables don't have real values yet-- all those -1s from before need to be set to something. The basic logic of the drawing loop is 1) figure out if a subtitle needs to be drawn, and if so, draw it, and 2) figure out if the "current" subtitle needs to be moved to the next one in the array. Let's do #2 first, because on the first time through the loop, we don't know anything about it yet! The criterion (in general) for moving to the next subtitle is if we're past the end of the current one : currentFrame > endFrame. If that is true, then we need to shift all of our variables to the next subtitle. subtitleIndex is easy, we just add one and done. The rest are... not as easy. I know it looks disgusting, but I'll talk about that at the end so as to not break the flow. Skip ahead to the bottom if you just can't wait :)
After (if necessary) changing all of the variables so that they're relevant to the current subtitle, we need to do some actual displaying. The second if statement checks to see if we're "inside" the frame-boundaries of the current subtitle. Because the currentSubtitle variable can either refer to the subtitle that needs to be displayed RIGHT NOW, or merely just the next one in the sequence, we need to do some checking to determine which one it is for this frame. That's the second if statement-- if we're past the start and before the end, then we should be displaying the subtitle! Recall that our currentSubtitle variable is an array, so we can't just display it directly. We'll need to loop through it and display each element on a separate line. You mentioned the text() command, so I won't go too in depth here. The tricky bit is the y-coordinate of the text, since it's supposed to be on multiple lines. We want the first element to be above the second, which is above the third, etc. To do that, we'll have the y-coordinate depend on which element we're on, marked by i. We can scale the difference between lines by changing the value of fontSize; that'll just be up to your taste. Know that the number you set it to will be equal to the height of a line in pixels.
Now for the messy bit that I didn't want to explain above. This code depends on String's split() method, which is performed on the string that you want split and takes a string as a parameter that instructs it how to split the string-- a regex. To get the startFrame out of a subtitle line in the file, we need to split it along the curly braces, because those are the dividers between the numbers. First, we'll split the string everywhere that "}{" occurs-- right after the first number (and right before the second). Because split() returns an array, we can reference a single string from it using an index between square braces. We know that the first number will be in the first string return by splitting on "}{", so we'll use index 0. This will return (for example) "{1234", because split() removes the thing you're splitting on. Now we need to just take the substring that occurs after the first character, convert it to an int using int(), and we're done!
For the second number, we can take a similar approach. Let's split on "}{" again, only we'll take the second (index 1) element in the returned array this time. Now, we have something like "9331}Those swings are dang...", which we can split again on "}", choose the first string of that array, convert to int, and we're done! In both of these cases, we're using subtitles[subtitleIndex] as the original String, which represents the raw input of the file that we loaded using loadStrings() at the beginning. Note that during all this splitting, the original string in subtitles is never changed-- split(), substring(), etc only return new sequences and don't modify the string you called it on.
I'll leave it to you to figure out how the last line in that sequence works :)
Finally, you'll see that there are a bunch of backslashes cluttering up the split() calls. This is because split() takes in a regex, not a simple string. Regexs use a lot of special notation which I won't get into here, but if you just passed split() something like "}{", it would try to interpret it and it would not behave as expected. You need to escape the characters, telling split() that you don't want them to be interpreted as special and you just want the characters themselves. To do that, you use a backlash before any character that needs to be escaped. However, the backslash itself is yet another special character, so you need to escape it, too! This results in stuff like "\\{" -- the first backslash escapes the second one, which escapes whatever the third character is. Note that the | character also needs to be escaped.
Sorry for the wall of text! It's nice to see questions asked intelligently and politely, so I thought I'd give a good answer in return.

Is it possible to reference value of another watched expression in vs2010?

When I hit a breakpoint I have "this" in my watch window
this -> 0x2cceb42c
I copy that value into a new line in my watch window (it displays both the name and the value in hex)
0x2cceb42c -> 0x2cceb42c
On a third line I cast my value into a pointer to my class:
(MyClass*)0x2cceb42c -> { members of class... }
The problem is, next time I run the program the address has changed so I have to edit the address on my third line. Only, I'm not just using it in the third line, but also in 5 other watch expressions. Which means the next time I run the program I have to change the address in all 5 watched expressions.
What I would like to do is have my 5 watch expressions refer to the value in line 2 - then I only ever need to change the address in one place and all my watches will update automatically.
Is this possible? Or can anyone suggest a trick to achieve as close to this as possible?
Clarification: I want to see the results of my 5 watch expressions when I'm on a breakpoint elsewhere in the code (where "this" is no longer the value I'm interested in, which is why I'm copying the address out of "this").

print line before page changed in vfp reports

I'm creating a report in vfp. The report contains grouping. In the end of each group, i draw a line. Each row in the detail band doesn't contain any line, only at the end of each group. The problem is when the group expand to the next page, in the previous page i want to draw a line at the bottom. Like this :
(page 1)
group A
name, etc
x1,etc
x2,etc
???how do I add line here?
(page 2)
group A
name,etc
x3,etc
x4,etc
group B
name,etc
y1,etc
y2,etc
I've tried to place the line in the page footer band, but the last line of the report doesn't have exact position, so it doesn't look nice.
Hope I described the situation clear enough. Thank You for taking the time to help me.
Without some significant smoke-and-mirrors trickery: running the report twice, once hidden and track where the breaks are via function calls in the report, and then again for production, its not EASILY done.
The only thing I could suggest is putting a line at the TOP of a PAGE FOOTER which prints on EVERY page. How long have you been working with VFP. Depending, I MIGHT be able to guide you through it.
Ok, here are the steps I would take. This is under the assumption that you are pre-querying the results for your report and ordering them by some means into a temporary report cursor. You need to add 2 columns to your query as place-holders and be sure your do your cursor as " INTO CURSOR READWRITE " as we will be writing to this from within the report... that is the trick.
Next, modify your report. Go to the detail band and put a single line at the bottom of it. Adjust as needed if you need a few pixels under the last detail element. Double click the line and get to the tab where it allows you to put in a "Print When" condition for the line. Enter one of the new column names called "ShowLine" (but without the quotes).
Now, the "hook" for smoke and mirrors. Create another textbox field output in the report detail. It can be as small as 2 pixels wide and never actually prints anything. It can be put at the beginning or end of the report detail, no matter, just as long as its in the detail band. Double click it to bring up what it will print. In the expression, enter the following... WhatPageAmIOn( _PageNo )
This will actually call a function we'll add to your program which writes back to your report cursor... I'll hit that next.
Now, the code. The following is a sample snippet of code I've written to query the data for the report, have the extra columns, and put into a READWRITE cursor. From that, I run the report but to NOCONSOLE so it doesn't actually visually do anything, just runs in the background. It then cycles through and looks for the break between each page and goes backward 1 record from the break and stamps that record as "ShowLine" = .T... Then run the report again as normal and you have your one line appearing in the detail band regardless of a data group, but always the last data line at the end of each page.
Here's the code
*/ Query your data, order by whatever,
*/ but tack on the two extra fields and make it READWRITE
select;
YourData,;
AnotherField,;
MoreData,;
.f. as ShowLine,;
00000 as WhatPage;
FROM ;
YourData;
ORDER BY ;
WhateverForYourReport
INTO ;
CURSOR C_RptData READWRITE
*/ Pre-run the report NOCONSOLE so your windows don't get messed up / scrolled
REPORT FORM YourReport NOCONSOLE
*/ now, go back to the cursor that your report ran with
SELECT C_RptData
*/ set a variable for the first page you are looking to find a break for.
*/ in this case, the first detail that APPEARED on page 2.
lnLastPage = 2
*/ Start at top of the report cursor file and keep going until we reach
*/ the end of file where the LOCATE can no longer find "Pages".
GO TOP
DO WHILE NOT EOF()
*/ find the first record on ex: Page 2
LOCATE FOR WhatPage = lnLastPage
*/ Did we find one?
IF FOUND()
*/ Yes, go backwards 1 record
SKIP -1
*/ This is the last detail that appeared on the page before it (ie: pg 1)
*/ Mark this line as ok to "ShowLine" the next time the report is run.
replace ShowLine WITH .T.
*/ Now, advance the page counter to look for the NEXT page break...
*/ ex: between page 2&3, 3&4, 4&5, etc...
lnLastPage = lnLastPage +1
ENDIF
ENDDO
*/ Run your final version of the report
REPORT FORM YourReport Preview (or print)
RETURN
Here's the only hook below to track/update the page associated with the detail. I don't know if you have a main "SET PROCEDURE TO" file, or just a bunch of free .PRG files all in your project, or even if your reporting is done from within a PRG file itself. however, all you need is this function to be included in any of those locations. For simplest test, I would just create it as a stand-alone .prg file (if you are NOT using SET PROCEDURE, or doing your report within a PRG file and not from within a class method/event).
FUNCTION WhatPageAmIOn
LPARAMETERS lnPage
replace whatPage WITH lnPage
RETURN ""
As in the original description, the report is going to include a field in the detail band based on a function "WhatPageamIOn" and passes the parameter of _PageNo which is the internal VFP variable that keeps track of the current report page that is typically used in report header / footers. So, as each detail is getting processed, we are "STAMPING" the detail data with whatever the page is. We return an empty string "" so nothing actually gets printed, yet we've hooked what we needed. From this, the loop finding the first record at the beginning of every page (starting at page 2), and skipping backwards to the last entry for the prior page and we're done.
Good luck.

Resources