How to extend the Response in Opine (Deno framework)?

first question here.

Does anyone know how to extend the response in Opine (Deno framework) so that I can create custom responses?

For example I would like to create:

res.success(message)

So that I don’t need to set HTTP codes every time like this:

res.setStatus(200).json({data: "success" });

I tried extending the response like it’s done here:
https://deno.land/x/[email protected]/test/units/app.response.test.ts

But when I use it in a controller I get:

Property ‘shout’ does not exist on type
‘OpineResponse’.deno-ts(2339)

Thank you.

combine use: and on:click in Sveltekit

I would be greatful if you could help me merging an action of use: and a function of on:click in one button in Sveltekit:

  <button
   class="notitle export"
   use:sth={exportBtnTrain}
   on:click={shareData('data', commentsArea.$value.value, screenshotImg)}
   >export data</button>

what is wrong with the image delivery

I’ve given the relative of the images on my personal portfolio website. but the images failed to load. The console shows the 404 error. In my local machine, the code and the path worked correctly but online the images not loading correctly.Nabeel Ahmed here is the link to my website.

Convert HTML to PDF in Chrome Extensions

I am new to chrome extensions, and I trying to figure out a solution for creating an extension that converts a website to a PDF. I am aware of the libraries for doing that, but in chrome extensions, it doesn’t work. So how can I do that? I also thought of creating a new webpage that interacts with the extension, so that I can handle importing libraries as content-scripts do not support importing modules. So actually I think that the way is to create another webpage, but how can I do that with extensions, and how does the communication work between webpages and extensions.
Best Regards,

Have two variables in one foreach bad insert

Hello i have a trouble with my code.

I have HTML with JS:

