How to I add the sum of 2 dice throw continuously in JS?

I’m doing a school project of a dice game, the player select a number between 6-9 and afterwards throw two dices. If the dices show the chosen number, its game over. But i cant get the sum to add upp after each throw, it just shows each specific throws sum.

Also, how do i get the program to understand that it’s game over when the dices shows the “knockout” number?



let knockoutSiffra = 0;

const dices = document.querySelectorAll('.dice');
console.log(dices);

dices.forEach(bt =>{
    bt.addEventListener('click', (e) =>{
        knockoutSiffra = e.target.innerHTML;
        console.log(knockoutSiffra)
    })
})

document.getElementById('go')
.addEventListener('click', () => {


    if(knockoutSiffra != 0){
        choose.style.display = 'none'
        play.style.display = 'block'
        console.log('kör')
    }
        
        else{
            console.log('välj ett nummer')
            

        }

        const showNumber = document.getElementById('showNumber');
        showNumber.innerText = 'Ditt valda nummer är:' + " " + knockoutSiffra

      
    })

// Slide 3

     let lost = document.querySelector('.lost')
       lost.style.display = 'none';

      const dice1 = document.querySelector('.dice1');
      const dice2 = document.querySelector('.dice2');
      const result = document.querySelector('.dice-result');
      const game = document.querySelector('.game');

     let score = 0;

      game.addEventListener('click', () => {
          let d1 = GetRandomDice ();
          let d2 = GetRandomDice ();


          dice1.src = `Dice img/Dice-${d1}.png`;
          dice2.src = `Dice img/Dice-${d2}.png`;


          let sum = d1 + d2;
          result.innerText = 'Antal poäng:' + " " + sum;

          function GetRandomDice(){
            return Math.ceil(Math.random() * 6);


        }
          
      })





This is just the last part of the HTML


    <h1 id="showNumber">Ditt valda nummer är: </h1>
    <h2 class="dice-result">Antal poäng:</h2>

    <button class="game">Kasta tärningarna</button>
    

    <section class="throw">
       <img src="Dice img/Dice-3.png" alt="3" class="dice1">
       <img src="Dice img/Dice-6.png" alt="6" class="dice2">
    </section>

    <section>
        <h2 class="lost">Du förlorade!</h2>
        <button class="playAgain">Spela igen</button>

Tried very much of different stuff but i can’t get the code to work properly.

Have bottom var accessible on top

Make JS function at bottom set var at top.

My js function post_count_function only works at the bottom of my JS, Not sure why.

but I need to pass the var to the top to use in a different function, is there a simple solution ?

    var post_count = 0;
    

Alpine.data("filterPosts", (adminURL) => ({
    posts: "",
    limit: 6,
    category: 0,
    post_type_js: post_id,
    showDefault: true,
    showFiltered: false,
    offset: 0,
    total: 0,
    
    
    filterPosts(id) {
        this.showDefault = false;
        this.showFiltered = true;
        this.category = id;
        this.offset = 0; // <-- reset offset to zero
        this.fetchPosts();
        this.total = post_count;
    },
    
    loadMore() {
        this.loadingMore = true;
        this.offset += 6;
        this.showFiltered = true;
        this.fetchPosts(true);
    },

    fetchPosts(append = false) {
        var formData = new FormData();
        formData.append("action", "filterPosts");
        formData.append("limit", this.limit);
        formData.append("post_type_js", this.post_type_js);
        formData.append("offset", this.offset); 

        if (this.category) {
            formData.append("category", this.category);
            formData.append("total", this.total);
        }

    fetch(adminURL, {
        method: "POST",
        body: formData,
    })
    .then((res) => res.json())
    .then((res) => {
            if (append) {
                // Appends posts to the end of existing posts data
                this.posts = this.posts.concat(res.posts);
            } else {
                // Resets the posts data with new data
                this.posts = res.posts;
            }

            this.loading = false;
        });
    },
    
    getTotal() {
    var formData = new FormData();
    formData.append("action", "filterPosts");
    fetch(adminURL, {
        method: "POST",
        body: formData,
    })
    .then((res) => res.json())
    .then((res) => {
        this.total = res.total;
    });
},

init() {
    this.getTotal();
}

}));
})

 function post_count_function(obj) {
    var post_count = obj.getAttribute('data-value')
    console.log("post amount", post_count);
}

