I have an issue with computed fields in aurelia framework...
Background:
eg: we have tree structure of classes (3 levels) for better expression we have HouseOfFlats, Floors and Flats. All classes are json array, every class has some properties as Price.
And what I need:
I need to create class 'Compute' which encapsulate the observe of the fields and the class input will be function like
this.Price = ko.computed(function() {
return self.Quantity() * $Flat.PricePerBoxStatic();
});
Meaning, 1 house of flats, 3 floors, 5 flats on each floor. And when I change the price on flat I need to compute the price of all falts on the floor and the price of whole houseofflats. So the prices will be recalculated in whole tree immediately the price of flat has changed.
Thank you all for any idea how to solve this with some smart solution.
picture for better understanding:
so let's say total is what you are looking for.
in your view model:
get total(): number {
// put here your calculation logic and return your total
}
in your view, simply use string interpolation:
<p>${total}</p>
whenever any of the variables that participate in the calculation of total change its values - the total will be recalculated and you will see the updated value in the view.
Related
I have a following time scheduling optimisation problem:
There are n breaks to be scheduled. A break takes up k time grains of 15 minutes each. The total horizon I am looking at is of m time grains. Each time grain has a desired amount of breaks to optimise for. The range to start a break at is defined per break, you cannot freely pick the range.
To make it more general - there is a distribution of breaks over time as a goal. I need to output a result which would align with this desired distribution as much as possible. I am allowed to move each break within certain boundaries, e.g. 1 hour boundary.
I had a look at the TimeGrain pattern as a starting point which is described here: https://www.optaplanner.org/blog/2015/12/01/TimeSchedulingDesignPatterns.html and in this video: https://youtu.be/wLK2-4IGtWY. I am trying to use Constraint Streams for incremental optimisation.
My approach so far is following:
Break.scala:
case class Break(vehicleId: String, durationInGrains: Int)
TimeGrain.scala:
#PlanningEntity
case class TimeGrain(desiredBreaks: Int,
instant: Instant,
#CustomShadowVariable(...), // Dummy annotation, I want to use the entity in constraint stream
var breaks: Set[Break])
BreakAssignment:
#PlanningEntity
case class BreakAssignment(
break: Break,
#PlanningVariable(valueRangeProviderRefs = Array("timeGrainRange"))
var startingTimeGrain: TimeGrain,
#ValueRangeProvider(id = "timeGrainRange")
#ProblemFactCollectionProperty #field
timeGrainRange: java.util.List[TimeGrain],
#CustomShadowVariable(
variableListenerClass = classOf[StartingTimeGrainVariableListener],
sources = Array(new PlanningVariableReference(variableName = "startingTimeGrain"))
)
var timeGrains: util.Set[TimeGrain]
)
object BreakAssignment {
class StartingTimeGrainVariableListener extends VariableListener[Solution, BreakAssignment] {
override def afterVariableChanged(scoreDirector: ScoreDirector[Solution], entity: BreakAssignment): Unit = {
val end = entity.startingTimeGrain.instant
.plusSeconds((entity.break.durationInGrains * TimeGrain.grainLength).toSeconds)
scoreDirector.getWorkingSolution.timeGrains.asScala
.filter(
timeGrain =>
timeGrain.instant == entity.startingTimeGrain.instant ||
entity.startingTimeGrain.instant.isBefore(timeGrain.instant) && end
.isAfter(timeGrain.instant)
)
.foreach { timeGrain =>
scoreDirector.beforeVariableChanged(timeGrain, "breaks")
timeGrain.breaks = timeGrain.breaks + entity.break
scoreDirector.afterVariableChanged(timeGrain, "breaks")
}
}
}
}
Constraints.scala:
private def constraint(constraintFactory: ConstraintFactory) =
constraintFactory
.from(classOf[TimeGrain])
.filter(timeGrain => timeGrain.breaks.nonEmpty)
.penalize(
"Constraint",
HardSoftScore.ONE_SOFT,
(timeGrain: TimeGrain) => {
math.abs(timeGrain.desiredBreaks - timeGrain.breaks.size)
}
)
As you can see I need to iterate over all the grains in order to find out which ones needs to be updated to hold the break which was just moved in time. This somewhat negates the idea of Constraint Streams.
A different way to look at the issue I am facing is that I cannot come up with an approach to link the BreakAssignment planning entity with respective TimeGrains via e.g. Shadow Variables. A break assignment is spanning multiple time grains. A time grain in return contains multiple break assignments. For the soft constraint I need to group all the assignments within the same grain, accessing the desired target break count of a grain, while doing this for all the grains of my time horizon. My approach therefore is having each grain as a planning entity, so I can store the information of all the breaks on each change of the starting time grain of the assignment himself. What I end up is basically a many-to-many relationship between assignments and time grains. This does not fit into the inverse mechanism of a shadow variable from my understanding as it needs to be a one-to-many relationship.
Am I going in the wrong direction while trying to come up with the correct model?
If I understand properly what you mean, then conceptually, in the TimeGrain class, I would keep a (custom) shadow variable keeping (only) the count of Break instances that are overlapping that TimeGrain (instance). Let me call it breakCount for simplicity. Let me call x the number of TimeGrains a Break spans.
So, upon the solver assigning a Break instance to a TimeGrain instance, I would increment that TimeGrain instance's breakCount. Not only thát TimeGrain instance's breakCount, but also the breakCount of the next few (x-1) TimeGrain instances. Beware to wrap each of those incrementations in a "scoreDirector.beforeVariableChanged()"-"scoreDirector.afterVariableChanged()" bracket.
The score calculation would do the rest. But do note that I myself would moreover also square the difference of a TimeGrain's ideal breakCount and it's "real" breakCount (i.e. the shadow variable), like explained in OptaPlanner's documentation, in order to enforce more "fairness".
Edit : of course also decrement a TimeGrain's breakCount upon removing a Break instance from a Timegrain instance...
I wonder, where general (or util functions) should be placed?
For example:
public class Credit {
private Integer _duration;
private Double _interestRate;
private Integer _creditSum;
private PaymentStream _paymentStream;
private Date _openDate;
}
PaymentStream impements strategy pattern for gettin paymentList.
Question:
I have a construnctor (duration, interestRate, creditSum, paymentStream, openDate). But I also want followin functions:
getCreditDuration(creditSum, monthlyPayments, interestRate)
getCreditSum(montlyPayment, interestRate, duration)
etc
Obviously, they can't be on credit instance, as I don't have enough info for a constructor. So where they should be placed?
Added: I've also need to store all the calculations (getCreditDuration, etc) into db. So, if this is static functions returning double(int) I can't image of a good way to store them into DB. What object should I save?
Requirments are: user can choose between Duration calculation and Credit sum calculation (and etc.) There are separate views for calculations. Every time user click "Calculate button" calculation result must be persisted into DB. User can has a view with all calculation, where he can click any item.
For ex (с means value is calculated):
Sum Duration Interest Payment
10000 2 yrs 12% 1000(с) -> opens view to calculate monthly payment
12000(с) 3 yrs 10% 1200 -> opens view to calculate credit sum
They are stateless methods (all data they work on is passed as a parameter) whose logic is clearly tied the concepts of the Credit object. So one possibility is just to make them static methods of the Credit class.
I'm trying to develop a survey application that can deal with various types of responses, such as boolean, multiple choice, as well as ranges from 1-5, 1-10, 1-100, -2 to +2, even decimal values. So, I've created a hierarchy of Response types:
class Response {
String name
}
class BooleanResponse extends Response {
boolean score
}
class SimpleGradeResponse extends Response {
char score // A-F
}
class ComplexGradeResponse extends Response {
char score // A-F
char modifier // +, -, blank
}
class IntegerResponse extends Response {
int min, max, score
}
class DecimalResponse extends Response {
double min, max, score
}
I think of that as the metadata. It describes the survey response types. You could have question 1 that's an IntegerResponse from 1 to 10, question 2 that's an IntegerResponse from 0-100, question 3 that's a DecimalResponse, etc.
Where I'm uncertain is where to store the actual responses from users. Do you mingle the scores in with the metadata, as I've done with the score field above? That seems awkward, since every range-type response carries with it the min and max.
What I really want (I think) is to be able to curry the range response parameters to create a new type, and then reflect that type in a table of actual responses. So, a question that takes a 1-10 range would be a row in IntegerResponse with min=1 and max=10. But how does the ActualResponse table (I need to improve the naming convention, once I figure this out!) hold a score and refer to the curried IntegerResponse with min and max set?
If there is a better way to approach this whole problem, I'm eager to hear it.
Thanks,
Lee
min and max should rather be stored in a Question object, or even in QuestionType - depending on how flexible the system should be in runtime.
Will there be arbitrary limitations to different kinds of Responses? Data structure hugely depends on it. You can either hardcode different Response types or support them in runtime. First approach is one order of magnitude simpler.
I'm wrangling with issues regarding how character equipment and attributes are stored within my game.
My characters and equippable items have 22 different total attributes (HP, MP, ATP, DFP). A character has their base-statistics and can equip up to four items at one time.
For example:
BASE ATP: 55
WEAPON ATP: 45
ARMOR1 ATP: -10
ARMOR2 ATP: -5
ARMOR3 ATP: 3
Final character ATP in this case would be 88.
I'm looking for a way to implement this in my code. Well, I already have this implemented but it isn't elegant. Right now, I have ClassA that stores these attributes in an array. Then, I have ClassB that takes five ClassA and will add up the values and return the final attribute.
However, I need to emphasize that this isn't an elegant solution.
There has to be some better way to access and manipulate these attributes, including data structures that I haven't thought of using. Any suggestions?
EDIT: I should note that there are some restrictions on these attributes that I need to be put in place. E.g., these are the baselines.
For instance, the character's own HP and MP cannot be more than the baseline and cannot be less than 0, whereas the ATP and MST can be. I also currently cannot enforce these constraints without hacking what I currently have :(
Make an enum called CharacterAttributes to hold each of STR, DEX, etc.
Make an Equipment class to represent any equippable item. This class will have a Dictionary which is a list of any stats modified by this equipment. For a sword that gives +10 damage, use Dictionary[CharacterAttributes.Damage] = 10. Magic items might influence more than one stat, so just add as many entries as you like.
The equipment class might also have an enum representing which inventory it slots to (Boots, Weapon, Helm).
Your Character class will have a List to represent current gear. It will also have a dictionary of CharacterAttributes just like the equipment class, which represents the character's base stats.
To calculate final stats, make a method in your Character class something like this:
int GetFinalAttribute(CharacterAttributes attribute)
{
int x = baseStats[attribute];
foreach (Equipment e in equipment)
{
if (e.StatModifiers[attribute] != null)
{
x += e.StatModifiers[attribute];
}
}
// do bounds checking here, e.g. ensure non-negative numbers, max and min
return x;
}
I know this is C# and your post was tagged VB.NET, but it should be easy to understand the method. I haven't tested this code so apologies if there's a syntax error or something.
Let's say I have to model the meals of a diner.
A meal can consist of several "components":
(Fries OR rice OR wedges)
AND (One of six different beverages)
AND (One or two out of seven different sauces OR none at all)
Another meal can consist of:
(Salad OR rice)
AND (Garlic OR no garlic)
Further meals can consist of:
Just fries
Just a beverage
Just ...
How can I model this? (UML, entity-relationship, code, ... whatever you can explain best)
Perhaps it helps if you know some tasks I want to perform, so:
Allowing the customer to choose a meal first and display all remaining "add-ons".
Detecting a meal from a list of components. For example if the customer ordered fries, a sauce and a beverage, it should be possible to detect the meal from the first example.
I've thought about dividing all components into articles and then adding some kind of role mapping to mark "fries" as supplement to "cheeseburger", "schnitzel", "..." but then I wondered, how I could model multiple add-ons, optional add-ons, n-out-of-m add-ons...
I hope you can help me out...
If this is homework, it may not matter...
But - if this is going to be used in a real-world app, I would strongly recommend against using concrete classes for each food item ie. Coke class, Salad class, Rice class, etc. as recommended above.
This is a sure way to make your application inflexible.
It would be much better to have a food item class and a drink class with a name property or some such..
Imagine having to rebuild your whole application just because there is now a new special or food item... not cool ;).
I think what is missing from the other answers is the idea of a group.
Each food item could belong to a group along with other items, or by itself.
Say fries, rice, and wedges belong to group A. Drinks belong to group B.
Then you could model a combo as a list of groups - ie. 1 group A item and 1 group B item, or two group A items and1 group B item.
You could also make food items able to belong to multiple groups at the same time... to make the options more flexible.
The db model could get complicated defining all of the relationships, but I think it's necessary.
Perhaps something like this:
group(id, name, desc) - group of like items - entrees, appetizers, drinks... or anything
foodItem(id, name, desc) - represents a single item - fries, rice, etc.
foodItem_group(foodIgem_Id, group_Id) - maps food items to their group - many to many
combo(id, name, desc) - describes a combo
combo_group(combo_Id, group_Id) - maps groups to combos - many to many
I think this would do for representing the basic required model - you may want additional tables to store what the customer actually ordered.. and of course detecting if a customer order matches a combo is left up to your business logic.
It seems like an order can consist of either meals, components, or a mix of both, so I would say, have an Order class that has a list of Components and Meals. Meal should either subclass Component, or they should implement the same interface.
A Meal consists of several "slots," which can be filled by some set of Components. Meals should know how many slots they have and what Components can fill them.
The "detecting a Meal from a list of Components" question is tricky. Off the top of my head, the best way I can think of is giving each Meal a method that takes a list of Components and returns true if that Meal can be made from them (or maybe the subset of Components that would make up that Meal). Order would go through the list of Meals it knows about and see if any of them can be made from the Components in the current Order. There may be a better way to do this, though.
Hope this helps!
Create Component class, and sublcasses (or objects) for all possible types of Components.
Create an abstract Meal class, and subclasses for all possible types of Meals. A Meal can check, whether a certain list of Components matches it (for detecting a meal from a list of components). And a Meal can present to a customer all the choices of components for this meal.
I agree with Amanda that the Meal should be built of the "Slots". Each slot represents one of the Component choices of the Meal, e.g. Fries OR rice OR wedges. A Slot may also model the m-outof-n option.
The Meal class:
class Meal
{
class MealSlot
{
Add(Component);
bool DoesItMatch(vector<Component> ComponentsVector)
{
//Check if this Slot is filled by some element(s)
// of ComponentsVector
}
PrintSlotOptions();
vector<Component> Options;
// for m-of-n option, if multiple items can be chosen in this slot
int HowManyNeededToFillIt;
};
bool DoesItMatch(vector<Component> ComponentsVector)
{
//Check if all Slots are filled by ComponentsVector elements,
//using Slot::DoesItMatch function
}
void PresentChoices()
{
for(i=0; i < Slots.size(); i++)
Slots[i].PrintSlotOptions;
}
vector<Slot> Slots;
};
One of Concrete Meals: (Salad OR rice) AND (Garlic OR no garlic)
class MealType2 : public Meal
{
MealType2()
{
Slots[0].Add(Salad);
Slots[0].Add(Rice);
Slots[1].Add(Garlic);
Slots[1].Add(NOTHING);
}
};
Create an Order class which will contain a Meal name, and a list of Components. If a Meal is ordered, call Meal.PresentChoices() . And if a list of Components is given, go over all the Meals and call Meal.DoesItMatch .
I assume this will eventually get stored in a database. I suggest to create two tables:
Would store the components (fries, salad, garlic, etc)
Would have: id1, id2, relationship. Relationship being:
belongs to
goes with
Based on the "belongs to" relationship, you could find if all components belong to a certain meal. Maybe then go and select all components that belong to that meal and suggest the meal if the components selected make up 50% or more of the meal.
Based on the "goes with" relationship, you could suggest add-ons to the meal, or to the components selected.
seems like you meal can be almost any collection of food items, so start with one abstract base class (or interface) for a Food. make lots of concrete subclasses, one for each food: coke, tea, steak, chicken, potato, rice, pasta, soup, salad, etc.
make your components interfaces: appetizer, dinner, protein, starch, dessert, drink, etc.
refactor your concrete classes into whatever hierarchy they seem to want to go into as you write code and tests.
sprinkle in the component interfaces where they make sense.