Can anyone explain to me why escaping numbers n Regular Expressions causes an error

I am writing some code for someone and wanted to show them different ways they could count the no of times a character/no occur in a longer string using both IEnumerable and RegEx however I have found that when I am trying to count the no of times a number occurs in a string none of my methods work despite me converting the no into a literal character first. However trying to use a variable and the cast methods does not work e.g:

char chr = '2'; // works fine

So this literal works however all the other ways which I need to be able to use on variables such as converting an int variable into a char with either (char)no or Convert.ToChar(no) doesn’t work for some reason.

I am sure there is a simple reason but I cannot seem to crack it.

This is my code, the reason there are two methods using RegEx is that I was testing the best way to count special characters such as dots . in a string with C#.

I didn’t know whether it was best to just RegEx.Escape any variable being passed in to my count method or whether I needed to check first whether it needed to be escaped before doing so or just leaving the character alone.

The code calling the test functions is below, the reason I am using a static class to log out the errors is I am just adding this method into a bigger project to do the test quickly and all the HelperLib class is used for is logging with adding a date stamp next to each line, debugging, setting up system wide settings on load and so on…

private void TestCode()
{
    this.HelperLib.LogMsg("IN TestCode - Run Tests on numbers");

    string word = "22.2.34.3";
    int no = 2;
    // char chr = (char)(no); // converting a variable which I need to do doesn't work
    char chr = Convert.ToChar(no) // doesn't work
    // char chr = '2'; // when we do it as a literal it works

    // correct amount of 2 (as a char) in the string should be 3 but we get 0 for each attempt
    int a = word.CountChars(chr);
    HelperLib.LogMsg("Use IEnumerable.Count; There are " + a.ToString() + " occurrences of " + chr.ToString() + " in " + word);

    int b = word.CountChars2(chr);
    HelperLib.LogMsg("RegEx.Escape all chars; There are " + b.ToString() + " occurrences of " + chr.ToString() + " in " + word);

    int c = word.CountChars3(chr);
    HelperLib.LogMsg("Test for special char first before escaping; There are " + c.ToString() + " occurrences of " + chr.ToString() + " in " + word,);

    return;
}

And the methods I am using are in an Extensions class so I can just add them to strings.

public static int CountChars(this string value, char letter)
{
    int count = value.Count(ch => ch == letter);
    return count;
}

public static int CountChars2(this string value, char letter)
{
     // if the letter is a special char then escape it otherwise leave it alone
     string re = (letter.IsSpecialChar()) ? Regex.Escape(letter.ToString()) : letter.ToString();                           
     int c = Regex.Matches(value, re, RegexOptions.IgnoreCase).Count;
     return c;
 }

public static int CountChars3(this string value, char letter)
{
    // escape all characters passed in, in case its a special character               
    string re = Regex.Escape(letter.ToString());
    int c = Regex.Matches(value, re, RegexOptions.IgnoreCase).Count;
    return c;
}