$(document).ready(function () {
 
      // allowed maximum input fields
      var max_input = 5;
 
      // initialize the counter for textbox
      var x = 1;
 
      // handle click event on Add More button
      $('.add-btn').click(function (e) {
        e.preventDefault();
        if (x < max_input) { // validate the condition
          x++; // increment the counter
          $('.wrapper').append(`
            <div class="input-box">
              <input type="text" name="input_name[]"/>
              <input type="text" name="input_price[]">
              <a href="#" class="remove-lnk">Remove</a>
            </div>
          `); // add input field
        }
      });
 
      // handle click event of the remove link
      $('.wrapper').on("click", ".remove-lnk", function (e) {
        e.preventDefault();
        $(this).parent('div').remove();  // remove input field
        x--; // decrement the counter
      })
 
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
                        <div class="input-box">
                          <input type="text" name="input_name[]">
                          <input type="text" name="input_price[]">
                          <button class="btn add-btn">+</button>
                        </div>
                      </div>

and i need insert in DB all inputs (name and price)
Now if i trying insert only first line.

php script:
This is a function and $id_produkt is GET from url.

if (isset($_POST["input_name"]) && is_array($_POST["input_name"])){ 
 
 
    $input_name = $_POST["input_name"]; 
    $input_price = $_POST["input_price"]; 
  
  
    foreach (array_combine($input_name, $input_price) as $field_name => $field_price){

      $sql = "INSERT INTO variant_product ( id_product, name, price ) VALUES(?,?,?)";
      $data = array("isi", $id_produkt, $field_name, $field_price);
      
      $result = db_query($sql, $data);

      return $result;
    }
  
  }

Can help me please ? I am tired

Passing parameters to routes

I am currently fiddling with some exercise code, from what i seen in https://reactnavigation.org/docs/params/
You should be able to pass more than 1 params with route
But i can’t seem to do that .
I only manage to send 1 of the two params that i wanted to pass from Topping.js to Rasa.js
What am i possibly doing wrong ?
Any help is appreciated

Topping.js

export default function HalTopping({route,navigation}){ 
    const { JenisMie } = route.params;
    const TipeMie = JenisMie;

        return(  
            <ScrollView>
                <Text>itemId: {JSON.stringify(JenisMie)}</Text>
                <View style={styles.container}> 
                    <View style={styles.card}> 
                        <View style={styles.card_header}> 
                            <Text style={styles.title}> Telur Dadar </Text>    
                        </View>
                        <View style={{alignItems : 'center', margin : 20}}> 
                            <Image 
                                style={{width: 300, height : 300}} 
                                source={require('./Img/Dadar.jpg')} 
                            /> 
                        </View>  
                    </View> 
                </View> 
            </ScrollView>             
        )  
};

Rasa.js

export default function HalPedas({route,navigation}){ 
    const { JenisMie1 } = route.params;
    const { JenisTopping } = route.params;

return( 
       <Text>itemId1: {JSON.stringify(JenisMie1)}</Text>
       <Text>itemId2: {JSON.stringify(JenisTopping)}</Text>)

App.js

import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { useNavigation, NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

import HalTopping from './Topping';
import HalPedas from './Rasa';
import HalPesanan from './Pesanan';


const Stack = createNativeStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="HalTopping" component={HalTopping}/>
        <Stack.Screen name="HalPedas" component={HalPedas}/>
        <Stack.Screen name="HalPesanan" component={HalPesanan}/>
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

Result

save-svg-as-png not loading the svg css, while downloading the svg as png

I am using save-svg-as-png module to download generated svg from d3 hierarchy tree to png.

Below is the svg generated in browser

enter image description here

But when I download it, some css are missing

enter image description here

Below is the code i am using to download

var saveSvgToPng = document.getElementById("download-button");
saveSvgToPng.onclick = function () {
  saveSvgAsPng(d3.select('svg').node(), "dia.png", {
    scale: 2,
  });
};

How do I resolve this issue.

Thanks in advance!

How to round irrational number using JavaScript?

I want to divide 1000/3 as an example and set the answer into an input.
my problem is that I dont want them to be float , so i rounded the like this

 const answer =  Math.round(1000/3);

when I set them in 3 inputs
all are 333
and the answer of their sum is 999
but i want one of them to be 334 and the others 333
how can I handle that generally?
thanks for your help

Hashtag undefined twitter wall tutorial

I am following this tutorial : https://www.codewall.co.uk/how-to-build-a-twitter-hashtag-viewing-tool-tutorial/
When i get to step Adjusting the index file to print hashtag variable passed in from the post handler i get a reference error.
I cannot see where is the problem as I am doing it step by step and the code is identical to the one provided in the tutorial.

Here is my server.js code :

const express = require('express')
const app = express()
const twit = require("twit")
app.set('view engine', 'ejs')
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: true }));

// Start serv & listen on port 3000.
app.listen(3000, function () {
    console.log('Node listening on port 3000')
})

//Listen for get request on root url. eg. http://localhost:3000
//Listen for get request on root url. eg. http://localhost:3000
app.get('/', function (req, res) {
    res.render('index', { welcomeMessage: "Welcome to my app." })
})


let Twitter = new twit({
    consumer_key: '',
    consumer_secret: '',
    access_token: '',
    access_token_secret: '',
    timeout_ms: 60 * 1000, // optional HTTP request timeout to apply to all requests.
    strictSSL: true, // optional - requires SSL certificates to be valid.
});


Twitter.get('search/tweets', {
    q: '#100DaysOfCode',
    count: 100,
    result_type: "mixed"
}).catch(function (err) {
    console.log('caught error', err.stack)
}).then(function (result) {
    console.log('data', result.data);
});
app.post('/', function (req, res) {
    console.log(req.body.hashtag);
    if (req.body.hashtag !== undefined) {
      res.render('index',  {hashtag: req.body.hashtag})
    }
    res.render('index',  {hashtag: null})
    
  });

Here is my index.ejs code :

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Twitter Hashtag Viewer</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"
        type="text/css">
    <link href="/css/style.css" rel="stylesheet" type="text/css">
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"
        type="text/css">
</head>
<body>

    <div class="container">
        <div class="form mb-2 mt-2"> 
        <fieldset>
            <form action="/" method="post">
                <div class="input-group">
                <input class="form-control" name="hashtag" placeholder="eg. #100DaysOfCode" required type="text">
                <input type="submit" value="Analyze!">
                </div>
            </form>
        </fieldset>
    </div>   
    </div>
    <% if(hashtag !== null){ %>
        <h3>All popular tweets for <%- hashtag %></h3>
    
        <% } %>
    

  </body>
</html>

Here is the error that I am getting:
Hashtag is not defined
https://i.stack.imgur.com/fZZvS.png

Trying to have an onEdit trigger with GScirpt that would send a slack message

I’ve been trying to automate sending messages when some of my reports are uploaded through a checkbox trigger on Gscript. (Idea being report is updated-> User check the checkbox -> message is sent to slack)

So far, I’ve been able to create the script to send the message to slack, and even reset my checkboxes at night. The only issue I have is with the trigger.

I’ve used onEdit as a trigger, on my three checkboxes (A1,B1,C1):

function onEdit(e) {
  const as = e.source.getActiveSheet();
  const cell = e.range.getA1Notation();

  if(as.getName() == 'Sheet1' && cell.getRange('A1').ischecked() === true) {
    SendSlackMessage1();
  }
  else if (as.getName() == 'Sheet1' && cell.getRange('B1').ischecked() === true) {
    SendSlackMessage2();
  }
  else if (as.getName() == 'Sheet1' && cell.getRange('C1').ischecked() === true) {
    SendSlackMessage3();
  }}

As a reference here’s the function to send messages :

function SendSlackMessage1() {
  const url = "https://hooks.slack.com/services/XXXXXXXXXXXXX";
  const params = {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify({
      "text":"Report A has been uploaded"
    })
  }

  const sendMsg = UrlFetchApp.fetch(url, params)
  var respCode = sendMsg.getResponseCode()
  Logger.log(sendMsg)
  Logger.log(respCode)
}

(All of SendSlackmessages function are the same except for text (Report A/B/C), and I’ve already authorized the functions to run on google.

So obviously, I’m doing something wrong, but what ? my first guess would be that I’m not properly defining the e range, but I don’t know what to do next.

I’d be grateful if someone can give me a headstart or pointing me at where to look.
Thanks ! 😀

Why useState does not display the value?

There is something I don’t understand with useState. This is my code :

const Home = () => {
    const [randomCharacters, setRandomCharacters] = useState([]);
    const [totalCharacters, setTotalCharacters] = useState('');


    useEffect(() => {
        axios.get('https://rickandmortyapi.com/api/character')
            .then((response) => {
                setTotalCharacters(response.data.info.count)
            })
    }, [])

    useEffect(() =>{
        axios.get('https://rickandmortyapi.com/api/character/1,23,'+ randomNumber(0, totalCharacters,4))
            .then((response) => {
                response.data.map(() => (
                    setRandomCharacters(response.data)
                ))
            })
    }, [])

    return (
        <div>
            <Navigation/>
            {randomCharacters.map( (character) => (
                <Card key={character.id} character={character}/>
            ))}
        </div>
    );
};

When I console.log totalCharactersjust after having set, I get ‘826’ and my cards are displayed but when I refresh the page or if I navigate to an other page and go back, totalCharacters equal to nothing. I guess it’s because by default useState = ” but why did it work the first time ? and How can I set the dynamic value

How to get data from index.html to flask in realtime

I’m trying to get data from websocket to flask in real-time, I didn’t find a way to do it so I tried making a different route “/” and send it again to another route which is “/get” but it doesn’t work cause I only can return the whole index.html file but I need only the data in realtime

<!doctype html>
<html>
  <head>
    <title>Flask-Sock Demo</title>
  </head>
  <body onload="a()">
    
    <div id="log"></div>
    <br>
    <script>

      const log = (text, color) => {
        document.getElementById('log').innerHTML += <span style="color: ${color}">${text}</span><br>;
      };

      socket = new WebSocket('ws://' + "localhost:8000");

      socket.addEventListener('message', ev => {
        log( ev.data, 'blue');
        saveDynamicDataToFile(ev.data);

        console.log(ev.data);
      });

      function a(){
        console.log("alert!")
        
        const textField = "hello"
        socket.onopen = () => socket.send(textField.value);
      }

    </script>
  </body>
</html> 
import asyncio
import websockets
 
from flask import Flask, render_template, request
from flask_sock import Sock

app = Flask(__name__,template_folder='template')
sock = Sock(app)

@app.route('/')
def index():
    return render_template("index.html")

@app.route('/get', methods=['GET', 'POST'])
def get():      
        return 

if __name__ == '__main__':
    app.debug = True
    app.run(use_reloader=False)

Detect “long press” on touch devices

I’m using contextmenu event to capture right clicks. On touch devices that event fired via “long press”.

The problem I’m experiencing is that the contextmenu event doesn’t fire on touch devices until touch is released. I could listen for touchstart/mousedown events and set timeout, but it won’t be accurate since each device might have its own delay for long press activation.

So, is there a way accurately detect when long press is activated on touch screen devices? (On some devices there is haptic feedback when long press was activated)