I am writing a page to illustrate how to use a component I’ve developed and I’d like to build pairs of examples (rendered) with TSX source code that produces the example, ideally not having to repeat the code twice. I’d love to be able to grab the ref to the rendered component and get the TSX code from it to then inject it in a <pre> element and apply the highlighting. However the best I can seem to do is get the ìnnerHTML, which returns the component as rendered in the DOM, not the TSX code. Is there a way to achieve this? Or even better, a library that already does?
Category: javascript
Category Added in a WPeMatico Campaign
Rmd (No shiny): using ggiraph- display filtered data table
I try to setup an Rmd to get rendered in html (thus no shiny is allowed) .
I use ggiraph and crosstalk packages to create interactive plots.
I need to show the filtered table when a point on a plot is selected (similar to plotly).
I found a relevant example here, but it requires shiny: run_girafe_example("DT")
server.R
library(ggplot2)
library(ggiraph)
shinyServer(function(input, output, session) {
output$plot_ <- renderGirafe({
data <- mtcars
data$label <- gsub(pattern = "'", " ", row.names(data) )
data$onclick <- paste0("set_search_val("", data$label, "");")
p <- ggplot(aes(x=wt, y=mpg,
tooltip = label,
data_id = label, onclick = onclick ),data=data) +
geom_point_interactive(size = 3) + theme_minimal()
girafe(code = print(p),
options = list(
opts_hover(css = "fill:red;cursor:pointer;"),
opts_selection(type = "single", css = "fill:red;")
)
)
})
output$dt_ <- DT::renderDataTable({
mtcars
})
})
ui.R
library(ggiraph)
library(htmltools)
shinyUI(fluidPage(
fluidRow(
column(width=12,
includeScript(path = "set_search_val.js"),
h4("click a point, the data table will be filtered...")
)
),
fluidRow(
column(width=6,
girafeOutput("plot_")
),
column(width=6,
DT::dataTableOutput("dt_")
)
)
))
Can it be adapted (with js??) to my case?
Thank you!
MongoDB/Mongoose text search not returning results despite matching documents in database
Here’s a description of the problem you can use for your Stack Overflow post:
I’m developing a Node.js application using Express and Mongoose to interact with a MongoDB database. I’m trying to implement a search functionality for products, but I’m encountering an issue where my search query is not returning any results, even though I know there are matching documents in the database.
Here’s my current setup:
I have a Product model with fields including ‘title’ and ‘description’.
I’m using a GET route to search products based on a ‘keyword’ query parameter.
My search logic uses a regex to match the keyword in either the title or description fields.
Here’s the relevant part of my code:
`if (req.query.keyword) {
const query = {};
query.$or = [
{ title: { $regex: req.query.keyword, $options: "i" } },
{ description: { $regex: req.query.keyword, $options: "i" } },
];
mongooseQuery = mongooseQuery.find(query);
}
const products = await mongooseQuery;`
When I make a request to /api/v1/products?keyword=SanDisk, I get the following console output:
Query: {"keyword":"SanDisk"}
Mongoose Query: {
"keyword": "SanDisk",
"$or": [
{
"title": {
"$regex": "SanDisk",
"$options": "i"
}
},
{
"description": {
"$regex": "SanDisk",
"$options": "i"
}
}
]
}
Results: 0
I’ve confirmed that there are products in the database with “SanDisk” in the title or description. However, the search consistently returns 0 results.
I’ve tried several debugging steps, including:
Logging the total number of products in the database
Attempting simpler queries
Checking the structure of sample documents
Despite these efforts, I haven’t been able to identify why the search is not working as expected. Any insights or suggestions on how to troubleshoot this issue would be greatly appreciated.
Making object shifted to the side responsive with orthographic camera Three js
I’m trying to figure out the best way to make the position (and scale if needed) of the model across all devices without relying only on match medias. Ofc I can’t use %, so is there something built into Three.js that could help me achieve the best result? Also any other solution (if someone has it) is much appreciated. Right now I am using a orthographic camera in my scene.
This is what happens:
I want the model to position like this

But of course when I resize the screen it gets cut out like this

