How to Center Align Horizontal Bars with Multiple Datasets

I’ve created a bar chart with a couple different datasets, and it works well. However, one dataset is bottom aligned, and the other is top aligned, allowing some minor overlap that would be prettier without. I’d like to just have the bars be centered, so it aligns with the text.

I’ve tried changing bar percentage, category percentage, and playing around with scales (stacked, align, etc).

my horizontal bar chart

const chartLoc = document.getElementById('chart').getContext('2d');
chart = new Chart(chartLoc, {
    type:'bar',
    data: jsonvar,
    options: {
        indexAxis: 'y',  
        layout: {
            padding: {
                right: 100
            }
        },
        plugins: {
            datalabels: {
                labels: {
                    label: {
                        anchor: "end",
                        align: "end",
                        clip: false,
                    }
                }
            }
        }
    },
    plugins: [ChartDataLabels],
});

Get file length for rss.xml enclosure tag in Eleventy

I have the following RSS feed in Eleventy v3.1.1. I wish to add the tag so I can include the featured image in the feed. The tag requires the length of the file in bytes. There are numerous ways to parse a file’s length, but how can I include it in the XML? I assume I’ll have to create some sort of filter in eleventy.js. but I have no idea where to start.

--json
{
  "permalink": "rss.xml",
  "eleventyExcludeFromCollections": true,
  "metadata": {
    "title": "My Website",
    "description": "A neato description",
    "language": "en-US",
    "base": "https://my.site/",
    "author": {
      "name": "John Q. Smith"
    }
  }
}
---
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xml:base="{{ metadata.base | addPathPrefixToFullUrl }}" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title><![CDATA[{{ metadata.title }}]]></title>
    <link>{{ metadata.base | addPathPrefixToFullUrl }}</link>
    <atom:link href="{{ permalink | htmlBaseUrl(metadata.base) }}" rel="self" type="application/rss+xml" />
    <description><![CDATA[{{ metadata.description }}]]></description>
    <language>{{ metadata.language or page.lang }}</language>
    <category>Blog</category>
    <copyright>Copyright © 2012{{ helpers.currentYearRSS() | safe }} John Q. Smith. All rights reserved.</copyright>
    <image>
      <url>https://my.site/assets/images/site/logo.png</url>
      <title><![CDATA[{{ metadata.title }}]]></title>
      <link>{{ metadata.base | addPathPrefixToFullUrl }}</link>
      <description><![CDATA[{{ metadata.description }}]]></description>
      <width>144</width>
      <height>144</height>
    </image>
    {%- for post in collections.blog | sortByPubDate | reverse %}
    {%- set absolutePostUrl = post.url | htmlBaseUrl(metadata.base) %}
    <item>
      <title><![CDATA[{{ post.data.title }}]]></title>
      <link>{{ absolutePostUrl }}</link>
      <description><![CDATA[{{ post.data.excerpt }}]]></description>
      <pubDate>{{ post.data.pubdate | dateToRfc822 }}</pubDate>
      <lastBuildDate>{{ post.date | dateToRfc822 }}</lastBuildDate>
      <dc:creator>{{ metadata.author.name }}</dc:creator>
      <guid>{{ absolutePostUrl }}</guid>
      <enclosure url="https://my.site/{{ post.data.image }}"
    length="" type="image/jpeg" />
    </item>
    {%- endfor %}
  </channel>
</rss>

Storing a variable without changing its value and storing a variable that changes its value

I have two codes. The first uses the variable b, and the second uses the variable a. The variable b does not change its value, while the variable a changes its value multiple times in the for loop. I get the same performance result for both codes. Why ???

Code 1 :

    var A = performance.now();
    var b = 5;
    let a = 0;
    const demo = document.getElementsByClassName("demo");
    for (let i = 0; i < demo.length; i++) {
        demo[i].addEventListener("click", function() {
            a += i;
            this.style.color = "red";
        });
    }
    demo[0].click();
    document.getElementById("femo").addEventListener("click", function() {
        for (let i = 0; i < demo.length; i++) {
            demo[i].innerHTML = b;
        }
    });
    var B = performance.now();
    alert(B-A);

code 2 :

    var A = performance.now();
    var b = 5;
    let a = 0;
    const demo = document.getElementsByClassName("demo");
    for (let i = 0; i < demo.length; i++) {
        demo[i].addEventListener("click", function() {
            a += i;
            this.style.color = "red";
        });
    }
    demo[0].click();
    document.getElementById("femo").addEventListener("click", function() {
        for (let i = 0; i < demo.length; i++) {
            demo[i].innerHTML = a;
        }
    });
    var B = performance.now();
    alert(B-A);

