Why does chrome continue to give 404 errors for a file that’s not included anymore?

For a while, my website used to have two JS files, subtitle_tagline.js and lazysizes.min.js. A while back they were both folded into the main theme.js directly, and all the references to such were removed. Grepping for the file names in the final source produces zero results.

Chrome’s inspector still marks the requests it’s making as 404 (which is accurate), citing “(index)” as the initiator. Well, I can view source and Ctrl-f, and it’s most definitely not in there.

This shouldn’t be a caching issue, since I’ve cleared the entire cache multiple times, and dev tools are supposed to run in no-cache mode when they’re open regardless. Any ideas why a file with no references is still being requested?

EJS console.log() does print correctly, but it doesn’t while writing it to the table

Good Day everybody

If i use a console.log it prints it correctly, but it doesn’t write it to a table. And i have no idea why it doesn’t. Can someone help me please?

My EJS looks like this:

<% insrtdJngls.forEach((item) => { %>
                        <tr></tr>
                            <% console.log(item, "ejs print") %>
                            <% console.log(item.insrtdDateiname, "ejs print") %>
                            <td id="table_firma" class="tdList"><%=item.insrtdFirmaname%></td>
                            <td id="dateiname_table" class="tdList"><%=item.insrtdDateiname%></td>
                            <td id="table_time" class="tdList"><%=item.insrtdDateTime%></td>

                            <form method="post" action="/deleteOne">
                                <td><button class="DelOne"><img
                                            src="https://img.icons8.com/ios/25/000000/empty-trash.png" /></button></td>
                            </form>

                            <form method="post" action="/deleteAll">
                                <td><button class="DelAllBtn"><img
                                            src="https://img.icons8.com/fluency-systems-regular/25/000000/garbage-truck.png" /></button>
                                </td>
                            </form>
                            <% }); %>

And my ejs print looks like this:

{
  insrtdDateTime: 2022-01-12T01:18:00.000Z,
  insrtdDateiname: 'fantaWerbung',
  insrtdFirmaname: 'Fanta'
} ejs print
fantaWerbung ejs print
{
  insrtdDateTime: 2022-01-13T01:18:00.000Z,
  insrtdDateiname: 'fantaWerbung',
  insrtdFirmaname: 'Fanta'
} ejs print
fantaWerbung ejs print

But in the td, there is no output at all… if i write it with just item, it shows me, that there is one object, can someone explain?

Why doesn’t it write to the table like fantaWerbung? Because obviously the data it receives is correct…

Thanks a lot
Mats Groeneweg

“RNSScreenStackHeaderConfig” was not found in the UIManager

i know this question has been asked before, (requireNativeComponent: “RNSScreenStackHeaderConfig” was not found in the UIManager when running android app, React Navigation Error, Invariant Violation: requireNativeComponent: “RNSScreenStackHeaderConfig” was not found in the UIManager) but none of the answers helped in solving my Problem.

Problem Description
Its pretty simple, i get the following Error when i start my react-native App on IOS:

ERROR  Invariant Violation: requireNativeComponent: "RNSScreenStackHeaderConfig" was not found in the UIManager.

My app.js

import React from 'react';
import Header from './components/header';
import { SafeAreaView } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

import homeScreen from './screens/home'

const Stack = createNativeStackNavigator();

function App(){
  return (
    <SafeAreaView>
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name="Home" component={homeScreen} options={{ title: 'Welcome' }} />
        </Stack.Navigator>
      </NavigationContainer>
    </SafeAreaView>
  );
};

export default App;

It appeard after if followed this guide for navigating between Screens in react-native.

When removing const Stack = createNativeStackNavigator(); incl. the Stack.*** the Error also disappears. So i figured the Problem must be with that.

But due to me being a newbie to react-native, finding this Problem is quit hard.

Yes, i already tried the Solutions from the above mentioned Posts.

Thanks for any help,
Oliver

I am able to move into next step in antd step form even though i have added validation in react.js

