Can we use webEngage for flutter web? - flutter-web

I'm trying webEngage with flutter web. I tried adding this script in index.html.
<script id='_webengage_script_tag' type='text/javascript'>
var webengage;
! function(w, e, b, n, g) {
function o(e, t) {
e[t[t.length - 1]] = function() {
r.__queue.push([t.join("."), arguments])
}
}
var i, s, r = w[b],
z = " ",
l = "init options track screen onReady".split(z),
a = "feedback survey notification".split(z),
c = "options render clear abort".split(z),
p = "Open Close Submit Complete View Click".split(z),
u = "identify login logout setAttribute".split(z);
if (!r || !r.__v) {
for (w[b] = r = {
__queue: [],
is_spa: 1, //Change this to 0 if you do not wish to use default SPA behaviour of WebEngage SDK
__v: "6.0",
user: {}
}, i = 0; i < l.length; i++) o(r, [l[i]]);
for (i = 0; i < a.length; i++) {
for (r[a[i]] = {}, s = 0; s < c.length; s++) o(r[a[i]], [a[i], c[s]]);
for (s = 0; s < p.length; s++) o(r[a[i]], [a[i], "on" + p[s]])
}
for (i = 0; i < u.length; i++) o(r.user, ["user", u[i]]);
setTimeout(function() {
var f = e.createElement("script"),
d = e.getElementById("_webengage_script_tag");
f.type = "text/javascript", f.async = !0, f.src = ("https:" == e.location.protocol ? "https://ssl.widgets.webengage.com" : "http://cdn.widgets.webengage.com") + "/js/webengage-min-v-6.0.js", d.parentNode.insertBefore(f, d)
})
}
}(window, document, "webengage");
webengage.init('myCode'); //replace the YOUR_WEBENGAGE_LICENSE_CODE with your WebEngage Account License Code
</script>
but when calling webengage.init('myCode'); am getting this error.
%cWebEngage%c %cERROR

Related

handling a view frustum when not facing the object

