Console log showing mismatched value - console

When I select the first image, the "out" shows undefined & "in" shows the byte array result.
But after selecting the second image, "out" prints the byte array value of previous image & "in" shows the result of second(current) image.
upload(files: any) {
console.log('jj');
const file = files.files[0];
if (!file) return;
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (event) => {
this.url = reader.result;
var base64Index = this.url.indexOf(';base64,') + ';base64,'.length;
var base64 = this.url.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
let imgArray = new Uint8Array(new ArrayBuffer(rawLength));
for (let i = 0; i < rawLength; i++) {
imgArray[i] = raw.charCodeAt(i);
}
this.imgArrayy = imgArray;
console.log("in", this.imgArrayy);
}
console.log("out", this.imgArrayy);
}
Console output:-
How can I get the correct value for each corresponding image?

The readAsDataURL is an async function. That means the code may not execute in order.
The sequence of your code is:
schedule the readAsDataURL
print console.log out
execute the onload
print console.log in
console.log out is run before onLoad. Therefore the console.log out is undefined.
Is it typescript? I am not sure the syntax.
But the idea is change the upload function to async and use await to wait for the completion of file read.
Or you can change upload to async but use FileReaderSync instead. https://www.javascripture.com/FileReaderSync
Then, the sequence of code will be:
schedule the readAsDataURL
wait until readAsDataURL completed
execute the onload & print console.log in
print console.log out
To fix this, you can try:
const obj = {hello: 'world'};
const blob = new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json'});
async function upload(files) {
console.log('jj');
const file = files.files[0];
if (!file) return;
await new Promise((resolve) => {
var reader = new FileReader();
reader.onload = (event) => {
this.url = reader.result;
var base64Index = this.url.indexOf(';base64,') + ';base64,'.length;
var base64 = this.url.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
let imgArray = new Uint8Array(new ArrayBuffer(rawLength));
for (let i = 0; i < rawLength; i++) {
imgArray[i] = raw.charCodeAt(i);
}
this.imgArrayy = imgArray;
console.log("in", this.imgArrayy);
resolve(reader.result);
};
reader.readAsDataURL(file);
});
console.log("out", this.imgArrayy);
}
upload({files:[blob]});
output
jj
VM532:20 in Uint8Array(22) [123, 10, 32, 32, 34, 104, 101, 108, 108, 111, 34, 58, 32, 34, 119, 111, 114, 108, 100, 34, 10, 125]
VM532:25 out Uint8Array(22) [123, 10, 32, 32, 34, 104, 101, 108, 108, 111, 34, 58, 32, 34, 119, 111, 114, 108, 100, 34, 10, 125]

Related

PixiJS: Affine projection vs bilinear one