How to set seprate IFRAME body to each TextArea in view page using TextArea(Kendo) [Seting up Max Limit to text area]

I am working on a project which contain multiple textarea (Kendo editor). I want to set character limit to each textArea. I have tried achieve that using max length , setting keyDown and focus event but nothing works. I am not sure if this because of the Kendo editor or not. I got below link (Kendo UI Editor max and minimum characters) from that I come to below solution, but this solution adds a single iframe element for all textarea elements. The keydown event of any textarea affects the character limit message of all the textArea elements. I am looking for help achieve working with independent textarea elements.

HTML code:

<form class="LandindPage">
  <div class="form-group">
    <label>
      Heading 1 (0-100 character) <span class="mandatory">*</span>
    </label>
     
    <textarea
      class="kendo-input-editor"
      id="HeadingMessage1"
      onkeydown="HeadingMessage1Validation()"
      aria-label="editor"
      disabled
    >
      @Html.Raw(Model.HeadingMessage1)
    </textarea>
    <p class="text-warning">
      Heading 1 Character Count: <span class="text-warning" id="Head1textCount"></span>
    </p>
  </div>
  <div class="form-group">
    <label>
      Heading 2 (0-100 character) <span class="mandatory">*</span>
    </label>
    <textarea
      class="kendo-input-editor"
      id="HeadingMessage2"
      onkeydown="Heading2Validation()"
      aria-label="editor"
      disabled
    >
      @Html.Raw(Model.HeadingMessage2)
    </textarea>
    @* <p class="text-warning">Heading 2 Character Count: <span class="text-warning" id="Head2textCount"></span></p> *@
  </div>
</form>
$(document).ready(function () {
    $(function HeadingMessage1Validation() {       
        var minChar = 1;
        var maxChar = 100;
        var iframe1 = $("iframe");
        var HeadMsg1 = $("#HeadingMessage1").val();
        var kendoDecode=htmlDecode(HeadMsg1);
        var HtmltagReplace = removeTags(kendoDecode);
        var CharCount = HtmltagReplace.length;

        // Change event for iframe body content
        iframe1.contents().find("body").on('keydown', function (e) {
            // Clean up
            textarea.disabled = true;

            // Get Body (.text() strips out HTML tags)
            var data = $(this).text();
            if (this.which < 32) {
                return; // Do nothing
            }

            var isEditKey = (e.keyCode == 8 || e.keyCode == 46);

            if (data.length == maxChar && !isEditKey) {
                $("#Head1textCount").text(data.length + " of Maximum Limit (100 Character) Warning : Maximum Limit Reached");
                e.preventDefault();
            } else if (data.length > maxChar) {
                // Maximum exceeded
                $(this).text(data.substring(0, maxChar));
            } else if (data.length < minChar) {
                $("#Head1textCount").text(data.length + " of Maximum Limit (100 Character)");
            } else {
                $("#Head1textCount").text(data.length + " of Maximum Limit (100 Character)");
            }
        });

        // OnLoad call to get starting count
        $("#Head1textCount").text(CharCount + " of Maximum Limit (100 Character)");
    });
});

Booking data filter by today’s date and later [closed]

i have made a website where you can make bookings and on your profile you will be able to see your bookings, but i want to filter it so you can only see the bookings from today and later, but idk how to do it

i have done this for now but now it says on my profile that there are no bookings even though there should be some shown

export async function loader({ request }: Route.LoaderArgs) {
  const session = await getSession(request.headers.get("cookie"));
  const authUserId = session.get("authUserId");

  if (!authUserId) {
    throw redirect("/signin");
  }

  const user = await User.findById(authUserId).lean();

  // Get today's date at 00:00:00 UTC
  const now = new Date();
  const todayUTC = new Date(
    Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
  );

  // Only show bookings that end today or in the future
  const bookings = await Booking.find({
    user: authUserId,
    startDate: { $gte: todayUTC },
  })
    .sort({ startDate: 1 })
    .lean();

  return { bookings: JSON.parse(JSON.stringify(bookings)), user };
}

How would you use JSDoc for VSCode intellisense on an extended class method

I’m working on a library, and would like some functionality that requires users (meaning the user of the library) to extend a class. On that class will be a method that the user should override, and which takes in a specific parameter. It might look something like this:

class BaseClass {
    /**
     * @param {context} context
     */
    myMethod(context) {
        console.warn('myMethod should be overwritten')
    }
}

class UsersClass extends BaseClass {
    myMethod(context) {
        /*...*/
    }
}

