Tabulator data into a chart

I am using Tabulator to track stock prices that I get via a websocket. It works great. How do I get this data into a chart? Tried to put var into chart data (field:Nsym). And tried, (field:json.result.sym).
Chart data field requires actual number in the field, text will not work.

This code works for Tabulator table and GoBox.

   if (json.cmd === "L1Update")
   {
     var Nsym = json.result.sym;
     var Lprice = json.result.price.toFixed(2);
     var LVol = json.result.volume;
     var Lsize = json.result.size;

   //This code puts a number into GoBox on HTML page.
     document.getElementById("GoBox").innerHTML = Lprice; 

  //This code puts numbers into Tabulator table on HTML page.
    bohtTableOne.updateOrAddData([{ Ticker:Nsym, Tnowprice:Lprice,             
    TnowVol:LVol }]);

How to get this to work for chart data fields? Thanks for your help.

PHP form won’t submit with attached files

I’m currently running a PHP form script that allows users to upload their resume. The form works when you submit text fields only. But the form stops working when you attach a file. I’m not sure where the error is happening within the code.

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
/*
Tested working with PHP5.4 and above (including PHP 7 )

 */
require_once './vendor/autoload.php';

use FormGuideHandlxFormHandler;


$pp = new FormHandler(); 

$validator = $pp->getValidator();
$validator->fields(['firstname', 'lastname, 'email', 'phone', 'experience'])->areRequired()->maxLength(50);
$validator->field('email')->isEmail();


$pp->attachFiles(['resume']);


$pp->sendEmailTo(''); // ← Your email here

echo $pp->process($_POST);

I updated the code which lead to more errors.

How to recursively compress an image in js or jquery after cropping by Croppie.js

The user uploads an image and crops it using Croppie.js,

I compress the image recursively up to the size I define.

I create an img element, create a canvas with the img data, and lower the quality to 0.9 using canvas.toDataURL('image/jpeg', quality / 100);

The problem is that when the user crops the image to a circle, the image gets a black background outside the circle.

I understand that there is a problem with the format I set to 'image/jpeg', but only in this format can you set quality.
I tried to change to 'image/png' format, but it doesn’t work.

How can I do this without getting a black background?

This is the result I get

// After the user has cropped the image to circle

$('#modal-cropping-submit').on('click', function () {
    var points = $uploadCrop.croppie('get').points;
    var widthImage = parseInt(points[2]) - parseInt(points[0]);
    var heightImage = parseInt(points[3]) - parseInt(points[1]);

    $uploadCrop.croppie('result', {
        type: 'base64',
        size: 'original',
    }).then(function (resp) {
        var base64str = resp.substring(resp.indexOf(',') + 1);
        var sizeBytes = Math.ceil((base64str.length * (3 / 4)) - 2);
        if (sizeBytes > 52429) {  // 50kb
            compressFile(resp, 52429, 90, function (result) {
                base64str = result.substring(result.indexOf(',') + 1);

                //display the image in some element
                $('#src-img').css('backgroundImage', 'url(' + result + ')');
            });
        } else {
            //display the image in some element
            $('#src-img').css('backgroundImage', 'url(' + resp + ')');
        }
    });
});

function compressFile(sorce, maxsize, quality, callback) {
    const image = document.createElement('img');
    image.onload = () => {
        const canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        canvas.getContext('2d').drawImage(image, 0, 0);
        var resp = canvas.toDataURL('image/jpeg', quality / 100);    //Here there is a problem
        var base64str = resp.substring(resp.indexOf(',') + 1);
        var sizeBytes = Math.ceil((base64str.length * (3 / 4)) - 2);
        if (sizeBytes > maxsize)
            compressFile(sorce, maxsize, quality - 10, callback);
        else
            callback(resp);
    }
    image.src = sorce;
}

onesignal listener is accumulating when I refresh app from DevTool

I am running my ionic capacitor application in liveroad mode. When I make a change or when I refresh from DevTool, it keeps accumulating listener.
I am adding a listener in the bindNotifications function, this function is executed from the app.component when the application is initialized.

app.component.ts file

  constructor(
    private platform: Platform,
    private oneSignalNotificationService: OnesignalNotificationService,
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(async () => {
      this.oneSignalNotificationService.bindNotifications();
    })
  }

onesignal.service.ts file

  bindNotifications(): void {
    OneSignal.initialize(environment.onesignalAppId);
    OneSignal.Notifications.addEventListener("click", this.clickEventFunction);
  }

  clickEventFunction= (e: any) => {
    console.log("clickEvent");
    //Do something
  };

If I generate the app normally and use it normally, the amount of console.logs(“clickEvent”) is normal, but when I refresh in devtool (running the application in liveroad or debugging it), the amount of console.logs(“clickEvent”) becomes proportional to the amount of refreshes, that is, it increases (the listener accumulates).

Is it a coding error or is it a normal devTool error ? how can I fix it ?
I’m using version 5.0.4 onesignal-cordova-plugin

Thanks

How to get product by slug with Nextjs 14 and Sanity

I’m trying to return product details by current slug that is showing in the browser.

I can return all the products with code below:

export async function getAllProducts() {
  const productData = await client.fetch('*[_type == "product"]');

  return productData;
}

but when I try to return the products by slug, the value returned is null:

export async function getProductBySlug(slug) {
  const currentData = await client.fetch(
    `*[_type == "product" && slug.current == '${slug}'][0]`
  );

  return currentData;
}

Where do I go wrong?

Plugin for Capacitor Camera that is able to get Photos from File System Applications (Google Drive, Files)

Does anyone know if there is a Capacitor plugin that allows users to get photos from file solutions found on the device (ex: Google Drive)? It appears the current @capacitor/camera plugin does not allow you to select photos outside of gallery applications.

This was a feature in the cordova-plugin-camera-with-exif plugin. It showed the following screen when the user selected a pre-existing photo:

The current @capacitor/camera plugin only shows the following options when a user is trying to select an image:

Unable to Javascript Variable not triggering observeEvent

Trying to under stand what this code is not working, keep in mind I am not even a JS novice. The observeEvent does not even get triggered.

library(shiny)
library(shinyjs)
library(jsonlite)

ui <-
  {
    fluidPage(title = 'Title',
           useShinyjs(),
           actionButton(inputId = 'Button' , label = NULL),
           textAreaInput(inputId = 'Input4', label = 'Test4'),
           textInput(inputId = 'Input3', label = 'Test3')
    )
  }

server <- function(input, output, session) {
  
  shinyjs::runjs(
    '
    var metadata = "{"id":[115],"email":["test_email_address"]}";
    
    Shiny.setInputValue("Input3", metadata);
    '
  )
  
  observeEvent(input$Input3, ignoreInit = T, {
    updateActionButton(inputId = 'Button', label = 'Success')
    updateTextAreaInput(inputId = 'Input4', value = input$Input3)
  })
}

shinyApp(ui = ui, server = server,
         
)

peerjs peer.connect not opened for some users

PeerJs Server: custom server on nodejs

Client: Electron App

everything working great but it’s not working on some users’ devices without errors
after debugging I have figured that peer.connect never opens even on setTimeOut

const handelPeer = async (peerId: string) => {
    const id = `${Math.random().toString(16).slice(2)}_${user?.username
      ?.replaceAll(' ', '_')
      .toString()!}`;


    const peer = new Peer(id, {
      host: 'xxx.xxxx.xxx',
      path: '/peerjs',
      secure: true,
    });


    peer.on('open', () => {
   
      const connection = peer.connect(peerId); // Never open on some users 

      connection.on('open', async () => {

        // never getting here on some users
      });

    });

  };
console.log(connection)

enter image description here

many people say I have to change the stun server
I tried to change it with Google & some many others nothing changed

Why do I get error message “Uncaught TypeError: Cannot read properties of null (reading ‘value’)” [duplicate]

I get the error message “Uncaught TypeError: Cannot read properties of null (reading ‘value’)” in the console when i try too run this script. Can anyone help me understand why?

<h1>Hello World!</h1>

<div>
  <label for="username">Username</label>
  <input class="input__field" type="text" value="Your Petma username" id="username">

  <label for="name">Name</label>
  <input class="input__field" type="text" value="Your Petma name" id="name">

  <label for="description">Description</label>
  <input class="input__field" type="textarea" rows="2" value="Your post goes heree" id="description">
</div>

<div class="switch">
  <input class="switch__toggle" type="checkbox" id="dark-mode-on">
  <label class="switch__label" for="dark-mode-on">Dark Mode</label>
</div>

<div class="radio">

  <input id="radioButton1" type="radio" class="radio__button" name="variantGroup">
  <label for="radioButton1" class="radio__label">No Image</label>
  
  <input id="radioButton2" type="radio" class="radio__button" name="variantGroup">
  <label for="radioButton2" class="radio__label">Single Image</label>
  
  <input id="radioButton3" type="radio" class="radio__button" name="variantGroup">
  <label for="radioButton3" class="radio__label">Carousel</label>

</div>

<div>
  <button class="button button--primary" id="submit-post">Submit</button>
</div>

<script>
  document.getElementById("submit-post").onclick = () => {
    const name = document.getElementById('name').value;
    const username = document.getElementById('username').value;
    const description = document.getElementById('descruption').value;
    console.log("building my first plugin");
    console.log(name);
    console.log(username);
    console.log(description);
  }
  
</script>

Tried double-check id´s and names
Tried placement before and after html
Tried delaying the script to run after the window has loaded

How to dynamically calculate rowspan in a multi-level table from a nested JSON array in JavaScript?

I have a nested JSON array representing a multi-level table structure, and I’m trying to dynamically calculate the rowspan for each cell. Here’s an example of my input data:

[
    {
        "name": "goal1",
        "children": [
            {
                "name": "Objective1",
                "children": [
                    { "name": "50$" },
                    { "name": "80$" }
                ]
            },
            {
                "name": "Objective2",
                "children": [
                    { "name": "180$" },
                    { "name": "280$" }
                ]
            },
            {
                "name": "Objective1",
                "children": [
                    { "name": "380$" },
                    { "name": "280$" },
                    { "name": "480$" }
                ]
            }
        ]
    }
]

I’m looking for a JavaScript solution to transform this array into a structure that includes rowspan values for each cell, like the following:

  [
        [
            {
                "name": "goal1",
                "rowspan": 7
            },
            {
                "name": "Objective1",
                "rowspan": 2
            },
            {
                "name": "50$",
                "rowspan": 0
            }
        ],
        [
            {
                "name": "80$",
                "rowspan": 0
            }
        ],
        [
            {
                "name": "Objective2",
                "rowspan": 2
            },
            {
                "name": "180$",
                "rowspan": 0
            }
        ],
        [
            {
                "name": "280$",
                "rowspan": 0
            }
        ],
        [
            {
                "name": "Objective1",
                "rowspan": 3
            },
            {
                "name": "380$",
                "rowspan": 0
            }
        ],
        [
            {
                "name": "280$",
                "rowspan": 0
            }
        ],
        [
            {
                "name": "480$",
                "rowspan": 0
            }
        ]
    ]

Could someone provide guidance on how to achieve this dynamically in JavaScript?

Running several Jest tests when spying the same prototype function

I have some code similar to this:

class A {
    f1() { }
}
function f2() {
    const a = new A();
    a.f1();
}
test('test1', async () => {
    const spy_f1 = jest.spyOn(A.prototype, "f1");
    f2();
    console.log("In test1", spy_f1.mock.calls);
});
test('test2', async () => {
    const spy_f1 = jest.spyOn(A.prototype, "f1");
    f2();
    console.log("In test2", spy_f1.mock.calls);
});

I want to test how many times and with which arguments function f2 calls function f1.
To do that I would like to spy function f1. Though, for that, I need the object on which f1 is applied, and that object is local to function f2. So, I cannot.

Another possibility is to spy on the object A.prototype. It works if I run only test1 or only test2. But if I run both, the two tests are not independent on each other. For test2, it appears that f1 is called twice.

Other solutions?

Why am I not able to use .innerHTML property in this If Statement?

<button class="js-button" onclick="
    let buttonElement = document.querySelector('.js-button').innerHTML;

    if (buttonElement === 'Subscribe') {
      buttonElement = 'Subscribed';
    } else {
      buttonElement = 'Subscribe';
    }
  ">Subscribe</button>

When we click on the button, it should change to ‘Subscribed’ from ‘Subscribe’ and vice versa.

When I am saving .innerHTML along with the button in the variable buttonElement, the If statement doesn’t work properly. But, when I use the .innerHTML inside the If statement (ex. if (buttonElement.innerHTML === ‘Subscribe’) and I am not saving innerHTML inside the variable, the If Statement starts working properly. Can you please let me know what could be the reason.

Google Calendar API – Problem with filtering/displaying data

I created a small calendar application using Google Calendar API via Service Account. Despite some difficulties, I managed to write working code! However, there was a problem – the code almost works.

My goal was for the code to display only 6 days, skipping Sunday. Below these days were to generate buttons with hours. When I clicked on any of the buttons, it was to add an event to my Google calendar at a specific time. In addition, if an event at a particular hour already exists, the button for that hour should disappear. This is where the problem arises.

If I select an hour of, say, 1 p.m., I check my Google calendar and see that the booking exists and runs from 1 to 3 p.m. The button for 1 p.m. disappears, but the button for 2 p.m. is still visible, which surprises me. I guess the problem lies in my if condition, but I don’t know how to write it correctly?

if (isset($reservedHours[$day->format('l')][$hour])) {
echo ' disabled ';
}

In addition, I would like to be able to update the calendar for another week, but unfortunately I have no idea how to do it. I tried using Ajax, but unfortunately my code limits me:

$startDate = new DateTime('now');
$endDate = (new DateTime('now'))->modify('+6 days');

and I don’t know how limit the display to 6 days in another way

index.php

<?php
require_once 'vendor/autoload.php';

$calendarId = '[email protected]';

$keyFilePath = 'file.json';

$client = new Google_Client();
$client->setAuthConfig($keyFilePath);
$client->setScopes([Google_Service_Calendar::CALENDAR_READONLY]);

$service = new Google_Service_Calendar($client);

$startDate = new DateTime('now');
$endDate = (new DateTime('now'))->modify('+6 days');

$events = $service->events->listEvents($calendarId, [
    'timeMin' => $startDate->format(DATE_RFC3339),
    'timeMax' => $endDate->format(DATE_RFC3339),
]);

$reservedHours = [];

foreach ($events->getItems() as $event) {
    $startDateTime = new DateTime($event->start->dateTime);
    $day = $startDateTime->format('l');
    $hour = $startDateTime->format('G');

    $reservedHours[$day][$hour] = true;
}

$day = $startDate;

?>

<button id="nextWeekButton" onclick="updateCalendar()">Next Week</button>
<div id="calendarContainer">
    <div id="row">
        <div class="apud">
    <?php

    echo '<form action="make_reservation.php" method="post">';
    
    while ($day <= $endDate) {
        echo '<div id="calendar-cell">';
        if($day->format('D') != 'Sun'){
            echo '<div class="daysdaysdays">' . $day->format('D') .'<h1>'. $day->format('j') . '</h1></div>';
        for ($hour = 10; $hour <= 17; $hour++) {
            echo '<div class="calendar-cell-hours">';
            echo '<div class="radio-toolbar">';
            echo '<input type="radio" id="' . $day->format('Y-m-d') . 'T' . str_pad($hour, 2, '0', STR_PAD_LEFT) . ':00:00" " 
                    name="reservation[]" value="' . $day->format('Y-m-d') . 'T' . str_pad($hour, 2, '0', STR_PAD_LEFT) . ':00:00" ';
            if (isset($reservedHours[$day->format('l')][$hour])) {
                echo ' disabled ';
            }
            echo '><label for="' . $day->format('Y-m-d') . 'T' . str_pad($hour, 2, '0', STR_PAD_LEFT) . ':00:00"> ';
            echo $hour.':00 </label></div>';
            echo '</div>';
        }
    }
        echo '</div>';
        $day->modify('+1 day');
    }
    ?>
    <input type="submit" value="Make Reservations" id="submitButton" style="display: none;">
    </form>
    </div></div>
    <label for="name" id="nameLabel" style="display: none;">Name:</label><input type="text" id="name" name="name" required style="display: none;"><br>
    <label for="surname" id="surnameLabel" style="display: none;">Surname:</label><input type="text" id="surname" name="surname" required style="display: none;"><br>
    <label for="phone" id="phoneLabel" style="display: none;">Phone:</label><input type="tel" id="phone" name="phone" required style="display: none;"><br>
</div>
<button type="button" onclick="showForm();">NEXT</button>

Here I tried to update the calendar for another week, update-calendar.php looks the same as index.php
But I think this code limits me:

$startDate = new DateTime('now');
$endDate = (new DateTime('now'))->modify('+6 days');

Ajax in index.php:

<script>
function updateCalendar() {
        $.ajax({
            type: 'GET',
            url: 'update_calendar.php',
            success: function (data) {
                $('#calendarContainer').html(data);
            },
            error: function () {
                alert('Error updating calendar');
            }
        });
    }

    $('#updateButton').click(function () {
        updateCalendar();
    });
</script>

Getting undefined error for something that is defined in the chrome console [duplicate]

So I am trying to use things from the websites using my Chrome Extension, if I will try to access “UTMarketSearchFiltersViewController” from the website console there will be no errors and it will work, but when trying to access it from my extension it will show this error:
Uncaught ReferenceError: UTMarketSearchFiltersViewController is not defined
here is the code

window.UTAutoBuyerViewController = function () {
    window.UTMarketSearchFiltersViewController.call(this);
}

window.searchFiltersViewInit = 
UTMarketSearchFiltersViewController.prototype.init;

window.old.utils.JS.inherits(UTAutoBuyerViewController, 
UTMarketSearchFiltersViewController);

I am not trying to use variables from another script that I have I am trying to use something that is already in the website that I am using the extension on, I can’t edit its code or something like that

using built-in local storage object:not getting null in the output when using remove

I wrote a program for rock, paper, scissors with 4 buttons one extra for resetting. I wrote two functions one for computer move and one for player move. Along with that, it updates the wins, losses, and ties in the score object. so, I wrote the line to setItem in local storage for the score object in the playerMove function in the rock section. I wrote getItem for local storage at the beginning of the script.

I wrote removeItem in local storage in reset button and then it did not show me null. what should I do to improve?

    <!DOCTYPE html>
        <title>rockpaperscissor exercises</title>
        <body>
                  <script>
    
                    const score=
                    (JSON.parse(localStorage.getItem('score')));


                     function pickComputerMove()
                     {
                            const randomNumber= Math.random();
    
                        if(randomNumber >=0 && randomNumber <1/3)
                        {
                        computerMove='rock';
                        }

                        else if(randomNumber >=1/3 && randomNumber <2/3)
                        {
                        computerMove='paper';
                        }

                        else if(randomNumber >=2/3 && randomNumber <1)
                        {
                            computerMove='scissors';
                        }

                        return computerMove;
    
                     }


                function playGame(playerMove)
                {
                    const computerMove=pickComputerMove();
                
                    let result='';
                    if(playerMove === 'scissors')
                    {
                        if(computerMove === 'rock')
                        {
                            result='you lose';
                        }

                        else if(computerMove ==='paper')
                        {
                            result='you win';
                        }

                        else if(computerMove ==='scissors')
                        {
                            result='Tie';
                        }

                        if(result === 'you win'){
                            score.wins +=1;
                        }

                        else if(result === 'you lose'){
                            score.losses +=1;
                        }

                        else if(result ==='Tie'){
                            score.Ties +=1;
                        }

                        localStorage.setItem('score',JSON.stringify(score));
                        
                        alert(`you picked ${playerMove},
                        computer picked ${computerMove},${result}
                        wins: ${score.wins},losses: ${score.losses},Ties: ${score.Ties}`);
                    }


                    else if(playerMove ==='rock')
                    {
                        if(computerMove ==='rock')
                        {
                            result='Tie';
                        }

                        else if(computerMove ==='paper')
                        {
                            result='you lose';
                        }

                        else if(computerMove ==='scissors')
                        {
                            result='you win';
                        }


                        if(result === 'you win'){
                            score.wins +=1;
                        }
                        else if(result === 'you lose'){
                            score.losses +=1;
                        }
                        else if(result ==='Tie'){
                            score.Ties +=1;
                        }
                        alert(`you picked ${playerMove},
                        computer picked ${computerMove},${result}
                        wins: ${score.wins},losses: ${score.losses},Ties: ${score.Ties}`);
                    }
                    
                    else if(playerMove ==='paper')
                    {
                        if(computerMove ==='rock')
                        {
                            result='you win';
                        }
                        else if(computerMove ==='paper')
                        {
                            result='Tie';
                        }
                        else if(computerMove ==='scissors')
                        {
                            result='you loose';
                        }
    
                    if(result === 'you win'){
                        score.wins +=1;
                     }

                     else if(result === 'you loose'){
                        score.losses +=1;
                     }

                     else if(result ==='Tie'){
                         score.Ties +=1;
                      }

                        alert(`you picked ${playerMove},
                        computer picked ${computerMove},${result}
                        wins: ${score.wins},losses: ${score.losses},Ties: ${score.Ties}`);
                    }
                   
    
                }
                
                </script>

                <button onclick="
                playGame('rock');
                ">Rock</button>

            <button onclick="
            playGame('paper');
            ">paper</button>

            <button onclick="
            playGame('scissors');
            ">scissors</button>

            <button onclick="
            score.wins=0;
            score.losses=0;
            score.Ties=0;
            localStorage.removeItem('score');
            ">Reset score</button>
        
                
        </body>
        </html>

I expected a type error saying cannot read properties of null, but I didn’t get anything on the console