Create Date range chart using JS

I’m trying to create a chart like this (I’m currently using chart.js, but library doesn’t make sense).

image

So please give any suggestions to implement it.
perhaps you have a ready-made solution.

X axis provide date in format MMM/dd
Y destination city
In data we have 3 filed: startDate, endDate, City

Angular: show file list from FileSystemDirectoryHandle

FileSystemDirectoryHandle provides the list of entries of the directory by values(), which I want to display in the Angular HTML template.

@Component({
  selector: 'parent-component',
  standalone: true,
  imports: [],
  template: `
<div>
<input type="submit" (click)="handleButton()" value="Choose directory" />
</div>

<ol>
@for(let file of files | async; track file.name) {
   <li>{{file.name}}</li>
}
</ol>
`
})
export class FileListComponent
{
  private directorySubject = new Subject<FileSystemDirectoryHandle>()
  public readonly directory = this.directorySubject.asObservable()

   public async handleButton() : void {
      const path = await window.showDirectoryPicker()
      this.directorySubject.next(path)
   }

   public get files(): Observable<(FileSystemDirectoryHandle | FileSystemFileHandle)[]> {
      return this.directory
      .subscribe( d => {
         const result : (FileSystemDirectoryHandle | FileSystemFileHandle)[] = []
         for(const entry of await d.values()) {
            result.push(entry)
         }
         return result
      } )
   }
}

MongoDB complex Aggregate function

I’m facing a problem with aggregate function done on MongoDB schema model the case is I do have Model Orders that has the following form.
enter image description here

and an order model that has the following form.
enter image description here

What I want to do is to filter totalsales by medicine name so for example if I have panadol, catafast, test
I want to know how much Panadol I have sold and so on .
I’m trying to use an aggregate function to group me all completed orders and filter them then trying to lookup for the medicine name by the id in the array. however I got an empty array and I’m pretty sure of my data. what I’m not sure about is the pipeline in the function.

const getSalesDataByMedicine = async (req, res) => {

    try {
        const medicineSales = await Orders.aggregate([
            {
                $match: {
                    status: "Completed"
                }
            },
            {
                $unwind: "$items"
            },
            {
                $group: {
                    _id: "$items.MedicineId",
                    totalQuantity: { $sum: "$items.Quantity" },
                    totalAmount: { $sum: { $multiply: ["$items.Quantity", "$amount"] } }
                }
            },
            {
                $lookup: {
                    from: "medicine", // Replace with the actual name of your Medicine model's collection
                    localField: "_id",
                    foreignField: "MedicineId", // Assuming Medicine _id is used in MedicineId field
                    as: "medicineData"
                }
            },
            {
                $unwind: "$medicineData"
            },
            {
                $project: {
                    _id: 0,
                    medicineId: "$_id",
                    medicineName: "$medicineData.name", // Adjust to your actual field name in Medicine model
                    totalQuantity: 1,
                    totalAmount: 1
                }
            }
        ]);

        return res.status(200).json(medicineSales);
    } catch (err) {
        console.error("Error fetching medicine sales data:", err);
        return res.status(500).json({ error: "Internal Server Error" });
    }


};

Thanks in advance,

how to read Json res has periods within the keys [duplicate]

Im calling an API that returns key/value pairs with a ‘.’ inside of the key.

"sdm.devices.traits.Humidity": {
    "ambientHumidityPercent": 39
},

how can I read this? This will not work.

nest.thermostat.push({
    "humidity": json.devices[0].traits.sdm.devices.traits.Humidity.ambientHumidityPercent
});

im getting a undefined because the key itself is "sdm.devices.traits.Humidity" but when I pull it, nots undefined.

Ive tried this as well..

"humidity": json.devices[0].traits.["sdm.devices.traits.Humidity"].ambientHumidityPercent

and instead of [] I tried with {} as well…

JavaScript in Rails

I am new to Rails, and my js code is not running. My program should output the result of checking a number for a palindrome on the same page, without switching to a new one, but when I press the output button, nothing happens. The js code is enabled in the browser, all the necessary libraries seem to have been downloaded (however, you can still write to me that you need to double-check). The browser also shows the 200 status for js requests. Why aren’t they working?