/**
 * @typedef {Object} context
 * 
 * @prop {String} contextString
 * @prop {Number} someNumber
 * etc.
 */

The problem is, when the user goes to write myMethod, there won’t be any intellisense for the context parameter (ie. context.contextString, etc. won’t show up).

Is there any way to add this without requiring users to get an extension, etc?

extra message shows

Problem Description

I have integrated webchat.js with Microsoft Copilot Studio using the Direct Line API. When programmatically sending messages back to the bot using the Web Chat dispatch action,
Copilot Studio is displaying the intended message but is also generating an additional unwanted message immediately after. (Please see screenshot)

Technical Details

Integration Setup:

  • Web Chat JS integrated with Copilot Studio
  • Using Direct Line API for communication
  • Dispatching messages programmatically via Web Chat store

Code Implementation:

if (userresponse === "disLiked") {
  // Send a message back to the bot
  store.dispatch({
    type: 'WEB_CHAT/SEND_MESSAGE',
    // type: 'DIRECT_LINE/POST_ACTIVITY',
    payload: {
      text: apologyMessage,
    }
  });
  return; // tried this as well
}

Expected Behavior:

  • Bot should display only the apologyMessage when user response is “disLiked”
  • No additional messages should appear

Actual Behavior:

  • Bot displays the intended apologyMessage correctly
  • An extra, unwanted message appears immediately after
  • This extra message disrupts the user experience

useAnimatedValue is not a function

I’m working on a small React Native project and I’m using the animated api for the first time. I’m attempting to make a small animated View that is pretty similar to the example given in their Docs. The issue I’m running into though is that when trying to run the project, I get this error:

TypeError: (0 , _index.useAnimatedValue) is not a function

I’m not sure what is happening, the component looks identical to what is being used in the example Docs

Here is the component:

import { Animated, useAnimatedValue } from "react-native";


const CookingView = (props) => {
  
  const cookAnim = useAnimatedValue(0);

  useEffect(() => {
    Animated.timing(cookAnim, {
      toValue: 1,
      duration: 10000,
      useNativeDriver: true,
    }).start();
  },[cookAnim]);

  return (
    <Animated.View 
      style={{
        ...props.style,
        opacity: cookAnim
      }}
    >
      { props.children }
    </Animated.View>
  );
}

export default CookingView;

Any ideas on to what is going on would be helpful. Thanks!

How to change MUI-X default Datagrid scrollbar styles?

I’m using MUI-X datagrid in my application. The default scrollbar looks bad and I don’t see any way to customize it. I saw a few threads in github and tried the code below but that doesn’t seem to work. Is there any fix for this at all?

sx={{
  '& .MuiDataGrid-virtualScroller::-webkit-scrollbar': {
    width: '0.4em',
  },
  '& .MuiDataGrid-virtualScroller::-webkit-scrollbar-track': {
    background: '#f1f1f1',
  },
  '& .MuiDataGrid-virtualScroller::-webkit-scrollbar-thumb': {
    background: '#6BADCE',
    background: '-webkit-linear-gradient(to bottom, #6BADCE, #d7dde8)',  
    background: 'linear-gradient(to bottom, #6BADCE, #d7dde8)',
    borderRadius:'10px',
  },
  '& .MuiDataGrid-virtualScroller::-webkit-scrollbar-thumb:hover': {
    background: '#555',
  },
}}

How to disable gyroscope window prompt aframe

Every time the page loads on mobile a window prompting the user to allow or deny gyroscope access appears (window). My website doesn’t need gyroscope so I turned “look-controls=”magicWindowTrackingEnabled: false;” ” and while it did fully disable the gyroscope, the dreaded window still pops up. On a page on which there is one aframe I got away with writing an extra bit of javascript which clicks the Deny button as soon as it loads, therefore the window doesn’t even have time to pop up and eveything looks fine, but on a different page with more aframes, this method failed, with it only clicking the first “Deny” button no matter what i tried. I haven’t found anything that helped on the internet and this is my first Stackoverflow question. Thanks!

P.S. I am using aframe 1.7.0 if that helps at all

Can’t find JavaScript method in generated TypeScript file

When I am submitted a form, one of my Javascript methods is showing as undefined.

I have a form I am using that is defined like this:

// Index.cshtml

<script src="~/js/compiled/site.js" asp-append-version="true"></script>
<script src="~/js/compiled/errors.js" asp-append-version="true"></script>

<form id="f1" method="post" data-ajax="true" data-ajax-method="post" data-ajax-complete="formSubmitted" onsubmit="formSubmitting();">
    <button class="btn btn-primary" type="submit" id="btnSubmit">
        <span>Click here!!!</span>
    </button>