i have made a view frustum from scratch in javascript. i have been having trouble with objects that the camera is place within and also facing away from.
an example of the problem is below
ive been stuck on this for months with little help, chatgpt recommended that i switch to a right handed corodinate system, so i did, but it didnt seem to fix the problem.
my proccess for putting pixels on the screen is described below
step 1 = cross product with camera matrix
step 2 = cross product with projection matrix
step 3 = divide co-ordinates by their own w co-ord (normalize w to 1)
step 3.5 = im currently skipping culling. culling would go here, but since my object is made of multiple vertices i cant cull a vertex just because its offscreen as it forms part of a whole object, and that would deform the rest of the object
step 4 = cross product with projection to screen matrix
below shows how the co-ordinates of 1 vertex changes with each step
co-ordinates of vertex before projection
[5.00,9.00,10.00,1.00]
good projection (tile is good)
step 1 = [5, 9, -4.799999999999979, 10]
step 2 = [-8.660254038143698, 15.588457268658656, 15.353535353535376, 4.799999999999979]
step 3 = [-1.8042195912799448, 3.2475952643039006, 3.198653198653217, 1]
step 4 = [-120.63293869199174, 637.1392896455851, 3.198653198653217, 1]
pixels = -120.63293869199174,637.1392896455851
#############################
bad projection from within the object (tile is deformed)
step 1 = [5, 9, 0.6000000000000014, 10]
step 2 = [-8.660254038143698, 15.588457268658656, 20.808080808080813, -0.6000000000000014]
step 3 = [14.433756730239462, -25.980762114431034, -34.68013468013461, 1]
step 4 = [2315.0635095359194, -3747.114317164655, -34.68013468013461, 1]
pixels = 2315.0635095359194,-3747.114317164655
###############################
bad projection from behind (tile appears on the ceiling, when A it should be on the floor and B it shouldn't be visible)
step 1 = [5, 9, 16.800000000000004, 10]
step 2 = [-8.660254038143698, 15.588457268658656, 37.17171717171718, -16.800000000000004]
step 3 = [0.5154913117942677, -0.9278843612296817, -2.2126022126022122, 1]
step 4 = [227.32369676914016, 10.817345815547753, -2.2126022126022122, 1]
pixels = 227.32369676914016, 10.817345815547753
does anyone know which step could be wrong or need changing in situation 2 and 3? and why?
below is a minimal (i know its 500 lines... but its about as minimal as i can get it) just open it in a browser and use wasd to control it.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/11.3.3/math.js"></script>
<script async src="https://unpkg.com/es-module-shims#1.3.6/dist/es-module-shims.js"></script>
</head>
<body>
<div id="canvas div" style = "position: relative; left: 0px; float:left; top: 0px;" >
<h1> first person below </h1>
<canvas id="mi_canvas" width="300" height="300" style="border-style: solid;"></canvas> <br>
<h1> radar below </h1>
<canvas id="radar_canvas" width="300" height="300" style="border-style: solid;"></canvas>
</div>
<div id="big info div" style = "position: relative; left: 310px; float:left; float:top; top: 0px; width:400px;" >
<div id = "info_1111"> </div><br>
</div>
<script>
var floor_y_pos = 9
canvas = document.getElementById("mi_canvas");
ctx = canvas.getContext("2d");
radar = document.getElementById("radar_canvas");
radar_ctx = radar.getContext("2d");
render_distance = 1000;
fov = math.pi / 2
class Projection{
constructor(){
var NEAR = player.near_plane
var FAR = player.far_plane
var RIGHT = Math.tan(player.h_fov/2)
var LEFT = - RIGHT
var TOP = Math.tan(player.v_fov /2)
var BOTTOM = -TOP
var m00 = 2*NEAR / (RIGHT - LEFT)
var m02 = (RIGHT + LEFT)/(RIGHT - LEFT)
var m11 = 2*NEAR / (TOP - BOTTOM)
var m12 = (TOP + BOTTOM) /(TOP - BOTTOM)
var m22 = (FAR * NEAR) / (FAR - NEAR)
var m23 = -2 * NEAR * FAR / (FAR-NEAR)
this.projection_matrix = [
[-m00,0,m02,0],
[0,m11,0,0],
[m02,m12,-m22,-1],
[0,0,m23,0]
]
var HW=player.H_WIDTH
var HH = player.H_HEIGHT
this.to_screen_matrix = [
[HW,0,0,0],
[0,HH,0,0],
[0,0,1,0],
[HW,HH,0,1]
]
}
}
function multiply(a, b) {
var aNumRows = a.length, aNumCols = a[0].length,
bNumRows = b.length, bNumCols = b[0].length,
m = new Array(aNumRows); // initialize array of rows
for (var r = 0; r < aNumRows; ++r) {
m[r] = new Array(bNumCols); // initialize the current row
for (var c = 0; c < bNumCols; ++c) {
m[r][c] = 0; // initialize the current cell
for (var i = 0; i < aNumCols; ++i) {
m[r][c] += a[r][i] * b[i][c];
}
}
}
return m;
}
function mi_position_matrix_multiplier(A, B)
{
var new_matrix = []
for (var new_num_ind = 0; new_num_ind < A.length; ++new_num_ind)
{
this_num = 0;
for (var a_ind = 0; a_ind < A.length; ++a_ind)
{
this_num += (A[a_ind] * B[a_ind][new_num_ind])
}
// console.log("just added this num to my new matrix = "+this_num.toString())
new_matrix.push(this_num)
}
return new_matrix;
}
function pythagoras(thing1, thing2)
{
dist = (((thing1[0]-thing2[0])**2)+((thing1[1]-thing2[1])**2))**0.5
return dist
}
class vertex{
constructor(x, y,z , id){
this.id = id
this.position = [x,y,z,1]
this.min_dist = 1.5 // minimum possible distance between player and object
}
is_this_object_behind_player(){
var arrow_length = 0.0001;
var pointing_position = [player.position[0]+(player.forward[0]*arrow_length) , player.position[2]-(player.forward[2]*arrow_length)]
var dist1 = pythagoras([this.position[0],this.position[2]], pointing_position)
var dist2 = pythagoras([this.position[0],this.position[2]], [player.position[0],player.position[2]])
if (dist1 < dist2){
return true;}
else if (dist1 > dist2){
return false;}
else{console.log(" else ");}
}
screen_projection(){
var position = mi_position_matrix_multiplier(this.position , player.camera_matrix())
console.log(position+" = position , which is a cross product of this.position"+this.position+" & "+ player.camera_matrix()+ " = player.camera_matrix()")
update_matrix_info_debug("camera_matrix",player.camera_matrix())
update_matrix_info_debug("position", position)
position = mi_position_matrix_multiplier(position , projection.projection_matrix) // does this just convert the position to cameras reference frame.
console.log(position+" = position , which is a cross product of position"+position+" & "+ projection.projection_matrix+ " = projection.projection_matrix")
update_matrix_info_debug("projection_matrix",projection.projection_matrix)
update_matrix_info_debug("position after being multiplied by proj matrix", position)
// if so then i image to screen matrix is insufficient
for (let i = 0; i < position.length; i++) {
position[i] = position[i]/position[3]
}
console.log(position+" = position after being normaslized")
for (let i = 0; i < position.length; i++) {
if (i != 9787781){
console.log(i+" =-= "+position[i])
if (this.is_this_object_behind_player()){for (let ii = 0; ii < position.length; ii++) {position[ii] = -999999999;} console.log("culling1")}
if (position[i] > 2){for (let ii = 0; ii < position.length; ii++) {position[ii] = -9999;} console.log("culling2")}
if (position[i] < -2){for (let ii = 0; ii < position.length; ii++) {position[ii] = -9999;} console.log("culling3")}
}
} // also all examples say set position = 0 if culling
console.log(position+" = position after being culled")
position = mi_position_matrix_multiplier(position , projection.to_screen_matrix)
console.log(position+" = position after being multiplied by "+projection.to_screen_matrix+ " = projection.to_screen_matrix")
update_matrix_info_debug("projection.to_screen_matrix",projection.to_screen_matrix)
update_matrix_info_debug("position after being multiplied by projection.to_screen_matrix", position)
ctx.beginPath();
var scale_multiplier = (render_distance / pythagoras([this.position[0],this.position[2]] , [player.position[0],player.position[2]]))*1.5
var arrow_size = 0.02 * scale_multiplier;
ctx.moveTo(position[0]-arrow_size ,position[1]+arrow_size);
ctx.lineTo(position[0]+arrow_size ,position[1]-arrow_size);
ctx.moveTo(position[0]+arrow_size ,position[1]+arrow_size);
ctx.lineTo(position[0]-arrow_size, position[1]-arrow_size);
ctx.stroke();
}
return_screen_projection(dont_cull = false){
var position = mi_position_matrix_multiplier(this.position , player.camera_matrix())
position = mi_position_matrix_multiplier(position , projection.projection_matrix) // does this just convert the position to cameras reference frame.
for (let i = 0; i < position.length; i++) {
position[i] = position[i]/position[3]
}
position = mi_position_matrix_multiplier(position , projection.to_screen_matrix)
return [position[0],position[1]]
}
}
class player{
constructor(){
this.position =[0,0,0,1.0]
this.forward = [0,0,1,1]
this.up = [0,1,0,1]
this.right =[1,0,0,1]
this.h_fov = 3.1415926535/3
this.v_fov = this.h_fov * (canvas.height / canvas.width)
this.near_plane = 1
this.far_plane = 100
this.moving_speed = 0.2
this.rotation_speed = 0.1
this.H_WIDTH = canvas.width/2
this.H_HEIGHT = canvas.height/2
this.anglePitch = 0
this.angleYaw = 0
}
set_camera_angle(){
var rotate = multiply(rotate_x(this.anglePitch) , rotate_y(this.angleYaw))
this.forward = [0, 0, 1, 1]
this.up = [0, 1, 0, 1]
this.right = [1, 0, 0, 1]
this.forward = mi_position_matrix_multiplier(this.forward , rotate)
this.right = mi_position_matrix_multiplier(this.right , rotate)
this.up = mi_position_matrix_multiplier(this.up , rotate)
}
camera_yaw(angle){
this.angleYaw += angle}
translate_matrix(self){
var x = this.position[0];
var y = this.position[1];
var z = this.position[2];
var w = this.position[3];
return [
[1,0,0,0],
[0,1,0,1],
[0,0,1,0],
[-x,-y,z, 1]
]}
rotate_matrix(){
var rx = this.right[0]
var ry = this.right[1]
var rz = this.right[2]
var w = this.right[3]
var fx = this.forward[0]
var fy = this.forward[1]
var fz = this.forward[2]
var w = this.forward[3]
var ux = this.up[0]
var uy = this.up[1]
var uz = this.up[2]
var w = this.up[3]
return [
[rx,ux,fx,0],
[ry,uy,fy,0],
[rz,uz,fz,0],
[0,0,0,1]
]
}
camera_matrix(){
return multiply(this.translate_matrix(), this.rotate_matrix());
}
check_min_distance_isnt_overcome_by_this_move(dx, dy){
var can_move = true;
console.log(" zzzzzzzzzzzzz ")
for (let i = 0; i < objects.length; i++) {
var dist=Math.abs(pythagoras([objects[i].position[0], objects[i].position[2]] , [this.position[0], this.position[2]]))
var dist2=Math.abs(pythagoras([objects[i].position[0], objects[i].position[2]] , [this.position[0]+dx, this.position[2]+dy]))
console.log(dist +" ########################### " +dist2)
if ((dist2 < objects[i].min_dist)&(dist > dist2))
{can_move = false; console.log(objects[i].min_dist +" yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy")}
else{console.log(objects[i].min_dist+" can move this is bloody min dist xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx "+dist2);}
}
return can_move;
}
move(event)
{
var key_code = parseInt(event.keyCode)
if (key_code == 37 || key_code == 39 || key_code == 83 || key_code == 87 || key_code == 119|| key_code == 115)
{
var dx = Math.cos(this.angleYaw)*this.moving_speed
var dy = Math.sin(this.angleYaw)*this.moving_speed
console.log("that were moving = dx , dy = "+dx.toString()+" , "+dy.toString())
if ( key_code == 37 || key_code == 87 || key_code == 119) {
if (this.check_min_distance_isnt_overcome_by_this_move(dx, -dy)){
this.position[0] += -dy
this.position[2] += dx
}
}
if (key_code == 39 || key_code == 83 || key_code == 115) {
for (let i = 0; i < this.position.length; i++) {
if (this.check_min_distance_isnt_overcome_by_this_move(dx, dy)){
this.position[0] += dy
this.position[2] += -dx
}
}
}
}
else {
if ( key_code == 38 || key_code == 65 || key_code == 97) {
this.camera_yaw(-this.rotation_speed)
}
if (key_code == 40 || key_code == 68 || key_code == 100) {
this.camera_yaw(this.rotation_speed)
}
this.set_camera_angle()
}
}
}
function translate(pos){
tx,ty,tz=pos
return np.array([
[1,0,0,0],
[0,1,0,0],
[0,0,1,0],
[tx,ty,tz,1]
])}
function rotate_x(angle){
return [
[1,0,0,0],
[0,Math.cos(angle),Math.sin(angle),0],
[0,-Math.sin(angle),Math.cos(angle),0],
[0,0,0,1]
]
}
function rotate_y(a){
return [
[math.cos(a),0, -math.sin(a),0],
[0,1,0,0],
[math.sin(a), 0 , math.cos(a),0],
[0,0,0,1]
]
}
function update_radar(){
var arrow_length = 4;
var object_size = 6.5;
radar_ctx.beginPath();
var mid_screen = [radar.width/2,radar.height/2];
pointing_position = [mid_screen[0]+(player.forward[0]*arrow_length) , mid_screen[1]-(player.forward[2]*arrow_length)]
radar_ctx.moveTo(mid_screen[0], mid_screen[1]); // start of player pos on radar
radar_ctx.lineTo(pointing_position[0], pointing_position[1]);
radar_ctx.lineTo(pointing_position[0]-2, pointing_position[1]-2);
radar_ctx.lineTo(pointing_position[0]+2, pointing_position[1]+2);
radar_ctx.lineTo(pointing_position[0]-2, pointing_position[1]+2);
radar_ctx.moveTo(mid_screen[0], mid_screen[1]);
for (let i = 0; i < objects.length; i++) {
var dx = (player.position[0]-objects[i].position[0])
var dz = player.position[2]+objects[i].position[2]
var x = (dx*2) + mid_screen[0]
var z = (dz*2) + mid_screen[1]
x = x +(object_size/2)
z = z +(object_size/2)
radar_ctx.moveTo(x-object_size,z-object_size);
radar_ctx.lineTo(x+object_size,z+object_size);
radar_ctx.moveTo(x+object_size,z-object_size);
radar_ctx.lineTo(x-object_size,z+object_size);
}
radar_ctx.stroke();
}
function update_matrix_info_debug(matrix_name, matrix){
if (matrix[0].length > 1)
{
for (let x = 1; x < matrix.length+1; x++) {
for (let y = 1; y < matrix.length+1; y++) {
// console.log(matrix_name.toString()+"_"+x.toString()+y.toString());
document.getElementById(matrix_name.toString()+"_"+x.toString()+y.toString()).innerHTML = matrix[x-1][y-1]
}
}
}
else {
for (let x = 1; x < matrix.length+1; x++) {document.getElementById(matrix_name.toString()+"_"+"1"+x.toString()).innerHTML = matrix[x-1]}
}
}
class box{
constructor(x,z,size){
var low_y = 0.5
var high_y = low_y - size
this.position = [x+(size/2),0,z+(size/2)]
this.vertices = [new vertex(x,low_y,z,0),new vertex(x+size,low_y,z,1),new vertex(x,low_y,z+size,2),new vertex(x+size,low_y,z+size,3),
new vertex(x,high_y,z,4),new vertex(x+size,high_y,z,5),new vertex(x,high_y,z+size,6),new vertex(x+size,high_y,z+size,7)
]
this.faces=[ [0,1,3,2,0], [0,1,5,4,0] , [1,3,7,5,1] , [4,5,7,6,4] , [2,6,7,3,2] , [0,4,6,2,0]]
// this.faces=[ [0,4,6,2,0]]
}
draw_all_vertices(){
for (let i = 0; i < this.vertices.length; i++) {
this.vertices[i].screen_projection()
}
}
draw_all_faces(){
var each_point = []
for (let i = 0; i < this.vertices.length; i++) {
each_point.push(this.vertices[i].return_screen_projection())
}
var skip_drawing = if_most_of_these_numbers_are_off_screen(each_point)
if (skip_drawing){console.log(" skipp drawing any faces init ");return;}
ctx.fillStyle = '#f00';
var moved_to_first_yet = false
for (let face = 0; face < this.faces.length; face++) {
ctx.beginPath();
console.log("%%%%%%%%%%%%%%%%%%%%%%%%%");
console.log(this.faces);
console.log(this.faces[face]);
for (let vertex = 0; vertex < this.faces[face].length; vertex++)
{
console.log(vertex+" vertex bef dddddddddddddddddddddddddddddd")
var vertex2 = this.faces[face][vertex]
console.log(vertex2+" vertex aft ddddddddd ")
if (moved_to_first_yet == false)
{
moved_to_first_yet = true
ctx.moveTo( each_point[this.vertices[vertex2].id][0],each_point[this.vertices[vertex2].id][1]);
}
else{ctx.lineTo( each_point[this.vertices[vertex2].id][0],each_point[this.vertices[vertex2].id][1]);}
}
ctx.closePath();
ctx.fill();
}
}
}
class two_d_surdace {
constructor(verex1,verex2,verex3,verex4 , colour){
this.vertices = [verex1,verex2,verex3,verex4]
this.colour = colour
}
draw_all_faces(){
var each_point = []
for (let i = 0; i < this.vertices.length; i++) {
each_point.push(this.vertices[i].return_screen_projection(true))
}
ctx.fillStyle = this.colour;
var moved_to_first_yet = false
for (let vertex = 0; vertex < this.vertices.length; vertex++)
{
console.log(each_point[vertex][0]+" , "+each_point[vertex][1]+ " actual x y points on screen for this vertex of corner of floor ")
if (moved_to_first_yet == false)
{
moved_to_first_yet = true
ctx.moveTo( each_point[vertex][0],each_point[vertex][1]);
}
else{ctx.lineTo( each_point[vertex][0],each_point[vertex][1]);}
}
ctx.closePath();
ctx.fill();
}
}
function if_off_screen(x, y)
{
if (x> canvas.width || x < 0){console.log(x +" x = off screen "); return true;}
if (y > canvas.height || y < 0){console.log(y +" y = off screen "); return true;}
console.log(x +" , "+y + " =x,y = not off screen ");
return false;
}
function if_most_of_these_numbers_are_off_screen(numbers){
var threshold = 1; //Math.floor(numbers.length*0.49)
var counter = 0
console.log(numbers + " xxxx numbers as they come in ")
for (let i = 0; i < numbers.length; i++) { if (if_off_screen(numbers[i][0], numbers[i][1])){console.log(numbers[i]+" , "+numbers[i+1]+ " = numbers[i] are off screen"); counter +=1} else{console.log(numbers[i]+" , "+numbers[i+1]+ " = numbers[i] not off screen")} }
console.log("quuin quoirs of raptor");
if (counter >= threshold){console.log(threshold+" < " + counter);return true}
console.log(threshold+" > " + counter);
return false;
}
player = new player();
projection = new Projection()
objects = [] //
floor = new two_d_surdace(new vertex(50,floor_y_pos,50) , new vertex(-50,floor_y_pos,50) , new vertex(-50,floor_y_pos,-50) , new vertex(50,floor_y_pos,-50) , '#F90' )
update_radar()
$(document).on("keypress", function (event) {
player.move(event)
ctx.beginPath();
radar_ctx.beginPath();
radar_ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < objects.length; i++) {
objects[i].draw_all_faces()
objects[i].draw_all_vertices()
}
floor.draw_all_faces()
update_radar()
});
</script>
</body>

