Addition in "If" Statements - clock

I just wanted to know how to use addition in an if statement because in the clock I'm making (without applet), I don't know how to set the hours properly. I have "(if seconds == 60) minutes++, but if I do the same with hours, it adds an hour every second. I just want to know how to solve this problem. Thanks :)
EDIT: Thanks everyone, I fixed it. All I have to do now is find an alternative to "\b"! It doesn't look right without it...

If you please elaborate more it will be helpful to answer.
According to what I understand :-
use brackets as scope for if statement for more line to come under if:-
if(seconds==60)
{
//add your lines here
}
Now if you don't want to change hours then:-
if(minutes==60)
hours++;
To put it in seconds if statement scope do the following:-
if(seconds==60)
{
seconds=0; //let the counter of seconds begin once more
minutes++;
if(minutes==60){
minutes=0; //let the counter of minute begin once more
hours++;
}
}

Related

How to make an object appear after a specific amount of time in Processing

Im trying to make a program where you are a ship and you simply avoid comets that fly towards you. I somewhat know how to use array lists to add and subtract objects, but I'm not sure how to get the program to add and subtract objects after a specific time like 5 seconds. My goal is to make each comet spawn 2 seconds apart but I'm not sure how. If anyone can help please let me know!
Processing exposes a useful variable frameCount that you can use for such timing behaviours.
You could use it in combination with the modulo operator % (an operator that returns the remainder after the division of two numbers), as follows:
draw() {
.
.
.
if (frameCount % t == 0) {
spawnComet();
}
.
.
.
}
Assuming frameRate is fixed at 60, t takes the value of 60*(desired time delay in seconds). You want to spawn comets every 2 seconds: 60*2 = 120. Therefore set t to 120 to satisfy the requirement of your example. This means spawnComet() will trigger every 120 frames.

Flash as2 bullet removing enemy?