I need post_count at the top, but if i place the function at the top of the page i get not defined

Dynamic Google Tag Manager Load on Cookie Consent | 404 Error

I’m trying to dynamically load Google Tag Manager (GTM) based on user consent in a JavaScript function. My GTM ID is correct and the container is published (and updated).

I’m getting a 404 Not Found error when the script attempts to load.

This is the function I’ve written to load it:


function loadGTM() {
  if (window.dataLayer && window.dataLayer.find(obj => obj['gtm.start'])) {
    console.log('GTM already loaded');
    return;
  }
  
  (function(w, d, s, l, i) {
    w[l] = w[l] || [];
    w[l].push({
      'gtm.start': new Date().getTime(),
      event: 'gtm.js'
    });
    var f = d.getElementsByTagName(s)[0],
      j = d.createElement(s),
      dl = l != 'dataLayer' ? '&l=' + l : '';
    j.async = true;
    j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
    f.parentNode.insertBefore(j, f);
    
    console.log('GTM URL:', j.src);
  })(window, document, 'script', 'dataLayer', 'GTM-XXXXXXX');
}

The console logs the GTM URL being requested i.e https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXXX

The browser’s Network tab shows a 404 error for the GTM script request.

Any suggestions on what might be causing this issue and how to resolve it would be greatly appreciated. This is the first time I’ve dynamically loaded GTM on my site before.

Please let me know if you need any more information to help find the issue.

Kind regards

How to navigate to next page using selenium by finding the javscript URL within div

Using selenium and bs4 in Python, if I run the following code

driver = webdriver.Chrome()
driver.get(url)   # url = https://www.marathon.tokyo/2023/result/index.php, choose Men Marathon in first option, should show the 50 result entries on each page
soup = BeautifulSoup(driver.page_source)

then part of the course code is as follow:

<div class="fnav pager pagerBottom mb40">
<p class="taR">51~100/27927</p>
<ul>
<li><a href="javascript:page(1);">1</a></li><li><span>2</span></li><li><a href="javascript:page(3);">3</a></li><li><a href="javascript:page(4);">4</a></li><li><a href="javascript:page(5);">5</a></li><li><a href="javascript:page(6);">6</a></li><li><a href="javascript:page(7);">7</a></li> </ul>
</div>

This is essentially the navigation panel for going to different pages. How to locate the ‘clickable’ element, e.g. "javascript:page(X);"? I try the following

out = driver.find_element(By.CSS_SELECTOR, 'div.fnav li > a')
out.click()

But out seems to contain only the first clickable element, e.g. if I’m on page 1, it goes to page 2, if I’m on page 2, it goes to page 1. How to click on the ‘next’ page? Page 1 -> page 2 -> page 3 and so on?

Send json in a delete request

I need to send a JSON to the API. It is a delete request. With the POST I don’t have any problems but here I do…

  delReq(req: IReq): Observable<IReqResponse> {
    const url= this.utils.surl;
    return this.http.delete<IReqResponse>(url, JSON.stringify(req))
      .pipe(catchError(this.handleError<IReqResponse>('delReq'))
    );
  }

Appears “No overload matches this call”

Typeorm trying to update non-existing entity

So I’m trying to run this code:

const entities = await this.repository.createQueryBuilder(User)
      .leftJoinAndSelect(`User.photos`, 'photos') // One-to-many
      .leftJoinAndSelect('photos.status', 'photoStatus') // One-to-one
      .where('photoStatus.status = :status', { status: PhotoEnum.READY_TO_SEND })
      .getMany();

And then performing some operations to update status inside PhotoStatus entity for every user. Assume that I have updated status to new one and then I’m running this code:

    const userEntities = aggregates.map(aggregate => aggregate.userEntity);
    if (tr) {
      await tr.save(userEntities);
      return;
    }
    await this.repository.save(userEntities)

