Regular EXpression generator

how can I get regex for “main.477f85d4c0336d36.js.map” to run it as part of this curl command ?

 curl -X POST "https://observability-np.solutions.myhomepage.com/s/real_estate_us/api/apm/sourcemaps" 
-H "Content-Type: multipart/form-data" 
-H "kbn-xsrf: true" -u "_user:password" 
-F "service_name=onehome" -F "service_version=1.0.264-DEV" 
-F "bundle_filepath=https://aotf-uat.myhomepage.com/en-US/main.[a-z0-9]+.js" -F "sourcemap=@./main.(regex[a-z0-9]+.js.map" 
 curl -X POST "https://observability-np.solutions.myhomepage.com/s/real_estate_us/api/apm/sourcemaps" -H "Content-Type: multipart/form-data" -H "kbn-xsrf: true" -u "user:password" -F "service_name=onehome" -F "service_version=1.0.264-DEV" -F "bundle_filepath=https://aotf-uat.myhomepage.com/en-US/main.[a-z0-9]+.js" -F "sourcemap=@./main.[a-z0-9]+.js.map"

Express.js app returns 404 error despite correct route configuration- Vercel deployment issue

I have an

app.js file

const express = require('express');
// Routes
const homeRouter = require('./routes/homeRoutes');
...
const app = express();
routers.forEach(router => {
  app.use('/api/v1', router);
});
module.exports = app;
module.exports.handler = serverless;

i deleted a lot of code but the idea is that it works.

homeRoutes.js

const express = require('express');

const router = express.Router();

router.get('/home', (req, res) => {
  res.send('Hello from home!');
});

module.exports = router;

vercel.json

{
  "routes": [
    {
      "src": "/",
      "dest": "/"
    },
    { "src": "/home", "dest": "/" }
  ]
}

package.json

 "name": "server",
  "version": "1.0.0",
  "engines": {
    "node": ">=8.0.0"
  },

And i cant deploy express app on Vercel.
I tried following their docs, and different combination of Vercel.json but all the time i get:

404: NOT_FOUND
Code: NOT_FOUND

I can access locally
http://localhost:3000/api/v1/home
but the

vercel-url/api/v1/home
or any comibation like url/home…

doesnt work and i get the the same error all the time.
Different Vercel.json files that doesnt work:

{
  "routes": [{ "src": "/api/v1/home", "dest": "api/home.js" }]
}

or

{
  "rewrites": [{ "source": "/api/(.*)", "destination": "/api" }]
}

Do you know what can make this error or how to fix it?

Grab scrollbar below and above scrollbar track functionality?

So I’ve been given an untrivial task to make a thin scrollbar, that can be grabbed above and below as I showed in the picture.
enter image description here

I figured out how to make it one way – I made scrollbar very high – 32px, gave it a transparent background and mimiced scrollbar tracker and thumb with very thin inset box-shadow, but as I pointed out on picture 2, I can only grab it below, but not above (naturally).
enter image description here

These pictures are wrapped in this div:

        width: 218px;
        height: 165px;
        margin-right: 5px;
        display: flex;
        padding-top: 18px;
        padding-left: 3px;
        padding-right: 4px;
        flex-direction: row;
        grid-gap: 10px;
        gap: 10px;
        position: static;
        top: 0px;
        left: 0px;
        box-sizing: border-box;
        overflow-x: auto;
        overflow-y: hidden;

        cursor: pointer;

        @-moz-document url-prefix() {
            & {
                scrollbar-width: thin;
                scrollbar-color: #0090ff #aeafbc;
            }
        }

        &::-webkit-scrollbar {
            width: 2px;
            height: 32px;
        }
        &::-webkit-scrollbar-track {
            box-shadow: inset 0 2px 0 0 #aeafbc;
            background: transparent;
        }
        &::-webkit-scrollbar-thumb {
            width: 66px;
            box-shadow: inset 0 2px 0 0 #0090ff;
            background: transparent;
        }
}

Please, if you know some workaround, I’d be very grateful!

Write worksheet to xml file with ExcelJS without writing the whole workbook

I would like to know if there is any way using ExcelJS to write a specific worksheet directly to an xml file, without writing the whole workbook, like in the following pseudo code:

const ExcelJS = require('exceljs');

const workbook = new ExcelJS.Workbook();

workbook.xlsx.readFile(ExcelTemplate);

let worksheet = workbook.getWorksheet(worksheetName);

worksheet.getCell(1, 1).value = 123;

