Keep Overlapping Events On Top - javascript

I am using full calendar.
Here is a sample of the problem:
The problem being that non-working days should stay on top no matter what. Default Task should be sliding between nwd and super cool project.
Would anyone know what I could either do on serverside, which currently does:
var sortedList = eventList
.OrderBy(p => p.resource).
ThenBy(p => new
DateTime(ConvertFromUnixTimestamp(p.start).Year,
ConvertFromUnixTimestamp(p.start).Month,
ConvertFromUnixTimestamp(p.start).Day)
).ThenBy(p => !p.isDate)
.ThenBy(p => p.title).ToList();
List<dynamic> finalList = new List<object>();
for (int i = 0; i < sortedList.Count(); ++i)
{
var e = sortedList.ElementAt(i);
finalList.Add(
new
{
id = i.ToString(),
realid = e.realid,
isDate = e.isDate,
title = e.title,
start = ResolveStartDate(StartDate(ConvertFromUnixTimestamp(e.start).AddSeconds(i))),
end = e.end,
description = e.description,
allDay = e.allDay,
resource = e.resource,
editable = e.editable,
color = e.color
}
);
}
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(finalList);
Or client side, which fullcalendar seems to have:
function segCmp(a, b) {
//return (b.msLength - a.msLength) * 100 + (a.event.start - b.event.start);
return (a.event.start - b.event.start);
}
function segsCollide(seg1, seg2) {
//return seg1.end > seg2.start && seg1.start < seg2.end;
return false;
}
/* Event Sorting
-----------------------------------------------------------------------------*/
// event rendering utilities
function sliceSegs(events, visEventEnds, start, end) {
var segs = [],
i, len=events.length, event,
eventStart, eventEnd,
segStart, segEnd,
isStart, isEnd;
for (i=0; i<len; i++) {
event = events[i];
eventStart = event.start;
eventEnd = visEventEnds[i];
if (eventEnd > start && eventStart < end) {
if (eventStart < start) {
segStart = cloneDate(start);
isStart = false;
}else{
segStart = eventStart;
isStart = true;
}
if (eventEnd > end) {
segEnd = cloneDate(end);
isEnd = false;
}else{
segEnd = eventEnd;
isEnd = true;
}
segs.push({
event: event,
start: segStart,
end: segEnd,
isStart: isStart,
isEnd: isEnd,
msLength: segEnd - segStart
});
}
}
return segs.sort(segCmp);
}
// event rendering calculation utilities
function stackSegs(segs) {
var levels = [],
i, len = segs.length, seg,
j, collide, k;
for (i=0; i<len; i++) {
seg = segs[i];
j = 0; // the level index where seg should belong
while (true) {
collide = false;
if (levels[j]) {
for (k=0; k<levels[j].length; k++) {
if (segsCollide(levels[j][k], seg)) {
collide = true;
break;
}
}
}
if (collide) {
j++;
}else{
break;
}
}
if (levels[j]) {
levels[j].push(seg);
}else{
levels[j] = [seg];
}
}
return levels;
}
That could allow an event spanning multiple days to always stay below a non-working day? a non-working day is defined in the event as isDate. So if event.isDate then it is a non working segment.
Thanks

Related

iframe element returns undefined after onload event?

