How to calculate time left in a count down scenario - database

We have a requirement to count down based on a user taking a test. What would be a best way to tackle tracking the time taken by a user while taking the test.
We do capture start time, end time. But the calculations go awry if the application server or the OS goes down during the test. We were thinking of using another variable to store the current time after the user submits an answer to the question. So (end time - current time) would reasonably account for the amount of time left.
Is there an effective way to calculate the "time left" in such cases other than the one mentioned above?
We would like the solution to be database agnostic as possible

To be specific, I'll continue with MYSQL.
As you may stated, you have captured start time. When the test loaded by the user, write this timestamp in a DATETIME field. Another option is that using UNIX_STAMP. And then, when user submits the answer, you may easily put this data to another DATETIME field.
As well as other rdbms systems, mysql got the date-time manipulation functions.
SELECT CURRENT_TIMESTAMP(); query returns current timestamp. eg. '2007-12-15 23:50:26'
SELECT UNIX_TIMESTAMP(); query returns current unix timestamp which may be easy to calculate difference. eg. 1111885200
Also we have got DATE_SUB() and DATE_ADD() functions for addition, subtraction operations.
Please visit date-time manual page for details. I guess this information will lead you to a proper solution.
--
Added on Sep 18:
You may use javascript to track user behaviour. For instance, a function calls a server side script with a salt or something you have in session. That server side script records the current timestamp as "last update". Database parts same as above.

I have written such a set of exams using a countdown timer. As unfortunately there were times when power cuts happened frequently in the computer lab, I had to add code to handle this. Basically, the exam program saves its state (the answers and the time elapsed) in an .ini file every 30 seconds. When the exam program starts, it checks to see whether such an ini file exists - if so, it carries on from where the program ceased (in terms of which questions have yet to be answered and how long remains), otherwise the program begins anew.
In order to make the exams standalone and thus independent of any server, all the questions and options were exported to a resource file, which was then included in the build of the exam itself.

Related

Problems with incorrect timezones and locale-specific display of time