In my database I have one user with two photos and only first photo has status inside and another one doesn’t have. When I’m logging userEntities, I see one entity with one photo attached. But when I’m running save for these entities batch, I’m encountering that typeorm also trying to update another photo, that don’t have status. It cause a lot of problems and the thing is that I cannot filter out this “invinsible” photo in my aggregate. What can be the solution here? I don’t want to filter them after query

I wrote this part-time solution, but I want to get all required users with photos from query.

const trueEntity = userEntities.filter((e) => {
      const entity = e.photos.find((t) =>
        t.photoStatus?.status === PhotoEnum.READY_TO_SEND);
      if (entity) {
        return e;
      }
    });

Print Label With Labelwriter 450 In Laravel

I want to print label in Laravel with data coming dynamic and i want to use LabelWriter 450 for this purpose width: 89mm; height: 41mm; how can i do that?

i try following code but it open full page for printing not according to size

 <style>
        @media print {
            body * {
                visibility: hidden;
            }

            .label,
            .label * {
                visibility: visible;
            }

            .label {
                width: 89mm;
                height: 41mm;
            }
        }
    </style>
</head>

<body>
    <div id="labelContent" class="label">
        <button type="button" class="btn btn-info" id="printButton" onclick="printLabel()">Print</button>

        <h3>Order ID: {{ $repair->id }}</h3>
        <p>Client ID: {{ $repair->user->id }}</p>
        <p>Order Date: {{ $repair->created_at->format('Y-m-d') }}</p>
        <p>Fault: {{ $repair->selected_issues }}
        </p>
        <p>Pin/Password: {{ $repair->password }}</p>
        <p>Authorize For Reset: {{ !empty($repair->authorization) ? 'Yes' : 'No' }}</p>
    </div>
    <script>
        function printLabel() {
            window.print();
        }

    </script>
</body>

what should i try now to print with specific width and height

I’ve got a GridView in my yii2 project and I want to make the list of rows sortable

Please note that I am doing this with JavaScript and Jquery, I did not download any 3rd party extensions. And I’ve actually done this before so I’m not really sure why it’s not working.

This is my JS code:

<script>
$(document).ready(function() {
    $('tbody').sortable({
        items: 'tr',
        cursor: 'move',
        update: function(event, ui) {
            var ids = [];
            $('tbody tr').each(function() {
                var id = $(this).data('key');
                if(id !== undefined && id !== null && id !== '') {
                    ids.push(id);
                }
            });
            console.log(ids);

            $.ajax({
                type: 'POST',
                url: '/index.php?r=admin/case/updateorder&ids=' + ids + '',
                data: { ids: ids, _csrf: '<?= Yii::$app->request->csrfToken ?>' },
                success: function (data) {
                    // Handle success if needed
                },
                error: function () {
                    // Handle error if needed
                }
            });
        }
    });
});

</script>

And this is the function in my controller:

public function actionUpdateorder($ids)
{
    $array = explode(",", $ids);
    $count = count($array);
    $i = 1;
    if (isset($data['ids'])) {
        $ids = $data['ids'];
        $array = explode(",", $ids);
        $count = count($array);
        $i = 1;

        foreach($array as $id) {
            $model = CaseTask::findOne($id);
            if ($model !== null) {
                $model->order = $i;
                $model->save();
                $i++;
            }
        }

        Yii::$app->response->format = yiiwebResponse::FORMAT_JSON;
        return ['success' => true];
    } else {
        Yii::$app->response->setStatusCode(400);
        return ['error' => 'Invalid request. Missing ids parameter.'];
    }
}

The sort functionality in the gridview actually works perfectly but everytime I sort I am getting this error:

Invalid Argument – yiibaseInvalidArgumentException
Response content must not be an array.

Because of it my sort data in my order column in my db is not saving. Anyone know what the problem is??

I tried transferring my data with JSON but that always returns null for me for some reason that is why i’ve resorted to trying to send my array through the URL, but I think that is the problem.

Cannot iterate through elements in JS [closed]

I am saving links as string into a array.