</form>

The methods formSubmitting() and formSubmitted are defined in a TypeScript file:

// Javascript/site.ts

import { hideErrorMessage } from './errors';

export function formSubmitted(result: object): void {
    console.log("This gets hit");
    hideErrorMessage();
    console.log("This does not get hit");
}

export function formSubmitting(): void {
    console.log("hitting form submitting");
}

As you can see above, there isn’t much happening in formSubmitting() – it is just outputting to the log letting us know if finds this function, which it does.

The function formSubmitted is referencing another function called hideErrorMessage which is defined in the TypeScript file errors.ts:

// Javascript/errors.ts

export function hideErrorMessage(): void {
    console.log("Is this ever hit? The answer is no...");
}

The function hideErrorMessage() never gets hit, and instead produces this error in the logs:

Uncaught TypeError: Cannot read properties of undefined (reading 'hideErrorMessage')
    at HTMLFormElement.formSubmitted (site.ts:5:5)
    at Object.complete (jquery.unobtrusive-ajax.js:101:92)
    at fire (jquery.js:3223:31)
    at Object.fireWith (jquery.js:3353:7)
    at done (jquery.js:9642:21)
    at XMLHttpRequest.<anonymous> (jquery.js:9888:9)

I have my tsconfig.json set to compile the ts files here:

{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "outDir": "wwwroot/js/compiled",
    "moduleResolution": "node",
    "allowUnreachableCode": false,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "types": [ "jquery" ]
  },
  "compileOnSave": true,
  "exclude": [
    "node_modules",
    "wwwroot"
  ]
}

And that appears to be working, because it compiles the files the way I would expect:

// wwwroot/js/compiled/site.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formSubmitted = formSubmitted;
exports.formSubmitting = formSubmitting;
var errors_1 = require("./errors");
function formSubmitted(result) {
    console.log("This gets hit");
    (0, errors_1.hideErrorMessage)();
    console.log("This does not get hit");
}
function formSubmitting() {
    console.log("hitting form submitting");
}
//# sourceMappingURL=site.js.map
// wwwroot/js/compiled/errors.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hideErrorMessage = hideErrorMessage;
function hideErrorMessage() {
    console.log("Is this ever hit? The answer is no...");
}
//# sourceMappingURL=errors.js.map

So looking at the compiled output, hideErrorMessage() exists. So I don’t understand why it is showing as undefined?

I set up an example in GitHub if that is helpful.

Use the return value of a function for future evaluations [closed]

The table below is pulled from a database.
When I change the contents of a cell, I can see the result in the browser.
However, I can’t access the value of $newvalue outside the function, which prevents me from doing all my subsequent processing.

index.html

<html>
    <head>
        <link href="styles/styles.css" rel="stylesheet" />
        <script src="jquery-3.7.1.min.js"></script>
        <link rel="stylesheet" href="jquery-ui.min.css">
        <title>****________****</title>
    </head>
<body>

   
<?php
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    ?>
    <div text-align="center">
    <table>
        <tr>
            <?php
            while ($row = $result->fetch_array()) { ?> 
                <td contenteditale=false;><?php echo $row["name"]?></td>
                <?php 
                $i = 1;
                while ($i <= 31) {
                    $day = "d" . $i;  
                    $val = $row[$day]; 
                    ?>
                    <td contenteditable=true><?php echo $val ?></td>
                    <?php $i++; } ?>
        </tr>
        <?php
} 
$conn->close();
?>
</table>
</div>  
<script src="js/_main.js"></script>  
</body>
</html>

_main.js

$(document).ready(function() {
$(function(newdata) {
            var $newvalue ='';
            $('table td').blur(function() {
                console.log("new value: " + $(this).text()); // show the new value
                $newvalue = $(this).text();
                return $newvalue
            });
});
})

Trying to use Dom method to fetch messages [closed]

I am trying to use the fetch() method to fetch

get.php to load messages:

The problem is: ( 1.) messages are duplicated or sometime triplicated when loaded.

(2)The messageBox container is stable, it can play uploaded video alright.

The scrolling is stable ,but the messages keep duplicating or triplicating.

(3) When a new message is submitted by the user the message is displayed twice.What can I do?

Here is my code.

get.php

header(‘ Content-type: application/json’);

$lastId=isset($_GET[‘last_id’])?intval($_GET[‘last_id’]):0;

$groupID=$_GET[‘clubid’];

$qry=”select *from grp_messages where grpID=’$groupID’ and Id>’$lastId’ order by Id asc “;

$result= mysqli_query($link,$qry);

$output =” “;