// Instead ow writing the full workbook, write the worksheet as xml
// workbook.xlsx.writeFile(`${outputDir}/${fileName}.xlsx`);
worksheet.xlsx.writeFile(`${outputDir}/${fileName}.xml`);

I’m asking this because loading my ExcelTemplate into ExcelJS breaks some feature (charts, named range…), so I end up to a workaround where I use ExcelJS to fullfill with data an excel file, then I need to replace the blank data worksheet of the ExcelTemplate with the fulfilled one.
Writing the workseeth to xml, will simplify the process

Many thanks to everyone!

Why are files in Cloud Storage not publicly available?

I am using Firebase and the Cloud Storage to host images.

On my backend, this is how I write images:

const bucket = getStorage().bucket('gs://project-name.appspot.com');
const bucketFile = bucket.file(path);
await bucketFile.save(imageBuffer);

I am storing the bucketFile.publicUrl() in the database which is what clients use to display the image.

and these are the deployed storage.rules:

rules_version = '2';

// Craft rules based on data in your Firestore database
// allow write: if firestore.get(
//    /databases/(default)/documents/users/$(request.auth.uid)).data.isAdmin;
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read: if true;
    }
  }
}

Still, I cannot access the file.

That being said, I seem to be able to access them if I additionally call

await bucketFile.makePublic();

However, I don’t think this is ideal having to call this for each and every file. Call me picky, but I’d assume that this “simply works” based on my storage.rules.

Are my rules wrong or am I missing something?

Uncaught (in promise) TypeError: player.mute is not a function

I add the event listener to the dailymotion playlists. I want to implement the following: When the event catches, get the information about the related playlist and mute it.

    // Define the callback function
const callback = (state) => {
    var player = dailymotion.getPlayer(state.id).then((player) => {
    player.mute()
    });
}

// Get access to all embedded player instances on the page
Promise.all(dailymotion.getAllPlayers()).then((players) => {
    // Add an event listener to each player for the 'PLAYER_START' event
    players.forEach((player) => {
        player.on(dailymotion.events.PLAYER_START, callback)
    });
})

I get: Uncaught (in promise) TypeError: player.mute is not a function

I also tried the following way:

        var player = dailymotion.getPlayer(document.getElementById(state.id)).then((player) => {
player.mute()
});

And tried what was proposed in the comments:

    var player = dailymotion.getPlayer(state.id).then((player) => {
player.setMute(true)
});

and

    var x = dailymotion.getPlayer(state.id).then((x) => {
x.mute()
});

and

player = dailymotion.getPlayer(state.id);
    player.mute();

Pagination bullets move to the left on route change, when using vue-transition

I use Vue 3 and swiper.js. Pagination bullets move to the left on route change (when the component is unmounted). Looks like the styling for bullets and the active button disappear as well. I have a reproduction, didn’t care about styling much, but it’s enough to show the issue. Try switching between router-links on the nav panel and you’ll notice the bug. You can only notice it when using vue-transition, because there is a delay and you are able to see it.

Reproduction link:
https://stackblitz.com/edit/vitejs-vite-c5x8vm?file=src%2FApp.vue,src%2Fmain.js

I’m looking for possible solution.

Used custom input components in the same page in my react project, Now my input doesn’t work properly

I am new to ReactJS, and it’s my first project.

Currently, I’m facing an issue by using several same input components in a single page.

For example,
<FormRowSelectCustom /> <FormRowSelectCustom />

When I try to use input#2, input#1 gets the value from input#2 and input#1 doesn’t operate.

How can i handle this problem?

here is my components structure

<AllJobs>
  <SearchContainer>
    <Form>
      <FormRowSelectCustom /> // #1 for jobType
      <FormRowSelectCustom /> // #2 for jobStatus
      <SubmitBtn />
    <Form/>
  <SearchContainer />
  <JobContainer>
   <JobCard>
     <JobCardEdit>
      <FormRowSelectCustom /> // #3 for jobType
      <FormRowSelectCustom />// #4 for jobStatus
      <SubmitBtn />
    <Form/>
     <JobCardEdit/>
   <JobCard />
  <JobContainer />
<AllJobs/>

In total, I have 4 FormRowSelectCustom components in one page, when I change #3 input, #1 input is changed and # 3 doesn’t change the value and it is the same for #2 and #4.

Here is my FormRowSelectCustom.jsx

import { useState } from 'react';
import Wrapper from '../assets/wrappers/FormRowSelectCustom';
import { GoChevronDown, GoChevronUp } from 'react-icons/go';

