Error passing td.parentNode javascript on ‘onclick’ method

Im working with DataTables(https://datatables.net/examples/basic_init/zero_configuration.html) and javascript, right now Im dealing with ‘edit’ behavior, If I click on edit icon a whole row should be editable.

Now on my javascript file Im using ‘fnCreatedCell’ property (https://legacy.datatables.net/ref#fnCreatedCell) and passing a nTd.parentNode as parameter inside my button icon on ‘onclick=enableEditableRow(${nTd.parentNode})’ method, so my problem here is for some reason javascript is throwing me an error:

Uncaught SyntaxError: Unexpected identifier

Its not even useful… IDK how exactly pass this parameter.

Here is my code:

{
            data: null,
            title: 'Edit',
            orderable: false,
            fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                $(nTd).html(`<button type="button" class="btn btn-outline-secondary" 
                onclick='enableEditableRow(${oData.id}, ${iRow}, ${nTd.parentNode})'>
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pencil-square" viewBox="0 0 16 16">
                        <path d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z"/>
                        <path fill-rule="evenodd" d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z"/>
                    </svg>
                </button>`);
            }
}

How to insert data in many to many relation that has custom fields in typeorm/nestjs?

How to save data in many to many relation that has custom fields in nestjs/typeorm
Here, I have created relation between cart, customer, and product entity. Relation is as follows:
Cart and Customer - OneToOne
Cart and CartProduct(Junction table for cart and product) OneToMany
Product and CartProduct(Junction table for cart and product) OneToMany

customer.entity.ts

import {
  Column,
  Entity,
  OneToMany,
  OneToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { Cart } from './cart.entity';

@Entity()
export class Customer {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @OneToOne(() => Cart, (cart) => cart.customer)
  cart: Cart;
}

cart.entity.ts

import {
  Entity,
  JoinColumn,
  OneToMany,
  OneToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { CartProduct } from './cartProduct.entity';
import { Customer } from './customer.entity';

@Entity()
export class Cart {
  @PrimaryGeneratedColumn()
  id: number;

  @OneToOne(() => Customer, (customer) => customer.cart)
  @JoinColumn({ name: 'customerid' })
  customer: Customer;

  @OneToMany(() => CartProduct, (cartProducts) => cartProducts.cart)
  cartProducts: CartProduct[];
}

product.entity.ts

import {
  Column,
  Entity,
  ManyToOne,
  OneToMany,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { Brand } from './brand.entity';
import { CartProduct } from './cartProduct.entity';
import { OrderProduct } from './orderProduct.entity';
import { SubCategory } from './subCategory.entity';

@Entity()
export class Product {
  @PrimaryGeneratedColumn()
  id: number;

  @OneToMany(() => CartProduct, (cartProduct) => cartProduct.product)
  cartProducts: CartProduct[];
}

cartProduct.entity.ts Junction table for cart and product

import { Column, Entity, ManyToOne } from 'typeorm';
import { Cart } from './cart.entity';
import { Product } from './product.entity';

@Entity()
export class CartProduct {
  @Column()
  quantity: number;

  @ManyToOne(() => Cart, (cart) => cart.cartProducts, { primary: true })
  cart: Cart;

  @ManyToOne(() => Product, (product) => product.cartProducts, {
    primary: true,
  })
  product: Product;
}

Now, while creating cart what I did is,

async addProductToCart(
    customerid: number,
    productid: number,
    quantity: number,
  ): Promise<Cart> {
    const customer = await this.customer.findOne({ id: customerid });
    const cart = this.cart.create();
    const product = await this.product.findOne({ id: productid });
    cart.customer = customer;
    const cartProducts = this.cartProducts.create({
      cart,
      product,
      quantity,
    });
    cart.cartProducts = [cartProducts];
    await this.cartProducts.save(cartProducts); //if i add this line then it 
    // says, NOT NULL constraint failed: cart_product.cartId
    return this.cart.save(cart);
  }

When I make request to this addProductToCart function, then data don’t get stored in the database.
So, how to properly insert data using many to many relation with custom field.

Hyperlinks of multiple filtered views in google sheets using apps script part2

This is an extension of question:

I have sheet a sheet of names(sheet 1 in Columns A, B and C).
I want Have sales information of people in Sheet 2 , sheet 3 and Sheet 4.

I want an apps script for filter view hyperlinks on sheet 1. So Column A on Sheet 1 should take you to a filtered view on Sheet 2. Sheet 1 column B names will have hyperlinks of filter views in Sheet 3. Sheet 1 column C names will have hyperlinks of filter views in Sheet 4.

The code I have so far only takes names from one column in sheet 1 and gets hyperlinks from sheet 2. How do I cycle through Columns A, B and C in Sheet 1 and Sheets 2,3,4. Heres what I have so far ?

If possible, please provide code to even delete filter views, using the same method(I mean based on column names you select, delete specific filter views). When I delete filter views, I want to clear the hyperlinks on the Sheet1 as well(since these links will not exist any more)

function create_filter_view() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var ssId = ss.getId();
  var sheet1 = ss.getSheetByName("Sheet1");
  var sheet2 = ss.getSheetByName("Sheet2");
  var sheetId2 = sheet2.getSheetId();
  var range1 = sheet1.getRange("A2:A" + sheet1.getLastRow());
  var values1 = range1.getValues();
  var requests = values1.map(([a]) => ({ addFilterView: { filter: { title: a, range: { sheetId: sheetId2, startRowIndex: 0, startColumnIndex: 0 }, filterSpecs: [{ columnIndex: 1, filterCriteria: { condition: { type: "TEXT_EQ", values: [{ userEnteredValue: a }] } } }] } } }));
  var response = Sheets.Spreadsheets.batchUpdate({ requests }, ssId);
  var filter_view_ids = response.replies.map(({ addFilterView: { filter: { filterViewId } } }) => filterViewId);
  var richTextValues = filter_view_ids.map((e, i) => [SpreadsheetApp.newRichTextValue().setText(values1[i][0]).setLinkUrl(`#gid=${sheetId2}&fvid=${e}`).build()]);
  range1.setRichTextValues(richTextValues);
}

Pics of example sheets are below:

Sheet1 Has 3 columns: A, B, C. I want the hyperlinks on sheet1 Column A to come from sheet 2. hyperlinks on sheet1 Column B should come from sheet 3. hyperlinks on sheet1 Column C should come from Sheet 4.
I attached an example pic of the filter view in the last pic. “Vincent Lee” from Column C on Sheet 1 should have hyperlink of all “Vincent Lee ” records from Sheet4.

Sheet1pic

Sheet2 Pic

Sheet3 Pic

Sheet4 Pic

Example Filter View for Vincent Lee

Is there a way to display more than 5 buttons in Amazon lex-v2 response

This is my sessionState object

{
"sessionAttributes": {},
"dialogAction": {
  "type": "ElicitSlot",
  "slotToElicit": "flowName"
},
"intent": {
  "name": "WelcomeIntent",
  "confirmationState": "None",
  "slots": {
    "flowName": null
  },
  "state": "Fulfilled"
}

this is messages array

[
{
  "contentType": "ImageResponseCard",
  "content": "Some content",
  "imageResponseCard": {
    "title": "Choose option",
    "subtitle": "options are",
    "buttons": [
      {
        "text": "option1",
        "value": "option1"
      },
      {
        "text": "option2",
        "value": "option2"
      },
      {
        "text": "option3",
        "value": "option3"
      },
      {
        "text": "option4",
        "value": "option4"
      },
      {
        "text": "option5",
        "value": "option5"
      },
      {
        "text": "option6",
        "value": "option6"
      },
      {
        "text": "option7",
        "value": "option7"
      }
    ]
  }
}

]

iam sending 7 buttons from lamda function, but lex is not accepting more than 5 buttons. It is giving error saying buttons should be between 0,5 index. Is there way to display more than 5 buttons in lex response.

How to update float number into Arrays of objects

I have an array of objects as below:

const sinhvien=
[
    { firstName: 'Huy', lastName:'Pham', id: 1985218, math: 0, sport: 0},
    { firstName: 'Tran', lastName:'Ngoc', id: 199999, math: 0, sport: 0},
    { firstName: 'Cuong', lastName:'Nguyen', id: 199777, toan: 0, sport: 0}
]

I had built the random float number function want to generate and update into math attribute in each object

function random(min,max){
    return Math.random()*max + min;
}

var results= random(0,10);
console.log(results);

sinhvien.map(item => item.toan =results);
console.log(sinhvien[0].math);
console.log(sinhvien[1].math);

Problem: the value not update into attribute, any can suggest me.

PS C:temp1985218_JS> nodemon temp4.js
[nodemon] 2.0.15
[nodemon] to restart at any time, enter rs
[nodemon] watching path(s): .
[nodemon] watching extensions: js,mjs,json
[nodemon] starting node temp4.js
9.753263174624365
0
0
[nodemon] clean exit – waiting for changes before restart

Attached picture

Editable Vinyl/Text Editor using Javascript

Hello as I’m finding ways to create and editable Vinyl or text editor I cant make it work, I want an output similar to this link https://www.stickermule.com/products/vinyl-lettering , I made one but with buttons and it worked but I want to apply it via combo box but it wouldn’t work, can someone help me? I’m using HTML CSS and JavaScript.

Here is the code i have tried

    <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .container {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
  }
  p {
      width: 40%;
      border: 1px solid black;
      padding: 10px;
      font-weight: bold;
      font-size: 18px;
  }
  button {
      padding: 10px 20px;
      margin: 5px;
  }
  </style>
</head>
<body>
  
  <div class="container">
    Select Color:
    <select>
      <option>Choose a Color</option>
      <option id="btnRed">Red</option>
      <option id="btnBlue">Blue</option>
      <option id="btnGreen">Green</option>
    </select>
    <textarea style="width: 25%; height: 200px;"></textarea>
  </div>

  <script>
    let btnRed = document.querySelector('#btnRed');
    let btnBlue = document.querySelector('#btnBlue');
    let btnGreen = document.querySelector('#btnGreen');
    let content = document.querySelector('textarea');
    btnRed.addEventListener('click',() => content.style.color = 'red');
    btnBlue.addEventListener('click',() => content.style.color = 'blue');
    btnGreen.addEventListener('click',() => content.style.color = 'green');
  </script>
</body>
</html>

How to iterate through folder of files on GitHub using Javascript?

I want to be able to iterate through a local folder of files (CSVs) on GitHub and use the file contents in Javascript. I used this code but it only retrieves the contents of one file:

var array = [];
var file = new XMLHttpRequest();
file.onreadystatechange = function () {
   array.push(this.responseText);
}
file.open("GET", "[csv link]", true);

I read through other questions, and the suggested method was to use PHP, but because I am going to be using this for GitHub pages, PHP isn’t supported. Are there any workarounds to this?

What will be value of max-content?

Is there any way by which one can actually calculate how much will be max-content or min-content or fit-content and so on.

Something like

.btn:hover {
    width: calc(max-content);
}

I tried (max-content + 0px) but it didn’t worked either. Need a pure CSS solution. Use of JavaScript should be last priority!

How to trigger the right mouse click event through JS?

I want to trigger the right mouse click event through JS.

Here is my test code:

            var obj = document.getElementById("testItem");
            var evObj = document.createEvent("MouseEvents",);
            evObj.initEvent('click', true, false);
            Object.defineProperty(evObj, "button", {
                value: 2,
                writable: false
            });
            Object.defineProperty(evObj, "buttons", {
                value: 2,
                writable: false
            });
            obj.dispatchEvent(evObj);

I tried lots of methods, but they didn’t work.

Anyone know how to solve it?

Thank you in advance.

Modal popup for Django DeleteView

I’m trying to have a modal popup asking for confirmation before deleting the object using DeleteView. So far, I’ve tried solutions from this thread using the following code.

views.py

class SessionCancelView(
    SuccessMessageMixin, LoginRequiredMixin, UserPassesTestMixin, DeleteView
):
    model = Session
    success_url = "/profile"
    success_message = "Session was cancelled successfully"
    # FIXME: success message not showing - eh maybe not necessary tho

    def test_func(self):
        session = self.get_object()
        if self.request.user == session.student:
            return True
        return False

    def get(self, request, *args, **kwargs):
        return self.post(request, *args, **kwargs)

profile.html

<!-- Modal -->
<div class="modal fade" id="sessionDeleteModal" tabindex="-1" role="dialog" aria-labelledby="sessionDeleteModalLabel"
    aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Cancel Session</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                Are you sure you want to cancel this session?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button class="btn btn-outline-danger" type="submit">Yes, Cancel</button>
                <form method="POST" action="{% url 'session-cancel' session.id %}">
                    {% csrf_token %}<input type="submit" value="DELETE">
                </form>
            </div>
        </div>
    </div>
</div>

.
.
.

{% for session in user_sessions %}
    {% if session.is_upcoming %}
    <div class="card bg-light mb-3" style="width: 18rem;">
        <div class="card-header">{{ session.date|date:"F d [l]" }}</div>
        <div class="card-body">
            <h5 class="card-title">{{ session.get_timeblock_display }}</h5>
            <h6 class="card-subtitle mb-2 text-muted">{{ session.weekday }}</h6>
            <p class="card-text">{{ session.helptype }}</p>
            <a class='btn btn-outline-secondary btn-small mt-1 mb-1' href="{% url 'session-edit' session.id %}">Edit</a>
            <a class='btn btn-outline-danger btn-small mt-1 mb-1'
                href="{% url 'session-cancel' session.id %}">Cancel</a>
            <button type="button" class="btn btn-outline-danger btn-small mt-1 mb-1" data-toggle="modal"
                data-target="#sessionDeleteModal">
                Modal Cancel
            </button>
        </div>
    </div>
    {% endif %}
    {% endfor %}

urls.py

from django.urls import path
from . import views
from .views import (
    SessionListView,
    SessionDetailView,
    SessionCreateView,
    SessionEditView,
    SessionCancelView,
)

urlpatterns = [
    path("", views.home, name="scheduler-home"),
    path("about/", views.about, name="scheduler-about"),
    path("sessions/", SessionListView.as_view(), name="scheduler-sessions"),
    path("sessions/<int:pk>/", SessionDetailView.as_view(), name="session-detail"),
    path("sessions/new/", SessionCreateView.as_view(), name="session-create"),
    path("sessions/<int:pk>/edit", SessionEditView.as_view(), name="session-edit"),
    path(
        "sessions/<int:pk>/cancel", SessionCancelView.as_view(), name="session-cancel"
    ),
    path("issues/", views.report_issues, name="scheduler-issues"),
]

However, I’m getting the following error when loading profile.html page:

Exception Type: NoReverseMatch at /profile/
Exception Value: Reverse for 'session-cancel' with arguments '('',)' not found. 1 pattern(s) tried: ['sessions/(?P<pk>[0-9]+)/cancel$']

I am assuming this is happening because modal has no way of having session.id passed in, hence causing a NoReverseMatch error. Would appreciate if anyone could help point out what I did wrong!

Source tag didn’t update the src attribute

I tried to use useState to update the video background, but it seems not working.

Here is my code:

  const [bgChange, setbgChange] = useState(backgroundDay);

  const handleBackground = () => {
    bgChange === backgroundDay
      ? setbgChange(backgroundNight)
      : setbgChange(backgroundDay);
    console.log(bgChange);
  };

  return (
    <div className="container">
      <div className="-z-50 absolute">
        <video className="videoTag" autoPlay loop muted>
          <source src={bgChange} type="video/mp4" />
        </video>
      </div>
      <button onClick={handleBackground}>Change BG</button>
    </div>
  );

Why does the default react app file not run with eslint enabled?

I have globally installed eslint via cmd and its also installed as an extension in vs code. After that I used the following command in the vs code terminal to initialize it:

npx eslint --init 

I used the Airbnb style guide option while setting it up.
But even running the default file that comes when you create a react app multiple errors are shown like this screenshot of errors.
I have just started learning React, and don’t know what other details might be needed to solve this issue.
Below is the App.js file code.

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return ( <
    div className = "App" >
    <
    header className = "App-header" >
    <
    img src = {
      logo
    }
    className = "App-logo"
    alt = "logo" / >
    <
    p >
    Edit < code > src / App.js < /code> and save to reload. <
    /p> <
    a className = "App-link"
    href = "https://reactjs.org"
    target = "_blank"
    rel = "noopener noreferrer" >
    Learn React <
    /a> <
    /header> <
    /div>
  );
}

export default App;

Edit:
Imported React module and added

 "react/jsx-filename-extension": [1, { "extensions": [".js", ".JSX"] }]

in rules of .eslinrc.json but

Line 7:5:  JSX not allowed in files with extension '.js'  react/jsx-filename-extension 

this error is still there, despite deleting and reinitializing eslint for my app.

Moving Average Line in Highcharts Scattered Chart

I am trying to implement a Moving Average line in a Highachart’s Scattered chart. The x Axis is a Date and y axis is days but when I try to calculate the Moving average its is referring to date with year 1970.

Here is js fiddle link for my code:
enter link description here

I also have code without moving Average and the link is enter link description here

Here is the Highchart code with Moving average I am using :

Highcharts.chart('container', {
chart: {
    type: 'scatter',
    zoomType: 'xy'
},
title: {
    text: 'Height Versus Weight of 507 Individuals by Gender'
},
subtitle: {
    text: 'Source: Heinz  2003'
},
xAxis: {
  title: {
    enabled: true,
    text: 'PR Creation'
  },
  startOnTick: true,
  endOnTick: true,
  showLastLabel: true,
  type: 'datetime',
  dateTimeLabelFormats: {
  second: '%Y-%m-%d<br/>%H:%M:%S',
  minute: '%Y-%m-%d<br/>%H:%M',
  hour: '%Y-%m-%d<br/>%H:%M',
  day: '%Y<br/>%m-%d',
  week: '%Y<br/>%m-%d',
  month: '%Y-%m',
  year: '%Y'
}
},
 yAxis: {
title: {
  text: 'duration'
},
type: 'datetime', //y-axis will be in milliseconds
dateTimeLabelFormats: {
minute: '%H:%M'
                      }
 },
legend: {
    layout: 'vertical',
    align: 'left',
    verticalAlign: 'top',
    x: 100,
    y: 70,
    floating: true,
    backgroundColor: Highcharts.defaultOptions.chart.backgroundColor,
    borderWidth: 1
},
plotOptions: {
    scatter: {
        marker: {
            radius: 5,
            states: {
                hover: {
                    enabled: true,
                    lineColor: 'rgb(100,100,100)'
                }
            }
        },
        states: {
            hover: {
                marker: {
                    enabled: false
                }
            }
        },
        tooltip: {
            headerFormat: '<b>{series.name}</b><br>',
            pointFormat: '{point.x}'
        }
    }
},
 
series: [{
    name: 'PR',
    color: 'rgba(223, 83, 83, .5)',
     data: [{x:st4,y:3},{x:st5,y:7},{x:st6,y:8},{x:st7,y:9},{x:st8,y:9},{x:st9,y:7},{x:st10,y:7},{x:st11,y:3},{x:st12,y:2}]

},
{
   name: 'PR',
    color: 'green',
     data: [{x:st,y:5},{x:st3,y:7},{x:st11,y:1}]
}]
}
 ,function() {
            var Highcharts = this;
            var series = Highcharts.series[0];
            var data = [];
            var period = 2;
            var sumForAverage = 0;
            var i;
            for(i=0;i<series.data.length;i++) {
                sumForAverage += series.data[i].y;
                if(i<period) {
                    data.push(null);
                } else {
                    sumForAverage -= series.data[i-period].y;
                    data.push([series.data[i].x, sumForAverage/period]);
                }
            }
            Highcharts.addSeries({
                name: 'Moving Average',
                data: data
            });
        });

Please suggest if you have an idea on calculating the moving average . I am trying to implement something similar to the cycle time widget in Azure Devops