When I print the whole array, I prints out all the values:
enter image description here

When I try to access individual values, I just get ‘undefined’.
Eg: console.log(“First element: ” + WhatsappLinks[0]); returns First element: undefined

I save the values in the array using WhatsappLinks.push(/string value here/);

What am i doing wrong? WhatsappLinks.length also returns zero.

Tried iterating the array using a foreach function, but that also doesnt work.

After code signing and notarizing, my program that builds with electron-builder not opening.(MacOS ARM)

enter image description here

if I open from terminal:

open TopCreator.app
The application cannot be opened for an unexpected reason, error=Error Domain=RBSRequestErrorDomain Code=5 “Launch failed.” UserInfo={NSLocalizedFailureReason=Launch failed., NSUnderlyingError=0x600002205530 {Error Domain=NSPOSIXErrorDomain Code=153 “Unknown error: 153” UserInfo={NSLocalizedDescription=Launchd job spawn failed}}}

I tried to add this:

require('dotenv').config();
const fs = require('fs')
const path = require('path')
const electron_notarize = require('electron-notarize');

module.exports = async function (params) {
    if (process.platform !== 'darwin') {
        return console.log('Platform si now MacOS')
    }

    let appId = '***'

    let appPath = path.join(
        params.appOutDir,
        `${params.packager.appInfo.productFilename}.app`
    )
    if (!fs.existsSync(appPath)) {
        console.log('File not exist')
        return
    }

    console.log(`Notarizing ${appId} found at ${appPath} with Apple ID ${process.env.APPLE_ID}`)

    try {
        await electron_notarize.notarize({
            appBundleId: appId,
            appPath: appPath,
            appleId: process.env.APPLE_ID,
            appleIdPassword: process.env.APPLE_ID_PASSWORD
        })
    } catch (error) {
        console.error(error)
    }

    console.log(`Done notarizing ${appId}`)
}

it notarize succesfully, but program not opening.

adminjs, update mongoDB with custom component in list

Could not understand what is wrong while trying to update a param of an object in DB through custom component in adminjs. Receiving

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Probably need something additional with data manipulation on mongoDB. Can’t understand what exactly with this custom actions. Maybe someone can help with this

index.js

import AdminJS from "adminjs"
import { buildRouter as AdminJSExpress } from "@adminjs/express"
import express from "express"
import mongoose from "mongoose"
import * as AdminJSMongoose from "@adminjs/mongoose"

import { componentLoader } from "./componentLoader.js"
import { OfferStatus } from "./offerStatus.js"

const PORT = 3000
const DB = "..."

AdminJS.registerAdapter({
  Resource: AdminJSMongoose.Resource,
  Database: AdminJSMongoose.Database,
})