My resize code is as simple as this:
rendererSize.width = window.innerWidth;
rendererSize.height = window.innerHeight;
aspect = rendererSize.width / rendererSize.height;
//* [ORTHOGRAPHIC CAMERA]
camera.left = -f * aspect;
camera.right = f * aspect;
camera.updateProjectionMatrix();
renderer.setSize(rendererSize.width, rendererSize.height);
Using Syncfusion Vue3 DropdownList from CDN
I’m probably missing something obvious but I can’t get a simple DropdownListComponent work:
const {createApp} = Vue;
const app = createApp({
template: '#mySelect',
components: {
'ejs-dropdownlist': ejs.dropdowns.DropDownListComponent,
},
data: () => ({
myValue: null,
}),
created() {
this.myDataSource = [
{id: 1, content: "content1"},
{id: 2, content: "content2"},
];
this.fields = {text: "content", value:"id"};
},
methods: {
onMyValueChange() {
console.log(this.myValue);
},
},
});
app.mount("#myApp");
<head>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<link href="https://cdn.syncfusion.com/ej2/27.1.48/material.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.syncfusion.com/ej2/27.1.48/ej2-vue-es5/dist/ej2-vue.min.js" type="text/javascript"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
<div id="myApp" style="width: 10rem; margin: 0 auto;"></div>
<template id="mySelect">
<ejs-dropdownlist
placeholder='Select me'
:v-model="myValue"
:dataSource='myDataSource'
:fields='fields'
@change='onMyValueChange()'
>
</ejs-dropdownlist>
</template>
</body>
What am I doing wrong?
How to browserify NPM package for use in browser
I want to make an NPM package useable in the browser in a manner that makes all its exports available, without having to rerun the bundling process every time my application code uses an additional export.
How do I do this? All the tools I’ve found seem to want to create a bundle based on what dependencies my application code uses, which requires setting up a watch process and rebuilding the bundle every time I edit my code.
bootstrap 5 – load dynamic content into modal/offcanvas – pure vaniall js and ajax – no jquery
how can I load dynamic content into a Bootstrap 5 Modal.
With pure vanilla js (no jquery!).
I have e.g. the index.php.
I want to open a modal with a button.
The button should pass a URL (e.g. /example.php)
Then the modal should open an load the example.php into the modal body.
Can you help me with this?
Thank you so much!
I only found old or jquery solutions. But I don’t want to use jquery with Bootstrap 5.
IFrame Content Security Policy (CSP) Bypass in Neutralino.js
I want to know how to disable Content security policy headers in neutralino.js.
I want to add the header(title bar) on the top of the app. And the website should be opened in the iframe below the title bar header.
But the website doesn’t allow me to get it inside the iframe.
So I want to know how to bypass the CSP header in neutalino.js as it is an electron like javascript framework.
So I want to know how to bypass the CSP header in neutalino.js as it is an electron like javascript framework.
How can I get final hex color in Javascript from a relative CSS color string?
Let’s say I have a CSS like that, which uses CSS Relative Colors syntax:
.my-element {
color: rgb(from #aabbcc r + 30 g b - 30 / 80%);
}
(in real life, this example would use CSS variables which I know how to substitute with actual values, so I simplified it).
In CSS it calculates a color with increased red and decreased blue channels, and with 80% alpha-channel.
I need to get that color and further manipulate it in my JS. Tried using getComputedStyle – it doesn’t help, just returns the initial string representation of the color.
So, is there a way to get that final color in JS? Any built-in solution or a library?
I need help to combined two swaps in one transaction like a bundle on jupiter api, I always got Transaction too large error
What I did is, get the quotes from two swaps using jupiter api, then make the quotes as swap instructions and bundle it together like this:
// Combine both swap instructions into a single transaction
const combinedTx = new Transaction().add(…instruction1, …instruction2);
const { blockhash: blockhash1 } = await connection.getLatestBlockhash();
combinedTx.recentBlockhash = blockhash1;
combinedTx.feePayer = wallet.publicKey;
// Sign and send the transaction
const signaturetx = await sendAndConfirmTransaction(
connection,
combinedTx,
[wallet],
{ commitment: "confirmed", preflightCommitment: "processed" }
);
Correct way to handle non-blocking image processing
I have an JavaScript extension that in short: upon user action, converts an image into a dataURI (and then does some processing)
Problem:
My issue is that using callbacks becomes unpleasant to deal with if more processing is required, for example, scaling, modifying, etc, where I use similar functions (load into a canvas, return result via callback) as they become nested and so on. It’d be better to keep things inline.
Question:
I’d like to use await image.decode(), instead of image.onload => () {}, but I’m afraid if I use await, it’ll block the rest of the page, waiting for it to load.
I’ve read up on many an article and SO question, and I thought I understood asynchronous calls, but I’d just like to be certain.
Or should I even be using Promises?
Here’s what I’ve used so far –
function getImageDataURL(imageSource, callback){
let image = new Image();
let cans = document.createElement('canvas');
image.onload = function() {
// processing
cans.width = this.naturalWidth;
cans.height = this.naturalHeight;
cans.getContext('2d').drawImage(this, 0,0);
let q = 1
while (cans.toDataURL("image/webp", q).length > 7500 && q != 0) {
q -= 0.05; // Decreased quality increment size
}
callback(cans.toDataURL("image/webp", q));
cans.remove(); // Remove Element once complete
}
image.src = imageSource;
}
And I understand when the image load starts, it releases control of the execution to the rest of the page.
Which is good, as the user experience isn’t deteriorated.
If I did:
async function asyncGetImageDataUrl(source) {
...
image.src = source
await image.decode()
...
return dataURI
}
It appears to behave the same way in my testing, but is it? Or does it become blocking
Final question:
Would the result be any different, if I called result = await asyncGetImage(src)?
Perhaps in an instance where I would want it to be blocking.
Added Context:
My usage might look like:
source = getImageSource(..)
if (source == foo) {
doThis()
}
getImageURL(source, (result) => {
if (result.length < max) {
store(result)
}
else {
moreImageProcessing(result, (processedResult) => {
...
}
}
}
And you can see how the nesting occurs with the initial pattern, and becomes messy.
How to modify existing marker shape (triangle to upside down triangle)?
Regarding Apexcharts: How can I create a new shape or modify the existing triangle shape to be upside down?
markers: {
size: 0,
colors: undefined,
strokeColors: '#fff',
strokeWidth: 2,
strokeOpacity: 0.9,
strokeDashArray: 0,
fillOpacity: 1,
discrete: [],
shape: "triangle",
offsetX: 0,
offsetY: 0,
onClick: undefined,
onDblClick: undefined,
showNullDataPoints: true,
hover: {
size: undefined,
sizeOffset: 3
}
}
Button in a table cell to open a modal dialog
I have a table with some PHP and a form. Here is a part of it which shows that a button is placed in a cell:
if ($giorno == "ven"){
echo '<td>'.$qres["ven_1"].'</td>;
echo '<td>';
?>
<form action="?" method="post">
<input type="hidden" id="ven_1" name="ven_1" value="<?php echo $qres["ven_1"];?>">
<button type="submit" class="btn" id="ts">click me</button>
</form>
<?php
echo '</td>';
}
Below the table I have a script which triggers a modal dialog.
It basically counts some cells and shows the number in a dialog.
<script>
const re1 = /^[0-9][A-Z]/;
const re2 = /^c[0-9]/;
const actives = $('td').filter(function() {
const text = $(this).text();
const makeActive = text.match(re1) !== null;
$(this).toggleClass('active', makeActive);
$(this).toggleClass('compresenza', text.match(re2) !== null);
return makeActive;
}).length;
$('<div id="messaggio"></div>').html(`${actives}`).dialog({
title: 'Title',
width: '300px',
buttons: {},
modal: true,
});
</script>
As it is, the dialog opens when the HTML page is loaded.
I would like to set the dialog to autoOpen: false and open it only when the button in the table above is clicked on.
What is the correct procedure to achieve this?
Dont know how to send uploaded images from frontend to the backend or api
I have a problem.
I have a frontend with HTML, CSS and JavaScript where the user can upload or take a picture, and it should be sent to the API or backend with a prompt and then the result will be sent to the frontend for showing
Now, I have created the backend code from OpenAI documentation, but the problem is that it gives one and single picture locally by getting the path of the picture not getting the uploaded one.
And then it shows the result in the terminal by printing it, not showing it on the frontend.
Can you please help me to change my code?
import base64
import requests # type: ignore
OpenAI API Key
api_key = “”
Function to encode the image
def encode_image(image_path):
with open(image_path, “rb”) as image_file:
return base64.b64encode(image_file.read()).decode(‘utf-8’)
Path to your image
image_path = “C:/Users/zenith/Downloads/download.JPG”
Getting the base64 string
base64_image = encode_image(image_path)
headers = {
“Content-Type”: “application/json”,
“Authorization”: f”Bearer {api_key}”
}
payload = {
“model”: “gpt-4o-mini”,
“messages”: [
{
“role”: “user”,
“content”: [
{
“type”: “text”,
“text”: “detect and analyze the plant in this picture in 150 words”
},
{
“type”: “image_url”,
“image_url”: {
“url”: f”data:image/jpeg;base64,{base64_image}”
}
}
]
}
],
“max_tokens”: 300
}
response = requests.post(“https://api.openai.com/v1/chat/completions”, headers=headers, json=payload)
Documentation and nothing.
Is it possible to use JavaScript in C#.net web app to read Mifare card at android NFC?
I use C#.Net to create web app on an Android device. Is it possible to read a Mifare card through NFC on an Android device with Javascript like this and handling NFC Events?
I want to read block 1 of Mifare and using factory default keys 0x FF FF FF FF FF FF
in aspx file:
</td>
<td class="auto-style59"> </td>
</tr>
</table>
...
<script src="jquery.js"></script>
<script type="text/javascript">
function NFCRead() {
...
}
</script>
</asp:Content>
I have tried other ways and still no success