Google Code Jam: My solution to Train Timetable problem is failing

I'm trying to solve this problem from Google's Code Jam 2008:
The problem is called Train Timetable and you can find the full explanation here:
Code Jam - Train Timetable
Note: I've decided to solve the problem with Node.js.
My code is the next:
function timeToMinutes(time) {
const timeArray = time.split(":");
const hours = parseInt(timeArray[0]);
const minutes = parseInt(timeArray[1]);
const hoursInMinutes = hours * 60;
const total = hoursInMinutes + minutes;
return total;
}
function timetableFiller(NAB, NBA, array) {
let timetable = {
departuresFromA: [],
arrivalsToB: [],
departuresFromB: [],
arrivalsToA: [],
};
for (let i = 0; i < NAB + NBA; i++) {
let tempArr = [];
tempArr = array[i].split(" ");
if (i < NAB) {
timetable.departuresFromA.push(tempArr[0]);
timetable.arrivalsToB.push(tempArr[1]);
} else {
timetable.departuresFromB.push(tempArr[0]);
timetable.arrivalsToA.push(tempArr[1]);
}
}
return timetable;
}
function timetableToMinutes(timetable) {
let timetableMinutes = {
departuresFromA: [],
arrivalsToB: [],
departuresFromB: [],
arrivalsToA: [],
};
for (const property in timetable) {
timetable[property].map((element) =>
timetableMinutes[property].push(timeToMinutes(element))
);
}
return timetableMinutes;
}
function trainsNeededCounter(arrivalsFromDestiny, departuresFromOrigin, tat) {
let trainsNeeded = departuresFromOrigin.length;
for (let i = 0; i < arrivalsFromDestiny.length; i++) {
for (let j = 0; j < departuresFromOrigin.length; j++) {
if (arrivalsFromDestiny[i] + tat <= departuresFromOrigin[j]) {
trainsNeeded = trainsNeeded - 1;
departuresFromOrigin.splice(j, 1);
}
}
}
return trainsNeeded;
}
function responseGenerator(inputA, inputB, caseNumber) {
return `Case #${caseNumber}: ${inputA} ${inputB}`;
}
function problemSolution(input) {
const numberOfCases = parseInt(input[0]);
input.shift();
let response = [];
let caseNumber = 0;
let NAB;
let NBA;
for (let i = 0; i < input.length; i = i + NAB + NBA + 2) {
caseNumber = caseNumber + 1;
const tat = parseInt(input[i]);
const arrayNTrips = input[i + 1].split(" ");
NAB = parseInt(arrayNTrips[0]);
NBA = parseInt(arrayNTrips[1]);
const arraySchedule = input.slice(i + 2, i + 2 + NAB + NBA);
const timetable = timetableFiller(NAB, NBA, arraySchedule);
const timetableMinutes = timetableToMinutes(timetable);
const trainsNeededAB = trainsNeededCounter(
timetableMinutes.arrivalsToA,
timetableMinutes.departuresFromA,
tat
);
const trainsNeededBA = trainsNeededCounter(
timetableMinutes.arrivalsToB,
timetableMinutes.departuresFromB,
tat
);
response.push(
responseGenerator(trainsNeededAB, trainsNeededBA, caseNumber)
);
}
return response;
}
function readInput() {
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false,
});
let problem = [];
rl.on("line", (line) => {
problem.push(line);
}).on("close", () => {
const solution = problemSolution(problem);
solution.map((response) => console.log(response));
});
}
readInput();
How to replicate the issue
You should login into Code Jam with your Google account.
Paste into the code area on the right side and activate the Test run mode.
As input you can copy paste the sample input provided in the problem and you can see that the output is exactly as the sample output.
I've tried with my own variations of the input and the responses seems correct but when I run the real attempt the platform says WA or Wrong Answer.
Thank you so much for your help!
I made a video about this recently. You should check it out.
I think you can understand the logic flow from it. We are both doing the same thing basically.
https://youtu.be/_Cp51vMDZAs
-check this out
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
void solve(int t)
{
int NA, NB;
float T;
cin >> T >> NA >> NB;
cin.ignore();
vector<string> ASchedule, BSchedule;
if (NA > 0)
for (int i = 0; i < NA; i++)
{
string s;
getline(cin, s);
ASchedule.push_back(s);
}
if (NB > 0)
for (int i = 0; i < NB; i++)
{
string s;
getline(cin, s);
BSchedule.push_back(s);
}
int alength, blength;
alength = (int)ASchedule.size();
blength = (int)BSchedule.size();
if (alength == 0 || blength == 0)
{
cout << "Case #" << t << ": " << alength << " " << blength << endl;
return;
}
float TT = T / 10;
string val, value;
int d;
float ADH, ADM, AAH, AAM, BDH, BDM, BAH, BAM;
vector<float> AD, AA, BD, BA;
for (int i = 0; i < alength; i++)
{
val = ASchedule[i];
ADH = stof(val.substr(0, 2));
AAH = stof(val.substr(6, 2));
ADM = stof(val.substr(3, 2));
AAM = stof(val.substr(9, 2));
if (val.at(9) == '0')
{
AAM /= 10;
AAM += TT;
AAM *= 10;
}
else
AAM += T;
if (AAM > 59)
{
d = -1;
while (AAM != 59)
{
AAM -= 1;
d++;
}
AAH++;
AAM = 0;
AAM += d;
}
// if (ADH > 23)
// ADH = 0;
// if (AAH > 23)
// AAH = 0;
ADM /= 100;
ADH += ADM;
AAM /= 100;
AAH += AAM;
AD.push_back(ADH);
AA.push_back(AAH);
}
for (int j = 0; j < blength; j++)
{
value = BSchedule[j];
BDH = stof(value.substr(0, 2));
BDM = stof(value.substr(3, 2));
BAH = stof(value.substr(6, 2));
BAM = stof(value.substr(9, 2));
if (value.at(9) == '0')
{
BAM /= 10;
BAM += TT;
BAM *= 10;
}
else
BAM += T;
if (BAM > 59)
{
d = -1;
while (BAM != 59)
{
BAM -= 1;
d++;
}
BAH++;
BAM = 0;
BAM += d;
}
// if (BDH > 23)
// BDH = 0;
// if (BAH > 23)
// BAH = 0;
BDM /= 100;
BDH += BDM;
BAM /= 100;
BAH += BAM;
BA.push_back(BAH);
BD.push_back(BDH);
}
int no1 = alength, no2 = blength;
sort(BD.begin(), BD.end());
sort(BA.begin(), BA.end());
sort(AA.begin(), AA.end());
sort(AD.begin(), AD.end());
for (int i = 0; i < alength; i++)
for (int j = 0; j < blength; j++)
if (AD[i] >= BA[j])
{
no1--;
BA[j] = 50;
break;
}
for (int i = 0; i < blength; i++)
for (int j = 0; j < alength; j++)
if (AA[j] <= BD[i])
{
no2--;
AA[j] = 50;
break;
}
cout << "Case #" << t << ": " << no1 << " " << no2 << endl;
}
int main()
{
int N;
cin >> N;
cin.ignore();
for (int t = 1; t <= N; t++)
solve(t);
}

