I want a create a mouse tracker for my new project but I cant find any resources for this. It’s a example: www.canyonbase.com. I want a create cursor tracker just like on this website. Can someone help me about this?
Category: javascript
Category Added in a WPeMatico Campaign
Use pattern (not img) inside danvas
When I create visualization inside svg, I can fill a rect using pattern that is defined inside defs
<defs>
<pattern id="hash4_4" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
<rect width="4" height="8" transform="translate(0,0)" fill="lightgray"></rect>
</pattern>
</defs>
I want to use the same pattern inside canvas visualization but can’t find a way to do that. I googled it and found method canvas.createPattern() but all examples include inserting there an image, not custom rect pattern as above.
Is it possible to use somehow my own <pattern> inside canvas?
Typescript object with arrays to array
I need some help solving this 🙂
I want to transfer the object to an array. The expected result should be:
result = [
{
id: 'test-1',
message: 'test#1.1'
},
{
id: 'test-1',
message: 'test#1.2'
},
{
id: 'test-2',
message: 'test#2.1'
},
{
id: 'test-2',
message: 'test#2.2'
}
]
My apparent solution is with objects.keys() and map(). Unfortunately, this does not work as desired:
mockData = {
'test-1': [
{
message: 'test#1.1'
},
{
message: 'test#1.2'
}
],
'test-2': [
{
message: 'test#2.1'
},
{
message: 'test#2.2'
}
]
}
const result = Object.keys(this.mockData).map((id) => {
return {
id,
...this.mockData[id],
}
})
console.log(result)
do I have to put another map() over this.mockData[id]? what am I doing wrong and what is best practice here (maybe reduce()?)?
I hope you can help me
matomo delay in content impression
I’m trying to track some content with Matomo’s tracking-client.
After initializing the client my snippet is like this:
window.matomoAsyncInit = function () {
console.log('track start');
try {
var contentTracker = Matomo.getTracker('...Host...', '...');
contentTracker.trackAllContentImpressions();
} catch( err ) {}
};
Everything works well except for a timeout of 3 seconds between the log-message ‘track start’ and the request to matomo-server.
Is there any configuration or option to reduce this delay?
How to play one video from array at a time using react js
Getting response from API. API response
Group_Name: "Group_1"
Video_Name: "http://localhost:4000/video/0"
After populating data to table create one button then ag-grid look like this
Then call API using fetch.after that stores response in usestate, I am currently mapping through all the videos to button and II click button it opens multiple video but I want only one video at a time but I don’t know how to properly play one at a time. I appreciate any help. I’ve been stuck on this for a few days.
app.js
export default function App(data, handleFormSubmit) {
const { id } = data;
const actionButton = (params) => {
setOpen(true);
};
const [response, setResponse] = useState([]);
const [open, setOpen] = React.useState(false);
const [formData, setFormData] = useState(initialValue);
const handleClose = () => {
setOpen(false);
response.map(({ Video_Name }) => videoName);
setFormData(initialValue);
console.log(videoName);
};
const onChange = (e) => {
const { value, id } = e.target;
// console.log(value,id)
setFormData({ ...formData, [id]: value });
};
const columnDefs = [
{ headerName: "Name", field: "Company_Name", filter: "agSetColumnFilter" },
{ headerName: "Floor", field: "Floor Number" },
{ headerName: "Group", field: "Group_Name" },
{ headerName: "Camera", field: "Camera_Number" },
{ headerName: "Videos", field: "Video_Name" },
{
headerName: "Actions",
field: "Video_Name",
cellRendererFramework: (params) => (
<div>
<Button
variant="contained"
size="medium"
color="primary"
onClick={() => actionButton(params)}
>
Play
</Button>
</div>
),
},
];
const onGridReady = (params) => {
console.log("grid is ready");
fetch("http://localhost:8000/get_all")
.then((resp) => resp.json())
.then((resp) => {
console.log(resp.results);
setResponse(resp.results);
params.api.applyTransaction({ add: resp.results });
});
};
return (
<div className="App">
<h1 align="center"> React FastAPI Integration</h1>
<h3> API Data </h3>
<div className="ag-theme-alpine" style={{ height: "400px" }}>
<AgGridReact
columnDefs={columnDefs}
defaultColDef={defaultColDef}
onGridReady={onGridReady}
pagination={true}
></AgGridReact>
</div>
<div>
<Dialog
open={open}
onClose={handleClose}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogContent>
{response.map(({ Video_Name }) => (
<iframe
width="420"
height="315"
title="videos"
src={Video_Name}
/>
))}
</DialogContent>
</Dialog>
</div>
</div>
);
}
Multiple video open at same time,I don’t know how to properly play one at a time. I appreciate any help. I’ve been stuck on this for a few days.
Multiple video open at a time. but i want one video at a time
Thanks in advance
export * except from module
Given I have two imports with lots of named exports (too many to write them all out) and I want to reexport these except a few of them. In my case this is because a few exports collide.
As an example of what I want to archive lets assume we have two files:
foo.js:
export const a = 1;
export const b = 2;
bar.js:
export const b = 1;
export const c = 3;
If I want to aggregate and reexport them all using CommonJS I could do something like this:
/* use rest destructuring to put everything except "b" into variable "foo" */
const { b, ...foo } = require("./foo");
const bar = require("./bar");
module.exports = {
...foo,
...bar
};
As I’m using typescript the closest I’ve gotten is using export = { ... } in a similar way:
import * as foo from "./foo";
import * as bar from "./bar";
const { b, ...foo2 } = foo;
export = {
...foo2,
...bar,
};
However it is my understanding this will create a file with CommonJS module.exports instead of a proper ESM module (and probably require esModuleInterop). And it is a typescript construct and not available when writing vanilla JS.
Is there a way to archive this using ESM import / export instead?
When mongoose’s save() callback function err part executes
In the below code :
new_user.save(function(err,result){
if (err){
console.log(err);
}
else{
console.log(result)
}
})
I understand that in case of any error while saving the data, if() part will be executed but what in case of no operation performed by save function i.e., the data which it is trying to save in db is already present and hence no insert or update operation is happening?
Now, if() part of callback function will be executed or else()?
Assume that I am adding _id field from my side explicitly to prevent auto generation and inserting new document on the basis of it
How post requests get header parameter
Backend services are working correctly. I’m trying to set the header parameter. But I am making a mistake somewhere. I can’t get a response.
Error appearing in console: Request failed with status code 417
How can I solve it?
PolicyService.js
const getAsosPaymentInfo = (getPolicyAccountInfoRequestDto) => {
return new Observable((observer) => {
axiosInstance
.post(SERVICE_PATH + '/getAsosPaymentInfo', getPolicyAccountInfoRequestDto, {
headers: { 'sales-channel': 200008, 'agency-code': 10038, }
})
.then((response) => {
observer.next(response.data);
observer.complete();
})
.catch((err) => {
console.log(err);
});
});
};
policy-payment-info.js
const req = {
policyNumber: '1277976920',
renewalNumber: '01',
policyTypeExtCode: '800',
productTypeExtCode: '2000062'
};
useEffect(() => {
if (props.location.state.policy.isActive === true) {
PolicyService.getAsosPaymentInfo(req).subscribe(
(response) => {
console.log(response);
}
);
}
}, []);
client.build is not a function
My code:
const DiscordMusicBot = require("./structures/DiscordMusicBot");
const client = new DiscordMusicBot();
client.build();
module.exports = client;
When I start the bot it gives me this error::
client.build();
^
TypeError: client.build is not a function
at Object.<anonymous> (C:UsersnotliDesktopoxiria-musicindex.js:4:8)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
Can someone help me?
How to get the index of a multidimensional array and splice that array
There is a problem in FreeCodeCamp.I’m not here to search solution to that problem. While trying to solve the problem I found some lines of my code do not work. I can not understand why that is not working. So I am here to ask YOU, good people, to help me.
problem
There is a function. I will pass an array and a number to that function. And what I need to return is also an array.
The array is a multidimensional array.
what I want to do
First of all I want to check if the inner or subarray contains the number i passed while calling the function. If that contains i need the index of that number in that subarray. Then I want to delete the number from that subarray using splice(). At last I wanted to return an array where there are sub arrays in it but none of them contain the given number.
where i am stuck in
But I am stuck in finding the index of the number in sub arrays, how can i use splice() to delete the number? Is it possible to do this way? Do you have any better suggestion for me?
my code
where for the first for loop it just prints -1
for the second loop, it prints the index of the array,not the index of the subarray.
function filteredArray(arr, elem) {
let newArr = [];
// Only change code below this line
newArr = [...arr]
let L = arr.length;
for (let i = 0; i < L; i++) {
// -------1-----------
for (elem in newArr[i]) {
console.log(newArr[i].indexOf(elem));
}
}
console.log('first loop ends')
for (let i = 0; i < L; i++) {
// --------2---------
for (let j = 0; j < newArr[i].length; j++) {
if (newArr[i][j] == elem) {
console.log(newArr[i].indexOf(elem))
}
}
// Only change code above this line
return newArr;
}
}
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
function filteredArray(arr, elem) {
let newArr = [];
// Only change code below this line
newArr = [...arr]
let L = arr.length;
// for (let i = 0; i < L; i++) {
// // -------1-----------
// for (elem in newArr[i]) {
// console.log(newArr[i].indexOf(elem));
// }
// }
console.log('first loop ends')
for (let i = 0; i < L; i++) {
// --------2---------
for (let j = 0; j < newArr[i].length; j++) {
if (newArr[i][j] == elem) {
console.log(newArr[i].indexOf(elem))
}
}
// Only change code above this line
return newArr;
}
}
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
Import vs require – different output (Æ’ vs Module)
In my service, I used to import items, and their type was Æ’. Now I am turning my service into an npm package, and my imports were changed to require. But now I got them as Modules. Is there any way to make them to be functions again?
x is a class.
old: import y from 'x.js'; this gives me back y = Æ’
new: const y = require('x.js'); this gives me back y = Module {__esModule: true...
(I need to reach the constructor from x to create singletons.)
Dynamically add a table row with a bootstrap selectpicker
I’m trying to dynamically add a table row. one of the td’s has a bootstrap select picker field. when I add the class select picker in JavaScript the field does not render the field, when i remove the class the select field renders without the search input. i would like the select to be rendered as a bootstrap select picker rather than a plain select field
function addRow() {
$("#addRowBtn").button("loading");
var tableLength = $("#productTable tbody tr").length;
var tableRow;
var arrayNumber;
var count;
if (tableLength > 0) {
tableRow = $("#productTable tbody tr:last").attr("id");
arrayNumber = $("#productTable tbody tr:last").attr("class");
count = tableRow.substring(3);
count = Number(count) + 1;
arrayNumber = Number(arrayNumber) + 1;
} else {
// no table row
count = 1;
arrayNumber = 0;
}
$.ajax({
url: "php_action/fetchProductData.php",
type: "post",
dataType: "json",
success: function (response) {
$("#addRowBtn").button("reset");
var tr =
'<tr id="row' +
count +
'" class="' +
arrayNumber +
'">' +
"<td>" +
'<div class="form-group">' +
'<div class="search_select">' +
'<select class="form-control" data-live-search="true" name="productName[]" id="productName' +
count +
'" onchange="getProductData(' +
count +
')" >' +
'<option value="">~~SELECT~~</option>';
// console.log(response);
$.each(response, function (index, value) {
tr += '<option value="' + value[0] + '">' + value[1] + "</option>";
});
tr +=
"</select>" +
"</div>" +
"</div>" +
"</td>" +
'<td style="padding-left:20px;"">' +
'<input type="text" name="rate[]" id="rate' +
count +
'" autocomplete="off" disabled="true" class="form-control" />' +
'<input type="hidden" name="rateValue[]" id="rateValue' +
count +
'" autocomplete="off" class="form-control" />' +
'</td style="padding-left:20px;">' +
'<td style="padding-left:20px;">' +
'<div class="form-group">' +
'<input type="number" name="quantity[]" id="quantity' +
count +
'" onkeyup="getTotal(' +
count +
')" autocomplete="off" class="form-control" min="1" />' +
"</div>" +
"</td>" +
'<td style="padding-left:20px;">' +
'<input type="text" name="total[]" id="total' +
count +
'" autocomplete="off" class="form-control" disabled="true" />' +
'<input type="hidden" name="totalValue[]" id="totalValue' +
count +
'" autocomplete="off" class="form-control" />' +
"</td>" +
"<td>" +
'<button class="btn btn-default removeProductRowBtn" type="button" onclick="removeProductRow(' +
count +
')"><i class="glyphicon glyphicon-trash"></i></button>' +
"</td>" +
"</tr>";
if (tableLength > 0) {
$("#productTable tbody tr:last").after(tr);
} else {
$("#productTable tbody").append(tr);
$(".search_select").selectpicker("refresh");
}
}, // /success
}); // get the product data
} // /add row
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table" id="productTable">
<thead>
<tr>
<th style="width:40%;">Product</th>
<th style="width:20%;">Rate</th>
<th style="width:15%;">Quantity</th>
<th style="width:15%;">Total</th>
<th style="width:10%;"></th>
</tr>
</thead>
<tbody>
<?php
$arrayNumber = 0;
for ($x = 1; $x < 4; $x++) { ?>
<tr id="row<?php echo $x; ?>" class="<?php echo $arrayNumber; ?>">
<td style="margin-left:20px;">
<div class="form-group">
<select class="form-control selectpicker" data-live-search="true"
name="productName[]" id="productName<?php echo $x; ?>"
onchange="getProductData(<?php echo $x; ?>)">
<option value="">~~SELECT~~</option>
<?php
$productSql = "SELECT * FROM product WHERE active = 1 AND status = 1 AND quantity != 0";
$productData = $connect->query($productSql);
while ($row = $productData->fetch_array()) {
echo "<option value='" . $row['product_id'] . "' id='changeProduct" . $row['product_id'] . "'>" . $row['product_name'] . "</option>";
} // /while
?>
</select>
</div>
</td>
<td style="padding-left:20px;">
<input type="text" name="rate[]" id="rate<?php echo $x; ?>" autocomplete="off"
disabled="true" class="form-control" />
<input type="hidden" name="rateValue[]" id="rateValue<?php echo $x; ?>"
autocomplete="off" class="form-control" />
</td>
<td style="padding-left:20px;">
<div class="form-group">
<input type="number" name="quantity[]" id="quantity<?php echo $x; ?>"
onkeyup="getTotal(<?php echo $x ?>)" autocomplete="off" class="form-control"
min="1" />
</div>
</td>
<td style="padding-left:20px;">
<input type="text" name="total[]" id="total<?php echo $x; ?>" autocomplete="off"
class="form-control" disabled="true" />
<input type="hidden" name="totalValue[]" id="totalValue<?php echo $x; ?>"
autocomplete="off" class="form-control" />
</td>
<td>
<button class="btn btn-default removeProductRowBtn" type="button"
id="removeProductRowBtn" onclick="removeProductRow(<?php echo $x; ?>)"><i
class="glyphicon glyphicon-trash"></i></button>
</td>
</tr>
<?php
$arrayNumber++;
} // /for
?>
</tbody>
</table>
Why is this validator allowing all URLS
I am trying to write a custom validator to check if a given URL content type is pdf, doc or docx. If the url is not one of these, the user should not be able to save.
In my component I have:
checkUrl(): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
const validFiles = [
'application/msword',
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
]
const url = control.value.toLowerCase()
const xhttp = new XMLHttpRequest()
xhttp.open('HEAD', url)
xhttp.onreadystatechange = function() {
if (this.readyState == this.DONE) {
console.log(this.status)
if (!validFiles.includes(this.getResponseHeader('Content-Type')!)) {
console.log('Match')
return { notValid: { value: control.value } }
}
}
}
xhttp.send()
return null
}
I also have
url: [
'',
[
Validators.required,
Validators.pattern(
'(http://www.|https://www.|http://|https://)?[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(:[0-9]{1,5})?(/.*)?$'
),
this.checkUrl(),
],
],
And
formControlName="url" type="url" pattern="(http://www.|https://www.|http://|https://)?[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(:[0-9]{1,5})?(/.*)?$"
in the HTML.
Now when I enter the 77677 into the URL, I do get the error of not a url. However, if I enter https://www.google.com, it is accepted which it should not be as that is not a pdf, doc or docx file. Only if the user enters a url which is a pdf, doc or docx which I am checking by content-type should they be allowed to save.
As far as I can tell this should be working, but it is not and I cannot see what I am doing wrong.
Infinite load when iframe is embedded
I have a web page that uses a “preloader” spinner animation with the following code:
window.onload = function() {
"use strict";
var preloader = $('#loading'),
loader = preloader.find('#loading-center-absolute');
loader.fadeOut();
preloader.delay(400).fadeOut('slow');
};
This works fine for all .html except for the one that has a <iframe> YouTube embedded video:
<iframe width="420" height="315" src="https://www.youtube.com/embed/tgbNymZ7vqY"></iframe>
In this page, the preloading spinner never ends. Maybe the <iframe> is calling a kind-of onLoad function internally and the loading falls in an infinite loop.
How can I avoid this behavior without deleting the preloading spinner?
Thanks!
Highlight word in webpage without .innerhtml
I want to highlight a word in a page without involving the document.body.innerHTML as this totally alters the functionality of the page. The current code I am using is this:
document.body.innerHTML= document.body.innerHTML.replace(/SampleCollected/g, function(m){
return '<span style="background-color:YELLOW">'+m+'</span>'
Is there any other way to do it?
Thank you

