How can I ensure that services occur in the same route using constraints? - traveling-salesman

I'm trying to use Jsprit constraints to ensure that a solution route has a specific set of services.. Given the services [S1, S2, S3, ..., S10], I want to ensure that services [S2, S4, S6] occur in the same route..
For this, I am using HardRouteConstraint..
#Override
public boolean fulfilled(JobInsertionContext context) {
// jobIds = [S2, S4, S6]
Job thisJob = context.getJob();
if (jobIds.contains(thisJob.getId())) {
for (String jobId : jobIds) {
VehicleRoute route = stateManager.getProblemState(stateManager.createStateId(jobId), VehicleRoute.class);
// if the jobs are assigned to a different route, reject this route
if (route != null && route != context.getRoute()) return false;
}
}
return true;
}
This works partially fine.. If S2, S4 and S6 are part of the solution, they appear in a single route, and are not split between different routes..
The problem is that if I have a limited vehicle capacity (say, 3), Jsprit can possibly return a solution like:
Routes: [
[S1, S2, S3]
[S5, S7, S8]
[S9, S10]
]
Unassigned Jobs: [S4, S6]
This is understandable, but not what I want.. I want that if a route includes S2, it should also include S4 and S6, in any order..
How can I ensure that a valid solution does not contain such routes: [X, S2, Y] or [S2, X, S4]..
Thanks,
Asim

Related

The problem of determining whether this is a piece of land in land map array

This is an issue in typescript.
As such, I have a variable with various string entries in the form of x, y position.
["3,3","3,4","3,5","2,3","2,4","2,5","-1,-2","-2,- 2","-2,-1"]
I want to know if this piece of land is one piece or several pieces.
Establish the mathematical guidelines
Two tiles are neighbors if they are different by a value of 1 in either x or y (but not both).
If you only need to determine whether they are all connected, then you really need to determine that every pair of vertices have a path from one to the other.
Plan the coding implementation
One way to go about this is to create an empty land mass array, start by adding a single tile from the source array, then you add each tile in the source array to the land mass array if it is a neighbor to one of the items in the land mass. If it does not have a neighbor, it may just not have one on the land mass yet, so we add it to a deferred queue and return to those when we have exhausted the source.
This method has O(n^2) complexity, but maybe someone else has a better solution computationally.
Give it a try
let source = [...coordinateArray]; // from prop or API or wherever
let landMass = [];
let deferred = [];
while(source.length) {
// add the tile if it has a neighbor on the land mass
// defer the tile if it does not have a neighbor on the land mass
source.forEach(pair1 => {
const [x1, y1] = pair1.split(",");
const hasNeighbor = !landMass.length || landMass.some(pair2 => {
const [x2, y2] = pair2.split(",");
// return "true" if off by 1 in x or y position and 0 in the other
return (Math.abs(x1 - x2) === 1 && y1 === y2) || (Math.abs(y1 - y2) === 1 && x1 === x2);
});
// push tile to landMass or to defer queue
if(hasNeighbor) {
landMass.push(pair1);
} else {
deferred.push(pair1);
}
});
// if source is now the same as deferred,
// then nothing was added to the land mass
// therefore it is disconnected and we can break out
if(source.length === deferred.length) {
break;
}
// otherwise, we have exhausted the source,
// so we move the "deferred" to the "source"
// and empty the "deferred" to repeat
source = [...deferred];
deferred = [];
// if the deferred queue had length 0,
// then we will break out of the while loop
}
// if the source has length > 0, then some tiles could not be mapped
// in that case, it is disconnected
// if the source has no length, then everything was mapped to the land mass
// in that case, it is connected
const allTilesAreConnected = !source.length;

Writing Rust-y code: Keeping references to different structs depending on type of object in XML