So, there is absolutely no reason why we should be having this problem in this day and age, but we do. Our database has datetime columns, and when the dates are pulled out from the database, they are retrieved as CDT (this time of year, CST in the winter). That time is then passed as CDT to the UI through JSON. This could not be more wrong.
The time stored in the database is the time relative to the location specified in the data. So, if we have a trip going from Los Angeles at 6AM PDT to New York at 11PM EDT, then the start time will be retrieved from the database as 6AM CDT and the end time will be retrieved as 11PM CDT.
Requirements:
The UI needs to display in the time local to the data, 6AM and 11PM in the previous example.
The UI needs to indicate items in the near future, such as arrivals within the next 3 hours.
When the data is edited, it needs to be input in the same manner, the user enters 6AM in Los Angeles, and 11PM in New York.
The user also needs to be able to enter times relative to the current time, such as "H+5" for 5 hours from now.
The UI needs to sort based on time. This is more of a nice to have as the application they are used to using doesn't do this right either.
Our current solution is just burying our head in the sand and displaying it (untested for browsers in other timezones, such as those in our California office), which is actually surprisingly effective, even though it is not at all semantically correct.
11PM CDT is read from the database
It gets displayed as 11PM, and is understood by the user to be EDT
The user edits it, puts in 10PM
It is parsed back as 10PM CDT and saved that way, exactly as we want it.
Where the current solution fails miserably is in times relative to the current time.
11PM CDT is read from the database
It gets displayed as 11PM, and is understood by the user to be EDT
The user edits it, puts in "NOW" (assume the user's local clock is 9PM CDT)
It is parsed back as 9PM CDT and saved that way, but it should have been 10PM because it is 10PM in New York!
I'm looking for a way to handle these five cases that isn't totally hideous. I am open to a solution in any layer (architecture detailed above), but there are constraints because we share the database with another application. If there are additional tools/frameworks that would be useful and fit with what we already have, I am open to using them.
Database: SQL Server 2008
API: Rails with JSON responses
Frontend: JS + Moment + other stuff unrelated to dates
Any attempt to correct the data and/or schema is totally out of the question as we would break the other application.
The addition of new views/table columns/tables/stored procedures is usually possible.
The addition of indexes is NOT allowed. The status of any more exotic features is unknown.
There are many tables/endpoints that are affected by this problem, so any brute-force solution is going to be incredibly tedious.
Any solution only needs to work in the Continental US.
Note that this is not a simple timezone conversion as the timezone we get back from the database is straight up wrong, so conversions of the timezone will also be wrong.

Calculate resources in a webbrowser game in real time

I decided to write a web browser game. But my mind comes sick when I try to think how to code the resources shown of each player when this display the website.
For example:
User 1 have 500 gold now, and produces +100 gold each hour, how can I show the real resources when the user open the website?
What is the best way?
I think that update all the database of each user adding resources every second is suicidal.
The think is that I have no idea how to code.
Any ideas?
Thanks
When a user interacts with your website, look at the date of the last time you updated its gold amount. If it's more than 1 hour, increment the amount of gold of the number of hours passed since it's last interaction, and update the stored date.
You may do some optimisation on this principle to avoid testing it at each user request during a session (use a cache, of store the date in the session).
Update: store the next update time instead of the last, to avoid multiple calculations (that is to say store the timestamp of the current update + 1 hour). And then compare current time to the stored time.

One or two field to represent "current step" and "is or not finished" state?

Sorry if this question is too silly or neurotic... But I can't figure it out by myself. So I want to see how others deal with it.
My question is:
I want to write a program show progress of do some thing. So I need to record which state is it currently in so that someone can check it by anytime. there are two method:
Use two field to represent the progress state: step and is_finished.
Just one filed: step. For example, if this thing need 5 step, then 6 means finished. ( 0 means not started? )
Compare above two methods.
two field:
Seems more clear. And the most important is that logically speaking step and finished or not are two concepts? I'm not sure about this.
If thing are finished. We change is_finished field to true ( or 1 as you like ). But what to do with step field now? Plus one, or just not touch it because it has no meaning any more now?
one field:
Simple, space saving. But not very intuitive. For example, we don't know what 6 really means by just looking at this field because it may represent finish or middle step. It need other information e.g. total step to determine. And potentially this meaning is not very stable if the total steps will change ( is_finished field in two field method would not affected by this).
So How do you will deal with it? Thanks!
UPDATE:
I forgot some point maybe useful in the previous post:
The story is: We provide a web-based service for customers. (This service has time limitation e.g. 1 year term) After customer purchase it our deployment programe prepare hardware(virtual machine) and deploy some software which need some time to finish. And we want to provide progress info for customer. When deployment is finished, the customer should be informed.
Database design:
It need a usage state field to represent running normal, running but owe (expired), stop. What confusing me is should it include not deployed yet and deploying information or not?
The progress info should include some other info e.g. the start time so we can tell how much time elapsed since start. But this info is no need to be persistent because we won't care about these info as long as it's finished. So I decide to store these progress info in a separate (temporary) table. Then I think it need another field in another more persistent table to tell if things are done . So can we combine it into the usage state field mentioned above?
I like the one-field approach better, for the following reasons:
(Assuming you want to search on steps) you can "cover" all steps using only one simple index.
Should you ever want to attach some additional information to each of the steps, the one-field approach can easily accommodate a FOREIGN KEY towards a new table containing that information.
Requires slightly less storage space. Storage is cheap these days, but that's not the point - caching and network performance is.
Two-field approach:
(Assuming you want to search on steps) might require a "fatter" composite index or even two indexes (which takes space, lowers the cache effectiveness and incurs maintenance cost for INSERT/UPDATE/DELETE operations).
Requires a CHECK to defend the database from "impossible" combinations. Funny enough, some DBMSes don't enforce CHECKs (I'm looking at you, MySQL).
Requires slightly more storage space (and therefore slightly less of it fits into cache, takes up slightly more network bandwidth etc.).
NOTE: Should you choose to use NULLs, that could have "interesting" consequences under certain DBMSes (for example, Oracle doesn't index NULLs).
For example, we don't know what 6 really means
That doesn't really matter, as long as the client application knows what it means.
Design the database for applications, not humans.
And potentially this meaning is not very stable if the total steps will change
True, but you have the same problem with two-field approach as well, if new step is added in the "middle" of existing steps.
Either UPDATE the table accordingly,
or never change the step values. For example, if the step 5 is the last one, then newly added step 6 is considered earlier despite having greater value - your application (or the additional table I mentioned) will know the order of steps, even if their values are not ordered. If you really want "order by value" without resorting to UPDATE, make the steps: 10, 20, 30 etc, so you can insert new steps in the gaps (the old BASIC line number trick).
It remains a matter of taste but I would suggest the second option of a single int field step. On inserting a new record, initialize the value of step to 0 which would indicate "not started yet". Any positive integer value would obviously denote the current step. As soon as the trajectory is completed I would set step to NULL. As you correctly stated this method does require solid documentation but I think that it is not too confusing

Best Method For Storing Various Statistics in a Database

I'm developing a game where I will be storing all actions the user makes with their character as a statistic. If the player chooses to have his character attack with with a melee weapon. We increment a counter that counts the number of times that character has performed a melee attack. We also increment a counter that counts the number of times they have attacked with that particular weapon. Further, the character is capable of increasing in level and these statistics should all be recorded per level for the character. The character will also have attributes. Such as speed, fortitude, etc. Whenever one of these attribute's values is accessed I will increment a counter for that per level as well.
I am on a low budget so I am using SQL Server Express for this project. I know how I can accomplish this task with just my experience in databases but, admittedly, I have never recorded this type of data and to this degree. Can anyone offer any tips or advice that might seem out of the ordinary for someone with business application database experience?
When done, the data should be easily aggregated and selectable to use in various necessary calculations both in-game and as part of a statistics dashboard that will be part of the game.
If anyone has any specific schema suggestions as well that would be helful.
Thanks
It is really as easy as tying some code down to the action to update the stats.
The absolute fastest way is with a trigger, because it cuts down on round trips to the server, and is actually darn nice "encapsulation" of code and data. But SQL Server's triggers are a little funky, being only statement-level, so you can also do it in code.
In code you have the same idea, presumably some class code is responsible for the action with the item. When any action is taken that must be recorded, call a stat updater routine that names player, item, and other parameters, enough so the stat updater can figure out which table/column/row to go to and which stat to update.
Hope this helps.

Design question: How would you design a recurring event system? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
If you were tasked to build an event scheduling system that supported recurring events, how would you do it? How do you handle when an recurring event is removed? How could you see when the future events will happen?
i.e. When creating an event, you could pick "repeating daily" (or weekly, yearly, etc).
One design per response please. I'm used to Ruby/Rails, but use whatever you want to express the design.
I was asked this at an interview, and couldn't come up with a really good response that I liked.
Note: was already asked/answered here. But I was hoping to get some more practical details, as detailed below:
If it was necessary to be able to comment or otherwise add data to just one instance of the recurring event, how would that work?
How would event changes and deletions work?
How do you calculate when future events happen?
I started by implementing some temporal expression as outlined by Martin Fowler. This takes care of figuring out when a scheduled item should actually occur. It is a very elegant way of doing it. What I ended up with was just a build up on what is in the article.
The next problem was figuring out how in the world to store the expressions. The other issue is when you read out the expression, how do those fit into a not so dynamic user interface? There was talk of just serializing the expressions into a BLOB, but it would be difficult to walk the expression tree to know what was meant by it.
The solution (in my case) is to store parameters that fit the limited number of cases the User Interface will support, and from there, use that information to generate the Temporal Expressions on the fly (could serialize when created for optimization). So, the Schedule class ends up having several parameters like offset, start date, end date, day of week, and so on... and from that you can generate the Temporal Expressions to do the hard work.
As for having instances of the tasks, there is a 'service' that generates tasks for N days. Since this is an integration to an existing system and all instances are needed, this makes sense. However, an API like this can easily be used to project the recurrences without storing all instances.
I've had to do this before when I was managing the database end of the project. I requested that each event be stored as separate events. This allows you to remove just one occurrence or you could move a span. It's a lot easier to remove multiples than to try and modify a single occurrence and turn it into two. We were then able to make another table which simply had a recurrenceID which contained the information of the recurrence.
#Joe Van Dyk asked: "Could you look in the future and see when the upcoming events would be?"
If you wanted to see/display the next n occurences of an event they would have to either a) be calculated in advance and stored somewhere or b) be calculated on the fly and displayed. This would be the same for any evening framework.
The disadvantage with a) is that you have to put a limit on it somewhere and after that you have to use b). Easier just to use b) to begin with.
The scheduling system does not need this information, it just needs to know when the next event is.
When saving the event I would save the schedule to a store (let's call it "Schedules" and I'd calculate when the event was to fire the next time and save that as well, for instance in "Events". Then I'd look in "Events" and figure out when the next event was to take place and go to sleep until then.
When the app "wakes up" it would calculate when the event should take place again, store this in "Events" again and then perform the event.
Repeat.
If an event is created while sleeping the sleep is interrupted and recalculated.
If the app is starting or recovering from a sleep event or similar, check "Events" for passed events and act accordingly (depending on what you want to do with missed events).
Something like this would be flexible and would not take unnecessary CPU cycles.
Off the top of my head (after revising a couple things while typing/thinking):
Determine the minimum recurrence-resolution needed; that's how often the app runs. Maybe it's daily, maybe every five minutes.
For each recurring event, store the most recent run time, the run-interval and other goodies like expiration time if that's desirable.
Every time the app runs, it checks all events, comparing (today/now + recurrenceResolution) to (recentRunTime + runInterval) and if they coincide, fire the event.
When I wrote a calendar app for myself mumble years ago, I basically just stole the scheduling mechanism from cron and used that for recurring events. e.g., Something taking place on the second Saturday of every month except January would include the instruction "repeat=* 2-12 8-14 6" (every year, months 2-12, the 2nd week runs from the 8th to the 14th, and 6 for Saturday because I used 0-based numbering for the days of the week).
While this makes it quite easy to determine whether the event occurs on any given date, it is not capable of handling "every N days" recurrence and is also rather less than intuitive for users who aren't unix-savvy.
To deal with unique data for individual event instances and removal/rescheduling, I just kept track of how far out events had been calculated for and stored the resulting events in the database, where they could then be modified, moved, or deleted without affecting the original recurrent event information. When a new recurring event was added, all instances were immediately calculated out until the existing "last calculated" date.
I make no claim that this is the best way to do it, but it is a way, and one which works quite well within the limitations I mentioned earlier.
If you have a simple reoccuring event, such as daily, weekly or a couple days a week, whats wrong with using buildt in scheduler/cron/at functionallity? Creating an executable/console app and set up when to run it? No complicated calendar, event or time management.
:)
//W

Resources