// new setup
const FormRowSelectCustom = ({
  name,
  labelText,
  list,
  onChange,
  defaultValue = 'Select One',
}) => {
  const [isOpened, setIsOpened] = useState(false);
  const [dynamicValue, setDynamicValue] = useState('');

  return (
    <Wrapper
      className="form-row"
      onMouseLeave={(e) => {
        if (
          e.target.classList.contains(`select-item`) ||
          e.target.classList.contains(`dropdown`) ||
          e.target.classList.contains(`row-btn`) ||
          e.target.classList.contains(`form-label`) ||
          e.target.classList.contains(`form-row`)
        ) {
          setIsOpened(false);
        }
      }}>
      <label htmlFor="form-row-button">
        <h4 className="form-label">{labelText || name}</h4>
      </label>
      <button
        type="button"
        id="form-row-button"
        className="row-btn"
        onClick={() => {
          setIsOpened(!isOpened);
        }}>
        <span>{dynamicValue || defaultValue}</span>
        {isOpened ? <GoChevronUp /> : <GoChevronDown />}
      </button>

      <div className={isOpened ? `dropdown` : `dropdown hidden`}>
        {list.map((item) => {
          return (
            <label className="select-item" key={item} htmlFor={item}>
              {item}
              <input
                className="option"
                type="radio"
                name={name}
                id={item}
                value={item || defaultValue}
                onClick={() => {
                  setIsOpened(false);
                  setDynamicValue(item);
                }}
                onChange={onChange}
              />
            </label>
          );
        })}
      </div>
    </Wrapper>
  );
};
export default FormRowSelectCustom;

How can I fix this?

I would appreciate your help.

Thank you,

I have no Idea how to fix this… I searched on google, didn’t find any answers for this.

Vue3 – value of wrong store ref is being changed?

Here’s the store:

import { ref } from "vue";

// Store for all data
export const countriesData = ref();
export const isLoading = ref(true);

async function getData() {
    try {
        isLoading.value = true;
        const response = await fetch("https://restcountries.com/v3.1/all");
        const data = await response.json();
        countriesData.value = data;
    } catch (error) {
        console.error("error", error);
    } finally {
        isLoading.value = false;
    }
}

getData();

// Store for filtered data
export const filteredData = ref(countriesData);

The countriesData should be updated once, with the async getData() and then never changed. filteredData does change, based on searching and filtering elsewhere in the app.

Here’s the search input code:

<script setup>
import { ref } from "vue";
import { countriesData, filteredData } from "../../store/store";

const searchValue = ref("");

function handleSubmit(e) {
    e.preventDefault();
console.log(countriesData.value.length);

    for (let i = 0; i < countriesData.value.length; i++) {
        console.log(countriesData.value.length);
        if (
            countriesData.value[i].name.common.toLowerCase() ===
            searchValue.value.toLowerCase().trim()
        ) {
            filteredData.value = [countriesData.value[i]];
            // setError(false);
            searchValue.value = "";
            return;
        } else {
            // setError(true);
        }
    }
}
</script>

For whatever reason, after running this for loop (which works, I get the correct country I search for), the original store, countriesData, changes to only give me countriesData.value[i].

filteredData should be countriesData.value[i], I have no idea why countriesData is also changing to countriesData.value[i].

The code

filteredData.value = [countriesData.value[i]];

in the loop seems to cause both filteredData and countriesData to change to countriesData.value[i], so if I comment that line out, the original countriesData store remains untouched.

How do I get only filteredData to change and leave countriesData untouched?

Array to Excel Javascript

i’m trying to export an array to an Excel file, i found a solution in another question that works fine when the rules array inside the Entity object is small, but if the array of rules is too big, the Excel column ‘overflows’ causing the information to be incomplete once I download the file.
Code I used is below:

