Regex expression to match numbers that don’t contain percentage

I have a requirement where in a user input the regular expression should match only numbers either digits or numbers with decimal points, however if there is a number followed with a percentage symbol then that should be excluded, but numbers followed with alphabets like 100g or 500 grams should be matched without picking up the alphabet part

I have come up with the following:

let numberPart = importValue.match(/d+(?:[.,]d+)?b(?!(?:[.,]d+)|(?:s?%|spercent))/g);

11 grams nutella 1,5% is matched and we get 11 as output

however 11grams nutella 1,5% isn’t matched

how can I change it so it matches numbers followed immediately by an alphabet or alphabets.

Chrome Extension doesn’t work with MV3, getting “Insecure CSP value “‘unsafe-eval'” in directive ‘script-src’.”

I’m trying to make a simple Chrome extension that replaces all images with another one (img.jpg).

Main folder

  • clrimgs.js
  • img.jpg
  • manifest.json
  • window.html

window.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ClrImgs</title>
    <script type="text/javascript" src="clrimgs.js"></script>
</head>
<body>
    <button onclick="clrimgs()"></button>
</body>
</html>

clrimgs.js:

function clrimgs(){
    images = document.getElementsByTagName("img")
    for(image in images){
        image.src = "img.jpg";
    }
}

manifest.json:

{
    "manifest_version": 3,
    "name": "ClrImgs",
    "description": "Description",
    "version": "1.0",
    "minimum_chrome_version": "46",
    "content_security_policy": {
        "extension_pages": "script-src 'self' 'unsafe-eval'; object-src 'self'",
        "sandbox": "..."
       },
    "action": {
    "default_icon": "img.jpg",
    "default_popup": "window.html"
    }
    }

When I try to reload the extension, I get this error:

‘content_security_policy.extension_pages’: Insecure CSP value
“‘unsafe-eval'” in directive ‘script-src’. Could not load manifest.

Is there any way to use MV3 and still use such code? If yes, what am I doing wrong? I have tried doing numerous things, but I keep getting an error or the other.

How to populate a laravel chart with data from database with apexchart?

In my controller I have this query :

$categories = DB::table('categories')
    ->select('type',DB::raw('COUNT(*) as count_type')) 
    ->groupBy('type')
    ->orderBy('type','desc')
    ->get();

When I populate series and labels with static results everything works fine, but when I try to populate it from database it doesn’t work, The whole problem is with series and labels as shown below in the script :

    <script>
            var options = {
here=>        series: [@foreach($categories as $categorie) $categorie->count_type @endforeach],
              chart: {
              width: 380,
              type: 'pie',
            },
and here=>    labels: [@foreach($categories as $categorie) $categorie->type @endforeach],
            responsive: [{
              breakpoint: 480,
              options: {
                chart: {
                  width: 200
                },
                legend: {
                  position: 'bottom'
                }
              }
            }]
            };
            var chart = new ApexCharts(document.querySelector("#chart"), options);
            chart.render();
    </script>

So the question is how can I populate this graph from my query result?

Search results by Filtering an array inside an object

I’m trying to build a dynamic search function by using an eventListener and filtering the JSON results of an API call.

Everything works fine when I filter by name, but I’m really struggling to figure out how to filter through a dynamic array inside the object.

I’ve tried forEach, map and looked over other questions but can’t seem to find a solution…

let allContractors = []; // this is populated by an async function bellow, not included in code

searchBar.addEventListener("keyup", (e) => {
  let target = e.target.value;

  const filteredContractors = allContractors.filter((contractor) => {
    return (
      contractor.name.toLowerCase().includes(target.toLowerCase()) ||
      contractor.categories[0].title.toLowerCase().includes(target.toLowerCase)
    );
  });
  displayContractors(filteredContractors);
});

It works fine when I iterate a specific array index, but when I try to use forEach, includes cannot read the element.

contractor.categories.forEach(element => {
        element.title
      }).includes(target)

