Handling Cyclic Dependencies in GUI Components - oop

I have a design problem for which I'm sure a design pattern exists, and I want to know that pattern and get more insight into the best practice for attacking it.
I have an interactive interface for entering a time interval. This time interval has restrictions on the number of days (d), hours (h), minutes (m) and seconds(s):
d <= c (c is given)
h:m:s <= 5:30:00
In the above interface, you can manually change the knobs (those circular gauges) to obtain a value for every parameter (there are 4 knobs, 3 concentric and 1 independent). Besides, you can edit the textboxes yourself and the knobs are supposed to reflect your changes. Of course, as you rotate the knobs, you're getting changes in values during rotation, not after your movement stabilizes. This means a hell of events firing and numerous corner cases to handle. For example, imagine h:m:s to be 4:38:00 and the user increments the hours. Instead of the simple 5:38:00, it should be 0:08:00 besides incrementing the days, or 5:30:00 if the day is already a maximum.
What happens currently is that all the logic is written in the TextChanged event of the textboxes, and the knobs' ValueChanged events just change the text in the appropriate textbox thus firing its TextChanged event. So the general question is, how can one handle such a scenario - where many objects change each other and depend on each other in a circular way?? Notice that as you're rotating the knob, a change can be refused by the textbox thus reassigning a previous value to the knob's pointer "while rotating".

I think MVVM could apply well to your scenario. You have:
one model that contains days, hours, minutes and seconds, plus the business logic for handling changes to any of them and reflecting it on the others as required (in .NET you could use Dependency Properties)
two views: textboxes and knowbs
two viewmodels, one for each view, that can handle events from the view and pass them to the model, as well as handling changes on the model and reflecting them to the view
This approach isolates the two views and lets you maintain the logic around the values in one single place (the model or a Controller if you want to add an MVC pattern).
The viewmodels also encapsulate the way you want to handle events on the UI.

Related

Optaplanner, update shadow variables after every step

I am trying to add moves selectors which consider the state of the current working solution. For example, suppose in the cloud balancing problem I was trying to make a move which preferentially moved a process onto a computer which already holds few processes. I have a shadow variable which tracks the number of processes on the computer, then I have a valueSelector which implements SelectionProbabilityWeightFactory that gives a higher weight to computers with fewer processes.
This setup works fine and produces the moves that I want. But it is terribly slow because it is updating the shadow variable far more often than I need it to. Since I am not using this shadow variable for scoring, I don't need it to be updated after every move attempted during the step. I only need the shadow variable to be updated after each accepted move (i.e. the end of the step).
Alternately, I could use a custom move factory, but that requires that every computer have its process count fully re-calculated at each step. This means I would lose the incremental calculation benefit I get with the shadow variables.
So is there a way to force shadow variables to update after each step, rather than after each move. Or is there a better way to track the status of the working solution for use in move selectors?
Bad news first:
It's not possible to have VariableListener only update a shadow variable per step and not per move. And it's unlikely we'll ever want to allow that particular change, as it would hurt the predictability and integrity of the state of the domain model between move iterations. This could create a lot of havoc, including multiple forms of corruptions, if used slightly incorrectly.
Good news next:
Yes, you need to calculate some state per step to generate moves efficiently. This is a common problem I've run into a few times before too.
But why put that on the domain model? It doesn't belong there.
It belongs on the the move selector. For example, if you use a MoveIteratorFactory, that has a method called phaseStarted() (called when the phase starts) and a method createRandomMoveIterator() (called when a step starts even with SelectionCacheType.JIT).
Some something like this should do the trick:
public class MyMoveIteratorFactory implements MoveIteratorFactory<...> {
default void phaseStarted(ScoreDirector<...> scoreDirector) {
}
Iterator<Move_> createRandomMoveIterator(ScoreDirector<...> scoreDirector, Random workingRandom) {
List<Computer> alreadyUsedComputerList = ...; // runs once per step
return new MyIterator(alreadyUsedComputerList, workingRandom);
}
Now, the plot thickens when multiple move selectors need to reuse the same calculation. That's where SupplyManager comes into play, which is not public API. But this is definitely a good requirement for our "move streams API" experiment that we'll do next year.

Can I build auto-firing guns with ScriptCraft in Minecraft?

I am reading https://github.com/walterhiggins/ScriptCraft/blob/master/docs/YoungPersonsGuideToProgrammingMinecraft.md and want to try it out with my son.
I see there is a list of events available, though, being new to this mod, I am not sure I can implement what I am thinking of.
Say, I have a territory around my castle, say, square of 300x300 blocks on a plain field. I know the coordinates of the square.
Now, can I track if any mob intersects the bounds from outside to inside?
If it's possible, what's the event I should look for?
Then, can I add some mechanism that would through something in the direction of the mob's position? How could it look like? Or, even just signalling that a mob is in the zone.
Generally, I want to track mobs and do perform some actions for events.
First and foremost, kudos for exploring this with your son.
I wish I could provide exacting details, but my familiarity with ScriptCraft is limited. However, given that is based on Spigot (not Forge, as suggested in the comments), I can provide an answer from that perspective. I’ll leave the nitty-gritty details of accessing POJOs to your expertise with JavaScript.
While player movements fire PlayerMoveEvent events, there is no corresponding event for other entities/mobs. If there were, it would be a matter of checking whether an entity’s location has breached your perimeter and handling it accordingly.
The simplest approach would be to define a function that calls getLivingEntities() on a World, iterator over the list to determine the type of entity and perform whatever actions are desired; say, announce that it has breached your barrier. This function would be registered as a scheduled task with the BukkitScheduler as a repeating synchronous task. I found this example for scheduling a task, though it is for a single delayed asynchronous task.
load(__folder + "../drone/drone.js");
load(__folder + "../core/scriptcraft.js");
Drone.extend("big",function(){
server.scheduler.scheduleAsyncDelayedTask(global.plugin,function(){
(new Drone()).box(1,500,100,500);
print("done");
});
});
On a large server with many entities, the approach would be optimized by accessing each Chunk containing the protected area and retrieving entities contained therein with getEntities().

MVC with Objective-C. Where does formatting data for the view take place?

I'm working on an iPhone application and trying to conform to MVC as much as possible (I'm still learning). I have an Unsigned integer in my data model that represents a number of seconds. I want this to be displayed in a view in the format '00:00'(minutes:seconds). My question is, where should this formatting take place?
Is it the model object's responsibility to be able to provide it in this format?
Does the controller format this after taking it from the model but before passing it to the view?
Or does the view handle the formatting?
Thank you for any help.
If this formatting is only used in one place, the best solution is to put formatting into the view, and this approach often works quite well. If you do not have a custom view, however, then it is natural to put this work into the view controller. In Cocoa's version of MVC, view controllers are allowed broad flexibility in how they manage the views. (This is a significant place that Cocoa's MVC differs from SmallTalk's MVC, which it is based on.)
But what if you want to share the same formatting between views (or view controllers)? Then you factor out the formatting code into an NSFormatter subclass (or use an existing NSDateFormatter in your case). You can pass these around, put then in ivars, or even create a Singleton to hold them.
Why not just put it in the model in that case? Well, say you have four views that show the time this way, but you then add two other views that shows the time as 00:00.0, and then there's one accumulator view that shows hours and minutes. Now you have to keep expanding the model to handle these cases. The model is picking up more and more information about the views. Keeping the formatting in a formatter allows you to share the code (and bug fixes) without polluting the model with these details. And views that have very special formatting needs can still have their own custom code.
There's no need to create separate NSFormatter subclasses for every kind of formatting. You can create a single MYObjectFormatter class that takes options like "hours," "minutes," "seconds," etc. It would work just like an NSDateFormatter in this regard, and give the simplicity of use you need, while keeping your formatting code out of the model. This is exactly how NSDate and NSDateFormatter are partitioned.
You're likely to run into a range of opinions on that one.
Essentially, as it's purely presentational, I'd put it in the View layer; there's no control logic, it's entirely a question of formatting some existing data for display.