Сode :

# app/controllers/palindrome_controller.rb
class PalindromeController < ApplicationController
  def index; end

  def show
    @number = params[:number]
    @error = validate_input(@number)
    calculate_palindrome unless @error

    respond_to do |format|
      format.js 
    end
  end

  private

  def validate_input(number)
    return 'No number entered' if number =~ /D/
    return 'The number is already a palindrome' if number == number.reverse

    nil
  end

  def calculate_palindrome
    @number = @number.to_i
    @results = []
    while @number.to_s != @number.to_s.reverse
      @results << @number
      @number += @number.to_s.reverse.to_i
    end
    @results << @number
  end
end

<!-- app/views/palindrome/index.html.erb -->
<h1>Testing the palindrome hypothesis</h1>
<%= form_with url: '/palindrome/show', method: 'get', remote: true do %>
  <%= label_tag :number, "Enter a number:" %>
  <%= text_field_tag :number %>
  <%= submit_tag "Check" %>
<% end %>
<div id="results"></div>
# config/routes.rb
Rails.application.routes.draw do
  root 'palindrome#index'
  get 'palindrome/show', to: 'palindrome#show'
end
<!-- app/views/palindrome/show.js.erb -->
<% if @error %>
  $("#results").html("<p><%= @error %></p>");
<% else %>
  var table = "<table><tr><th>Step number</th><th>Current value</th></tr>";
  <% @results.each_with_index do |result, index| %>
    table += "<tr><td><%= index + 1 %></td><td><%= result %></td></tr>";
  <% end %>
  table += "</table>";
  if ("<%= @results.last.to_s %>" == "<%= @results.last.to_s.reverse %>") {
    table += "<p>The hypothesis is confirmed</p>";
  } else {
    table += "<p>The hypothesis has not been confirmed</p>";
  }
  $("#results").html(table);
<% end %>

How to reset the vue-tel-input input?

I have the following code:

<vue-tel-input ref="telinput" v-model="phone" @input="updatePhone"></vue-tel-input>

and then:

const updatePhone = (event, p) => {
    if (event.constructor.name === "InputEvent") {
        return;
    }
    if (p !== undefined && p.valid) {
        phone.value = p.nationalNumber
        valid.value = true
    } else {
        valid.value = false
        phone.value = ""
    }
}

const addPhone = () => {
    store.mailing.tokens.unshift([
        phone.value,
        variable.value
    ])
    valid.value = false
    phone.value = ""
    window.Toast.fire({
        title: 'Contato adicionado com sucesso!',
        icon: 'success'
    });
}

But the phone variable is never changed by the v-model and when I call the addPhone method the input still showing the phone typed by the user.

Optimize current code to fill columns cells faster

I’m creating a script (chrome extension) where rows of a table of a website can be moved up or down by the click of a button. This works perfectly by changing the parameter and reorder the rows based on the new parameters.

The code shown below is used to fill the cells of a certain column of the table with the new order of the rows. So the new first row get the number ‘0’, the 2nd row ‘1’, etc.

The issue is that the script below does it perfectly, but is very slow.
Is there any way to increase the speed of filling the cells?

    if (test.getElementsByClassName("tr").length == 0) {
    var tr2 = test_otheruser.getElementsByClassName("tr"), l;
} else {
    var tr2 = test.getElementsByClassName("tr"), l;
}

for (k = 0; k < tr2.length; k++) {
    let form_control = tr2[k].getElementsByClassName("td"), m;
    //write number in reorder cell downwards
    form_control[Reorder_column].getElementsByClassName('form-control')[0].focus();
    const inputElement = form_control[Reorder_column].getElementsByClassName('form-control')[0];
    //document.execCommand('insertText', false, 'input value');
    inputElement.value = k;
    inputElement.dispatchEvent(
        new Event("input", { bubbles: true, cancelable: true })
    );
    form_control[Reorder_column].getElementsByClassName('form-control')[0].blur();
}