Let's say there is an arbitrary composite shape in PixiJS:
I need to project a texture onto it by some kind of a grid warp in a way, so the result would be:
I have tried to do it via PIXI.SimplePlane and it seems that default projection algorithm at this framework is affine transformation. And the result have to be based on quad bi-linear projection.
Yes, PixiJS has additional projections plugin (https://pixijs.io/examples/#/plugin-projection/quad-homo.js), but it seems that output could be controlled just by four corner points. In my case, I need more. At least 10 or even 15.
If I couldn't use projection plugin, maybe there is a way to implement a custom shader?!
let pattern64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAEACAIAAABK8lkwAAAACXBIWXMAAAAnAAAAJwEqCZFPAAAFIGlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMxNDAgNzkuMTYwNDUxLCAyMDE3LzA1LzA2LTAxOjA4OjIxICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0RX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AKAEAiBIAgCgBAIgSAIAoAQCIEgCAKAEAiBIAgCgBAIgSAIAoAQCIEgCAKAEAiBIAgCgBAIha7/d7egOMeZ5negKM8QMAiBIAgCgBAIgSAIAoAQCIEgCAKAEAiBIAgCgBAIgSAIAoAQCIEgCAKAEAiBIAgCgBAIgSAIAoAQCIEgCAKAEAiBIAgCgBAIgSAIAoAQCIEgCAKAEAiBIAgCgBAIgSAIAoAQCIEgCAKAEAiBIAgCgBAIgSAIAoAQCIEgCAKAEAiBIAgCgBAIgSAIAoAQCIEgCAKAEAiBIAgCgBAIgSAIAoAQCIEgCAKAEAiBIAgCgBAIgSAIAoAQCIEgCAKAEAiBIAgCgBAIgSAIAoAQCIEgCAKAEAiBIAgCgBAIj6By1EGKDptaHUAAAAAElFTkSuQmCC";
const app = new PIXI.Application({ width: 512, height: 324, antialias: true });
document.body.appendChild(app.view);
app.loader.add('pattern', pattern64).load(inits);
function inits() {
const graphics = new PIXI.Graphics();
let path = [34, 100, 176, 100, 176, 224, 34, 224];
graphics.lineStyle(0);
graphics.beginFill(0xBCBCBC, 1);
graphics.drawPolygon(path);
graphics.endFill();
path = [176, 100, 258, 60, 258, 264, 176, 224];
graphics.lineStyle(0);
graphics.beginFill(0xCDCDCD, 1);
graphics.drawPolygon(path);
graphics.endFill();
path = [258, 60, 422, 104, 422, 220, 256, 264];
graphics.lineStyle(0);
graphics.beginFill(0x606060, 1);
graphics.drawPolygon(path);
graphics.endFill();
path = [422, 104, 478, 104, 478, 220, 422, 220];
graphics.lineStyle(0);
graphics.beginFill(0x909090, 1);
graphics.drawPolygon(path);
graphics.endFill();
app.stage.addChild(graphics);
const texture = app.loader.resources.pattern.texture;
const plane = new PIXI.SimplePlane(texture, 5, 3);
app.stage.addChild(plane);
let buffer = plane.geometry.getBuffer('aVertexPosition');
// graphics.beginFill(0xFF0000);
// graphics.drawRect(buffer.data[20], buffer.data[21], 8, 8);
// graphics.endFill();
//manually set just for this demo
buffer.data[0] = 34;
buffer.data[1] = 100;
buffer.data[2] = 176;
buffer.data[3] = 100;
buffer.data[4] = 258;
buffer.data[5] = 60;
buffer.data[6] = 422;
buffer.data[7] = 104;
buffer.data[8] = 478;
buffer.data[9] = 104;
buffer.data[10] = 34;
buffer.data[11] = 162;
buffer.data[12] = 176;
buffer.data[13] = 162;
buffer.data[14] = 258;
buffer.data[15] = 162;
buffer.data[16] = 422;
buffer.data[17] = 162;
buffer.data[18] = 478;
buffer.data[19] = 162;
buffer.data[20] = 34;
buffer.data[21] = 224;
buffer.data[22] = 176;
buffer.data[23] = 224;
buffer.data[24] = 258;
buffer.data[25] = 264;
buffer.data[26] = 422;
buffer.data[27] = 220;
buffer.data[28] = 478;
buffer.data[29] = 220;
buffer.update();
}
body { margin: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/6.5.5/browser/pixi.js"></script>

How to define a heavy object in Matter JS

To explain better what I need, think about a tank and a can of soda.
No matter what the speed of that can of soda would be, the tank wouldn't move if it's hit.
But the tank should be able to move when force is applied to it.
Already opened an issue here with more details:
https://github.com/liabru/matter-js/issues/841
And I also made an example here for what I need.
var Engine = Matter.Engine,
Render = Matter.Render,
World = Matter.World,
Bodies = Matter.Bodies,
Body = Matter.Body;
var engine = Engine.create();
engine.positionIterations = 10;
engine.velocityIterations = 8;
var render = Render.create({
element: document.body,
engine: engine,
options: {
width: 800,
height: 400,
wireframes: false
}
});
engine.world.gravity.y = 0;
var topWall = Bodies.rectangle(400, 50, 720, 20, { isStatic: true });
var leftWall = Bodies.rectangle(50, 210, 20, 300, { isStatic: true });
var rightWall = Bodies.rectangle(750, 210, 20, 300, { isStatic: true });
var bottomWall = Bodies.rectangle(400, 350, 720, 20, { isStatic: true });
var ball = Bodies.circle(100, 200, 5, {
friction: 0.05,
frictionAir: 0.05,
density: 0.001,
restitution: 0.2
});
var bigBox = Matter.Bodies.rectangle(500, 200, 120, 120, {
inertia: Infinity,
frictionAir: 1,
friction: 1,
density: 0.1
});
World.add(engine.world, [topWall, leftWall, rightWall, bottomWall, ball, bigBox]);
Engine.run(engine);
Render.run(render);
// CMD + SHIFT + 7 to reload
$('.shoot').on('click', function () {
var speed = 0.02;
var angle = 0;
let vector = Matter.Vector.create(Math.cos(angle) * speed, Math.sin(angle) * speed);
Body.applyForce(ball, ball.position, vector);
});
https://codepen.io/dmerlea/pen/BaoQJYK

how to make curve line using css with animate?

I am trying to create curve line like this using css:
You can try canvas:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.strokeStyle = '#ff0000';
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(100, 20);
ctx.bezierCurveTo(105, 30, 110, 30, 115, 20);
ctx.lineTo(150, 20);
ctx.stroke();
Example code: https://www.w3schools.com/code/tryit.asp?filename=FW7CGRNXNTWQ

How to add additionalIcons to the tile in a Band

I am developing Microsoft Band2 Apps, I want to add Additional icons to my app tile in a band, like setting tile in Band2. I followed the below code to add Additional icons to the tile
Guid pageguid = Guid.NewGuid();
var panel = new ScrollFlowPanel
{
Rect = new PageRect(0, 0, 260, 128),
};
panel.Elements.Add(new FlowPanel
{
Rect = new PageRect(0, 0, 32, 32),
HorizontalAlignment = Microsoft.Band.Tiles.Pages.HorizontalAlignment.Center,
});
panel.Elements.Add(new Icon
{
HorizontalAlignment = Microsoft.Band.Tiles.Pages.HorizontalAlignment.Center,
Rect= new PageRect(0, 0, 32, 32),
ColorSource= ElementColorSource.BandHighlight,
});
var layout = new PageLayout(panel);
BandTile tile = new BandTile(tileGuid)
{
Name = "EmergencyHelp ",
TileIcon = await LoadIcon("ms-appx:///Assets/User that is member of security group.png"),
SmallIcon = await LoadIcon("ms-appx:///Assets/User that is member of security groupSmall.png"),
};
int firstIconIndex = tile.AdditionalIcons.Count + 2; // First 2 are used by the Tile itself
tile.AdditionalIcons.Add(await LoadIconMethod(AdjustUriMethod("ms-appx:///Assets/User that is member of security groupSmall.png")));
pageLayoutData.ById<IconData>(3).IconIndex = (ushort)(firstIconIndex + 0);
tile.PageLayouts.Add(layout);
if (tile.TileId != null)
{
await client.TileManager.RemoveTileAsync(tile.TileId);
}
await client.TileManager.AddTileAsync(tile);
await client.TileManager.SetPagesAsync(
tileGuid,
new PageData(pageguid, 0, new TextButtonData(1, "Emergency")));
I am getting the exception as shown in below figure,

Change color of destination waypoint: Google directions service

I am trying to change color of destination waypoint to green from red. Currently following the code from example:
Google waypoints
I googled, but could not find answer.
Many thanks in advance.
I'm afraid you can't.
What you can do is pass the google.maps.DirectionsRenderer an options object to disable markers altogether
var DirectionsRenderer= new google.maps.DirectionsRenderer({map:map, suppressMarkers: true});
and then add your custom markers yourself using the location of the origin and destination that you passed to the google.maps.DirectionsService instance.
proof of concept fiddle
// global variables to keep the start and end locations
var startLocation = {};
var endLocation = {};
Parse the directions response, putting a custom marker at the start and end of the route
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
if (i == 0) {
startLocation.latlng = legs[i].start_location;
startLocation.address = legs[i].start_address;
createMarker(legs[i].start_location, "start", legs[i].start_address, "green");
}
endLocation.latlng = legs[i].end_location;
endLocation.address = legs[i].end_address;
}
}
createMarker(endLocation.latlng, "end", endLocation.address, "red");
custom marker functions (you can simplify this if you only need 2 markers):
var icons = [];
icons["red"] = {
url: 'http://maps.google.com/mapfiles/ms/micons/red.png',
// This marker is 34 pixels wide by 34 pixels tall.
size: new google.maps.Size(34, 34),
// The origin for this image is 0,0.
origin: new google.maps.Point(0, 0),
// The anchor for this image is at 9,34.
anchor: new google.maps.Point(17, 34)
};
function getMarkerImage(iconColor) {
if ((typeof (iconColor) == "undefined") || (iconColor == null)) {
iconColor = "red";
}
if (!icons[iconColor]) {
icons[iconColor] = {
url: "http://maps.google.com/mapfiles/ms/micons/" + iconColor + ".png",
// This marker is 34 pixels wide by 34 pixels tall.
size: new google.maps.Size(34, 34),
// The origin for this image is 0,0.
origin: new google.maps.Point(0, 0),
// The anchor for this image is at 6,20.
anchor: new google.maps.Point(17, 34)
};
}
return icons[iconColor];
}
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var iconImage = {
url: 'http://maps.google.com/mapfiles/ms/micons/red.png',
// This marker is 20 pixels wide by 34 pixels tall.
size: new google.maps.Size(20, 34),
// The origin for this image is 0,0.
origin: new google.maps.Point(0, 0),
// The anchor for this image is at 9,34.
anchor: new google.maps.Point(9, 34)
};
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var iconShape = {
coord: [9, 0, 6, 1, 4, 2, 2, 4, 0, 8, 0, 12, 1, 14, 2, 16, 5, 19, 7, 23, 8, 26, 9, 30, 9, 34, 11, 34, 11, 30, 12, 26, 13, 24, 14, 21, 16, 18, 18, 16, 20, 12, 20, 8, 18, 4, 16, 2, 15, 1, 13, 0],
type: 'poly'
};
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function createMarker(latlng, label, html, color) {
var contentString = '<b>' + label + '</b><br>' + html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: getMarkerImage(color),
shape: iconShape,
title: label,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
marker.myname = label;
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}

Resources