Typescript spread operator causing object to be treated as a string

I’m reasonably new to typescript and I have been attempting to create a DAO for DynamoDB to insert objects into a table. However, when using the spread operator it appears to cause the object to be split into individual characters instead.

My method simply takes the object, adds a few fields to it via the spread operator and then inserts it into the table. From my understanding this should work however as you can see by the console.log() before and after the spread operation on the ‘itemToInsert’ something is going wrong.

The Method

async createItem(item: FleetAccount): Promise<FleetAccount> {
        console.log(item);

        const itemToInsert: FleetAccount = {
            ...item,
            id: generateUniqueKey("ACC"),
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),

        };

        console.log(itemToInsert);

        try {
            await this.docClient.send(new PutCommand({
                TableName: this.tableName,
                Item: itemToInsert,
                ConditionExpression: 'attribute_not_exists(id)'
            }));
        } catch (e) {
            if (e instanceof ConditionalCheckFailedException) { //Error when the item already exists.
                return Promise.reject("Item with specified Id already exists.");
            } else {
                console.log("FAILURE!");
                console.log(e);
                return Promise.reject();
            }
        }

        return itemToInsert;
    }

The Interface/Type

export default interface FleetAccount {
    id: string;
    businessName:
    businessAddress: string;
    abn: string;
    primaryContactId: string;
    invoiceIds: Array<string>;
    availableMerchants: Array<string>;
    requireVehicleRegistration: boolean; 
    users: Array<string>;
    createdAt:
    updatedAt: string;
}

Item

{
"businessName": "Test Company",
"businessAddress": "123 Fake Street, Canberra, Australia, 2903",
"abn": "123456",
"primaryContactId": "FUI1234",
"invoiceIds": ["1"],
"availableMerchants": ["1"],
"requireVehicleRegistration": false,
"users": ["1"]
}

itemToInsert