I'm having a hard time formulating this in a rust-y manner, since my brain is still hardwired in Python. So I have a XML file:
<xml>
<car>
<name>First car</name>
<brand>Volvo</brand>
</car>
<plane>
<name>First plane</name>
<brand>Boeing</brand>
</plane>
<car>
<name>Second car</name>
<brand>Volvo</brand>
</car>
</xml>
In reality it's much more complex and the XML is about 500-1000MB large. I'm reading this using quick-xml which gives me events such as Start (tag start), Text and End (tag end) and I'm doing a state machine to keep track.
Now I want to off-load the parsing of car and plane to different modules (they need to be handled differently) but share a base-implementation/trait.
So far so good.
Now using my state machine I know when I need to offload to the car or the plane:
When I enter the main car tag I want to create a new instance of car
After that, offload everything until the corresponding </car> to it
When we reach the end I'm going to call .save() on the car implementation to store it elsewhere, and can free/destroy the instance.
But this means in my main loop I need to create a new instance of the car and keep track of it (and the same for plane if that's the main element.
let mut current_xml_section: I_DONT_KNOW_THE_TYPE = Some()
loop {
match reader.read_event(&mut buf) {
Ok(Event::Start(ref e)) => {
if state == State::Unknown {
match e.name() {
b"car" => {
state = State::InSection;
current_section = CurrentSection::Car;
state_at_depth = depth;
current_xml_section = CurrentSection::Car::new(e); // this won't work
},
b"plane" => {
state = State::InSection;
current_section = CurrentSection::Plane;
state_at_depth = depth;
current_xml_section = CurrentSection::Plane::new(e); // this won't work
},
_ => (),
};
}else{
current_xml_section.start_tag(e); // this won't work
}
depth += 1;
},
Ok(Event::End(ref e)) => {
depth -= 1;
if state == State::InSection && state_at_depth == depth {
state = State::Unknown;
current_section = CurrentSection::Unknown;
state_at_depth = 0;
current_xml_section.save(); // this won't work
// Free current_xml_section here
}else{
if state == State::InSection {
current_xml_section.end_tag(e) // this won't work
}
}
},
// unescape and decode the text event using the reader encoding
Ok(Event::Text(e)) => (
if state == State::InSection {
current_xml_section.text_data(e) // this won't work
}
),
Ok(Event::Eof) => break, // exits the loop when reaching end of file
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
_ => (), // There are several other `Event`s we do not consider here
}
// if we don't keep a borrow elsewhere, we can clear the buffer to keep memory usage low
buf.clear();
}
}
So I basically don't know how to keep a reference in the main loop to the "current" object (I'm sorry, Python term), given that:
We may or may not have a current tag we're processing
That section might be a reference to either Car or Plane
I've also considered:
Use Serde, but it's a massive document and frankly I don't know the entire structure of it (I'm black box decoding it) so it would need to be passed to Serde in chunks (and I didn't manage to do that, even though I tried)
Keeping a reference to the latest plane, the latest car (and start by creating blank objects outside of the main loop) but it feels ugly
Using Generics
Any nudge in the right direction would be welcome as I try to un-Python my brain!
Event driven parsing of XML lends itself particularly well to a scope driven approach, where each level is parsed by a different function.
For example, your main loop could look like this:
loop {
match reader.read_event(&mut buf) {
Ok(Event::Start(ref e)) => {
match e.name() {
b"car" => handle_car(&mut reader, &mut buf)?,
b"plane" => handle_plane(&mut reader, &mut buf)?,
_ => return Err("Unexpected Tag"),
}
},
Ok(Event::Eof) => break,
_ => (),
}
}
Note that the inner match statement only has to consider the XML tags that can occur at the top level; any other tag is unexpected and should generate an error.
handle_car would look something like this:
fn handle_car(reader: &mut Reader<&[u8]>, buf:&mut Vec<u8>) -> Result<(),ErrType> {
let mut car = Car::new();
loop {
match reader.read_event(buf) {
Ok(Event::Start(ref e)) => {
match e.name() {
b"name" => {
car.name = handle_name(reader, buf)?;
},
b"brand" => {
car.brand = handle_brand(reader, buf)?;
},
_ => return Err("bad tag"),
}
},
Ok(Event::End(ref e)) => break,
Ok(Event::Eof) => return Err("Unexpected EOF"),
_ => (),
}
}
car.save();
Ok(())
}
handle_car creates its own instance of Car, which lives within the scope of that function. It has its own loop where it handles all the tags that can occur within it. If those tags contain yet more tags, you just introduce a new set of handling functions for them. The function returns a Result so that if the input structure does not match expectations the error can be passed up (as can any errors produced by quick_xml, which I have ignored but real code would handle).
This pattern has some advantages when parsing XML:
The structure of the code matches the expected structure of the XML, making it easier to read and understand.
The state is implicit in the structure of the code. No need for state variables or depth counters.
Common tags, that appear in multiple places (such as <name> and <brand> can be handled by common functions that are re-used
If the XML format you are parsing has nested structures (eg. if <car> could contain another <car>) this is handled by recursion.
Your original problem of not knowing how to store the Car / Plane within the main loop is completely avoided.

Why does variable === "Work" evaluate to false when the value is set to "work"?

I'm working with two different lists(arrays) which, in theory, are supposed to store different kind of information. Down below are the two arrays.
let items = ["Buy Food", "Cook Food", "Eat Food"];
let workItems = [];
The code below is responsible for assigning values to each array, based on the value(name of the list to which the item belongs) passed to the function .
app.post("/", function(req, res){
let item = req.body.newItem;
var a = req.body.list;//this variable stores the list name
var b = "Work";
console.log(a, b);// When 'a' is "Work", this prints: "Work" "Work"
//My problem starts here
//When the value stored in 'a' is "Work", the comparison below never returns true, even though they're >//the same thing.
if ( a === b){
//never got here!
workItems.push(item);
console.log(workItems);//At this stage it shouldn't be an ampty array
res.redirect ("/work");
} else{
items.push(item);
res.redirect ("/");
console.log(workItems)
}
});
Terminal: terminal
complete code link https://controlc.com/8931bb24
On your screenshot, it looks like there are two spaces between the Work Work console output. One possible reason is that you actually get Work as variable a. If you want to ignore this you can use trim():
if (a.trim() === b)
Moreover, if you are interested only in semantic meaning and not the case to can compare to a lower-cased string:
if (a.trim().toLowerCase() === 'work')
If that is not working for you, you should check more thoroughly what is the value of a, most probably, it's not 'Work' exactly.

Nestjs & TypeOrm: No results from Query Builder using getOne() / getMany()

I don't get this. I have a service that injects entity repositories and has dedicated methods to do some business logic and functions.
Beside that I expose a method that just returns QueryBuilder - to avoid injecting repositories all over the place - for a few occasions when other service needs just a quick query:
type EntityFields = keyof MyEntity;
entityQueryBuilder(alias?: string, id?: number, ...select: EntityFields[]) {
const q = this.entityRepository.createQueryBuilder(alias);
if (id) {
q.where({id});
}
if (select) {
q.select(select);
}
return q;
}
Now when I am trying to use this and call:
const r = await service.entityQueryBuilder('a', 1, 'settings').getOne();
the result is always empty although in the log the generated SQL is correct.
However when I do:
const r = await service.entityQueryBuilder('a', 1, 'settings').execute();
I get (almost) what I need. I get array instead of an entity object directly but the data are there.
I am unhappy though as I need to map the result to the object I wanted, which is something that getOne() should do on my behalf. getMany() does not return results either.
What did I do wrong?
Edit:
FWIW here is the final solution I came up with based on the hint in accepted reply:
entityQueryBuilder(id?: number, ...select: EntityFields[]) {
const q = this.entityRepository.createQueryBuilder('alias');
if (id) {
q.where({id});
}
if (select) {
q.select(select.map(f => `alias.${f}`));
}
return q;
}
Admittedly it has hardcoded alias but that I can live with and is OK for my purpose.
Hope this helps someone in the future.
It happens because you put no really proper select. In your case, you need a.settings instead of settings:
const r = await service.entityQueryBuilder('a', 1, 'a.settings').getOne(); // it should works

How to apply filter on finch endpoint without using finagle filters?

I have more than one endpoints.I am able to apply common filters on endpoints using finagle filter.But now I want to apply a filter on a specific endpoint.
How can I achieve this?
I had a similar question (for basic authentication filtering) that popped up while playing with redbubble's finch template which I partially solved in the following way:
class AuthenticatedEndpoint[A](e: Endpoint[A]) extends Endpoint[A] { self =>
final def apply(mapper: Mapper[A]): Endpoint[mapper.Out] = mapper(self)
final def apply(input: Input): Endpoint.Result[A] =
if (checkSession(input.request)) {
e(input)
} else {
// TODO return something meaningful to the caller (if possible?)
EndpointResult.Skipped
}
}
object AuthenticatedEndpoint {
def validSession[A](e: Endpoint[A]): Endpoint[A] = new AuthenticatedEndpoint(e)
}
(with checkSession returning true if all is well with the request). Then my api is defined as:
val api = "v1" :: loginApi :+: validSession(peopleApi :+: healthApi :+: adminApi)
This works well in the sense that requests without a session won't have access to the endpoints passed to validSession, but I have yet to find an easy way to return an error message to the caller, and I'd be curious to know if I chose the right path here.
This is how I got around it. It's probably not ideal but works.
class AuthenticatedEndpoint[A](e: Endpoint[A])(implicit auth: Request => Boolean) extends Endpoint[A] { self =>
final def apply(mapper: Mapper[A]): Endpoint[mapper.Out] = mapper(self)
final def apply(input: Input): Endpoint.Result[A] =
if (auth(input.request)) {
e(input)
} else {
EndpointResult.Matched[Nothing](input, Rerunnable( Unauthorized(new Exception(s"Authentication Failed."))) )
}
}
object AuthenticatedEndpoint {
def validSession[A](e: Endpoint[A]): Endpoint[A] = new AuthenticatedEndpoint(e)
}

Resources