// test to see if we need to escape a character that is a special character in RegEx
public static bool IsSpecialChar(this char letter)
{
    char[] x = { '.', '\', '+', '*', '?', '[', ']', '$', '(', ')', '{', '}', '=', '!', '<', '>', '|', ':', ':', '-', '#' };
    bool ret = (x.Contains(letter)) ? true : false;
    return ret;
}

And the debug I get back is below…

10/12/2021 23:11:28 - IN TestCode - Run Tests on numbers;
10/12/2021 23:11:28 - Use IEnumerable.Count; There are 0 occurrences of 2 in 22.2.34.3;
10/12/2021 23:11:28 - RegEx.Escape all chars; There are 0 occurrences of 2 in 22.2.34.3;
10/12/2021 23:11:28 - Test for special char first before escaping; There are 0 occurrences of 2 in 22.2.34.3;

So I can count letters including special characters used in RegEx like dots without a problem but when it comes to numbers even converting them to a character first doesn’t seem to work and I am stuck to why this is occurring as a literal ‘2’ works but a variable converted to a Char doesn’t.

Also when using JavaScript, as I have a test page for testing expressions before using them in whatever language I need, I have found that escaping every character doesn’t work when it comes to numbers OR special characters for example with the same string “22.2.34.3” when I try 2 it return 0 matches but just 2 returns 3 with this code:

// returns 0
var value = "22.2.34.3";
re = "2"; // tried with double \ and triple \
var exp = new RegExp(re,"gi");
var no = value.match(exp)||[];
alert("NO OF MATCHES " + no.length);

// returns 3
var value = "22.2.34.3";
re = "2";
var exp = new RegExp(re,"gi");
var no = value.match(exp)||[];
alert("NO OF MATCHES " + no.length);

What does a single escaping backslash next to a digit mean to the RegEx machine as it works with letters except special RegEx characters like d or w however I thought by escaping those characters it would mean they would be treated like literals not special characters (digit, word char) etc?

Therefore in JavaScript what would I need to do to count the number of a single no in a longer number e.g “2” in “22.2.34.3” OR count the number of character “d” in a string like “does it matter don’t do it” as a single escape string doesn’t work with the code I am using shown above (or a double/triple backslash)??

Any help in understanding this would be appreciated. Thanks.

How to get Async code to actually wait for the function to finish executing before continuing [duplicate]

What I’m trying to do

I’m still new to working with asynchronous code, I’m trying to do something basic, but I’m not seeing what’s missing here.

So I have this function that gets all orders from Firestore.

getAllOrders() = async () => {
    var orderArray = []

    this.firestore.collection('orders')
      .where('status', '==', status) 
      .where('createdAt', '>=', start)
      .where('createdAt', '<=', end)
      .get()  
      .then(snapshot => {              
        snapshot.forEach(docs => {
            orderArray.push(docs.data())
        })
        console.log(orderArray); //outputs the orders correctly
        return orderArray;
       }).catch(error => {
        console.log(error)
       })
}

I want to call getAllOrders to get the orders and output them to the console. I tried the 2 following methods to get the orders to print. Both output undefined.

Method 1

const onSubmit = async () => {
    props.firebase.getAllOrders().then((orders) => {
        console.log(orders);
    })
}

Method 2

const onSubmit = async () => {
    const orders = await props.firebase.getAllOrders()
    console.log(orders)

}

The first thing that is outputted is undefined and then the correct order array, so the await is not working. I know I’m missing something to get this to work. What should I change it to make it work?

In Angular, how would you move a component in the dom?

Started to learn Angular, so this might have a simple answer 🙂

Without getting to code specific. I’m looking for help, getting in the right direction.

Working on a little shoppinglist application.
The point is, when you found something at the grocery store, you click on the item and it move down in a “found items region of the page”
click and move below image

atm. the blue components are actually just buttons in the template, but could be anything really.
They are instances of a “grocery component”, that are nested within a “shopping list” component, build with an ngFor.

In my head it would make sense to work with a single array and filter on that.
I’ve tried that, and it sort of works, but I can’t get it to move once the initialization is done.
so somehow when I click on a grocery component, I need to tell the shopping list component to move this down in the “grocery found” part of the dom. or vice versa if you want to move it back up.

Any hits or comments would be helpful.

javascript – react material ui pupulate table using API

I am trying to populate the StickyTable template in react. I am not seeing anyhting in my console log but an empty array.

Is there anything obvious that I am missing in my code? I cannot seem to figure out where I am going wrong with this and perhaps a second pair of eyes could help me.

I know my backend is working properly but there is something going wrong on this frontend code

export default function StickyHeadTable() { 
    const rows = useState( [
      createData(1, "fruit ID", 'fruitId'),
      createData(2, "fruit Name", 'fruitName'),
      createData(3, "Fruit Price", 'fruitPrice'),

    ]);

    const [dataRows] = useState([]);
    const [data, setData] = useState("");
  
  useEffect(() => {
     
    (async () => {
    fetch(SERVER_URL + "fruits/")
    .then((response) => response.json())
    .then(rowData => {
      // fruits: responseData
      const data= dataRows.map((a) => {
        const dataRows = [];
        this.state.rows.forEach((a, i) => {
          dataRows.push(createData(a.FruitId, a.fruitType, a.fruitPrice));
      });
      })
      console.log("rows", dataRows);
    })

  })();
});

  return (
    <Paper sx={{ width: "100%", overflow: "hidden" }}>
      <TableContainer sx={{ maxHeight: 440 }}>
        <Table stickyHeader aria-label="sticky table">
          <TableHead>
            <TableRow>
              {columns.map((column) => (
                <TableCell
                  key={column.id}
                  align={column.align}
                  style={{ minWidth: column.minWidth }}
                >
                  {column.label}
                </TableCell>
              ))}
            </TableRow>
          </TableHead>
          <TableBody>
            {rows.map((row) => {
              return (
                <TableRow
                  hover
                  role="checkbox"
                  tabIndex={-1}
                  key={row.Attribute}
                >
                  {columns.map((column) => {
                    const value = row[column.id];
                    return (
                      <TableCell key={column.id} align={column.align}>
                        {column.format && typeof value === "number"
                          ? column.format(value)
                          : value}
                      </TableCell>
                    );
                  })}
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </TableContainer>
    </Paper>
  );
}

How to Get Data From One Array of Objects into another in Array of Objects in TypeScript

I have a get request in a component that returns a response

  getPaymentIntents():Observable<Payment>>{
    const url: string = 'https://store.com//payments';

    return this.http.get<Payment>>
    (url);
  }

The response data looks something like this (the “Payment” type)

[
    {
        "id": "pi_3K4B432423dqM1gTYncsL",
        "amount": 2000,
        "amount_capturable": 0,
        "amount_received": 0,
        "application": null,
        "canceled_at": null,
        "cancellation_reason": null,
        "created": 1638911287,
        "currency": "usd",
        "customer": "cus_KjDBkdsaHIT6AN"
},
    {
        "id": "pi_3K4BW7EE9YQoA1qM1gTYncsL",
        "amount": 1000,
        "amount_capturable": 0,
        "amount_received": 0,
        "application": null,
        "canceled_at": null,
        "cancellation_reason": null,
        "created": 1638913687,
        "currency": "usd",
        "customer": "cus_KjDBkxEVHIT6AN"
}
]

I want this data to be in a “Material Table” https://material.angular.io/components/table/overview

But I only want it to display a subset of the data. (In the future I will want to combine another response’s data into the table as well)

The type I want to pass to the table as a dataSource is this

export interface OrderToProcess{
  Id: string,
  Amount: number,
  Currency: string
}

How do I go about converting one type into the other, I’ve tried filter() map() object.entries() and I’m sure I’m not using them right but none seem to do what I am after.

Thanks for any help!

Chart js does not display when a variable is used as part of the array

the script below displays a chart using chart js.

<script>
var xValues = ["Italy", "France", "Spain", "USA", "Argentina"];

    var yValues = [55, 49, 44, 24, 15];

var barColors = ["red", "green","blue","orange","brown"];

new Chart("myChart", {
  type: "bar",
  data: {
    labels: xValues,
    datasets: [{
      backgroundColor: barColors,
      data: yValues
    }]
  },
  options: {
    legend: {display: false},
    title: {
      display: true,
      text: "World Wine Production 2018"
    }
  }
});
</script>

But I need to replace the numbers with variables that have already been assigned numbers in the document. The chart disappears when I do this as shown below

I replaced this above

var yValues = [55, 49, 44, 24, 15];

with this

var yValues = [$tto_app, $a_rel, $monthly_exp, $cumm_exp];

Please how can I fix this?

Sending files via axios to backend

I have a problem with sending the mp3 file using axios to the backend, everything seems fine when I do console logs on the front, everything is in it, unfortunately on the backend the file field is empty (not null not undefined, just empty).

front console log:
enter image description here

backend console log:
enter image description here

API:

const API = axios.create({baseUrl: 'http://localhost:5000'})


API.interceptors.request.use((req) => {
    if (localStorage.getItem('profile')) {
        req.headers.Authorization = `Bearer ${JSON.parse(localStorage.getItem('profile')).token}`;
    }

    return req;
})
export const addSong = (newSong) =>  API.post('/songs', newSong);

backend

export const addSong = async (req, res) => {
  const song = req.body;


  console.log(song)


  const newSong = new Song({...song, creator: req.userId, createdAt: new Date().toISOString()});

  try {
    await newSong.save();
    res.status(201).json(newSong);
  } catch (error) {
    res.status(409).json({ message: error.message });
  }
};

Matter.js multiple sprites/textures when using poly-decomp in ESM

I am building a simple prototype 2D physics collider editor web app where the problem can be easily recreated.
Tool runtime: https://phys-ed.glitch.me/
With code: https://glitch.com/edit/#!/phys-ed?path=script.js

When I try to use poly-decomp.js to decompose the collider shape (tick ‘Decompose’ checkbox) the resulting body in matter.js has multiple sprites/textures, one per decomposed polygon I guess.

I am using vanilla ESM with no compile step so I wonder if this is a limitation/bug in the libraries which don’t have native ESM support as far as I know or if I am missing some step as I haven’t used poly-decomp.js previously.

Most pertinent code is likely here:
https://github.com/joegaffey/phys-ed/blob/main/script.js#L158
and here:
https://github.com/joegaffey/phys-ed/blob/main/script.js#L188

how to call direct parent’s function by child? [duplicate]

I have three components: ComponentA, ComponentB and Home (Home is the component parent). I want to call a function contains in ComponentA using a button that is inside of ComponentB.

const ComponentA= () => {
  const hello=()=>{
    console.log("hello");
  }
  return <></>
})

const ComponentB= () => {
  const callComponentAFunction=()=>{
   // I need call "hello()" from ComponentA
  }
  return 
   <>
    <button onClick={callComponentAFunction}>Call function from ComponentA</button>
   </>
})

const Home= () => {
 return 
  (<>
   <ComponentA>
     <ComponentB />
   </ComponentA>
   </>)
 })

How can I call hello() function (inside of ComponentA) from ComponentB?

Validate and secure WebSocket data

I have a WebSocket server written in javascript and send data to it from my CSharp application. Now I ask myself how can I make sure that these are correct and not faked. I thought I could do something with hash values but I don’t know how to do that. Does anyone have an idea or code example

is there a way to fluidly calculating total sales using JS with Django

I’m looking for a way to take the information being entered into a database and not only calculate the overall total for a year but also calculate the total for individual months. I’m using Django and Javascript.

The Django View:

@login_required
def proposal_signed(request):
    prop = Proposal.objects.all().order_by('proposal_approved_date')

    return render(request, 'client/proposal_signed.html', {
        'prop': prop,
    })

The HTML and JS:

{% extends 'client/base.html' %}

{% block content %}
    <br>
    <div class="jumbotron jumbotron-fluid">
        <div class="container">
            <div class="text-center">
                <h1 class="display-4"> Sales For Signed Proposals </h1>

            </div>
        </div>
    </div>

    <head>
        <style>
            table {
                font-family: arial, sans-serif;
                border-collapse: collapse;
                width: 100%;
            }

            td, th {
                border: 1px solid #dddddd;
                text-align: left;
                padding: 8px;
            }

            tr:nth-child(even) {
                background-color: #dddddd;
            }
        </style>
        <title></title>
    </head>

    <div class="container">

    <table id="countit">
            <tr>
                <th><strong>Approval Date:</strong></th>
                <th><strong>Job Type:</strong></th>
                <th><strong>Address:</strong>
                <th><strong>Client:</strong></th>
                <th><strong>Bid/Job Total:</strong></th>

            </tr>
            {% for item in prop %}
                 {% if item.proposal_approved_date %}

                    <tr>
                        <td>{{ item.proposal_approved_date }}</td>
                        <td>{{ item.client.requested_service }}</td>
                        <td>{{ item.client.work_site_address }}</td>
                        <td>{{ item.who_to_bill_name }}</td>
                        <td class="count-me">{{ item.client.invoice_set.get.bill_amount }}</td>
                    </tr>

                {% endif %}
            {% endfor %}

        </table>

    <script language="javascript" type="text/javascript">
            var tds = document.getElementById('countit').getElementsByTagName('td');
            var sum = 0;
            for(var i = 0; i < tds.length; i ++) {
                if(tds[i].className === 'count-me') {
                    sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
                }
            }
            document.getElementById('countit').innerHTML += '<tr><td><strong>Total:</strong></td><td>' + sum + '</td></tr>';
        </script>
    

    </div>

    <br>
    <br>

{% endblock %}

This gives me the table with the values and the grand total for the items in the Bid/Job Total on the bottom but I could use some help with breaking it down by month and year. The amount per month is flexible.

Thank you for any help, Dace

Dependency injection question / small example problem

Can simple vanilla dependency injection, such as modules exporting a function that expects an object of dependencies fix the below problem of helper files trying to share their helper functions with each other? Thanks.

index.js

const { sumEvens } = require("./math");

const nums = [1, 2, 1, 1, 2];

console.log(sumEvens(nums));

math.js

const { removeOdds } = require("./filters");

const isEven = (n) => n % 2 === 0;

const sumEvens = (nums) => removeOdds(nums)
  .reduce((sum, n) => sum + n, 0);

module.exports = {
  isEven,
  sumEvens
}

filters.js

const { isEven } = require("./math");

const removeOdds = (nums) => nums.filter((n) => isEven(n));

module.exports = {
  removeOdds
}

TypeError: isEven is not a function, I think because of some circular requiring?

Uncaught TypeError: Cannot read properties of undefined (reading ‘target’) & (reading ‘value’)

After JQuery Version Upgrades to 3.5.0 from 2.14, I am receiving the following error, but I did not fully understand what the problem is,there is radio = event.target The error I received in the definition of Cannot Read Properties of Undefined (Reading ‘target’)
Anyone can you help me solve?
*

var testMethod = {
    testSubMethod: function (event) {
    
        var radio = event.target;
        var isMultiInput = $('#MultipleInputYes').is(':checked');

        if (isMultiInput) {
            $('.divMultiInput').removeClass("dp-none");

            $('.divMinMaxVal').addClass("dp-none")
            $('#divMinMaxDate').addClass("dp-none")

            $('#divRgxWarnMsg').addClass("dp-none")

            $('#minValueInpt').val('');
            $('#maxValueInpt').val('');

            $('.divInputValUpper').addClass("dp-none");
            $('[name=ValueType]').val('');
            $('#inputValueTypeSelect').removeClass('required');
            $('#inputValueTypeSelect').removeClass('customError');

        }
        else if (!isMultiInput || radio.value == undefined) {
            $('.divMultiInput').addClass("dp-none");

            $('.divMinMaxVal').removeClass("dp-none");
            $('#divMinMaxDate').removeClass("dp-none");
            $('#divRgxWarnMsg').removeClass("dp-none")

            $('.divInputValUpper').removeClass("dp-none");
            $('[name=ValueType]').val('1');
            $('#inputValueTypeSelect').addClass('required');

            $('#divWarnMsg').css("display", "inherit");
            $('#placeHolderInpt').val('');
            $("#maskInpt").select2("val", "");

            if (radio.value == 'false') {
                $('#divInputValueType').prop('disabled', false);
                $('#divInputValueType').attr('style', '');
            }

            $('#htmlEditorDiv').css("display", "inherit");
            $('#useMultiLineDiv').css("display", "inherit");

            $("#Tags").tagit("removeAll");
        }
    },
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/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>
<div class="radio radio-success">
<input type="radio" id="MultipleInputYes" value="true" name="IsMultiInput" onchange="testMethod.testSubMethod(this)">
<label for="MultipleInputYes"> Yes</label>
</div>

<div class="radio radio-success">
<input type="radio" id="MultipleInputNo" value="false" checked="checked" name="IsMultiInput" onchange="testMethod.testSubMethod(this)">
<label for="MultipleInputNo">No</label>
</div>