{
  '0': '{',
  '1': 'r',
  '2': 'n',
  '3': ' ',
  '4': ' ',
  '5': ' ',
  '6': ' ',
  '7': '"',
  '8': 'b',
  '9': 'u',
  '10': 's',
  '11': 'i',
  '12': 'n',
  '13': 'e',
  '14': 's',
  '15': 's',
  '16': 'N',
  '17': 'a',
  '18': 'm',
  '19': 'e',
  '20': '"',
  '21': ':',
  '22': ' ',
  '23': '"',
  '24': 'T',
  '25': 'e',
  '26': 's',
  '27': 't',
  '28': ' ',
  '29': 'C',
  '30': 'o',
  '31': 'm',
  '32': 'p',
  '33': 'a',
  '34': 'n',
  '35': 'y',
  '36': '"',
  '37': ',',
  '38': 'r',
  '39': 'n',
  '40': ' ',
  '41': ' ',
  '42': ' ',
  '43': ' ',
  '44': '"',
  '45': 'b',
  '46': 'u',
  '47': 's',
  '48': 'i',
  '49': 'n',
  '50': 'e',
  '51': 's',
  '52': 's',
  '53': 'A',
  '54': 'd',
  '55': 'd',
  '56': 'r',
  '57': 'e',
  '58': 's',
  '59': 's',
  '60': '"',
  '61': ':',
  '62': ' ',
  '63': '"',
  '64': '1',
  '65': '2',
  '66': '3',
  '67': ' ',
  '68': 'F',
  '69': 'a',
  '70': 'k',
  '71': 'e',
  '72': ' ',
  '73': 'S',
  '74': 't',
  '75': 'r',
  '76': 'e',
  '77': 'e',
  '78': 't',
  '79': ',',
  '80': ' ',
  '81': 'C',
  '82': 'a',
  '83': 'n',
  '84': 'b',
  '85': 'e',
  '86': 'r',
  '87': 'r',
  '88': 'a',
  '89': ',',
  '90': ' ',
  '91': 'A',
  '92': 'u',
  '93': 's',
  '94': 't',
  '95': 'r',
  '96': 'a',
  '97': 'l',
  '98': 'i',
  '99': 'a',
  '100': ',',
  '101': ' ',
  '102': '2',
  '103': '9',
  '104': '0',
  '105': '3',
  '106': '"',
  '107': ',',
  '108': 'r',
  '109': 'n',
  '110': ' ',
  '111': ' ',
  '112': ' ',
  '113': ' ',
  '114': '"',
  '115': 'a',
  '116': 'b',
  '117': 'n',
  '118': '"',
  '119': ':',
  '120': ' ',
  '121': '"',
  '122': '1',
  '123': '2',
  '124': '3',
  '125': '4',
  '126': '5',
  '127': '6',
  '128': '"',
  '129': ',',
  '130': 'r',
  '131': 'n',
  '132': ' ',
  '133': ' ',
  '134': ' ',
  '135': ' ',
  '136': '"',
  '137': 'p',
  '138': 'r',
  '139': 'i',
  '140': 'm',
  '141': 'a',
  '142': 'r',
  '143': 'y',
  '144': 'C',
  '145': 'o',
  '146': 'n',
  '147': 't',
  '148': 'a',
  '149': 'c',
  '150': 't',
  '151': 'I',
  '152': 'd',
  '153': '"',
  '154': ':',
  '155': ' ',
  '156': '"',
  '157': 'F',
  '158': 'U',
  '159': 'I',
  '160': '1',
  '161': '2',
  '162': '3',
  '163': '4',
  '164': '"',
  '165': ',',
  '166': 'r',
  '167': 'n',
  '168': ' ',
  '169': ' ',
  '170': ' ',
  '171': ' ',
  '172': '"',
  '173': 'i',
  '174': 'n',
  '175': 'v',
  '176': 'o',
  '177': 'i',
  '178': 'c',
  '179': 'e',
  '180': 'I',
  '181': 'd',
  '182': 's',
  '183': '"',
  '184': ':',
  '185': ' ',
  '186': '[',
  '187': '"',
  '188': '1',
  '189': '"',
  '190': ']',
  '191': ',',
  '192': 'r',
  '193': 'n',
  '194': ' ',
  '195': ' ',
  '196': ' ',
  '197': ' ',
  '198': '"',
  '199': 'a',
  '200': 'v',
  '201': 'a',
  '202': 'i',
  '203': 'l',
  '204': 'a',
  '205': 'b',
  '206': 'l',
  '207': 'e',
  '208': 'M',
  '209': 'e',
  '210': 'r',
  '211': 'c',
  '212': 'h',
  '213': 'a',
  '214': 'n',
  '215': 't',
  '216': 's',
  '217': '"',
  '218': ':',
  '219': ' ',
  '220': '[',
  '221': '"',
  '222': '1',
  '223': '"',
  '224': ']',
  '225': ',',
  '226': 'r',
  '227': 'n',
  '228': ' ',
  '229': ' ',
  '230': ' ',
  '231': ' ',
  '232': '"',
  '233': 'r',
  '234': 'e',
  '235': 'q',
  '236': 'u',
  '237': 'i',
  '238': 'r',
  '239': 'e',
  '240': 'V',
  '241': 'e',
  '242': 'h',
  '243': 'i',
  '244': 'c',
  '245': 'l',
  '246': 'e',
  '247': 'R',
  '248': 'e',
  '249': 'g',
  '250': 'i',
  '251': 's',
  '252': 't',
  '253': 'r',
  '254': 'a',
  '255': 't',
  '256': 'i',
  '257': 'o',
  '258': 'n',
  '259': '"',
  '260': ':',
  '261': ' ',
  '262': 'f',
  '263': 'a',
  '264': 'l',
  '265': 's',
  '266': 'e',
  '267': ',',
  '268': 'r',
  '269': 'n',
  '270': ' ',
  '271': ' ',
  '272': ' ',
  '273': ' ',
  '274': '"',
  '275': 'u',
  '276': 's',
  '277': 'e',
  '278': 'r',
  '279': 's',
  '280': '"',
  '281': ':',
  '282': ' ',
  '283': '[',
  '284': '"',
  '285': '1',
  '286': '"',
  '287': ']',
  '288': 'r',
  '289': 'n',
  '290': '}',
  id: 'ACCBPNEJB84SMJJHFA',
  createdAt: '2023-11-18T14:24:38.256Z',
  updatedAt: '2023-11-18T14:24:38.256Z'
}

Is there another way that these fields should be added to this object to make it more clear to JS that this is not a string? I have already tried Object.assign() with the same result.

How to properly expose the Bun inspector inside a docker container

For some reason I cannot get bun to work with the --inspect flag inside a docker container. I have tested it outside the container and it functions as expected, however inside the container the logs tell me all is fine but I can’t connect in the UI with the provided link.