const startAdminJS = async () => {
  try {
    await mongoose.connect(DB, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
    console.log("Connected to MongoDB")

    const app = express()

    const admin = new AdminJS({
      resources: [OfferStatus],
      componentLoader: componentLoader,
    })

    const adminRouter = AdminJSExpress(admin)

    app.use(admin.options.rootPath, adminRouter)
    admin.watch()

    app.listen(PORT, () => {
      console.log(
        `Listening on port ${PORT}, AdminJS server started on URL: http://localhost:${PORT}${admin.options.rootPath}`
      )
    })
  } catch (error) {
    console.error("Error starting AdminJS", error)
  }
}

startAdminJS()

entity

import mongoose from "mongoose"

const orderSchema = new mongoose.Schema({
  network_id: {
    type: Number,
    required: true,
  },
  offer_status: { type: Boolean, required: true },
})

export const Order = mongoose.model("Order", orderSchema)

resource options

import { Order } from "./order.entity.js"
import { Components } from "./componentLoader.js"

const toggleStatusAction = {
  name: "toggleStatus",
  actionType: "record",
  isVisible: true,
  handler: async (request, context) => {
    const { record, resource } = context
    if (record.isValid() && record.param("offer_status") !== undefined) {
      await resource.update(request.params.recordId, {
        offer_status: !record.param("offer_status"),
      })
      return {
        record: record.toJSON(),
        notice: {
          message: "Status successfully toggled",
          type: "success",
        },
      }
    } else {
      throw new AdminJS.ValidationError(
        {
          offer_status: {
            message: "Status could not be toggled",
          },
        },
        {
          message: "An error occurred during status toggle",
        }
      )
    }
  },
  components: {
    list: Components.CustomCheckbox,
  },
}

export const OfferStatus = {
  resource: Order,
  options: {
    properties: {
      _id: {
        type: "string",
        isVisible: {
          edit: false,
          show: false,
          list: false,
          filter: false,
        },
      },
      offer_status: {
        type: "boolean",
        components: {
          list: Components.CustomCheckbox,
        },
      },
    },
  },
  actions: {
    toggleStatus: toggleStatusAction,
  },
}

custom component

import React, { useState } from "react"
import { CheckBox } from "@adminjs/design-system"

const CustomCheckbox = ({ record, property }) => {
  const [checked, setChecked] = useState(record.params[property.name])

  const handleChange = async () => {
    const newValue = !checked
    setChecked(newValue)

    try {
      await fetch(
        `/admin/api/resources/Order/records/${record.id}/toggleStatus`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            recordId: record.id,
          }),
        }
      )
    } catch (error) {
      console.error("Error to change status", error)
      setChecked(!newValue)
    }
  }

  return <CheckBox checked={checked} onChange={handleChange} />
}

export default CustomCheckbox

The Ribbon Workbench Enable rule is not firing only when Group By is applied on an editable grid

I am currently experiencing following issue and would greatly appreciate any assistance. Thanking you in advance.

Issue Description:

  • The Ribbon Workbench Enable rule is not firing only when Group By is applied on an editable grid.
  • The enable rule fires in all other cases, such as for single-record selection and even for multiple-record selection(Select All) when Group By is not applied.
  • Surprisingly, it also works for single-record selection manually even when grouping is applied, but it does not work only for ‘Select all’ selection when grouping is applied.
  • Note: The editable grid is formed by applying the Editable Grid component on a normal Subgrid.

Detailed Explanation:

  • I’ve added an ‘Approve’ button to the editable subgrid using Ribbon Workbench. 
  • The visibility logic of the button is controlled by an enable rule, which involves a Custom Rule calling JavaScript logic. 
  • The visibility works seamlessly with both normal subgrids and editable subgrids, except in one scenario where Group By is applied to the editable grid.
  • In the working scenario, when all records are selected in the editable grid and Group By is set to ‘no Grouping,’ the ‘Approve’ button is visible. Deselecting all records hides the ‘Approve’ button.
  • However, in a non-working scenario, when all records are selected in the editable grid and Group By is set to ‘Start Date,’ the ‘Approve’ button should be visible, but it remains hidden. The issue lies in the enable rule not getting fired in this case, specifically when Group By is applied to ‘Start Date.’

respond write function in Server Sent Event api not writing back to client

I am writing a persistent real time application that consumes a Server Sent Event API. I am using NodeJS as listening client and another NodeJS as SSE api that act as a server. The both api worked as expected as the client api consumed and receives persistent message from the SSE Server but there are some logical errors.

***The Problem

a) Inside the Server Sent Event api route “/sample/api/v1/test”, the respond write function message inside the set Interval function was not executed but if there is any syntax error inside the set Interval function, it would be detected but it was not writing message back to the listening client using the response write function when inside the set Interval.

b) The callback function inside the transporter send Mail function, the conditional checking of the callback function(error, response) to know if email is sent or not does not send response write function back to the client but it sent console log message to the console of the SSE server running the api.

I am concerned why response write was not sent inside set interval function and inside the transporter send Mail call back function.

// *** THE SERVER SENT EVENT

const express = require("express");
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const http = require("http");    //DEVELOPMENT PROCESS
const https = require('https'); 

var corsOptions = {  
  origin: 'http://127.0.0.1:3001',
  methods: ["GET","HEAD","PUT","PATCH","POST","DELETE"],  
};

 let emailSenderOptions = (to, subject, htmlToSend, fromEmail) =>{
  return mailOptions = {
   from: fromEmail,
   to : to,
   subject : subject,
   html : htmlToSend   
};
}