How to create sourcemaps for concatenated files

I want to concatenate a bunch of different files of a single type into one large file. For example, many javascript files into one large file, many css files down to one etc. I want to create a sourcemap of the files pre concatenation, but I do not know where to start. I am working in Node, but I am also open to solutions in other environments.
I know there are tools that can do this, but they seem to be on a language by language basis (uglifyjs, cssmin or whatever its called these days), but I want a tool that is not language specific.
Also, I would like to define how the files are bound. For example, in javascript I want to give each file its own closure with an IIFE. Such as:
(function () {
// File
}());
I can also think of other wrappers I would like to implement for different files.
Here are my options as I see it right now. However, I don't know which is best or how to start any of them.
Find a module that does this (I'm working in a Node.js environment)
Create an algorithm with Mozilla's source-map module. For that I also see a couple options.
Only map each line to the new line location
Map every single character to the new location
Map every word to its new location (this options seems way out of scope)
Don't even worry about source maps
What do you guys think about these options. I've already tried options 2.1 and 2.2, but the solution seemed way too complicated for a concatenation algorithm and it did not perform perfectly in the Google Chrome browser tools.
I implemented code without any dependencies like this:
export interface SourceMap {
version: number; // always 3
file?: string;
sourceRoot?: string;
sources: string[];
sourcesContent?: string[];
names?: string[];
mappings: string | Buffer;
}
const emptySourceMap: SourceMap = { version: 3, sources: [], mappings: new Buffer(0) }
var charToInteger = new Buffer(256);
var integerToChar = new Buffer(64);
charToInteger.fill(255);
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('').forEach((char, i) => {
charToInteger[char.charCodeAt(0)] = i;
integerToChar[i] = char.charCodeAt(0);
});
class DynamicBuffer {
buffer: Buffer;
size: number;
constructor() {
this.buffer = new Buffer(512);
this.size = 0;
}
ensureCapacity(capacity: number) {
if (this.buffer.length >= capacity)
return;
let oldBuffer = this.buffer;
this.buffer = new Buffer(Math.max(oldBuffer.length * 2, capacity));
oldBuffer.copy(this.buffer);
}
addByte(b: number) {
this.ensureCapacity(this.size + 1);
this.buffer[this.size++] = b;
}
addVLQ(num: number) {
var clamped: number;
if (num < 0) {
num = (-num << 1) | 1;
} else {
num <<= 1;
}
do {
clamped = num & 31;
num >>= 5;
if (num > 0) {
clamped |= 32;
}
this.addByte(integerToChar[clamped]);
} while (num > 0);
}
addString(s: string) {
let l = Buffer.byteLength(s);
this.ensureCapacity(this.size + l);
this.buffer.write(s, this.size);
this.size += l;
}
addBuffer(b: Buffer) {
this.ensureCapacity(this.size + b.length);
b.copy(this.buffer, this.size);
this.size += b.length;
}
toBuffer(): Buffer {
return this.buffer.slice(0, this.size);
}
}
function countNL(b: Buffer): number {
let res = 0;
for (let i = 0; i < b.length; i++) {
if (b[i] === 10) res++;
}
return res;
}
export class SourceMapBuilder {
outputBuffer: DynamicBuffer;
sources: string[];
mappings: DynamicBuffer;
lastSourceIndex = 0;
lastSourceLine = 0;
lastSourceCol = 0;
constructor() {
this.outputBuffer = new DynamicBuffer();
this.mappings = new DynamicBuffer();
this.sources = [];
}
addLine(text: string) {
this.outputBuffer.addString(text);
this.outputBuffer.addByte(10);
this.mappings.addByte(59); // ;
}
addSource(content: Buffer, sourceMap?: SourceMap) {
if (sourceMap == null) sourceMap = emptySourceMap;
this.outputBuffer.addBuffer(content);
let sourceLines = countNL(content);
if (content.length > 0 && content[content.length - 1] !== 10) {
sourceLines++;
this.outputBuffer.addByte(10);
}
let sourceRemap = [];
sourceMap.sources.forEach((v) => {
let pos = this.sources.indexOf(v);
if (pos < 0) {
pos = this.sources.length;
this.sources.push(v);
}
sourceRemap.push(pos);
});
let lastOutputCol = 0;
let inputMappings = (typeof sourceMap.mappings === "string") ? new Buffer(<string>sourceMap.mappings) : <Buffer>sourceMap.mappings;
let outputLine = 0;
let ip = 0;
let inOutputCol = 0;
let inSourceIndex = 0;
let inSourceLine = 0;
let inSourceCol = 0;
let shift = 0;
let value = 0;
let valpos = 0;
const commit = () => {
if (valpos === 0) return;
this.mappings.addVLQ(inOutputCol - lastOutputCol);
lastOutputCol = inOutputCol;
if (valpos === 1) {
valpos = 0;
return;
}
let outSourceIndex = sourceRemap[inSourceIndex];
this.mappings.addVLQ(outSourceIndex - this.lastSourceIndex);
this.lastSourceIndex = outSourceIndex;
this.mappings.addVLQ(inSourceLine - this.lastSourceLine);
this.lastSourceLine = inSourceLine;
this.mappings.addVLQ(inSourceCol - this.lastSourceCol);
this.lastSourceCol = inSourceCol;
valpos = 0;
}
while (ip < inputMappings.length) {
let b = inputMappings[ip++];
if (b === 59) { // ;
commit();
this.mappings.addByte(59);
inOutputCol = 0;
lastOutputCol = 0;
outputLine++;
} else if (b === 44) { // ,
commit();
this.mappings.addByte(44);
} else {
b = charToInteger[b];
if (b === 255) throw new Error("Invalid sourceMap");
value += (b & 31) << shift;
if (b & 32) {
shift += 5;
} else {
let shouldNegate = value & 1;
value >>= 1;
if (shouldNegate) value = -value;
switch (valpos) {
case 0: inOutputCol += value; break;
case 1: inSourceIndex += value; break;
case 2: inSourceLine += value; break;
case 3: inSourceCol += value; break;
}
valpos++;
value = shift = 0;
}
}
}
commit();
while (outputLine < sourceLines) {
this.mappings.addByte(59);
outputLine++;
}
}
toContent(): Buffer {
return this.outputBuffer.toBuffer();
}
toSourceMap(sourceRoot?: string): Buffer {
return new Buffer(JSON.stringify({ version: 3, sourceRoot, sources: this.sources, mappings: this.mappings.toBuffer().toString() }));
}
}
I, at first, implemented "index map" from that spec, only to find out that it is not supported by any browser.
Another project that could be useful to look at is magic string.

SP.NavigationNode.get_isVisible() broken?

I need to read the "Top Nav", the "Children Nodes" and check if each node is visible.
I am using JSOM to accomplish this. Everything is working fine except for the get_isVisible() function. It always returns true. MSDN: http://msdn.microsoft.com/en-us/library/office/jj246297.aspx
I am on a publishing site in 2013 and I know some of the items are hidden. (My web and context are defined outside of this snippet)
var visParents = [], visChildren = [];
var topNodes = web.get_navigation().get_topNavigationBar();
context.load(topNodes);
context.executeQueryAsync(onQuerySucceeded, onQueryFailed)
function onQuerySucceeded() {
var nodeInfo = '';
var nodeEnumerator = topNodes.getEnumerator();
while (nodeEnumerator.moveNext()) {
var node = nodeEnumerator.get_current();
nodeInfo += node.get_title() + '\n';
if (node.get_isVisible())
visParents.push(node);
}
console.log("Current nodes: \n\n" + nodeInfo);
console.log("Visible Parents", visParents)
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
It is a known issue, it seems that SP.NavigationNode.isVisible property does not correspond to the property that indicates whether navigation node is hidden or shown.
Please refer "Hidden" property of SPNavigationNode for a details
The following function demonstrates how to retrieve hidden node Urls:
function getGlobalNavigationExcludedUrls(Success,Error)
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var subwebs = web.get_webs();
var pagesList = web.get_lists().getByTitle("Pages");
var pageItems = pagesList.getItems(SP.CamlQuery.createAllItemsQuery());
var allProperties = web.get_allProperties();
context.load(web);
context.load(subwebs);
context.load(allProperties);
context.load(pageItems);
context.executeQueryAsync(
function() {
var excludedIds = allProperties.get_item('__GlobalNavigationExcludes').split(';');
var exludedUrls = [];
for (var i = 0; i < excludedIds.length - 1; i++ )
{
for (var j = 0; j < subwebs.get_count(); j++ )
{
var subweb = subwebs.getItemAtIndex(j);
if(subweb.get_id().toString() == excludedIds[i]){
exludedUrls.push(subweb.get_serverRelativeUrl());
break;
}
}
for (var j = 0; j < pageItems.get_count(); j++ )
{
var pageItem = pageItems.getItemAtIndex(j);
if(pageItem.get_item('UniqueId').toString() == excludedIds[i]){
exludedUrls.push(web.get_serverRelativeUrl() + pageItem.get_item('FileRef'));
break;
}
}
}
Success(exludedUrls);
},
Error
);
}
//Usage: print excluded nodes Urls
getGlobalNavigationExcludedUrls(function(excludedNodeUrls){
for (var j = 0; j < excludedNodeUrls.length; j++ )
{
console.log(excludedNodeUrls[j]);
}
},
function(sender,args){
console.log(args.get_message());
});

Text version compare in FCKEditor

Am using Fck editor to write content. Am storing the text as versions in db. I want to highlight those changes in versions when loading the text in FCK Editor.
How to compare the text....
How to show any text that has been deleted in strike through mode.
Please help me/...
Try google's diff-patch algorithm http://code.google.com/p/google-diff-match-patch/
Take both previous and current version of the text and store it into two parameters. Pass the two parameters to the following function.
function diffString(o, n) {
o = o.replace(/<[^<|>]+?>| /gi, '');
n = n.replace(/<[^<|>]+?>| /gi, '');
var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/));
var str = "";
var oSpace = o.match(/\s+/g);
if (oSpace == null) {
oSpace = ["\n"];
} else {
oSpace.push("\n");
}
var nSpace = n.match(/\s+/g);
if (nSpace == null) {
nSpace = ["\n"];
} else {
nSpace.push("\n");
}
if (out.n.length == 0) {
for (var i = 0; i < out.o.length; i++) {
str += '<span style="background-color:#F00;"><del>' + escape(out.o[i]) + oSpace[i] + "</del></span>";
}
} else {
if (out.n[0].text == null) {
for (n = 0; n < out.o.length && out.o[n].text == null; n++) {
str += '<span style="background-color:#F00;"><del>' + escape(out.o[n]) + oSpace[n] + "</del></span>";
}
}
for (var i = 0; i < out.n.length; i++) {
if (out.n[i].text == null) {
str += '<span style="background-color:#0C0;"><ins>' + escape(out.n[i]) + nSpace[i] + "</ins></span>";
} else {
var pre = "";
for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) {
pre += '<span style="background-color:#F00;"><del>' + escape(out.o[n]) + oSpace[n] + "</del></span>";
}
str += " " + out.n[i].text + nSpace[i] + pre;
}
}
}
return str;
}
this returns an html in which new text is marked green and deleted text as red + striked out.

Resources