I’m sure there is a syntax error above, I’ve messed around with it quite a bit, just thought it would be helpful to show what I’m dealing with.

jquery script not being instantiated properly

I am trying to implement an overlay on a page, however I dont think I am instantiating my code correctly?

Use case:

  • when user click search icon on a page, it displays an overlay
  • when the overlay is displayed, user can click close button to remove the overlay

Problem:
When I refresh and view my js code in the browser, my overlay is already being visibly displayed, which shouldn’t before I click the search icon, so am I not instantiating properly?

Although, I am calling both ‘openOverlay’ and ‘closeOverlay’ functions in the events() function in my Search.js which should trigger it…

dev environment:

  • node.js with webpack
  • scripts.js: imports main css file and instantiate modules
  • Search.js with my overlay code (imports jquery and exports default Search)

scripts.js

import "../css/styles.css"

// modules
import Search from "./modules/Search"

//instantiate new object using modules/classes
const search = new Search()

// Allow new JS and CSS to load in browser without a traditional page refresh
if (module.hot) {
  module.hot.accept()
}

Search.js

import $ from 'jquery';


//alert("helo there");

function Search(){
    //describe/create object
    var openButton = $(".js-search-trigger");
    var closeButton = $(".s-overlay__close");
    var searchOverlay = $(".s-overlay");

    //events
    function events() {
        openButton.on("click", openOverlay);
        closeButton.on("click", closeOverlay);
    };
    events();
    
    //methods
    function openOverlay(){
        searchOverlay.addClass("s-overlay--active");
    };
    function closeOverlay(){
        searchOverlay.removeClass("s-overlay--active");
    };
}
export default Search;

html:

<div class="s-overlay s-overlay--active">
    <div class="s-overlay__top">
        <div class="s-container">
            <i class="s-overlay__icon" aria-hidden="true">
                <svg>...</svg>
            </i>
            <input id="search-term" class="search-term" type="text" placeholder="What are looking for?">
            <i class="s-overlay__close" aria-hidden="true">
                <svg>...</svg>
            </i>
        </div>
    </div>
</div>

css:

.s-overlay { overflow-y: auto; overflow-x: hidden; z-index: 110; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(255, 255, 255, 0.96); visibility: hidden; opacity: 0; transform: scale(1.09); transition: opacity 0.3s, transform 0.3s, visibility 0.3s; box-sizing: border-box;}
.s-overlay--active { visibility: visible; opacity: 1; transform: scale(1);}
.s-overlay__top {  margin-top: 32px; position: relative; padding: 1em; background-color: rgba(0, 0, 0, 0.12); }
.s-overlay__icon { line-height: 0; display: block; }
.s-overlay__close {margin-left: auto; line-height: 0; display: block; transition: all 0.3s;}
.s-overlay__close:hover { opacity: 1; }

How do I loop number counter after 10 seconds

I’m trying to get the following number counter to start only once scrolled to and then have it loop after 10 seconds, could anyone please assist me

const counterAnim = (qSelector, start = 0, end, duration = 8000) => {
 const target = document.querySelector(qSelector);
 let startTimestamp = null;
 const step = (timestamp) => {
  if (!startTimestamp) startTimestamp = timestamp;
  const progress = Math.min((timestamp - startTimestamp) / duration, 1);
  target.innerText = Math.floor(progress * (end - start) + start);
  if (progress < 1) {
   window.requestAnimationFrame(step);
  }
 };
 window.requestAnimationFrame(step);
};
//#endregion - end of - number counter animation

document.addEventListener("DOMContentLoaded", () => {
 counterAnim("#count1", 0, 10000,8000);
 counterAnim("#count2", 0, 40, 8000);
 counterAnim("#count3", 0, 5, 8000);
});
<div class="ohio-heading-sc heading text-left" id="ohio-custom-61aa36a52809a">
<h2 class="title"><span id="count1" class="display-4"></span>+  </h2>
<p class="subtitle">lorem ipsum</p>
</div>