import { Component } from '@angular/core';
import * as XLSX from 'xlsx';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  arr: Array<any>;

  constructor() {
    this.arr = [
      {
        Response: 0,
        Success: true,
        Message: '',
        StatusCode: 200,
        Records: [],
        Entity: {
          conversionTableEntityId: 3,
          name: 'PArea',
          translationKey: 'views.conversiontable.table.parea',
          rules: [
            {
              conversionTableRuleId: 3521,
              conversionTableEntityId: 3,
              levelValue1: '*',
              levelValue2: '-',
              levelValue3: '-',
              levelValue4: '-',
              levelValue5: '-',
              levelValue6: '-',
              result1: 'MISSING PLANT CONVERSION',
              result2: 'CST',
              result3: '',
              createdBy: 'Initial Load',
              createdDate: '2019-12-17T00:00:00',
            },
            {
              conversionTableRuleId: 4686,
              conversionTableEntityId: 3,
              levelValue1: 'US_1000',
              levelValue2: '-',
              levelValue3: '-',
              levelValue4: '-',
              levelValue5: '-',
              levelValue6: '-',
              result1: 'Admin-WestPalmBeach',
              result2: 'EST',
              result3: '',
              createdBy: 'Initial Load',
              createdDate: '2021-03-31T00:00:00',
            },
            {
              conversionTableRuleId: 146,
              conversionTableEntityId: 3,
              levelValue1: 'US_1033',
              levelValue2: '-',
              levelValue3: '-',
              levelValue4: '-',
              levelValue5: '-',
              levelValue6: '-',
              result1: '',
              result2: 'EST',
              result3: '',
              createdBy: 'Initial Load',
              createdDate: '2019-12-17T00:00:00',
            },
            {
              conversionTableRuleId: 147,
              conversionTableEntityId: 3,
              levelValue1: 'US_1035',
              levelValue2: '-',
              levelValue3: '-',
              levelValue4: '-',
              levelValue5: '-',
              levelValue6: '-',
              result1: '',
              result2: 'EST',
              result3: '',
              createdBy: 'Initial Load',
              createdDate: '2019-12-17T00:00:00',
            },
          ],
          fields: [
            {
              conversionTableFieldId: 3,
              conversionTableEntityId: 3,
              name: 'custom_string2',
              translationKey: 'views.conversiontable.field.custom_string2',
              createdDate: '0001-01-01T00:00:00',
            },
          ],
          createdDate: '0001-01-01T00:00:00',
        },
        TotalRecordCount: 0,
      },
    ];
  }

  exportToExcel($event) {
    const mappedArr = this.arr.map((item) => {
      if (item.Entity == null) {
        item.Entity = '';
      } else if (typeof item.Entity == 'object') {
        item.Entity = JSON.stringify(item.Entity);
      }
      return {
        ...item,
      };
    });

    const fileName = 'test.xlsx';

    const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet(mappedArr);
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'test');
    XLSX.writeFile(wb, fileName);
  }
}

Is it possible to add a row for each item on the rules and the fields array?
This is the output I get currently:
enter image description here

How to map model with a boolean value to RadioButton in Vaadin hilla

I have below react code

const {field, model, read} = useForm(MyModel);
 <VerticalLayout style={{ alignItems: 'stretch', width: '18rem', maxWidth: '100%' }}>
                    <TextField label="Title" {...field(model.title)} />
                    <NumberField label="Order" {...field(model.order)} />
                    <RadioGroup label="Status" {...field(model.isEnabled)} >
                        <RadioButton value="true" label="Enable" />
                        <RadioButton value="false" label="Disabled" />
                    </RadioGroup>
                </VerticalLayout>

when i am changing its value using

read(model);

its giving below error on browser

The radio button with the value “true” was not found.

NodeJS socketio race conditions

I’m caching with socket io and I need to update my values ​​very quickly. (20 simultaneous requests), and at the end of it all, a get request to check, however, my get returns the value before the updates finish, that is, I expect a result of 20, and my get returns 10, 11, etc. I put a timeout in the catch function and it worked, but it is not very performant.

I’ve already tried using mutex, semaphore and lock, and it didn’t work. Can anyone help?

heres the code:

const { Server } = require("socket.io");
const io = new Server({});

var cache = {};

io.on('connection', (socket) => {
    socket.on('clear', () => {
        cache = {};
    });


    socket.on('addToQueue', async (data, cb) => {
        if (data.type == `get`) {
            // function that await a time
            await new Promise(resolve => setTimeout(() => resolve(true), 20))
            cb({ value: cache[data.key] })
        }

        if (data.type == `transaction`) {
            //performs a calculation on each request and edits the cache
        }
    });
});

(async () => {
    io.listen(6456);
    console.log(`Server listening at *:${PORT}`);
})()

Avoid race conditions without making an unnecessary timeout every time.

Why doesn’t this simple javascript in nodeRED for Visual Flow Creator work?

I’m new to javascript and nodeRED. I’m working in Visual Flow Creator and trying to take 4 values:

var msg = {
    payload: {
        Dryblend_Dose_Finished: true, // Sample values, could be dynamically set
        Filler_Dose_Finished: true,
        Weight_Sent_DryBlend: 100, // Sample values, could be dynamically set
        Weight_Sent_Filler: 50
    }
};