UITableViewController: Multiple Instance or multiple data sources?

I have a UITableViewController, I have 4 types of tabular data to present in the same format. Is it better to use one UITableViewController and reload data each time I need to present data, or should I create four UITableViewController instances with its own data source?
Points I considered (which I'm not sure if true):
I could save resources by reusing one instance of UITableViewController.
However, always calling UITableView's reloadData before presenting the grid might have impact on performance.
What is the best approach in terms of performance / memory consumption / best practice? Or is there no difference? Hope I am clear.
Update: To be exact, I have popover controllers with a table. I use it to as a "Selection Screen" for various fields in my screens.
The number of fields needing the popover are dynamic, so there can be 4 in one screen or upto 10 in another screen. The dilemma is should I create multiple instances of selection popover (one per field), or should I just use one selection screen and reload the data per field?
Short answer :
It doesn't really matter unless your data sets are massive (thousands of rows). Whatever is easiest for you is fine!
Long answer :
I would have a different one per data type - it's probably going to be a slightly more responsive ui if you do (as you pointed out, this comes at the cost of more memory usage).
However, I would use delayed instantiation i.e. only create them the first time they are asked for.
I would also release them if I received a low memory warning notification and they weren't visible.

How to fill Gtk::TreeModelColumn with a large dataset without locking up the application

I need to fill in a large (maybe not so much - several thousands of entries) dataset to a Gtk::TreeModelColumn. How do I do that without locking up the application. Is it safe to put the processing into separate thread? What parts of the application do I have to protect with a lock then? Is it only the Gtk::TreemodelColumn class, or Gtk::TreeView widget it is placed in, or maybe even surrounding frame or window?
There are two general approaches you could take. (Disclaimer: I've tried to provide example code, but I rarely use gtkmm - I'm much more familiar with GTK in C. The principles remain the same, however.)
One is to use an idle function - that runs whenever nothing's happening in your GUI. For best results, do a small amount of calculation in the idle function, like adding one item to your treeview. If you return true from the idle function, then it is called again whenever there is more processing time available. If you return false, then it is not called again. The good part about idle functions is that you don't have to lock anything. So you can define your idle function like this:
bool fill_column(Gtk::TreeModelColumn* column)
{
// add an item to column
return !column_is_full();
}
Then start the process like this:
Glib::signal_idle().connect(sigc::bind(&fill_column, column));
The other approach is to use threads. In the C API, this would involve gdk_threads_enter() and friends, but I gather that the proper way to do that in gtkmm, is to use Glib::Dispatcher. I haven't used it before, but here is an example of it. However, you can also still use the C API with gtkmm, as pointed out here.