<div class="ohio-heading-sc heading text-left" id="ohio-custom-61aa36a52809a">
<h2 class="title"><span id="count2" class="display-4"></span>+  YEARS</h2>
<p class="subtitle">lorem ipsum</p>
</div>

<div class="ohio-heading-sc heading text-left" id="ohio-custom-61aa36a52809a">
<h2 class="title"><span id="count3" class="display-4"></span>   YEAR</h2>
<p class="subtitle">lorem ipsum</p>
</div>

how do i Insert into different tables of db according to option selected in dropdown list using php pdo please help me

I have 5 different table. e.g. mechanical,civil,chemical,petroleum and elect. i want a page with name and dropdown option in php. so, according to the selected dropdown option the name should be inserted to the associate table in db. eg. if i give any name mechanical and select mechanical option. then the name sholud be inserted in mechanical table.
here is my code

how to fix “Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.” [duplicate]

1 In Next.js, I created a component that fetch data from Github, then I faced this error. Anybody knows this reason and how to fix this?? On my understanding, this error has happened because type of “data” is object and perhaps “promise”, but I am not sure how could I fix this then. I replaced “data” to “{data.login}”, but it didn’t work and nothing changed.

2 The result of console.log itself has successfully achieved but this result was shown 5 times but don’t know why…

const GetGithubData = async () => {
  // For owner and repo, enter the GitHub username and repository name you want to retrieve.
  const owner = "aaaa"; // dummy
  const repo = "bbbb"; // dummy

  const url = `https://api.github.com/repos/${owner}/${repo}/contributors`;
  const res = await fetch(url);
  const data = await res.json();

  return console.log(data);
};

export default GetGithubData;

Retrieve items from SharePoint list using JS

I know there are many posts like mine, but I couldn’t find any answer to why it is not working for me.

Based on that answer: https://stackoverflow.com/a/59340514/17645049

I changed the name of the columns, the list’s name and of course the list’s URL. Running the code gives me the error “Request failed. Unexpected server response data. Null”.

Any suggestion?

Browser: Edge. Full code:

var siteUrl = 'listURL';
var listName = 'listName';

function retrieveListItems() {
    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle(listName);
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name='ID'/>' + '<Value Type='Number'>1</Value></Geq></Where></Query><RowLimit>10</RowLimit></View>');
    this.collListItem = oList.getItems(camlQuery);
    clientContext.load(collListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args) {
    var listItemInfo = '';
    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        listItemInfo += 'nID: ' + oListItem.get_id() +
            'nTitre: ' + oListItem.get_item('Titre') +
            'nCorps: ' + oListItem.get_item('Corps') +
            'nLangue: ' + oListItem.get_item('Langue');
    }
    alert(listItemInfo.toString());
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + 'n' + args.get_stackTrace());
}

Listening onchange events on a dropdown to update a chart data list

I’m trying to figure it out how can I create an onchange event to listen to the value from the dropdown, so the chart will change it values depending on that id, for that I have the following elements:

In views.py:

def html(request, filename):
    #Data for the graph
    id = list(Device.objects.values_list('patientId', flat=True).distinct())
    labels = list(Device.objects.values_list('hour', flat=True))
    glucose_data = list(Device.objects.values_list('glucoseValue', flat=True))
    data =  glucose_data
    formatted_data = select_formatted_date(labels)
    lastPatientData = Device.objects.filter(patientId = id[-1])
    #the last element added
    hourArray = []
    glucoseArray = []
    for item in lastPatientData:
        lastPatientHour = Device._meta.get_field('hour')
        lastPatientGlucose = Device._meta.get_field('glucoseValue')
        formattedHour = lastPatientHour.value_from_object(item)
        frt_hour = formattedHour.strftime('%Y-%m-%d %H:%M:%S')
        formattedGlucose = lastPatientGlucose.value_from_object(item)
        hourArray.append(frt_hour)
        glucoseArray.append(formattedGlucose)
    device_list = list(Device.objects.all())
    for device in device_list:
        print(device)

    #f = DateRangeForm(request.POST)
    context = {"filename": filename,
               "collapse": "",
               "hourArray":hourArray,
               "glucoseArray": glucoseArray,
               "patientId": id,
               "dataSelection": formatted_data,
               "deviceList": device_list,
               "labels": json.dumps(labels, default=str),
               "data": json.dumps(data)
               }