…and when the 2 BOOLean vars are both TRUE, add the 2 “Weight…” values together, storing the result in a new property that will be added to the msg.payload array.

My Code:

// Bring in the payload

var array = msg.payload;

// Check to see if the BOOLs are both TRUE

if (array.Dryblend_Dose_Finished === "true" && array.Filler_Dose_Finished === "true")
{   
    //add the 2 weights together and store for incorporation into the outgoing msg.payload
    array.total = array.Weight_Sent_DryBlend + array.Weight_Sent_Filler;
}
else {
    array.didntWork = 1;
}

// put everything back into the payload

msg.payload = array;

return msg;

It seems to me like this should be “simple” and yet, no matter what I do, it seems like it simply doesn’t even run. In my debug node after the function block, I get the same values out that went in with no changes. I added the “didntWork” var thinking I might sanity check my logic, but that doesn’t show up either, so now I don’t even know if the stupid function is even running (except that nodeRED/Visual Flow Creator says the function completed in 4.08ms.

Anyone have any ideas? This should not be that difficult, and yet this refuses to work.

What am I doing wrong?

Select element option value not showing in js

I’m working on dependent dropdown box with https://tutorial101.blogspot.com/2021/01/python-flask-dynamic-loading-of.html as a reference but with ibm_db.

The idea is when an particular option is selected in the first dropdown box, related options are displayed in second dropdown box.

When I’m selecting an option in first box, second box is not being displayed because the parent id from first box is not going to the second box.

In flask.py second route parent_id is supposed to be populated.

@app.route("/unplanned_outage", methods=['GET', 'POST'])
def unplanned_outage():
    cur1 = conn.cursor()
    select="select * from impacted_tools"
    cur1.execute(select)
    tools = cur1.fetchall()
    cur1.close()
    return render_template(r'unplannedoutage.html', tools=tools)

@app.route("/get_servers_list", methods=['POST', 'GET'])
def get_servers_list():
    cur2 = conn.cursor()
    if request.method == 'POST':
        parent_id = request.form['parent_id']
        print(parent_id)
        cur2.execute("select * from impacted_servers where tools_id = %s", [parent_id])
        servers = cur2.fetchall()
        return jsonify({'htmlresponse': render_template('response.html', servers=servers)})

first_box.html

search_category_id from select element is not picking option value row[0] and hence I’m getting undefined for console.log($(‘#search_category_id’).val()). Hence its not going to get_servers_list route.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" ></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> 
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
    <title>Home Page</title>

    <script> 
    console.log($('#search_category_id').val());
    $(document).ready(function() {
    $('.js-example-basic-multiple').select2();
    });
    $(document).ready(function() {
        $('#search_category_id').change(function(){
            $.post("/get_servers_list", {
                parent_id: $('#search_category_id').val(),
            }, function(response){ 
                $('#show_sub_categories').html(response);
                $('#show_sub_categories').append(response.htmlresponse);
            });
    return false;
  });
}); 
    </script>
</head>
<body>
<form id="form-id" class="row g-3" style="margin: auto; width: 80%;  padding: 30px;" onsubmit="return false;" method="post">
        <div class="col-md-8">
            <label for="search_category_id" class="form-label">Impacted Tools</label>
            <select name="search_category"  id="search_category_id" class="form-control form-select js-example-basic-multiple" multiple="multiple" data-placeholder="Select Tools">
              <option value="" selected></option>
              {% for row in tools %}
              <option value='{{row[0]}}'>{{row[1]}}</option>
              {% endfor %}
            </select>
          </div>
          <div id="show_sub_categories"></div>
          <div class="col-md-12">
            <label for="inputState3" class="form-label">Expected Output</label>
            <select id="inputState3" class="form-select">
              <option selected></option>
              <option>RTC</option>
            </select>
          </div>

        <div class="col-12">
          <button type="submit" class="btn btn-primary">Validate</button>
        </div>
      </form>
</body>

response.html
I pasted the same header in this just in case.

<body>
    <div class="col-md-12 form-group">
        <label for="sub_category_id" class="form-label">Impacted Services</label>
        <select name="sub_category"  id="sub_category_id" class="form-control">
          <option value="" selected></option>
          {% for row in servers %} 
          <option value="{{row[0]}}">{{row[2]}}</option>
          {% endfor %}
        </select>
      </div>
</body>

Please help me on where I’m going wrong.