while ($row=mysqli_fetch_assoc($result)){

$msgId=$row[‘Id’];

$clubid=$row[‘grpID];

$gpname=$row[‘grpName’];

$userid=$row[‘id_user’];

$first=$row[‘firstname’];

$last=$row[‘lastname’];

$usernamd=$row[‘username’];

$member_photo=$row[‘userProfPhoto’];

$message=$row[‘messages’];

$sent_on=$row[‘created_at’];

$dateMod=$row[‘created_at_modify’];

$message_photo=$row[‘grpMsgPhotos’];

$message_video=$row[‘grpMsgVideos’];

$message_video_ext=$row[‘grpMsgExtentions’];

$profile_photo_path=”usersPphotos/”;

$message_photo_path=”grpChatPhotos/”;

$message_video_path=”grpChatVideos/”;

video_show=”grpChatVideos/$message_video”;

$trc=$message_photo_path.$message_photo;

$Tsrc=$profile_photo_path.$member_photo ;

$imagalt=”Loading Image ….”;

$redirect=
”<a id=”refN”href=”mem_profile.php?…….”>”;

If($message_video==” “){

$msgvideo=” “;

}
else{

$msgvideo = “

<video onerror=”this.style.display=’none’” id=’msg_videotag’ loop muted controls><source src=’$video_show’type=’video/$message_video_ext’> Your browser doesn’t support the video tag.
”;

}

if(($message_video !=’’)&&($message_photo ==’’ )){

$output.=””;

$output.=”

$redirect

$first $last:

$msgvideo$message

Sent:”.$dateMod.””;

$output.=””;

}

$lastId=$msgId;

}

echo json_encode([“last_id”=>$lastId,”messages”=>
$output]);

JavaScript script.js
messageBox= document.getElementById(‘messages’);

var clubID=document.getElementById(‘clubid’). value;

var lastMessageId=0;

setInterval(()=>{

var isAtBottom=messageBox.scrollTop + messageBox.clientHeight >=messageBox.scrollHeight-10;

fetch(‘get.php? last_id=’ + lastMessageId + ‘&clubid=’ + clubID)

.then(response=>response.json())

.then(data=>{

if(data.messages){

document.getElementById(‘contbox’).style.display=”none “;

var tempDiv= document.createElement(‘div’);

temDiv.innerHTML= data.messages;

lastMessageId=data.last_id;

var lastChild=tempDiv.lastElementChild;

var lastMsgId=lastChild? lastChild.getAttribute(‘data-id):null ;

Array.from(tempDiv.children).for each(msg=>{

var msgId=msg.getAttribute(‘data-id’);

if(!msgId.includes(lastMsgId+1)){

messageBox.appendChild(msg);

}

});

if(isAtBottom){

messageBox.scrollTop = messageBox.scrollHeight ;

}

}

})

},1000);

PCIbex sequence of trials resulting in blank screen

I have been trying to code an experiment in PCIbex farm, where stimuli are kept in a .csv file. Prime and target trials are created from a pair of sentences (in the .csv file they’re located in the same row).

The problem is – there always is only a blank screen when I try running this code. In the logs it’s OK: the sentences are read and all. I’ve also tried generating unique IDs for each trial created from a template, but it didn’t help + the .csv is too long to write the sequence manually. Naming the trials within the template differently (training_prime and training_target)

As my experimental trials have the same structure as the training ones, here is the simplified version of the script. It is supposed to generate “training_prime” and “training_target” trials dynamically from the training_trials.csv file. Each “training_prime” is immediately followed by its corresponding “training_target”, maintaining the pairing from the same row:

PennController.ResetPrefix(null)

Sequence(
    randomize("training"),
    SendResults()
)

Template("training_trials.csv", row =>
[
  newTrial("training",
    newText("PRIME: " + row.prime_sentence).print(),
    newController("AcceptabilityJudgment", {
        s: row.prime_sentence,
        as: ["1", "2", "3", "4", "5", "6", "7"],
        presentAsScale: true,
        instructions: "Evaluate the sentence",
        leftComment: "weird",
        rightComment: "good"
    }).center().print().wait(),
    newTimer("pause", 300).start().wait()
  ),

  newTrial("training",
    newText("TARGET: " + row.target_sentence.replace("___", "<input type='text' id='gap'>")).print(),
    newButton("Next").print().wait()
  )
])

And here is training_trials.csv:

pairID,prime_sentence,target_sentence
t1,PRIME 1.,In a hole in the ground there lived a ___.
t2,PRIME 2.,A mouse took a stroll through the ___ dark wood.

I’ve spent an inadequately long time on this…