return render(request, f"{filename}.html", context=context)

In forms.py, I have this, but I really don’t know what to do with this data:

from django import forms

idsList = forms.ModelChoiceField(queryset = Device.objects.values_list('patientIId'),widget = forms.Select(attrs = {'onchange' : "myFunction()"}))

my model is:

class Device (models.Model):
    patientId = models.IntegerField(unique=True)
    deviceId = models.CharField(unique=True,max_length=100)
    hour = models.DateTimeField()
    type = models.IntegerField()
    glucoseValue = models.IntegerField()

And in the index.html, I have the following(in data and label fields):

    <label for="patientId">Choose a patient:</label>
       <select name="patient" id="patient">
          {% for item in patientId %}
            <option value="{{item}}">
              {{item}}
            </option>
          {% endfor %}
        </select>

<div class="card-body">
 <div class="chart-area">
  <canvas id="weeklyChart"></canvas>
 </div>
</div>

The chart value is stored in a script tag, as follows:

var ctx = document.getElementById("weeklyChart");
var myLineChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: {{ hourArray|safe}},//here in the labels
    datasets: [{
      label: "Value",
      lineTension: 0.3,
      backgroundColor: "rgba(78, 115, 223, 0.05)",
      borderColor: "rgba(78, 115, 223, 1)",
      pointRadius: 3,
      pointBackgroundColor: "rgba(78, 115, 223, 1)",
      pointBorderColor: "rgba(78, 115, 223, 1)",
      pointHoverRadius: 3,
      pointHoverBackgroundColor: "rgba(78, 115, 223, 1)",
      pointHoverBorderColor: "rgba(78, 115, 223, 1)",
      pointHitRadius: 10,
      pointBorderWidth: 2,
      data: {{ glucoseArray|safe}},//and the other coordinate is here
    }],
  }
);

My question is what is the most efficient method to change that chart values based on the id that I’m choosing from the dropdown.

Most efficient way to update an object property within an array of objects

I am wondering what is the most efficient way to update an object property that is stored in an array with 10k+ items.

For example if I have an array that holds objects like this {name:””, price:””)

I want to replace or more like update the price values if the array contains that element already.

Check if Array contains object with name = x, if so replace the price with the newest price.

I dont want to have duplicate elements in that array so its not getting to big, i figured I should update it if a property value already exists in it.

So far I have tried several ways like with using indexOf, splice, or just for loops. I am wondering what is the best way performance wise to deal with big arrays.

let array = [
{name:"abc", price: 24},
{name:"cde", price: 25},
{name:"fgh", price: 22},
{name:"gfds", price: 21},
]

function addToArray(elem){
  //check if array contains elem by checking for name property value
  if(array.filter(el => el.name === elem.name).length > 0){
    //update the array element that has the name of the passed elem
  }
}

Replace empty values with previous values in Objects Array

I am trying to replace empty values with previous non-empty values with dynamic keys.

[{
        "ACRI": "1298",
        "APL": "231.123",
        "BDTV": "8667.29",
        "BPOS": "29.43"
    },
    {
        "ACRI": "",
        "APL": "",
        "BDTV": "8667.29",
        "BPOS": "29.43"
    }
]

this array need to be converted into like below

[{
            "ACRI": "1298",
            "APL": "231.123",
            "BDTV": "8667.29",
            "BPOS": "29.43"
        },
        {
            "ACRI": "1298",
            "APL": "231.123",
            "BDTV": "8667.29",
            "BPOS": "29.43"
        }
    ]

I referred this Question but this only working with fixed keys not the dynamic keys.