EDIT: Is there no one who can shed some light on this issue? Anything would be appreciated. :)
I have a script that is supposed to check to see if an elements html contains a given string..
When these elements do exist, my code throws this error: Uncaught TypeError: Cannot read property 'outerHTML' of null
This is the line: let check = document.querySelector("#iframe_${globalI}").contentWindow.document.querySelector(".Row"+inc).outerHTML
I then check to see if the string includes a check string.. IE: check.includes("Pre Trip")
If I run this line directly in the console it works and returns true... So what is going on here..?? How can I get this check to pass..?
I have this check executing after a setTimeout of 20 seconds, then wrapped again in another setTimeout for 500ms as I was trying to figure this out..
Also, I need to note that there are no XSS / CORS issues.
Here is my code..
function checkRowCount(x){
console.log("Row count called on "+x);
let rowCount = 0;
for(let i = 0; i < 30; i++){
if(typeof(document.querySelector(`#iframe_${x}`).contentWindow.document.querySelector('.Row'+i)) != 'undefined' && document.querySelector(`#iframe_${x}`).contentWindow.document.querySelector('.Row'+i) != null){
rowCount++;
}
}
console.log(rowCount);
return rowCount;
}
let globalCompiler = []; //globalCompiler[globalI] = {unit: unitNumber[globalI], data: ["X", " ", "NO POST TRIP]}
let unitNumber = [1031,1743,1744,1986,3239,3256,3257,4024,4062,4063,4064,4065,4247,4309,4315,4326,4327,4334,4335,4337,4350,4382,4385,7166,7380,7381,8765,8823,8945,8950,8988,10720,17045,17163,40014,40069,40122,40380,80129,80188,80700,80701,80702,80728,80831,80852,80875,"80876","81027","81038","401288","401306","402409","60099T","CH889","CH890","SR31077","T19","U5509","U6660","U6667","U6675","U8854","US1025T"];
let url = "http://winweb.cleanharbors.com/Vehicle/VehicleTDSearch.aspx?SearchType=DVIR";
function iframeLoaded(selector, unit, setDate, callback){
document.querySelector(`#iframe_${selector}`).contentWindow.document.querySelector("#txtStartDate").value = setDate;
document.querySelector(`#iframe_${selector}`).contentWindow.document.querySelector("#txtEndDate").value = setDate;
document.querySelector(`#iframe_${selector}`).contentWindow.document.querySelector("#txtVhcleNo").value = unit;
document.querySelector(`#iframe_${selector}`).contentWindow.document.querySelector("#btnRetrieve").click();
}
let loadFinished = {};
for(let dec = 0; dec < unitNumber.length; dec++){
loadFinished[unitNumber[dec]] = false;
}
console.log(loadFinished);
for(let globalI = 0; globalI < 3; globalI++){
globalCompiler[globalI] = {unit: unitNumber[globalI], data: []};
let iframeObj = document.createElement('iframe');
iframeObj.id = `iframe_${globalI}`;
iframeObj.hidden = false;
iframeObj.src = url;
iframeObj.onload = () => {
if (loadFinished[unitNumber[globalI]] == false) {
loadFinished[unitNumber[globalI]] = true;
let setDate = "11/01/2019";
iframeLoaded(globalI, unitNumber[globalI], setDate);
console.log("iframeloaded called on " + globalI);
setTimeout(() => {
setTimeout(() => {
let dateCheckObject = {}, rowCount = checkRowCount(globalI), trackingArr = [];
if (rowCount == 0) {
globalCompiler[globalI].data.push(" ");
} else {
for (let inc = 1; inc <= rowCount; inc++) {
//let check = $('#iframe_'+globalI).contents().find(`.Row` + inc).html().includes("Pre Trip");
let check = document.querySelector(`#iframe_${globalI}`).contentWindow.document.querySelector(".Row"+inc).outerHTML
if (check.includes("Pre Trip")) {
dateCheckObject.pre = true;
} else {
dateCheckObject.post = true;
}
}
if(dateCheckObject.pre && dateCheckObject.post) {
console.log("X");
globalCompiler[globalI].data.push("X");
dateCheckObject = {};
} else if (dateCheckObject.pre == 'undefined') {
console.log("NO PRE");
globalCompiler[globalI].data.push("NO PRE TRIP");
dateCheckObject = {};
} else {
console.log("NO POST");
globalCompiler[globalI].data.push("NO POST TRIP");
dateCheckObject = {};
}
}
},500);
}, 20000);
}
};
document.body.appendChild(iframeObj);
console.log("Global Loop called");
}
```
A for loop ran one count too far...
e.g.: for (let inc = 1; inc <= rowCount; inc++)
Should have been for (let inc = 1; inc < rowCount; inc++)

How to fix similar predictions in tenserflow.js

I'm doing a coding challenge from the coding train, and I'm trying to improve on his code. The idea is that the cars are driving around a race track. When I went back to check something, I noticed that I misspelled "activation: sigmoid", as in activation function. When I fixed it, the cars seemed to be driving in circles.
I'm a very new coder (as I am 12 years old), so many things in my code are broken, hard to understand, or just not finished. I'm also pretty new to stack overflow, so I might be breaking a lot of rules.
The link to download my project is here: https://1drv.ms/u/s!ApmY_SAko19ChzCKe5uNT7I9EZAX?e=YUg2ff
The misspelled words are at lines 29 and 34 in the nn.js file.
car.js
function pldistance(p1, p2, x, y) {
const num = abs((p2.y - p1.y) * x - (p2.x - p1.x) * y + p2.x * p1.y - p2.y * p1.x);
const den = p5.Vector.dist(p1, p2);
return num / den;
}
class Car {
constructor(brain, color = [random(255), random(255), random(255)]) {
this.colorGene = color;
this.dead = false;
this.finished = false;
this.fitness = 0;
this.rays = [];
this.wallRays = [];
this.degreeOfSight = degreeOfSight;
this.degreeOfRays = degreeOfSight / (numOfRays - 1);
if (this.degreeOfSight == 360) {
this.degreeOfRays = degreeOfSight / numOfRays;
}
this.pos = createVector(start.x, start.y);
this.vel = createVector();
this.acc = createVector();
this.sight = sight;
this.maxspeed = maxspeed;
this.maxforce = maxTurningSpeed;
this.currentGoal = 0;
this.timeTillDeadC = timeTillDead;
this.timeTillDead = this.timeTillDeadC;
this.goal;
this.rate = mutationRate;
if (degreeOfSight != 360) {
for (let a = -(this.degreeOfSight / 2); a <= this.degreeOfSight / 2; a += this.degreeOfRays) {
this.rays.push(new Ray(this.pos, radians(a)));
}
} else {
for (let a = -(this.degreeOfSight / 2); a < this.degreeOfSight / 2; a += this.degreeOfRays) {
this.rays.push(new Ray(this.pos, radians(a)));
}
}
for (let a = 0; a < 360; a += 45) {
this.wallRays.push(new Ray(this.pos, radians(a)));
}
if (brain) {
this.brain = brain.copy();
} else {
this.brain = new NeuralNetwork(this.rays.length + 2, 16, 2);
}
}
applyForce(force) {
this.acc.add(force);
}
update(x, y) {
this.timeTillDead--;
if (this.timeTillDead <= 0) {
this.dead = true;
}
if (!this.dead || this.finished) {
this.pos.add(this.vel);
this.vel.add(this.acc);
this.vel.limit(this.maxspeed);
this.acc.set(0, 0);
}
for (let i = 0; i < this.rays.length; i++) {
this.rays[i].rotate(this.vel.heading());
}
for (let i = 0; i < this.wallRays.length; i++) {
this.wallRays[i].rotate(this.vel.heading());
}
}
show(walls) {
push();
translate(this.pos.x, this.pos.y);
if (visualization) {
fill(this.colorGene[0], this.colorGene[1], this.colorGene[1]);
} else {
fill(0);
}
stroke(255);
const heading = this.vel.heading();
rotate(heading);
rectMode(CENTER);
rect(0, 0, 10, 5);
pop();
if (!this.dead) {
checkpoints[this.currentGoal].show();
}
for (let i = 0; i < this.rays.length; i++) {
let closest = null;
let record = this.sight;
for (let wall of walls) {
const pt = this.rays[i].cast(wall);
if (pt) {
const d = p5.Vector.dist(this.pos, pt);
if (d < record && d < this.sight) {
record = d;
closest = pt;
}
}
}
if (closest) {
if (showLines) {
ellipse(closest.x, closest.y, 4)
stroke(255, 100)
line(this.pos.x, this.pos.y, closest.x, closest.y);
}
}
}
}
check(checkpoints, walls) {
if (!this.dead) {
this.goal = checkpoints[this.currentGoal];
const d = pldistance(this.goal.a, this.goal.b, this.pos.x, this.pos.y);
if (d < 5) {
this.fitness++;
this.currentGoal++;
this.timeTillDead = this.timeTillDeadC;
if (this.currentGoal == checkpoints.length) {
this.finished = true;
this.fitness = this.fitness * 1.5;
if (endBarrier) {
this.dead = true;
} else {
this.currentGoal = 0;
}
}
}
}
for (let i = 0; i < this.wallRays.length; i++) {
let closest = null;
let record = this.sight;
for (let wall of walls) {
const pt = this.wallRays[i].cast(wall);
if (pt) {
const d = p5.Vector.dist(this.pos, pt);
if (d < record) {
record = d;
closest = pt;
}
}
}
if (record < 4) {
this.dead = true;
}
}
}
look(walls) {
const inputs = [];
for (let i = 0; i < this.wallRays.length; i++) {
let closest = null;
let record = this.sight;
for (let wall of walls) {
const pt = this.rays[i].cast(wall);
if (pt) {
const d = p5.Vector.dist(this.pos, pt);
if (d < record && d < this.sight) {
record = d;
closest = pt;
}
}
}
inputs[i] = map(record, 0, 50, 1, 0);
}
inputs.push(end.x);
inputs.push(end.y);
const output = this.brain.predict(inputs);
let angle = map(output[0], 0, 1, -PI, PI);
let speed = map(output[1], 0, 1, -this.maxspeed, this.maxspeed);
angle += this.vel.heading();
const steering = p5.Vector.fromAngle(angle);
steering.setMag(speed);
steering.limit(this.maxforce);
this.applyForce(steering);
}
mutateDemBabies() {
if (this.finished) {
this.rate = finishingMutationRate;
}
this.brain.mutate(this.rate);
let changeColor = this.brain.mutated();
if (changeColor) {
for (let color of this.colorGene) {
let r = map(random(20), 0, 20, -25, 25);
color += r;
}
}
this.rate = mutationRate;
}
dispose() {
this.brain.dispose();
}
}
nn.js
//<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#1.1.0/dist/tf.min.js"></script>
class NeuralNetwork {
//this how many inputs, hidden, and output nodes there are. modelC is the brain that we want to copy to give to the new bird
constructor(inputNumber, hiddenNumber, outputNumber, modelC) {
if (modelC instanceof tf.Sequential) {
//this is the making a copy of the neural network
this.input_nodes = inputNumber;
this.hidden_nodes = hiddenNumber;
this.output_nodes = outputNumber;
this.model = modelC;
} else {
//this is the creating a random brain
this.input_nodes = inputNumber;
this.hidden_nodes = hiddenNumber;
this.output_nodes = outputNumber;
this.model = this.createBrain();
}
this.changeColor = false;
}
createBrain() {
//the model is the neural network
const model = tf.sequential();
//configuring the hidden layer
const hiddenLayer = tf.layers.dense({
units: this.hidden_nodes,
inputShape: [this.input_nodes],
activaation: "sigmoid"
});
//configuring the output layer
const outputLayer = tf.layers.dense({
units: this.output_nodes,
activaation: "sigmoid"
});
//adding the hidden layer to the model
model.add(hiddenLayer);
//adding the output layer to the model
model.add(outputLayer);
//returning the model
return model;
}
predict(inputs) {
//clearing the tensors after using them
//then returning the output
return tf.tidy(() => {
//creating a tensor with the inputs
const xs = tf.tensor2d([inputs]);
//running the inputs through the neural network
const ys = this.model.predict(xs);
//getting the raw numbers from the tensor object
const outputs = ys.dataSync();
//returning the outputs
return outputs;
});
}
copy() {
//clearing the tensors after using them
//then returning the output
return tf.tidy(() => {
//creating a new neural network
const modelCopy = this.createBrain();
//getting the weights from the old neural network
const weights = this.model.getWeights();
//setting the new weights
modelCopy.setWeights(weights);
//making a new network but this time with all the weights then returning it
return new NeuralNetwork(
this.input_nodes,
this.hidden_nodes,
this.output_nodes,
modelCopy
);
});
}
mutate(rate, colorGene) {
//clearing the tensors after using them
tf.tidy(() => {
this.changeColor = false;
//getting the weights so that we can change them later
const weights = this.model.getWeights();
//the variable that will be holding the mutated weights
const mutatedWeights = [];
for (let i = 0; i < weights.length; i++) {
//getting the shape of the current weights
let shape = weights[i].shape;
//making a copy of the raw numbers from the object tensor
//dataSync gets the numbers, but doesn't make a copy, so slice will make the copy
let values = weights[i].dataSync().slice();
for (let j = 0; j < values.length; j++) {
//if the random number is less than mutation rate the it runs the code
if (random(1) < rate) {
this.changeColor = true;
//mutating the value
//randomGaussianis returns a float from a series of numbers with a mean of 0
values[j] = values[j] + randomGaussian();
}
}
//holding the new value of each weight
mutatedWeights[i] = tf.tensor(values, shape);
}
//setting the mutated weights as the new weights
this.model.setWeights(mutatedWeights);
});
}
mutated() {
if (this.changeColor) {
this.changeColor = false;
return true;
} else {
this.changeColor = false;
return false;
}
}
dispose() {
//disposing the brain so that memory doesn't leak
this.model.dispose();
}
}

JavaScript: multiple instances wrong reference to private property

In the fiddle is a "class" I have written to manage navigation over the data model and a test which shows that multiple instances (starting from second) of this "class" are referencing something wrong.
https://jsfiddle.net/btvmnaxc/
(outputs to console)
Expected output would be
[{"name":"xx"}]
[{"name":"yy"}]
But after setting Elements via setElements, in other methods Elements is empty, strangely only after creating the second instance. I could think that setElements overwrites the reference, but why other methods keep this old reference instead of getting a new one from the var.
Could somebody explain this behavior?
P.S. I probably can think on a solution, as packing vars in a property which is an object.
function Pagination() {
var props = {Elements:[], ...}
}
P.S.S
function Pagination() {
var that = this;
var Elements = [0,1];
var Frame = [];
var FrameNumber = 0;
var EntitiesPerFrame = 25;
var FrameChangedCB = [];
this.subscribeFrameChange = function(cb) {
if (typeof cb === "function") {
FrameChangedCB.push(cb);
} else {
throw new Error("Not a function");
}
}
this.setEntitiesPerFrame = function(entities_per_frame) {
entities_per_frame = parseInt(entities_per_frame);
if (entities_per_frame > 0) {
EntitiesPerFrame = entities_per_frame;
while (!this.canDisplayFrame(FrameNumber) && FrameNumber > 0) {
FrameNumber--;
}
calculateFrame();
}
}
frameChanged = function() {
FrameChangedCB.forEach(function(cb) {
cb();
});
}
this.setElements = function(elements) {
if (Array.isArray(elements)) {
Elements = elements;
calculateFrame();
console.log("qq");
} else {
throw new Error("Can only work with arrays");
}
}
this.getStart = function() {
return FrameNumber * EntitiesPerFrame;
}
this.getEnd = function() {
var end = (FrameNumber + 1) * EntitiesPerFrame;
return end > Elements.length ? Elements.length : end;
}
this.getEntitiesPerFrame = function() {
return EntitiesPerFrame;
}
calculateFrame = function() {
var start = that.getStart();
var end = that.getEnd();
if (that.canDisplayFrame(FrameNumber)) {
Frame = Elements.slice(
start,
end
);
frameChanged();
} else {
throw new Error("Boundaries");
}
}
this.canDisplayFrame = function(nr) {
nr = parseInt(nr);
var can = false;
var start = nr * EntitiesPerFrame
var end = (nr + 1) * EntitiesPerFrame;
if (start <= Elements.length && nr >= 0) {
can = true;
}
return can;
}
this.getFrame = function() {
return Frame;
}
this.next = function() {
return this.goto(FrameNumber + 1);
}
this.prev = function() {
return this.goto(FrameNumber - 1);
}
this.goto = function(frame_nr) {
var changed = false;
if (that.canDisplayFrame(frame_nr)) {
FrameNumber = parseInt(frame_nr);
calculateFrame();
changed = true;
}
return changed;
}
this.getLength = function() {
return Elements.length;
}
}
var b = new Pagination();
var a = new Pagination();
a.setElements([{name: 'xx'}]);
b.setElements([{name: 'yy'}]);
console.log(JSON.stringify(a.getFrame()));
console.log(JSON.stringify(b.getFrame()));
This is happening because you are abusing implicit globals.
Your Pagination function contains two places where a function is assigned to an identifier without using var:
calculateFrame = function() {
var start = that.getStart();
var end = that.getEnd();
if (that.canDisplayFrame(FrameNumber)) {
Frame = Elements.slice(
start,
end
);
frameChanged();
} else {
throw new Error("Boundaries");
}
}
This will assign this function to a global variable named calculateFrame and any call to calculateFrame() will be calling whichever of those was assigned last (and therefore be using whatever scope it has access to).
To fix this, use var:
var calculateFrame = function() {
var start = that.getStart();
var end = that.getEnd();
if (that.canDisplayFrame(FrameNumber)) {
Frame = Elements.slice(
start,
end
);
frameChanged();
} else {
throw new Error("Boundaries");
}
}
Or better yet, use a named function declaration:
function calculateFrame() {
var start = that.getStart();
var end = that.getEnd();
if (that.canDisplayFrame(FrameNumber)) {
Frame = Elements.slice(
start,
end
);
frameChanged();
} else {
throw new Error("Boundaries");
}
}
After fixing the two places where you have this issue, the snippet outputs the expected result.
function Pagination() {
var that = this;
var Elements = [0, 1];
var Frame = [];
var FrameNumber = 0;
var EntitiesPerFrame = 25;
var FrameChangedCB = [];
this.subscribeFrameChange = function(cb) {
if (typeof cb === "function") {
FrameChangedCB.push(cb);
} else {
throw new Error("Not a function");
}
}
this.setEntitiesPerFrame = function(entities_per_frame) {
entities_per_frame = parseInt(entities_per_frame);
if (entities_per_frame > 0) {
EntitiesPerFrame = entities_per_frame;
while (!this.canDisplayFrame(FrameNumber) && FrameNumber > 0) {
FrameNumber--;
}
calculateFrame();
}
}
function frameChanged() {
FrameChangedCB.forEach(function(cb) {
cb();
});
}
this.setElements = function(elements) {
if (Array.isArray(elements)) {
Elements = elements;
calculateFrame();
console.log("qq");
} else {
throw new Error("Can only work with arrays");
}
}
this.getStart = function() {
return FrameNumber * EntitiesPerFrame;
}
this.getEnd = function() {
var end = (FrameNumber + 1) * EntitiesPerFrame;
return end > Elements.length ? Elements.length : end;
}
this.getEntitiesPerFrame = function() {
return EntitiesPerFrame;
}
function calculateFrame() {
var start = that.getStart();
var end = that.getEnd();
if (that.canDisplayFrame(FrameNumber)) {
Frame = Elements.slice(
start,
end
);
frameChanged();
} else {
throw new Error("Boundaries");
}
}
this.canDisplayFrame = function(nr) {
nr = parseInt(nr);
var can = false;
var start = nr * EntitiesPerFrame
var end = (nr + 1) * EntitiesPerFrame;
if (start <= Elements.length && nr >= 0) {
can = true;
}
return can;
}
this.getFrame = function() {
return Frame;
}
this.next = function() {
return this.goto(FrameNumber + 1);
}
this.prev = function() {
return this.goto(FrameNumber - 1);
}
this.goto = function(frame_nr) {
var changed = false;
if (that.canDisplayFrame(frame_nr)) {
FrameNumber = parseInt(frame_nr);
calculateFrame();
changed = true;
}
return changed;
}
this.getLength = function() {
return Elements.length;
}
}
var b = new Pagination();
var a = new Pagination();
a.setElements([{
name: 'xx'
}]);
b.setElements([{
name: 'yy'
}]);
console.log(a.getFrame());
console.log(b.getFrame());

avoid sorting in the JSP pages

var sortitems = 1;
function move(fbox, tbox, all)
{
for ( var i = 0; i < fbox.options.length; i++)
{
if (!all && fbox.options[i].selected && fbox.options[i].value != "")
{
var no = new Option();
no.value = fbox.options[i].value;
no.text = fbox.options[i].text;
tbox.options[tbox.options.length] = no;
fbox.options[i].value = "";
fbox.options[i].text = "";
}
else
{
if (all && fbox.options[i].value != "")
{
var no = new Option();
no.value = fbox.options[i].value;
no.text = fbox.options[i].text;
tbox.options[tbox.options.length] = no;
fbox.options[i].value = "";
fbox.options[i].text = "";
}
}
}
BumpUp(fbox);
if (sortitems)
SortD(tbox);
checkSelectAll();
}
This move function is getting called after clicking on the button, then it will call the sort method where sorting is happening by alphabetically. So we dont need to sort we need to populate the data as it is from the left side box to right side box and vice versa, but sorting is happening. Please help out be here.
function SortD(box)
{
var temp_opts = new Array();
var temp = new Object();
for ( var i = 0; i < box.options.length; i++)
{
temp_opts[i] = box.options[i];
}
for ( var x = 0; x < temp_opts.length - 1; x++)
{
for ( var y = (x + 1); y < temp_opts.length; y++)
{
if (temp_opts[x].value > temp_opts[y].value)
{
temp = temp_opts[x].text;
temp_opts[x].text = temp_opts[y].text;
temp_opts[y].text = temp;
temp = temp_opts[x].value;
temp_opts[x].value = temp_opts[y].value;
temp_opts[y].value = temp;
}
}
}
for ( var i = 0; i < box.options.length; i++)
{
box.options[i].value = temp_opts[i].value;
box.options[i].text = temp_opts[i].text;
}
}
Depends on the bumpup box function. The elements are moving from one box to another. It will replace the element with empty space and move to top and do for all the elements. Please help out me here
Thanks in advance
function BumpUp(box)
{
for ( var i = 0; i < box.options.length; i++)
{
if (box.options[i].value == "")
{
for ( var j = i; j < box.options.length - 1; j++)
{
box.options[j].value = box.options[j + 1].value;
box.options[j].text = box.options[j + 1].text;
}
var ln = i;
break;
}
}
if (ln < box.options.length)
{
box.options.length -= 1;
BumpUp(box);
}
}
Maybe it's just me, but it's hard to see what the issue is here.
If it is simply that SortD(tbox) is being called within the move() function, that's because
sortitems is set to 1 right at the top of the code. The value of sortitems is never changed anywhere else, so this conditional is always true and SortD is always called.
if (sortitems)
SortD(tbox);

Time overlap issue javascript

I am working in add task module in my project.i want to check every time task add check if existing tasks overlap or not. i am almost did but,one problem occur on time overlap condition not allow add task, example if user add tasks below times like below:
09:00 AM - 10:00 AM
10:30 AM - 11:00 AM
if i add tasks to between 10:00 AM to 10:30 AM not allowed in my condition on below:
function disabletime(start_time, end_time) {
var start_date = new Date(new Date(start_time).getTime());
var end_date = new Date(new Date(end_time).getTime());
var disable_times = new Array();
var max_date = 0;
var min_date = 0;
if (tasks_array.length > 0) {
for (var i = 0; i < tasks_array.length; i++) {
var prev_s_date = Date.parse("1-1-2000 " + tasks_array[i].start_time);
var prev_e_date = Date.parse("1-1-2000 " + tasks_array[i].end_time);
var prev_start_date = new Date(new Date(prev_s_date).getTime());
var prev_end_date = new Date(new Date(prev_e_date).getTime());
if (i == 0) {
min_date = prev_start_date.getTime();
max_date = prev_end_date.getTime();
} else {
if (prev_end_date.getTime() > max_date) {
max_date = prev_end_date.getTime();
}
if (prev_start_date.getTime() < min_date) {
min_date = prev_start_date.getTime();
}
}
}
if ((start_date.getTime() == min_date) && (end_date.getTime() == max_date)) {
alert("Check the start and end time for this task!");
return false;
} else if ((start_date.getTime() < min_date) && (end_date.getTime() <= min_date) || (start_date.getTime() >= max_date) && (end_date.getTime() > max_date)) {
} else {
alert("Check the start and end time for this task!");
return false;
}
}
start_date = new Date(start_date.getTime() + 30 * 60000);
while (start_date < end_date) {
disable_times.push([start_date.getHours(), start_date.getMinutes()]);
start_date = new Date(start_date.getTime() + 30 * 60000);
}
return true;
}
here is my code flow, i add all tasks into json array in javascript. every time add new task check existing tasks on json array objects(inside if tasks exist) time overlap or not.
Here is a fiddle
I think it's a 'refactor if you want to debug' case.
Just breaking you problems into well isolated, small, simple problems will lead you to a solution faster than any deep debug cession.
You should break down the complexity of your code by using objects,
so you'll have a clear view on who does what, and you can test
easily each part.
I'm not sure the code below complies with all your needs, but it
should be much easier to use : i defined 2 objects : a task,
and a set of task.
For each i defined pretty simple methods, easy to read and debug.
I did not test the result, but you'll get the idea on how to do what
you want from here.
http://jsfiddle.net/gamealchemist/b68Qa/2/
// ------------------------------
// Task
function Task(startDate, endDate) {
this.start = startDate;
this.end = endDate;
}
// returns wether the time range overlaps with this task
Task.prototype.overlap = function (start, end) {
return (this.start <= end && this.end >= start);
}
// returns a string describing why the task is wrong, or null if ok
function checkTask(start, end) {
if (start > end) return "End time should exceed the start time";
if (start == end) return "End time should not same as the start time";
return null;
}
and now a set of tasks :
// ------------------------------
// Task Set
function TaskSet() {
this.tasks = [];
this.minDate = 0;
this.maxDate = 0;
}
// returns a string describing why the task cannot be added, or null if ok
TaskSet.prototype.check = function (start, end) {
var tasks = this.tasks;
// 1. Check date is valid
var dateCheck = checkTask(start, end);
if (dateCheck) return dateCheck;
// 2. overlap check
for (var i = 0; i < tasks.length; i++) {
var thisTask = tasks[i];
if (thisTask.overlap(start, end)) {
return 'time overlaps with another task';
}
}
return null;
}
// add the task.
TaskSet.prototype.add = function (start, end) {
var tasks = this.tasks;
if (task.length) {
this.minDate = start;
this.maxDate = end;
}
if (start < minDate) minDate = start;
if (end > maxDate) maxDate = end;
// you might want to check before inserting.
tasks.push(new Task(start, end));
}
// displays the current task inside the tasks div.
TaskSet.prototype.show = function () {
var tasks_array = this.tasks;
$("#tasks").html('');
$.each(tasks_array, function (index, item) {
var newRowContent = "<div>" + item.start_time + "-" + item.end_time + "</div>";
$("#tasks").append(newRowContent);
});
}
Let's use those objects :
// ---------------------------
var myTasks = new TaskSet();
$("#addtask").click(handle_AddTask_Clicked);
function handle_AddTask_Clicked(e) {
e.preventDefault();
var start = $("#task_stime").val();
var end = $("#task_etime").val();
var start_time = Date.parse("1-1-2000 " + start);
var end_time = Date.parse("1-1-2000 " + end);
var checkCanAdd = myTasks.check(start_time, end_time);
if (!checkCanAdd) {
myTasks.add(start_time, end_time);
myTasks.show(); // notice you might auto-refresh withinin add
} else {
alert(checkCanAdd);
}
}
finally i got solution from my friends on below code:
function disabletime(start_time, end_time) {
var start_date = start_time;
var end_date = end_time;
var disable_times = new Array();
var max_date = 0;
var min_date = 0;
var startTimeOverlapIndex = -1;
var endTimeOverlapIndex = -1;
var sameDateIndex = -1;
if (tasks_array.length > 0) {
for (var i = 0; i < tasks_array.length; i++) {
var prev_s_date = new Date("January 1, 1111 " + tasks_array[i].start_time);
var prev_e_date = new Date("January 1, 1111 " + tasks_array[i].end_time);
if(end_date<=prev_e_date) {
if(end_date>prev_s_date) {
endTimeOverlapIndex = i+1;
break;
}
}
if(start_date<prev_e_date) {
if(start_date>=prev_s_date) {
startTimeOverlapIndex = i+1;
break;
} else {
if(end_date>prev_s_date) {
endTimeOverlapIndex = i+1;
break;
}
}
}
if(start_date.toString()===prev_s_date.toString() && end_date.toString()===prev_e_date.toString()) {
sameDateIndex = i+1;
break;
}
}
if(sameDateIndex>0) {
alert("Sorry! your time cannot be same as task ("+startTimeOverlapIndex+"), please check again!");
return false;
} else if(startTimeOverlapIndex>0) {
alert("Sorry! your START time is overlaping with task ("+startTimeOverlapIndex+"), please check again!");
return false;
} else if(endTimeOverlapIndex>0) {
alert("Sorry! your END time is overlaping with task ("+endTimeOverlapIndex+"), please check again!");
return false;
} else {
//do whatever you do
return true;
}
}
return true;
}
Live link on fiddle find here
http://jsfiddle.net/mur7H/
It is 100% working. Please find below the correct answer with date and time overlapping.
function isBetween(ST, ET, PST, PET) {
var res = false;
if (((ST - PST) * (ST - PET) <= 0) || ((ET - PST) * (ET - PET) <= 0) || ((PST - ST) * (PST - ET) <= 0) || ((PET - ST) * (PET - ET) <= 0)) res = true;
return res;
}
function disabletime(start_time, end_time) {
debugger;
var start_date = new Date(start_time);
var end_date = new Date(end_time);
var disable_times = new Array();
var max_date = 0;
var min_date = 0;
var startTimeOverlapIndex = -1;
var endTimeOverlapIndex = -1;
var sameDateIndex = -1;
var resultA = true;
if (KitchenHourList.length > 0) {
for (var i = 0; i < KitchenHourList.length; i++) {
var prev_s_date = new Date(KitchenHourList[i].KitchenFromDate + " " + KitchenHourList[i].KitchenFromTime);
var prev_e_date = new Date(KitchenHourList[i].KitchenToDate + " " + KitchenHourList[i].KitchenToTime);
var STMinut = (start_date.getHours() * 60) + start_date.getMinutes();
var ETMinut = (end_date.getHours() * 60) + end_date.getMinutes();
var PSTMinut = (prev_s_date.getHours() * 60) + prev_s_date.getMinutes();
var PETMinut = (prev_e_date.getHours() * 60) + prev_e_date.getMinutes();
if (end_date <= prev_e_date) {
if (end_date > prev_s_date) {
if (isBetween(STMinut, ETMinut, PSTMinut, PETMinut)) {
endTimeOverlapIndex = i + 1;
break;
}
}
}
if (start_date < prev_e_date) {
if (start_date >= prev_s_date) {
if (isBetween(STMinut, ETMinut, PSTMinut, PETMinut)) {
startTimeOverlapIndex = i + 1;
break;
}
} else {
if (end_date > prev_s_date) {
if (isBetween(STMinut, ETMinut, PSTMinut, PETMinut)) {
{
endTimeOverlapIndex = i + 1;
break;
}
}
}
}
}
if (start_date.toString() === prev_s_date.toString() && end_date.toString() === prev_e_date.toString()) {
sameDateIndex = i + 1;
break;
}
}
if (sameDateIndex > 0) {
alert("Sorry! your time cannot be same as row (" + startTimeOverlapIndex + "), please check again!");
return false;
} else if (startTimeOverlapIndex > 0) {
alert("Sorry! your START time is overlaping with row (" + startTimeOverlapIndex + "), please check again!");
return false;
} else if (endTimeOverlapIndex > 0) {
alert("Sorry! your END time is overlaping with row (" + endTimeOverlapIndex + "), please check again!");
return false;
} else {
return true;
}
}
return true;
}

Categories

Resources