I am trying to make a simple as2 shooter but when I try to shoot an enemy the bullet just go thru it and doesn't remove the enemy. I tried to put
if (hitTest(_root.vihollinen)==true
){
_root.vihollinen.remove();
this.removeMovieClip();
}
but nothing happens
Most of the code is just copy/paste because I don't know much about coding but I'm trying to learn!
https://www.dropbox.com/s/58u34tbeve6oile/game.zip
The most significant issue is that your enemy needs an Instance Name in order for the code to understand it. Simply click on your enemy movieclip, and add vihollinen to the Instance Name field at the top.
Next, your bullet code is close, but needs some adjustments. Here is your code:
_root["bullet" + bulletsFired].onEnterFrame = function(){
this._x += this.xmov;
this._y += this.ymov;
if (hitTest(_root.vihollinen)==true){
_root.vihollinen.remove();
this.removeMovieClip();
}
};
If you're ever using an onEnterFrame handler like that with a function, it's good practice to always refer to the current object with this, like so: if(this.hitTest(_root.vihollinen) == true){
remove() is not an ActionScript2 function. Try using unloadMovie() instead, like this: _root.vihollinen.unloadMovie()
Changing those three things will make your code function. Be sure that you try to go through each part of your code and understand it to the best of your ability - it'll make things much easier in the long run, even if it takes a long time to figure out why each part is there!

What does the prefix in NSLog mean?

When I use NSLog, I get output similar to the following:
2012-01-24 17:05:32:860 App[21856:71939] {logging goes here}
I recognize that '2012-01-24 17:05:32:860' is the date, 'App' is the app name, but I have no clue what '[21856:71939]' means. Can someone fill me in on what that is and where it's generated at?
All I'm trying to do is get logging that lines up nicely so it's easy to read, but the '[21856:71939]' varies in digits enough to mess up any alignment attempts. If I knew how the numbers in '[21856:71939]' were generated, I could add spaces as needed to make it line up correctly, but that's my only idea at this point.
Any help would be much appreciated :)
21856 is the process id. 71939 is the thread id.
You can generate this portion of the log on your own using:
[NSString stringWithFormat:#"[%ld,%lx]",
(long) getpid(),
(long) pthread_mach_thread_np(pthread_self())];
Edit 2014-09-23:
At least on the simulator in iOS 8, the second number is now the pthread_threadid_np of the thread.
__uint64_t threadId;
if (pthread_threadid_np(0, &threadId)) {
threadId = pthread_mach_thread_np(pthread_self());
}
[NSString stringWithFormat:#"[%ld,%llu]", (long) getpid(), threadId]
IIRC, the 21856 is the process PID, and the 71939 is some sort of thread identifier.
It's a thread ID, but I don't actually know how they are generated.
you can grab it yourself using this
pthread_mach_thread_np(pthread_self())
but that doesn't answer how you would set it up with correct lining. On the other note, when you're debugging, go to the last tab (Show the log Navigator), double click on Debug App, it'll show up nicely

Rudimentary ways to measure execution time of a method

What object/method would I call to get current time in milliseconds (or great precision) to help measure how long a method took to execute?
NSDate's timeIntervalSinceDate will return NSInterval which is measured in seconds. I am looking for something finer grained, something similar to Java's System.currentTimeMillis.
Is there an equivalent version in objective-c/CocoaTouch?
For very fine-grained timings on OS X, I use mach_absolute_time( ), which is defined in <mach/mach_time.h>. You can use it as follows:
#include <mach/mach_time.h>
#include <stdint.h>
static double ticksToNanoseconds = 0.0;
uint64_t startTime = mach_absolute_time( );
// Do some stuff you want to time here
uint64_t endTime = mach_absolute_time( );
// Elapsed time in mach time units
uint64_t elapsedTime = endTime - startTime;
// The first time we get here, ask the system
// how to convert mach time units to nanoseconds
if (0.0 == ticksToNanoseconds) {
mach_timebase_info_data_t timebase;
// to be completely pedantic, check the return code of this next call.
mach_timebase_info(&timebase);
ticksToNanoseconds = (double)timebase.numer / timebase.denom;
}
double elapsedTimeInNanoseconds = elapsedTime * ticksToNanoseconds;
Actually, +[NSDate timeIntervalSinceReferenceDate] returns an NSTimeInterval, which is a typedef for a double. The docs say
NSTimeInterval is always specified in seconds; it yields sub-millisecond precision over a range of 10,000 years.
So it's safe to use for millisecond-precision timing. I do so all the time.
Do not use NSDate for this. You're loosing a lot of precision to call methods and instantiate objects, maybe even releasing something internal. You just don't have enough control.
Use either time.h or as Stephen Canon suggested mach/mach_time.h. They are both much more accurate.
The best way to do this is to fire up Instruments or Shark, attach them to your process (works even if it's already running) and let them measure the time a method takes.
After you're familiar with it this takes even less time than any put-in-mach-time-functions-and-recompile-the-whole-application solution. You even get a lot of information extra. I wouldn't settle for anything less.
timeIntervalSinceReferenceDate is perfectly fine.
However, unless it's a long-running method, this won't bear much fruit. Execution times can vary wildly when you're talking about a few millisecond executions. If your thread/process gets preempted mid-way through, you'll have non-deterministic spikes. Essentially, your sample size is too small. Either use a profiler or run 100,000 iterations to get total time and divide by 100,000 to get average run-time.
If you're trying to tune your code's performance, you would do better to use Instruments or Shark to get an overall picture of where your app is spending its time.
I will repost my answer from another post here. Note that my admittedly simple solution to this complex problem uses NSDate and NSTimeInterval as its foundation:
I know this is an old one but even I found myself wandering past it again, so I thought I'd submit my own option here.
Best bet is to check out my blog post on this:
Timing things in Objective-C: A stopwatch
Basically, I wrote a class that does stop watching in a very basic way but is encapsulated so that you only need to do the following:
[MMStopwatchARC start:#"My Timer"];
// your work here ...
[MMStopwatchARC stop:#"My Timer"];
And you end up with:
MyApp[4090:15203] -> Stopwatch: [My Timer] runtime: [0.029]
in the log...
Again, check out my post for a little more or download it here:
MMStopwatch.zip
#bladnman I love your stopwatch thing.. I use it all the time.. Here's a little block I wrote that eliminates the need for the closing call, and makes it even EASIER (if that even seemed possible) to use, lol.
+(void)stopwatch:(NSString*)name timing:(void(^)())block {
[MMStopwatch start:name];
block();
[MMStopwatch stop: name];
}
then you can just call it wherever..
[MMStopwatch stopwatch:#"slowAssFunction" timing:^{
NSLog(#"%#",#"someLongAssFunction");
}];
↪someLongAssFunction
-> Stopwatch: [slowAssFunction] runtime:[0.054435]
You should post that sucker to github - so people can find it easily / contribute, etc. it's great. thanks.

Is a variable named i unacceptable? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
As far as variable naming conventions go, should iterators be named i or something more semantic like count? If you don't use i, why not? If you feel that i is acceptable, are there cases of iteration where it shouldn't be used?
Depends on the context I suppose. If you where looping through a set of Objects in some
collection then it should be fairly obvious from the context what you are doing.
for(int i = 0; i < 10; i++)
{
// i is well known here to be the index
objectCollection[i].SomeProperty = someValue;
}
However if it is not immediately clear from the context what it is you are doing, or if you are making modifications to the index you should use a variable name that is more indicative of the usage.
for(int currentRow = 0; currentRow < numRows; currentRow++)
{
for(int currentCol = 0; currentCol < numCols; currentCol++)
{
someTable[currentRow][currentCol] = someValue;
}
}
"i" means "loop counter" to a programmer. There's nothing wrong with it.
Here's another example of something that's perfectly okay:
foreach (Product p in ProductList)
{
// Do something with p
}
I tend to use i, j, k for very localized loops (only exist for a short period in terms of number of source lines). For variables that exist over a larger source area, I tend to use more detailed names so I can see what they're for without searching back in the code.
By the way, I think that the naming convention for these came from the early Fortran language where I was the first integer variable (A - H were floats)?
i is acceptable, for certain. However, I learned a tremendous amount one semester from a C++ teacher I had who refused code that did not have a descriptive name for every single variable. The simple act of naming everything descriptively forced me to think harder about my code, and I wrote better programs after that course, not from learning C++, but from learning to name everything. Code Complete has some good words on this same topic.
i is fine, but something like this is not:
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
string s = datarow[i][j].ToString(); // or worse
}
}
Very common for programmers to inadvertently swap the i and the j in the code, especially if they have bad eyesight or their Windows theme is "hotdog". This is always a "code smell" for me - it's kind of rare when this doesn't get screwed up.
i is so common that it is acceptable, even for people that love descriptive variable names.
What is absolutely unacceptable (and a sin in my book) is using i,j, or k in any other context than as an integer index in a loop.... e.g.
foreach(Input i in inputs)
{
Process(i);
}
i is definitely acceptable. Not sure what kind of justification I need to make -- but I do use it all of the time, and other very respected programmers do as well.
Social validation, I guess :)
Yes, in fact it's preferred since any programmer reading your code will understand that it's simply an iterator.
What is the value of using i instead of a more specific variable name? To save 1 second or 10 seconds or maybe, maybe, even 30 seconds of thinking and typing?
What is the cost of using i? Maybe nothing. Maybe the code is so simple that using i is fine. But maybe, maybe, using i will force developers who come to this code in the future to have to think for a moment "what does i mean here?" They will have to think: "is it an index, a count, an offset, a flag?" They will have to think: "is this change safe, is it correct, will I be off by 1?"
Using i saves time and intellectual effort when writing code but may end up costing more intellectual effort in the future, or perhaps even result in the inadvertent introduction of defects due to misunderstanding the code.
Generally speaking, most software development is maintenance and extension, so the amount of time spent reading your code will vastly exceed the amount of time spent writing it.
It's very easy to develop the habit of using meaningful names everywhere, and once you have that habit it takes only a few seconds more to write code with meaningful names, but then you have code which is easier to read, easier to understand, and more obviously correct.
I use i for short loops.
The reason it's OK is that I find it utterly implausible that someone could see a declaration of iterator type, with initializer, and then three lines later claim that it's not clear what the variable represents. They're just pretending, because they've decided that "meaningful variable names" must mean "long variable names".
The reason I actually do it, is that I find that using something unrelated to the specific task at hand, and that I would only ever use in a small scope, saves me worrying that I might use a name that's misleading, or ambiguous, or will some day be useful for something else in the larger scope. The reason it's "i" rather than "q" or "count" is just convention borrowed from mathematics.
I don't use i if:
The loop body is not small, or
the iterator does anything other than advance (or retreat) from the start of a range to the finish of the loop:
i doesn't necessarily have to go in increments of 1 so long as the increment is consistent and clear, and of course might stop before the end of the iterand, but if it ever changes direction, or is unmodified by an iteration of the loop (including the devilish use of iterator.insertAfter() in a forward loop), I try to remember to use something different. This signals "this is not just a trivial loop variable, hence this may not be a trivial loop".
If the "something more semantic" is "iterator" then there is no reason not to use i; it is a well understood idiom.
i think i is completely acceptable in for-loop situations. i have always found this to be pretty standard and never really run into interpretation issues when i is used in this instance. foreach-loops get a little trickier and i think really depends on your situation. i rarely if ever use i in foreach, only in for loops, as i find i to be too un-descriptive in these cases. for foreach i try to use an abbreviation of the object type being looped. e.g:
foreach(DataRow dr in datatable.Rows)
{
//do stuff to/with datarow dr here
}
anyways, just my $0.02.
It helps if you name it something that describes what it is looping through. But I usually just use i.
As long as you are either using i to count loops, or part of an index that goes from 0 (or 1 depending on PL) to n, then I would say i is fine.
Otherwise its probably easy to name i something meaningful it its more than just an index.
I should point out that i and j are also mathematical notation for matrix indices. And usually, you're looping over an array. So it makes sense.
As long as you're using it temporarily inside a simple loop and it's obvious what you're doing, sure. That said, is there no other short word you can use instead?
i is widely known as a loop iterator, so you're actually more likely to confuse maintenance programmers if you use it outside of a loop, but if you use something more descriptive (like filecounter), it makes code nicer.
It depends.
If you're iterating over some particular set of data then I think it makes more sense to use a descriptive name. (eg. filecounter as Dan suggested).
However, if you're performing an arbitrary loop then i is acceptable. As one work mate described it to me - i is a convention that means "this variable is only ever modified by the for loop construct. If that's not true, don't use i"
The use of i, j, k for INTEGER loop counters goes back to the early days of FORTRAN.
Personally I don't have a problem with them so long as they are INTEGER counts.
But then I grew up on FORTRAN!
my feeling is that the concept of using a single letter is fine for "simple" loops, however, i learned to use double-letters a long time ago and it has worked out great.
i asked a similar question last week and the following is part of my own answer:// recommended style ● // "typical" single-letter style
●
for (ii=0; ii<10; ++ii) { ● for (i=0; i<10; ++i) {
for (jj=0; jj<10; ++jj) { ● for (j=0; j<10; ++j) {
mm[ii][jj] = ii * jj; ● m[i][j] = i * j;
} ● }
} ● }
in case the benefit isn't immediately obvious: searching through code for any single letter will find many things that aren't what you're looking for. the letter i occurs quite often in code where it isn't the variable you're looking for.
i've been doing it this way for at least 10 years.
note that plenty of people commented that either/both of the above are "ugly"...
I am going to go against the grain and say no.
For the crowd that says "i is understood as an iterator", that may be true, but to me that is the equivalent of comments like 'Assign the value 5 to variable Y. Variable names like comment should explain the why/what not the how.
To use an example from a previous answer:
for(int i = 0; i < 10; i++)
{
// i is well known here to be the index
objectCollection[i].SomeProperty = someValue;
}
Is it that much harder to just use a meaningful name like so?
for(int objectCollectionIndex = 0; objectCollectionIndex < 10; objectCollectionIndex ++)
{
objectCollection[objectCollectionIndex].SomeProperty = someValue;
}
Granted the (borrowed) variable name objectCollection is pretty badly named too.