In my Dockerfile

  • i use from oven/bun
  • I have exposed port 6499
  • and i execute bun run dev

In my docker-compose.yml

  • I have mapped 6499:6499

When running docker ps

  • 0.0.0.0:6499->6499/tcp, :::6499->6499/tcp

The dev command in my package.json
NODE_TLS_REJECT_UNAUTHORIZED=0 bun run --inspect --watch src/server.ts


However when I click the link provided in the stdout the UI shows but without any data.

how to use {{ form.as_p }} in javascript

I’ve a question, I am a Django developer, in my program I want to write a JavaScript file that when we click a button, the script file create a new form. The javaScript file:

function noid(){
    console.log("on");
    const mydiv = document.querySelector(".my");
    const myform = document.createElement("form");
    mydiv.appendChild(myform);
    myform.insertAdjacentHTML("afterend",
    "{% csrf_token %}")

 

    
    
    
}
document.querySelector("#mybtn").addEventListener("click",noid);

The html file:

{% extends "base.html" %}
{% load static %}
{% block head %}
<title>create</title>
<link rel="stylesheet" href="{% static "sakht.js" %}">


<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@200&display=swap" rel="stylesheet">
{% endblock head %}
{% block body %}


<div class='container bg-ligth rounded-3 my'>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">submit</button>
    </form>

    <button class="Mybtn" id="mybtn">Add</button>
    <form method="post">
        {% csrf_token %}
        {{ quesform.as_p }}
        <button type="submit">submit</button>
    </form>
</div>


<script src="{% static "sakht.js" %}"></script>
{% endblock body %}

I want to know that how can I add the {% csrf_token %} block and {{ quesfrom.as_p }} block to javascript file. please help me.

How can I add {% csrf_token %} and {{ quesform.as_p }} blocks to javascipt?

Twilio Taskrouter incoming call gets ended automatically