The code works, but the for loop containing the .focus(), document.execCommand, dispatchEvent and .blur() is slow. I tried several things like just updating .value, but the only way the website where I fill in the table via this chrome extension excepts data that is written by this particular order of selection, filling, de-selection.

Regular expression to get all set of digits independently between 2 signs [duplicate]

In this part of a string: : 41 48 83 86 17 | 83 86 6 31 17 9 48 53

I am trying to capture independently all the sets of digits between : and | to start.

I’ve been battling for the last part of the hour, and can only get at best the whole string:
'41 48 83 86 17' with this regexp : /(?<=:s)(s*d+s*)+(?=s|)/g;

I know I could split the string, but I really wonder if there’s not a RegExp way of doing this right away?

Heroku unable to find javascript files in FastAPI/React app

I have an app with a FastAPI server and a React frontend in the same root folder. It builds and deploys to Heroku without any errors, and serves the FastAPI routes without error, but I’m getting a 404 NOT FOUND error when trying to serve javascript and css files from my client/build/static folder.

In my main.py file I have the following code, which seems to be working as I expect:

# Construct the correct path to the "client/build" directory
static_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "client/build")
# logging shows static_dir = /app/client/build

# Mount the static files from "client/build"
app.mount("/static", StaticFiles(directory=static_dir), name="static")

When I run a heroku bash terminal, I can cd into my client build dir which has my index.html with expected src tags:

<!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Web site created using create-react-app"/><link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"><link rel="apple-touch-icon" href="/logo192.png"/><link rel="manifest" href="/manifest.json"/><title>MoodRaker</title><base href="/"/><script defer="defer" src="/static/js/main.71b3f3e2.js"></script><link href="/static/css/main.e6c13ad2.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script></body></html>

Heroku logs look like this when I go to app root url:

2023-12-14T19:44:19.106578+00:00 app[web.1]: 98.59.132.14:0 - "GET / HTTP/1.1" 200
2023-12-14T19:44:19.107626+00:00 heroku[router]: at=info method=GET path="/" host=moodtracker-35756345a3ca.herokuapp.com request_id=cb46c81b-2de2-4e1c-b408-d54965e732b2 fwd="98.59.132.14" dyno=web.1 connect=0ms service=2126ms status=200 bytes=1318 protocol=https
2023-12-14T19:44:19.280321+00:00 heroku[router]: at=info method=GET path="/static/css/main.e6c13ad2.css" host=moodtracker-35756345a3ca.herokuapp.com request_id=5517735c-adc3-4bc4-a606-64201bfd30fa fwd="98.59.132.14" dyno=web.1 connect=0ms service=3ms status=404 bytes=173 protocol=https
2023-12-14T19:44:19.273165+00:00 app[web.1]: 98.59.132.14:0 - "GET /js/main.71b3f3e2.js HTTP/1.1" 404
2023-12-14T19:44:19.278364+00:00 app[web.1]: 98.59.132.14:0 - "GET /css/main.e6c13ad2.css HTTP/1.1" 404
2023-12-14T19:44:19.273982+00:00 heroku[router]: at=info method=GET path="/static/js/main.71b3f3e2.js" host=moodtracker-35756345a3ca.herokuapp.com request_id=1424389f-e890-4231-b158-67616f9549d3 fwd="98.59.132.14" dyno=web.1 connect=0ms service=2ms status=404 bytes=173 protocol=https
2023-12-14T19:44:19.813433+00:00 heroku[router]: at=info method=GET path="/manifest.json" host=moodtracker-35756345a3ca.herokuapp.com request_id=5977aef1-6d06-448c-a764-7fffb1f5c650 fwd="98.59.132.14" dyno=web.1 connect=0ms service=8ms status=200 bytes=1318 protocol=https
2023-12-14T19:44:19.622001+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=moodtracker-35756345a3ca.herokuapp.com request_id=b7618d08-66e9-4eb5-b1b6-19f43f1af972 fwd="98.59.132.14" dyno=web.1 connect=0ms service=10ms status=200 bytes=1318 protocol=https
2023-12-14T19:44:19.619219+00:00 app[web.1]: 98.59.132.14:0 - "GET /favicon.ico HTTP/1.1" 200
2023-12-14T19:44:19.812451+00:00 app[web.1]: 98.59.132.14:0 - "GET /manifest.json HTTP/1.1" 200