app.post('/sample/api/v1/test', (req, res) => {

res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        Connection: 'keep-alive',
        'Cache-Control': 'no-cache',
    });

//this set timeout is not executed and not delaying for 10secs here
setTimeout(function () {
  console.log("Please wait");
}, 10000);


/* The compiler is not executing the res.write message inside the setInterval. I want everything to be sent to client API every 5 seconds.*/

setInterval(() => {
  res.write("Server: API Found");

  res.write(`nConnected at ${new Date()} n n`);

transporter.sendMail(emailSenderOptions(emailSenderOptions("[email protected]", "SAMPLE SUBJECT", "This is a sample as a letter body", "[email protected]"), function (error, response) {
    if (error) {
          
          //for an email that is not sent, this line is not sent to nodejs client
          res.write(`Email could not be sent`);

         /* for an email that is not sent, this line is successfully logged to the console.log of running nodejs server. It means that this line is executed but why is the res.write() not executed or sent to nodejs api*/

         console.log(chalk.red(`Email could not be sent.`));        
    }

    else{
          
         //for an email that is successfully sent, this line is not sent to nodejs client

         res.write(`Email has been sent.`);


    /* for an email that was successfully sent, this line is successfully logged to the console.log of running nodejs server. It means that this line is executed but why is the res.write() not executed or sent to nodejs api*/

         console.log(chalk.green(`Email has been sent`));
    }
}); 


}, 5000);


// compiler only executes the res.write message and send back to listening client from here

  res.write(`nConnected at ${new Date()} n`);

  res.write(`Only from here is sent back to listening client.  n n`);

transporter.sendMail(emailSenderOptions("[email protected]", "SAMPLE SUBJECT", "This is a sample as a letter body", "[email protected]"), function (error, response) {
    if (error) {
          
            //for an email that is not sent, this line is not sent to nodejs client
          res.write(`Email could not be sent`);

         /* for an email that is not sent, this line is successfully logged to the console.log of running nodejs server. It means that this line is executed but why is the res.write() not executed or sent to nodejs api*/

         console.log(chalk.red(`Email could not be sent.`));        
    }

    else{
          
         //for an email that is successfully sent, this line is not sent to nodejs client

         res.write(`Email has been sent.`);


    /* for an email that was successfully sent, this line is successfully logged to the console.log of running nodejs server. It means that this line is executed but why is the res.write() not executed or sent to nodejs api*/

         console.log(chalk.green(`Email has been sent`));
    }
}); 

});

================================NODEJS CLIENT

const express = require("express");
const app = express();
const http = require('http');
const https = require('https');
const fs = require("fs");
const checkinternetconnected = require('check-internet-connected');
const axios = require('axios');
var EventSource = require('eventsource');


app.use(express.json()); 

var server = http.createServer(app);

var connected = true;

const requestService = () =>{  

  var url = `/sample/api/v1/test`

  let payload = {
    username: username,
  };
  
  axios({
    url: url,
    method: 'post',
    data: payload
  })
  .then(function (response) {
      // your action after success
      console.log(response.data);
  })
  .catch(function (error) {
     // your action on error success
      console.log(error);
  });
}

const persistentRespond = (req, res) => {
  try {
    const e = new EventSource('http://127.0.0.1:3002/xc3113n77001z/api/v1/subscribe');

      e.addEventListener("Server Respond: ", (e) => {
        const data = e.data;

       // Your data
        console.log(`${data}`)
        
    })
    
res.on('close', () => {
        e.removeEventListener("Server Closed", (e) => {
      });
    })
  } catch (err) {
    console.log(err)
  } 
}


server.listen(port, host);
server.on('listening', function() {
    console.log(`Waiting for respond from server application n n `);

requestService();

persistentRespond();

});

***What I expected

  1. I wanted response write function to write message to the listening client every 5 seconds from inside set interval function.

  2. I wanted to write back to the listening client from transporter send mail function call back function if the email was sent or not.