I have a calling system setup with Twilio Taskrouter that queue’s calls and assigns the calls to workers with reservations. The frontend JS worker listens to reservations coming in and when one does, the worker can accept or reject the reservation. If it accepts, the device.on('incoming)' gets triggered and a call comes in. The function also automatically accepts the call.

But after the timeout time has ran out, the call gets disconnected. Which makes me think that 2 calls are being made in Twilio’s system, one that gets accepted, but also one that chills in the background and timesout, causing the active one (call) to end.

Why does that happen?

this.worker.on('reservation.created', async (reservation: any) => {
                this.reservation = reservation;
                this.callState = 'INCOMING';

                this.eventEmitter.on('reservation_accepted', async () => {
                    await reservation.dequeue();
                    if (this.call) {
                        await (this.call as any).accept();
                    }

                    this.callState = 'IN_PROGRESS';
                    this.startTimer();
                });

                this.eventEmitter.on('reservation_rejected', async () => {
                    await reservation.reject();
                    this.resetAll();
                });
            });

Total number of combinations

I generate userId string based on the rule below. If it works as I want, it should generate the userID the way it respects the order of elements in letters array (it is always the word USER).
I wonder how would I calculate total amount of unique strings I can generate this way?

function generateID() {
    
    let userID = '';
    let letters = ['U','S','E','R'];

    for (let l = 5; l < 12; l++)    // for random indexes from 4 to 11
    {
        let position = Math.floor(Math.random() * l);
        let digit = Math.floor(Math.random() * 10);
        letters.splice(position, 0, digit);
    }
    
    userID = letters.join('');


    return userID;
}

Thanks for help

React native rendering flickers

The following is the example code.

import React, {useState} from 'react';
import {
  Dimensions,
  LayoutAnimation,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

const _use = [{name: 'a'}, {name: 'b'}, {name: 'c'}];

const _unuse = [{name: 'k'}, {name: 'l'}, {name: 'm'}];

const _WIDTH = Dimensions.get('window').width;

const App = () => {
  const [Use, setUse] = useState(_use);
  const [UnUse, setUnUse] = useState(_unuse);

  const RenderUse = () => {
    return (
      <View
        style={{
          flexDirection: 'row',
          flexWrap: 'wrap',
          backgroundColor: 'black',
        }}>
        {Use.map((item, index) => {
          return (
            <Text
              key={item.name}
              style={{
                borderColor: '#333',
                borderWidth: 1,
                borderRadius: 2,
                width: '20%',
                marginRight: (index + 1) % 4 !== 0 ? 10 : 0,
                textAlign: 'center',
              }}>
              {item.name}
            </Text>
          );
        })}
      </View>
    );
  };

  const RenderUnUse = () => {
    return (
      <View
        style={{
          flexDirection: 'row',
          flexWrap: 'wrap',
        }}>
        {UnUse.map((item, index) => {
          return (
            <TouchableOpacity
              style={{
                borderWidth: 1,
                borderRadius: 2,
                width: '20%',
                marginRight: (index + 1) % 4 !== 0 ? 10 : 0,
              }}
              onPress={() => {
                console.log(item);
                LayoutAnimation.easeInEaseOut();
                setUse([...Use, item]);
                setUnUse(UnUse.filter(i => i.name !== item.name));
              }}>
              <Text
                key={item.name}
                style={{
                  borderColor: '#333',
                  textAlign: 'center',
                }}>
                {item.name}
              </Text>
            </TouchableOpacity>
          );
        })}
      </View>
    );
  };

  return (
    <View
      style={{
        paddingHorizontal: 10,
        marginTop: 20,
      }}>
      {RenderUse()}
      {/*<RenderUse />*/}
      <Text>UnUse</Text>
      {RenderUnUse()}
      {/*<RenderUnUse />*/}
    </View>
  );
};

export default App;

When I turn on LayoutAnimation.easeInEaseOut(); to call RenderUnUse and RenderUse in component mode, when I click k l m, RenderUnUse will flash

    <View
      style={{
        paddingHorizontal: 10,
        marginTop: 20,
      }}>
      <RenderUse />
      <Text>UnUse</Text>
      <RenderUnUse />
    </View>

But when I call as a function, it will not blink and display normally

    <View
      style={{
        paddingHorizontal: 10,
        marginTop: 20,
      }}>
      {RenderUse()}
      <Text>UnUse</Text>
      {RenderUnUse()}
    </View>

I want to know why it doesn’t blink when I call as a function, but it does blink when I call as a component

Why I can’t assign a variable of class to an abstract class type in TypeScript?

I have the following code and it works correctly:

type Class<T> = new (...args: unknown[]) => T;

abstract class AbstractClass<T = unknown> {
  constructor(protected element: T) {}

  method() {
    return "Abstract";
  }
}

class A extends AbstractClass<unknown[]> {
  constructor(element: unknown[]) {
    super(element);
  }
}

class B extends AbstractClass {
  constructor(element: unknown) {
    super(element);
  }

  method() {
    return "B";
  }
}

function factoryMethod(flag: boolean): Class<AbstractClass> {
  return flag ? A : B;
}

console.log(new (factoryMethod(true))().method());
console.log(new (factoryMethod(false))().method());

However, when I try to do the following I get an error:

const c: Class<AbstractClass> = A;

What I don’t understand is that it works in the factoryMethod but not when I assign it directly.

How to add use external script file for .ejs pages

I’m a beginner at nodeJs and express.
I’m learning over building a small multipage web app project.
But I don’t know how to use an external script tag to store all the javascript I’ll be using in all my ejs pages.

Project/
|-- app/
|   |-- script.js
|
|-- public/
|   |-- css/
|       |-- style.css
| 
|-- views/
|   |-- home.ejs
|
|-- app.js
|-- package.json
|-- package-lock.json

Although, I was successful in using a <script> tag in each of the .ejs pages, I’d like to see if it’s possible to get all the js in one file, rather than split in multiple.

So far, I tried these but didn’t work

  1. Placing the js file in an ‘app’ folder to access it from there, but only works with css
const app = express();
app.use(express.static(__dirname + "/public"));
app.use(express.static(__dirname + "/app"));
  1. Using “path.join”, but it doesn’t work for both the css and js
app.use('/app',express.static(path.join('../app')));
app.use('/public',express.static(path.join('../public')));

I got no 2. for the answer to a similar question at https://stackoverflow.com/a/65303067/20831188, but that was two years ago, so I don’t know if it’s because I’m using a later version that it doesn’t work

undergraduate guidance for prepping portfolio

How can i start my career to get internship, either online or on-site? how can i build skills to show the tech industries ik stuff ? im an online student and i dont have much exposure on these things to observe and participate? i have learnt few basics of programming Lang, visit my GitHub and LinkedIn to know what i have done so far. pls guide me
@hania345
Hania khalid shariff

i want to know how to build my linkedin premium profile as a cs undergrad student
and correct my resume to attract recruiters for an online internship
i want to how can i build projects

WinRT component field value not being read in WebView2 runtime

I have a WebView2 container app that I am developing for game publishing and have a few issues that are blocking the development process. More specifically, I have a field in a WinRT component that is supposed to be read on the Javascript side which is intended to block input to the game when the container app is not fully active (e. g. if the guide menu is open on an Xbox console). However, the field shows up as undefined on the Javascript side, resulting in the user’s input being blocked in all cases.

Here’s the field definition:

public static bool GameBarActive { get { return gameBarActive; } }

Activation detection is hanled through the associated window event:

private static void Window_Activated(CoreWindow sender, WindowActivatedEventArgs args)
         {
             if (args.WindowActivationState == CoreWindowActivationState.Deactivated)
             {
                 gameBarActive = true;
             }
             else
             {
                 gameBarActive = false;
             }
         }

What’s supposed to happen here is that when gameBarActive is false, then GameBarActive (which is the public, read only version) is supposed to return the value of the internal, writable version from the WinRT component. The C# code that connects the WinRT component to the WebView2 container places it in a top-level Javascript namespace called Xbox with a class named API which exposes the WinRT component to the game. However, for some odd reason the field is not being picked up on the Javascript side even though it’s set with the proper definitions.

Using the controller input detection from RPG Maker MV as an example, the input block is supposed to function as follows:

     if (Xbox.API.GameBarActive == false) {
         var lastState = this._gamepadStates[gamepad.index] || [];
         var newState = [];
         var buttons = gamepad.buttons;
         var axes = gamepad.axes;
         var threshold = 0.5;
         newState[12] = false;
         newState[13] = false;
         newState[14] = false;
         newState[15] = false;
         for (var i = 0; i < buttons.length; i++) {
             newState[i] = buttons[i].pressed;
         }
         if (axes[1] < -threshold) {
             newState[12] = true;    // up
         } else if (axes[1] > threshold) {
             newState[13] = true;    // down
         }
         if (axes[0] < -threshold) {
             newState[14] = true;    // left
         } else if (axes[0] > threshold) {
             newState[15] = true;    // right
         }
         for (var j = 0; j < newState.length; j++) {
             if (newState[j] !== lastState[j]) {
                 var buttonName = this.gamepadMapper[j];
                 if (buttonName) {
                     this._currentState[buttonName] = newState[j];
                 }
             }
         }
         this._gamepadStates[gamepad.index] = newState;
     }

Any insight as to what’s going on (or anything else that I can try) would be appreciated.

How to achieve a scrolling upwards effect, while parts of prev-text still in view

I’m aiming to recreate an animation using JavaScript and CSS. It involves a list of words from a CMS, where the quantity of a single word can change. The goal is to create an endless vertical scrolling effect without a visible loop restart, similar to a marquee. I’m struggling with modifying my code to achieve the desired behavior. CSS animations are a bit challenging for me to grasp, so any assistance would be greatly appreciated. I’m open for a new markup structure if necessary.

My code: https://codesandbox.io/s/2v85nk?file=/src/TextSlider.js

The desired effect: https://drive.google.com/file/d/1bDVqeulKpwFyDKA9sKqxduR7OFgBZKK0/view?usp=sharing

I attempted to modify these two lines within .slider-item, making some progress but not quite reaching the desired outcome.

.slider-item {
  opacity: 0.5; // Added to show the previous item slightly while transitioning
  transform: translateY(-100%); // Altered scrolling direction
}

while fetching the erc20 tokens from the redux store it says type error j is not a function

this counter does not go away there is no other error in the code whole thing is working this bug is not fixed . it also causes heavy usage of my mac cpu to extent that it heats up so much
console image
i causes to reload the tokens

i was not expecting this error whole thing is working i think this is because of version of the dependencies or something i have thoroughly checked the code i can not found any error in this

BeautifullSoup findall JavaScript alternative?

What’s the js alternative of this python script:

from bs4 import BeautifulSoup as bs
import requests

page = requests.get(url).text

soup = bs(page)
items = soup.findAll('li')

I’ve searched DOM Parser documentation but i can’t find anything like findall().

Can someone help me?