And if I navigate to this url https://moodtracker-35756345a3ca.herokuapp.com/static/js/main.71b3f3e2.js I get this response:

// 20231214104738
// https://moodtracker-35756345a3ca.herokuapp.com/static/js/main.71b3f3e2.js

{
  "detail": "Not Found"
}

Any idea what to try next?

I’ve tried rebuilding my react app and redeploying everything, which made no change.
At this point I’m just trying to get visibility into the issue. I’ve tried putting different url paths into the browser trying to access the javascript files that way (e.g. https://moodtracker-35756345a3ca.herokuapp.com/js/main.71b3f3e2.js), thinking maybe the path was not correct.

Everything works fine locally, and I’ve not been able to find any Heroku docs that address this issue.

I can’t seem to access chrome sync storage in my Google Chrome theme extension script

I have an existing theme which I’m updating to manifest v3. Everything is fine with that process but I decided to dig deeper and offer a users a couple of options for the theme. I now have an options.html and did have an options.js but had to embed that in the html file as I couldn’t get it to use the external script.

I have 95% of this all working (style, click events all firing correctly and a couple of variables I need to save to some local storage (or ideally using chrome.storage.local.set() and chrome.storage.local.get().

Every time I try to use these I keep getting an error Cannot read properties of undefined (reading 'local') I’ve tied local sync and session on both get and set but I always end up with this error. I’ve also tried just storage.local Uncaught ReferenceError: storage is not defined. Not sure if it’s my javascript, how I am running my extension locally, the limitations of running it local or something else.

manifest.json

{
    "version": "1.0",
    "manifest_version": 3,
    "name": "name of theme",
    "description": "description of theme",
    "theme": {
        "images": {
            "theme_ntp_background": "images/main.png"
        },
        "colors": {
            "bookmark_text": [ 0, 128, 0 ],
            "ntp_text": [ 128, 0, 0 ],
            "tab_background_text": [ 0, 0, 128 ],
            "tab_text": [ 255, 255, 255 ],
            "toolbar": [ 210, 212, 202 ]
        },
        "tints" : {
            "buttons" : [0.33, 0.5, 0.47]
        },
        "properties" : {
            "ntp_background_alignment" : "top"
        }
    },
    "permissions": [
        "storage"
    ],
    "options_ui": {
        "page": "options.html",
        "open_in_tab": false
    },
    "web_accessible_resources":[
        "options.js",
        "images/option-resolution-1.jpg",
        "images/option-resolution-2.jpg",
        "images/option-resolution-3.jpg",
        "images/option-style-1.jpg",
        "images/option-style-2.jpg",
        "images/option-style-3.jpg"
    ]
}

My options.html

<html>

<!--
...
-->

<script>
const tiles = document.getElementsByClassName('tile');
let style = 1;
let res = 3;

//...
const restoreOptions = () => {
    console.log('loaded restore');
    console.log('style: ' + style);
    console.log('res: ' + res);
    chrome.storage.sync.get(
       { style: 1, res: 1 },
       (items) => {
        style = items.style;
        res = items.res;
        }
    );
};


//onload
document.addEventListener('DOMContentLoaded', restoreOptions);
</script>
</html>

I’m even just trying this to try and get it to work.

chrome.storage.local.set({ key: "value" }).then(() => {
        console.log("Value was set");
    });
console.dir(storage); //Uncaught ReferenceError: storage is not defined
console.dir(storage.local); //Uncaught ReferenceError: storage is not defined
console.dir(chrome); //{csi, loadtimes, Object}
console.dir(chrome.storage); //undefined
console.dir(chrome.storage.local); //options.html:179 Uncaught TypeError: Cannot read properties of undefined (reading 'local')

The way I’m loading my extension is through chrome://extensions/ page with “development mode” on, I’m then selecting “Load unpacked” and choosing my directory where I have my files.

I then have to navigate (annoyingly) to a new tab, select the pencil then click “Edit the current theme you have installed” which sends me to a page which isn’t available but it gives me the unique id of the extension. I can then just simply go to chrome-extension://{myfunnylongidthatseemstostaystaticanyway}/options.html

Change style for element when dropdown is selected with conditions

I’m currently creating a dropdown from Javascript array. I want to show a span when some options are selected.

For example, I want to show the span when options “a” and “c” are selected, but not “b”.

CSS:

#output {
    display: none;
}

HTML:

<select name="city" id="city">
    <option value="-">- Choose city -</option>
</select>

<span id="output"></span>

JavaScript:

var city = ["a","b","c"];

// Add array to city dropdown
var select_city = document.getElementById("city");

for(var i = 0; i < city.length; i++) {
    let opt = city[i];
    let el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select_city.appendChild(el);
};

// Display output
var output = document.getElementById("output");

select_city.onchange = function() {
    output.style.display = (this.value == city.value && this.value == !"b") ? "block":"none";
};

My code is currently not working and I don’t know why. I’m new to javascript so hope someone can help me see the problem 🙂

Thanks in advanced!

why resolve function runs once in thenable

Helo, I’m trying to understand promises and don’t understand why this code:

class Thenable {
  constructor(num) {
    this.num = num;
  }
  then(resolve, reject) {
    console.log(resolve); // function() { native code }
    // resolve with this.num*2 after the 1 second
    new Promise( (resolve, reject) => {
       setTimeout(() => resolve(this.num * 2), 3000); // (**)
    }).then((ret)=>{ resolve('wow'); resolve('inside '+ret)})
  }
}

new Promise(resolve => resolve(1))
  .then(result => {
    return new Thenable(result); // (*)
  })
  .then((r) => { console.log(r) } ); // shows 2 after 1000ms
console.log('done')

prints only ‘wow’ and don’t print ‘inside 2’ :

done 
ƒ () {}
wow 

Thenable.then is an ordinary function, when I call it with .then((r) => { console.log(r) } ) the resolve became function with one argument who calls console.log .
Why it calls only first resolve(‘wow’) and doesn’t call next resolve(‘inside ‘+ret) ?
Does js engine somehow rewrite my .then function and left only one resolve invocation?

learn javascript for beginners

let me introduce myself, my name is Naja, I am a newbie programmer and I am new to Javascript and don’t even know anything about JavaScript, so what should I learn to code with Javascript?

I hope I can become an expert programmer like all of you

Conflict with scroll indicator and full page scroll

I want to implement a scroll indicator on the page, but for some reason when adding automatic scrolling by section using CSS, it breaks and fills only on the footer, I don’t know how to fix this and what is the error here?

Maybe it makes sense to try to fill the scroll indicator specifically on section blocks?

globals.css :

.container {
  position: relative;
  width: 100%;
  height: 100vh;
  scroll-behavior: smooth;
  scroll-snap-type: y mandatory;
  overflow-y: scroll;
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.section {
  width: 100%;
  height: 100vh;
  scroll-snap-align: start;
}

page.tsx :

import ...

export default function Home() {

  return (
    <div className="container">
      <ScrollIndicator />
      <div className="section"> <Dome /> </div>
      <div className="section"> <About /> </div>
      <div className="section"> <Lodge /> </div>
      <div className="section"> <AboutAdd /> </div>
      <div className="section"> <Reviews /> </div>
      <div className="section"> <Blog /> </div>
      <div className="section"> <Contacts /> </div>
    </div>
  );
}

layout.tsx :

import './globals.css';
import type { Metadata } from 'next';

import Navbar from './components/navbar/Navbar';
import { Footer } from './components/Footer';

...

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={font.className}>
        <Navbar />
        <main> {children} </main>
        <Footer />
      </body>
    </html> 
  );
};

codesandbox.io