I am able to move into next step in antd step form even though i have added validation in react.js
I have used default validation of antd form

 const steps = [
    {
      title: "Service Address",
      content: (
        <Form form={form}>
          <Card>
            <h1>Lead Information</h1>
                <Form.Item
                  rules={[{ required: true }]}
                  name={"first_name"}
                  label="First Name"
                >
                  <Input />
                </Form.Item>
                       </Card>
                          </Form>
     },
    {
      title: "Service Information",
      content: "Second-content",
    },

And this my map loop to return the steps

return (
    <>
      <Steps
        current={current}
      >
        {steps.map((item) => (
          <Step key={item.title} title={item.title} />
        ))}
      </Steps>
      <div className="steps-content">{steps[current].content}</div>
        {current < steps.length - 1 && (
              <Button type="primary" onClick={() => next()}>
                Next
              </Button>
        )}
 )
</>

Can some one please help me with This!
Thanks in Advance

Variable redeclaration in javascript [duplicate]

I have read that redeclaration of variables using let is not allowed in javascript.
If this is true, then how is it possible to redeclare a variable in block scope when it is already present in file scope using let in javascript?
Does this mean that file scope is not same as global scope?

let x = 10;
{
    let x = 2;
}
console.log(x)

The above code gives an output 10
But what I expected is an error
Kindly help me out in understanding this.

How can i emulate the scrolling of sites like Reddit, Twitter and LInkedIn with React?

I want the scroll effect where the sections on the sides scroll to the last, or dont scroll at all but the middle section keeps scrolling. I have seen something similar in reddit, twitter and linkedin.

Heres my code and an image of how it looks so far:

function Body() {
  return (
    <div className="Body">
      <div className="user-menu"></div>

      <main className="timeline">
        <div className="post-box"></div>
        <div className="post"></div>
        <div className="post"></div>
        <div className="post"></div>
        <div className="post"></div>
        <div className="post"></div>
        <div className="post"></div>
        <div className="post"></div>
      </main>

      <div className="discover">
        <div className="discover-box"></div>
        <div className="footer-box"></div>
      </div>
    </div>
  );
}

enter image description here

Recalculate pagination when filter request is applied

I have this React page generated by JHipster:

import ......

export interface IOrdersProps extends StateProps, DispatchProps, RouteComponentProps<{ url: string }> {}

export const Orders = (props: any) => {
  const [paginationState, setPaginationState] = useState(
    overridePaginationStateWithQueryParams(getSortState(props.location, ITEMS_PER_PAGE, 'id'), props.location.search)
  );

  const [searchNameParam, setSearchNameParam] = useState('');
  const lastSearchNameParam = useRef(searchNameParam);

  const [ordersList, setOrdersList] = useState<any>([]);
  const [itemsSize, setItemsSize] = useState<any>([]);
  const [tradesList, setTradesList] = useState<any>();
  const [twapList, setTwapList] = useState<any>();

  const getAllEntities = async () => {
    const page = paginationState.activePage - 1;
    const itemsPerPage = paginationState.itemsPerPage;
    console.log('Refreshing page: ' + page);
    const apiUrl = 'api/orders?page=' + page + '&size=' + itemsPerPage + '&searchNameParam=' + searchNameParam;

    const result = await axios.get<IOrders>(apiUrl);

    setOrdersList(result.data);
  };

  const sortEntities = () => {
    getAllEntities();
    const endURL = `?page=${paginationState.activePage}&sort=${paginationState.sort},${paginationState.order}`;
    if (props.location.search !== endURL) {
      props.history.push(`${props.location.pathname}${endURL}`);
    }
  };

  useEffect(() => {
    sortEntities();
  }, [paginationState.activePage, paginationState.order, paginationState.sort]);

  useEffect(() => {
    const request = async () => {
      const apiUrl = 'api/ordersCount';
      const result = await axios.get<IOrders>(apiUrl);
      setItemsSize(result.data);
    };
    request();
    getAllEntities();
  }, []);

  const sort = p => () => {
    setPaginationState({
      ...paginationState,
      order: paginationState.order === 'asc' ? 'desc' : 'asc',
      sort: p,
    });
  };

  const handlePagination = currentPage => {
    setTradesList(null);
    setTwapList(null);
    setPaginationState({
      ...paginationState,
      activePage: currentPage,
    });
  };

  const handleSyncList = () => {
    sortEntities();
  };

  const { match, loading, totalItems } = props;

  useEffect(() => {
    if (searchNameParam !== lastSearchNameParam.current) {
      handleSyncList();
      lastSearchNameParam.current = searchNameParam;
    }
  }, [searchNameParam])

  return (
    <div>    
          <div>    
              <Table>
                ............
                <thead>
                  <tr>
                    <th>                         
                      <div>
                        <span>Filter</span>
                        <input onChange={e => setSearchNameParam(e.target.value)}/>
                      </div>
                      ................                   
                  </tr>
                </thead>
                {ordersList && ordersList.length > 0 ? (
                <tbody>
                  {ordersList.map((orders, i) => (
                    
                  ))}
                </tbody>
                ) : (
                  !loading && <div className="alert alert-warning">No Orders found</div>
                )}
              </Table>

          </div>

          {/*{props.totalItems ? (*/}
          <div className={ordersList && ordersList.length > 0 ? '' : 'd-none'}>
            {/*<Row className="justify-content-center">*/}
            {/*  <JhiItemCount page={paginationState.activePage} total={totalItems} itemsPerPage={paginationState.itemsPerPage} />*/}
            {/*</Row>*/}
            <Row className="justify-content-center">
              <JhiPagination
                activePage={paginationState.activePage}
                onSelect={handlePagination}
                maxButtons={5}
                itemsPerPage={paginationState.itemsPerPage}
                totalItems={itemsSize}
              />
            </Row>
          </div>
        </Tab>
        <Tab eventKey={'Asset Volumes'} title="Asset Volumes" onSelect={() => {}}>
          <AssetVolumes />
        </Tab>
      </Tabs>

    </div>
  );
};

const mapStateToProps = ({ orders }: IRootState) => ({
  ordersList: orders.entities,
  loading: orders.loading,
  totalItems: orders.totalItems,
});

const mapDispatchToProps = {
  getEntities,
};

type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof mapDispatchToProps;

export default connect(mapStateToProps, mapDispatchToProps)(Orders);

When I enter something into search area API request is made and new data is populated.
But pagination is not updated.
How I can force the pagination pages to be recalculated when I receive new pages of data with search criteria?

Avoid recurring ‘if’ verification to check if an object has property

I do know how to check if a property exists (hasOwnProperty, in, !== undefined, etc).

But I don’t know how to avoid to perform an action on this property if it doesn’t exist.

Is there a solution to avoid the if (property && action in my case) verification each time ?

Similar question : Javascript – how to avoid multiple if condition checks when checking if object has a property? Not really relevant in my case

const myFunction1 = myFunction2 = () => {};
const generateElement = (p) => {
  let div = document.createElement(p.tag);
  p.classes && (div.className = p.classes);
  p.style && (div.style.cssText = p.style);
  p.content && (div.innerHTML = p.content);
  p.appendIn && p.appendIn.appendChild(div);
  p.attribs && Object.entries(p.attribs).forEach((y) => {
    div.setAttribute(y[0], y[1]);
  });
  p.events && Object.entries(p.events).forEach((y) => {
    div.addEventListener(y[0], y[1], false);
  });
  return div
}

var newElem = generateElement({
  tag: 'div',
  classes: 'mydiv',
  id: 'id42',
  content: 'Hello world!',
  style: 'background:#ccc',
  attribs: {
    'tabindex': 0,
    'title': 'Title #1'
  },
  events: {
    'click': myFunction1,
    'mouseout': myFunction2
  },
  appendIn: document.body
});

How to partition an array from the server side

The bottom line is, I need to get an array of people who have entered the server (the name is entered before entering the site). I implemented it very badly, on the client side I create an array and on the server side the same array and they are transferred between each other, but the problem is that the array created on the client side is filled only in requests to the server, that is, in the local scope, to me you need to access it globally. Here’s the implementation:
Client part:

const userName = prompt("Enter your name:");
nameBlock.innerHTML = userName;

let arrayUser = []; // array of users

socket.emit('connect user', {
    userConnect: userName, // pass the name
    arrayConnect: arrayUser // we pass the array where we write the names
});

socket.on('connect user', (userName) => {
    arrayUser.push(userName.arrayConnect);
    const item = document.createElement('div');
    item.innerHTML = `User <b><span class = "user">${userName.name}</span></b> connected to the chat!`
    userConnect.append(item);
});

Server part:

let arrayUser = []; // create an array
io.on('connection', (socket) => {
    socket.on('chat message', (msg) => {
        io.emit('chat message', {
            message: msg.message,
            name: msg.name
        });
    });

    socket.on('connect user', (userName) => {
        arrayUser.push(userName.userConnect);
        console.log(arrayUser);
        io.emit('connect user', {
            name: userName.userConnect,
            arrayConnect: arrayUser
        });
    });

How Fix deploy nodejs in ubuntu

I have a very strange error and I don’t know how to solve it.

I’m trying to publish my system to an Ubuntu 18.04 server.

I installed NODEJS and NPM, the versions that are on the server are:
NODEJS – v10.19.0
NPM – 6.14.4

My backend works all normal on my local machine, after I published it on Ubuntu’s online server it started to get this error:

  init = ({ app } = {}) => {
       ^

SyntaxError: Unexpected token =
    at Object.compileFunction (vm.js:406:10)
    at Generator.next (<anonymous>)
    at Object.<anonymous> (/var/www/backend.io/src/index.js:1)
    at Generator.next (<anonymous>)

My file full is :

const i18next = require("i18next");
const Backend = require("i18next-node-fs-backend");
const i18nextMiddleware = require("i18next-express-middleware");

class I18nManager {
  t;
  currentLang;
  init = ({ app } = {}) => {
    i18next
      .use(Backend)
      .use(i18nextMiddleware.LanguageDetector)
      .init({
        backend: {
          loadPath: "locales/{{lng}}/{{ns}}.json",
        },
        fallbackLng: "en",
        preload: ["en", "pt-br"],
      })
      .then((_t) => (this.t = _t));

    if (app) app.use(i18nextMiddleware.handle(i18next));
  };
}

const i18n = new I18nManager();

module.exports = {
  i18n,
  t: (...args) => i18n.t(...args),
  currentLang: () => i18next.language,
};

How to make a javascript object from a string? [closed]

I have a string value e.g.:

var keyword_custType = '[Private customer|PRIVATE, Corporate customer|COMPANY, Sole trader|SOLETRADER, Corporate Group|CORPGROUP]';

I would like to create a javascript object from it (array). I tried:

var obj = JSON.parse(keyword_custType);

But then I get an error: Uncaught SyntaxError: Unexpected token P in JSON at position 1 at JSON.parse ().

What should I do to create a js array from the string?

Trigger Apps Script function from Add-On: bypass 45 seconds run time

I have the following code that builds buttons in a Workspace Add-On.

function createCard(text) {
  var buttonSet = CardService.newButtonSet()
      .addButton(createButton('doStuff','Do Stuff'));
  var section = CardService.newCardSection()
      .addWidget(buttonSet);
  var card = CardService.newCardBuilder()
      .addSection(section);
  return card.build();
}

function createButton(functionName, text) {
  var action = CardService.newAction()
    .setFunctionName(functionName);
  var button = CardService.newTextButton()
    .setText(text)
    .setOnClickAction(action)
    .setTextButtonStyle(CardService.TextButtonStyle.FILLED);
  return button;
}

function doStuff() {
  // Heavy work on Google Doc
    }

The doStuff() function I previously made in Apps Script takes normally 5 minutes to run, and fits in the Google Apps Script quota, but when I copied it into the Workspace Add-On it gives Error with the add-on. Run time error. Exceeded maximum execution time, so it needs to fit into the Card Service quota (45 seconds).
I noticed that, in the standalone Script, the execution log differs from an add-on trigger or an “Unknown” trigger (when I run it normally).
How can I call the "doStuff()" function as “Unknown” so it uses the 6 minutes script runtime quota?

How to delete multiple url params

There is a problem with deleting several string parameters. Only the last parameter is being deleted now.

this code does not work correctly:

const updateFiltersSearchParams = (paramKey, newValue) => {
    const isParamExist = searchParams.getAll(paramKey).includes(newValue);

    if (!isParamExist) {
      searchParams.append(paramKey, newValue);
      setSearchParams(searchParams);
    } else {
      const updatedSearchParams = new URLSearchParams(
        [...searchParams].filter(
          ([key, value]) => key !== paramKey || value !== newValue
        )
      );
      setSearchParams(updatedSearchParams);
    }
  };

const handleDeleteParams = () => {
    [...checkboxParams].forEach((param) => {
      updateFiltersSearchParams("selected", param);
    });
  };

Sandbox

how to approve the spend of ERC20 tokens from the javascript file?

I have two contracts ERC20, and ERC721.
and everytime erc721 transferFrom function is called, I want to send some erc20 tokens to the creator (minter) of the ERC721.

After some research, I’ve found that I have to do two things.

  1. call ERC20.transferfrom in ERC721 transferFrom function
  2. Approve the spending of erc20 tokens from the frontend

it seems like the second is giving me some problems. Please see my code below:
Your help will be very much appreciated.

++ I am also not so sure if I am calling ERC20.transferFrom correctly from ERC721 contract. Is this the correct way to do it?

ERC721 contract:

import "../openzeppelin-contracts/contracts/token/ERC721/IERC721.sol";
import "../openzeppelin-contracts/contracts/token/ERC721/ERC721.sol";
import "../openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol";
import "../openzeppelin-contracts/contracts/math/SafeMath.sol";
import "../openzeppelin-contracts/contracts/utils/Address.sol";
import "../openzeppelin-contracts/contracts/utils/Counters.sol";
import "./ERC20Token.sol";

contract NFTtoken is ERC721 {
.
.
.
    ERC20Token Erc20Contract;

    constructor(address tokenAddress) ERC721("NC NFT example", "NCNFT") {
        owner = msg.sender;
        decimals = 0;
        Erc20Contract = ERC20Token(tokenAddress);
    }
function mint(string calldata nftName) external payable {
        uint256 newItemId = _tokenIds.current();
        _mint(msg.sender, newItemId);

        nftInfo[msg.sender].name = nftName;
        nftInfo[msg.sender].creator = msg.sender;

        allValidTokenIndex[newItemId] = allValidTokenIds.length;
        allValidTokenIds.push(newItemId);
        _tokenIds.increment();
    }
    function transferNFT(address from, address to, uint256 tokenId)  public returns (bool){
        transferFrom(from, to, tokenId);
        Erc20Contract.transferFrom(to, nftInfo[from].creator, 10);
    }
}
.
.
.

app.js

transferNFT: function() {
  NFTContract.deployed().then(function(contractInstance) {
    let toAddress = $("#to-address").val();
    //    function transferFrom(address _from, address _to, uint256 _tokenId) public payable {
    let NFTid_temp = $("#nft-id").val();
    let NFTid = NFTid_temp.substring(7);
    console.log("to = " + toAddress);
    console.log("nftid = " + NFTid);
    Voting.deployed().then(function(votingcontractInstance) { votingcontractInstance.approve(contractInstance.address, votingcontractInstance.balanceOf(web3.eth.accounts[1]))});
    contractInstance.transferNFT(web3.currentProvider.selectedAddress, toAddress, NFTid, {gas: 140000, from: web3.eth.accounts[0]});
  })
}

error message

app.js:10169 Uncaught (in promise) BigNumber Error: new BigNumber() not a number: [object Object]
    at raise (http://localhost:8080/app.js:10169:25)
    at http://localhost:8080/app.js:10157:33
    at new BigNumber (http://localhost:8080/app.js:9184:67)
    at new BigNumber (http://localhost:8080/app.js:9194:25)
    at toBigNumber (http://localhost:8080/app.js:2084:12)
    at Object.toTwosComplement (http://localhost:8080/app.js:2095:21)
    at SolidityTypeAddress.formatInputInt [as _inputFormatter] (http://localhost:8080/app.js:2995:38)
    at SolidityTypeAddress.SolidityType.encode (http://localhost:8080/app.js:3648:17)
    at http://localhost:8080/app.js:15577:29
    at Array.map (<anonymous>)