Having problem with npm login, it returns 403 Forbidden

I just faced the problem with npm adduser & npm login.

Here is the command npm adduser --registry=https://npm.pkg.github.com --scope=@ksheyon123 & npm adduser --registry=https://npm.pkg.github.com --scope=@ksheyon123

Both of command returns 403 Forbidden error.
enter image description here

Of course it is my accounts.

enter image description here

In my package.json

{
"name": "@ksheyon123/react-componentkit",
  "version": "2.0.0", // I have never used over 2.0.0 version. (It is highest version)
  "description": "Component Kit library for the React",
  "publishConfig": {
    "@ksheyon123:registry": "https://npm.pkg.github.com/"
  },
 ...my package.json
}

This is my .nvmrc in the root

@ksheyon123:registry=https://npm.pkg.github.com
//registry.npmjs.org/:_authToken=npm_xxxxx

My github & npm profile

enter image description here
enter image description here

Does anybody know the reason of this problem?

Rails Javascript – jQuery converted to Javascript with Rails 7 is not working

Rails 7 with Turbo / Hotwire. I am reusing code that I copied from an old ~ 2018 project. This code / jQuery was working for an informational popup:

      $(document).ready(function() {
      $('#info').hover(function() {
        $('#popup').show();
        }, function() {
        $('#popup').hide();
        });
      });

After rewriting it javascript ( correctly? ), this is what I’m currently testing – unsuccessfully:

      $(document).addEventListener("DOMContentLoaded", function() {
      $('#info_1').onmouseover(function() {
        $('#popup_1').show();
        }, function() {
        $('#popup_1').hide();
        });
      });

I have #info_1 / id=info_1 in one div and the popup #popup_1 / id=popup_1 in another div directly below the first one.

I’ve tested placing the javascript in the app/javascript/custom/menu.js file as well as using it in <script></script> tags on the view page.

How should I be handing this.

Thanks

Need help translating this code from python to javascript. It’s messing with arrays

Here is the python code:

 self.psii[1:self.ll - 1] = (self.c1 * (self.psir[2:self.ll] - 2.0 * self.psir[1:self.ll - 1]
                                    + self.psir[0:self.ll - 2]) 
                                    - self.c2 * self.Vx[1:self.ll - 1] * self.psir[1:self.ll - 1]
                                    + self.psii[1:self.ll - 1])
        self.psir[1:self.ll - 1] = (-self.c1 * (self.psii[2:self.ll] - 2.0 * self.psii[1:self.ll - 1]
                                    + self.psii[0:self.ll - 2]) 
                                    + self.c2 * self.Vx[1:self.ll - 1] * self.psii[1:self.ll - 1]
                                    + self.psir[1:self.ll - 1])
        self.psimag = self.psir**2 + self.psii**2

I originally tried a for loop with the index starting at 1 and running to self.ll.length – 1, but I feel like it needs more. I don’t know, I’ve been trying to figure this out for days.

I also feel like it should be easy, but maybe just burnt out at this point. Any help would be AMAZING, thanks.

for (let i = 1; i < this.ll - 1; i++) {
      this.psii[i] =
        this.c1 * (this.psir[i + 1] - 2.0 * this.psir[i] + this.psir[i - 1]) -
        this.c2 * this.Vx[i] * this.psir[i] +
        this.psii[i];
      this.psir[i] =
        -this.c1 * (this.psii[i + 1] - 2.0 * this.psii[i] + this.psii[i - 1]) +
        this.c2 * this.Vx[i] * this.psii[i] +
        this.psir[i];
      this.psimag[i] = this.psir[i] ** 2 + this.psii[i] ** 2;
    }
  }

It’s not working, the values are off compared to the python code.

How I can fix this problem with Google Docs API?

I write this script in React Component to include Google Docs in iframe.
I try everything. Nothing works. I dont know how to fix this. Its my first time in working with Google Docs API.

const Files = () => {
    const loadGoogleDocsApi = () => {
        window.gapi.load('client', () => {
            window.gapi.client.init({
                apiKey: 'api'
            }).then(() => {
                // Создание встроенного окна Google Docs
                const docUrl = 'https://docs.google.com/document/d/DOCUMENT_ID/edit';
                const docId = 'doc';
                const docName = 'Document Name';

                const iframe = document.createElement('iframe');
                iframe.src = `https://docs.google.com/document/d/${docId}/pub?embedded=true`;
                iframe.title = docName;
                iframe.width = '100%';
                iframe.height = '600';
                document.getElementById('google-docs-container').appendChild(iframe);
            });
        });
    };

    useEffect(() => {
        // Асинхронная загрузка скрипта API
        const loadScript = async () => {
            return new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = 'https://www.google.com/js/api.js';
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            });
        };

        // Загрузка скрипта API и выполнение loadGoogleDocsApi() после его загрузки
        loadScript()
            .then(() => {
                loadGoogleDocsApi();
            })
            .catch((error) => {
                console.error('Ошибка загрузки скрипта API:', error);
            });
    }, []);

    return (
        <div>
            <h1>Google Docs</h1>
            <div id="google-docs-container"></div>
        </div>
    );
};

export default Files;
So I have Errors:
Files.jsx:32 GET https://www.google.com/js/api.js net::ERR_ABORTED 404
Files.jsx:42  Ошибка загрузки скрипта API: Event {isTrusted: true, type: 'error', target: script, currentTarget: script, eventPhase: 2, …}
(анонимный) @ Files.jsx:42
Promise.catch (асинхронно)
(анонимный) @ Files.jsx:40
commitHookEffectListMount @ react-dom.development.js:23150
commitPassiveMountOnFiber @ react-dom.development.js:24926
commitPassiveMountEffects_complete @ react-dom.development.js:24891
commitPassiveMountEffects_begin @ react-dom.development.js:24878
commitPassiveMountEffects @ react-dom.development.js:24866
flushPassiveEffectsImpl @ react-dom.development.js:27039
flushPassiveEffects @ react-dom.development.js:26984
(анонимный) @ react-dom.development.js:26769
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
Files.jsx:42  Ошибка загрузки скрипта API: Event {isTrusted: true, type: 'error', target: script, currentTarget: script, eventPhase: 2, …}

TextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextText

I can’t compare two times properly in PHP

I have a problem in comparing and getting the difference between two times in PHP. I tried some answers in the other questions too but none of them answers my problem. Here is the date times I have to compare.

$time_must = strtotime("06:45:00 AM");
$time_in = strtotime("06:48:00 AM");

In that case, the $time_in should greater than the $time_must but the result is the $time_must is still ahead.

This is what I have tried to compare two times:

if (strtotime($row['time_in']) > $time_must) {
  echo "You are late.";
}

Am I doing it wrong? Your help and advice will be appreciated.

Trying to use regex after already using regex once

I have the following code and I’ve got the id and name value in its own square bracket as shown below. How can I access the value of id and name?

let data = "[[id=3, name=BOX-3, description=test, comment=test, locationId=5, capacity=null]];"

        let id = data.match(/(?<=id=)d+(?=,)/g);
        let name = data.match(/(?<=name=)[w|-]*/g);

console.log(data);
console.log(id);
console.log(name);


console.log(id.match(/(?<=[)[^][]*(?=])/g) );

//console.log(idVal);

Why is PDF.js failing to recognise page canvas: Cannot read properties of undefined (reading ‘canvas’)?

I’m trying to load a PDF on a webpage using PDF.js as according to this piece of code, but I cannot seem to render the actual PDF, for it returns this error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'canvas')
    at new InternalRenderTask (api.js:3307.41)
    at PDFPageProxy.render (api.js:1500.32)

Uncaught (in promise) TypeError: intentState.renderTasks is not iterable
    at PDFPageProxy._renderPageChunk (api.js:1792.50)
    at reader.read.then.intentState.streamReader (api.js:1842:16)

The HTML/JS code is below:

const url = "../../../server-filestore/test.pdf";
var pdfDoc = null;
var pageNum = 1;
var pageRendering = false;
var pageNumPending = false;

const scale = 1.5;
const canvas = document.getElementById("pdfRender");
const ctx = canvas.getContext("2d");


const RenderPage = num => {
    pageRendering = true;
    pdfDoc.getPage(num).then(page => {
        const viewport = page.getViewport({scale: scale});
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        const renderCtx = {
            canvasContent: ctx,
            viewport: viewport
        };
        page.render(renderCtx).promise.then(() => { // LOCATION OF ERROR
            pageRendering = false;
            if(pageNumPending !== null) {
                RenderPage(pageNumPending);
                pageNumPending = null;
            }
        });
        document.getElementById("PageNum").textContent = num;
    })
}

pdfjsLib.getDocument(url).promise.then(doc => {
    pdfDoc = doc;
    document.getElementById("PageCount").textContent = pdfDoc.numPages;
    RenderPage(pageNum);
});
<html>
    <head>
        <meta charset="utf-8">
        <title id="PageTitle"></title>
        <script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
    </head>
    <body>
        <div class="topBar">
            <button class="btn" id="previousPage"> Prev Page </button>
            <span id="Timer"></span>
            <button class="btn" id="nextPage"> Next Page </button>
            <span class="PageInfo">
                Page <span id="PageNum"></span> of <span id="PageCount"></span>
            </span>
        </div>
        <canvas id="pdfRender"></canvas>
    </body>
</html>

(The error seems to comes from the line page.render(renderCtx).promise.then(() => {)

It seems that the variable page itself does act as normal, yet it seems to not recognise the constant canvas declared outside the function. I’ve checked everything I can and I can’t seem to find a solution.

So, how can I prevent this error?

Any help would be greatly appreciated.

How to change the default scrollbar colors in Nextjs?

I have seen websites use the default scrollbar style and only change its colors through a dark/light mode button. For example, if you access tailwindcss.com or https://developer.mozilla.org/ in Chrome and Firefox(for comparison), you can see that a default scrollbar is applied, its style varies depending on which browser you’re using, and it change its colors through a dark/light button. You can notice that these websites all use the same colors for the arrow, track and thumb, so I imagine that it must be a built-in function.

I have tried changing its style with the simple ::webkit-scrollbar, track and thumb. But as you may know, it deletes the default scrollbar.

Generate string with special characters and all combinations

I’m trying to get all possible combinations of given strings with special chars after each char in the string.

Given:

const messages = generateMessages(['Test'], ['.', ','], 3);

What i have done so far:

function generateMessages(messages, specialChars, depth) {
    const generatedMessages = [];
    messages.forEach((message) => {
        for(let x = 0; x < message.length; x++) {
            specialChars.forEach((specialChar) => {
                let currentDepth = 1;
                while(currentDepth <= depth) {
                    let temp = '';
                    temp += message.substring(0, x+1); // I think here is the problem!
                    temp += generateSpecialChars(specialChar, currentDepth);
                    temp += message.substring(x +1);
                    generatedMessages.push(temp);
                    currentDepth++;
                }
            })
        }
    })

    return generatedMessages;
}

function generateSpecialChars(char, depth) {
    let temp = '';
    for (let i = 0; i < depth; i++) {
        temp += char;
    }

    return temp;
}

Current output:

[
  'T.est', 'T..est', 'T...est',
  'T,est', 'T,,est', 'T,,,est',
  'Te.st', 'Te..st', 'Te...st',
  'Te,st', 'Te,,st', 'Te,,,st',
  'Tes.t', 'Tes..t', 'Tes...t',
  'Tes,t', 'Tes,,t', 'Tes,,,t',
  'Test.', 'Test..', 'Test...',
  'Test,', 'Test,,', 'Test,,,'
]

The output i want:

[
  'T.est', 'T..est', 'T...est',
  'Te.st', 'T.e.st', 'T..e.st', T...e.st',
  'Te..st', 'T.e..st', 'T..e..st', T...e..st',
  'Te...st', 'T.e..st', 'T..e...st', T...e...st',
  'Tes.t', 'T.es.t', 'T..es.t', T...es.t',
  'Te.s.t', 'T.e.s.t', 'T..e.s.t', T...e.s.t',
  ...
]

I also want to combine the special chars dependend on the depth:
Assume the depth is 3 and we have the special chars [‘,’ and ‘.’]

[
  'T.est', 'T..est', 'T...est',
  'T.est', 'T..est', 'T..,est',
  'T.est', 'T..est', 'T.,,est',
  'T.est', 'T..est', 'T,,,est',
  'T.est', 'T.,est', 'T,,,est',
  'T.est', 'T,,est', 'T,,,est',
  'T,est', 'T,,est', 'T,,,est',
  ...
]

Can anyone help me please?

Counting Pixels JS Fiddle, Change to URL Image

I want to change this JS fiddle so that it counts the pixels from an Image URL instead.

What it does currently is count pixels from a shape that is drawn. This is instead of an Image loaded from a URL.

May I please get help on this? Thank you, it’s most appreciated. =)

The code is also below.

JavaScript:


var $canvas = $('#canvas');
var ctx = $canvas[0].getContext('2d');

ctx.fillStyle = '#0f0';
ctx.fillRect(10,10,10,10);
ctx.fillStyle = 'rgba(0,0,0,0.4)';
ctx.fillRect(100,100,100,100);
ctx.font = 'bold 32px Times';
ctx.textBaseline = 'top';
ctx.fillStyle = 'red';
ctx.fillText('Lorem ipsum', 0,0);




// Count number of transparent pixels.
// get bitmap
var idata = ctx.getImageData(0, 0, width, height),            // area to analyze
    buffer32 = new Uint32Array(idata.data.buffer),   // use 32-bit buffer (faster)
    i, len = buffer32.length;

var nrTotal = width * height;
var nrTransparent = 0;
for(i = 0; i < len; i++) {
  if (0 === buffer32[i] & 0xffffff) {
     nrTransparent++;
  }
}

$('#output').html('Total: ' + nrTotal + '<br>Transparent: '+nrTransparent + '<br>Non-transparent: '+ (nrTotal-nrTransparent));

HTML:

</canvas>

<div id="output">
</div>

CSS:

  background: #fff;
}

#output {
  background: #ddd;
  color: #000;
  padding: 5px;
}

canvas { 
  border: 1px solid red;

}```

Can’t test if radio buttons are rendered react testing library jest

Description

I’m working on a synthesizer (music instrument) in React.js. The interface of the instrument needs some radio buttons so users can change how it works (e.g choosing a waveform which is sort of the base sound). As part of this personal project I want to test the functioning of the synth with Jest to avoid clicking a lot and changing contexts between the browser and my text editor. Anyway, the problem is radio buttons can’t be found by Jest even though their name is specified in the assertion. Meaning, expect(screen.getAllByRole('radio').length).toBe(4); doesn’t have any problem at all, expect(screen.getByRole('radio',{name:'sine'})).toBeInTheDocument(); does throw an error in the console.

Important note:

Change ` character for ‘ in the code snippets above to not to break StackOverflow formatting

Test

import '@testing-library/jest-dom';
import {cleanup,getByTestId,render,screen, waitFor} from '@testing-library/react';
import Carrier from './carrier';
import Settings from './settings.json'

beforeEach(()=>{
  cleanup();
})

describe(`Rendering`, ()=>{

  it(`renders waveform type radio buttons`,()=>{
    render(<Carrier settings={Settings}/>);
    expect(screen.getAllByRole(`radio`).length).toBe(4);
  });

  it(`checks radio buttons label match waveform types`,()=>{
    render(<Carrier settings={Settings}/>);
    expect(screen.getByRole(`button`,{name:`sine`})).toBeInTheDocument(); 
  });
});

Output


    TestingLibraryElementError: Unable to find an accessible element with the role "button" and name "sine"

    Here are the accessible roles:

      group:

      Name "Waveform":
      <fieldset />

      --------------------------------------------------
      radio:

      Name "":
      <input
        data-testid="sine"
        name="sine"
        type="radio"
      />

      Name "":
      <input
        name="triangle"
        type="radio"
      />

      Name "":
      <input
        name="square"
        type="radio"
      />

      Name "":
      <input
        name="sawtooth"
        type="radio"
      />

Component

const Carrier = ({settings}) =>{
  return(
    <>
      <fieldset>
        <legend>Waveform</legend>
        <label htmlFor='sine'>sine</label>
        <input data-testid='sine' name='sine' type='radio'/>
        <label htmlFor='triangle'>triangle</label>
        <input name='triangle' type='radio'/>
        <label htmlFor='square'>square</label>
        <input name='square' type='radio'/>
        <label htmlFor='sawtooth'>sawtooth</label>
        <input name='sawtooth' type='radio'/>
      </fieldset>
    </>
  );
}

export default Carrier;

Attempts

  1. Checked a similar line of code with button element and the test is successful
  2. Used waitFor inside an async test to wait till the button was present on the DOM
  3. getByTestID works fine but I won’t like that way since there are lots of radio buttons
  4. Removed {name:'sine'} and the console obviously told me there were more than one button in the Document

Questions

  1. Why doesn’t name appear in the console output? I’ve checked some similar questions on the Internet (there are very few) and there shouldn’t be a problem with expect(screen.getByRole('radio',{name:'sine'})).toBeInTheDocument();

  2. What am I missing in my code?

refactoring an if/else if block within a javascript map

Is there a way to refactor this function “expandCols” and clean it up? I feel like the if/else if block within the map can be cleaned up but I’m brain farting.

The function below lives in a React component and is triggered when the user attempts to ‘expand a column’. The props passed in to this component are the column headers and other data related to the column.

const expandCols = () => {
const grid = [
    { id: 1, data: 1, name: 'col1', visible: true, foreignKey: null },
    { id: 2, data: 12, name: 'test', visible: true, foreignKey: 'vis' },
    { id: 3, data: 13, name: 'test', visible: true, foreignKey: 'vis' },
    { id: 4, data: 14, name: 'test', visible: true, foreignKey: 'vis' },
    { id: 5, data: 15, name: 'not test', visible: true, foreignKey: 'not vis' },
    { id: 6, data: 16, name: 'not test', visible: true, foreignKey: 'not vis' },
    { id: 7, data: 17, name: 'random 1', visible: true, foreignKey: 'N/A' },
    { id: 8, data: 18, name: 'random 2', visible: true, foreignKey: 'N/A' },
    { id: 9, data: 19, name: 'dynamic visible col', visible: true, foreignKey: 'make me visible' },
    { id: 10, data: 20, name: 'dynamic visible col', visible: true, foreignKey: 'make me visible' },
    { id: 11, data: 21, name: 'dynamic visible col', visible: true, foreignKey: 'make me visible' },
    { id: 12, data: 22, name: 'dynamic visible col', visible: true, foreignKey: 'make me visible' },
  ];

  //value from props passed in from parent can be: 'test', 'not test', or 'dynamic visible col'
  const headerVals = props.headerVals 
  let isExpanded = true;
  grid.map((column) => {
    if (column.name === 'test' && column.foreignKey === 'yup') {
      isVisible = !column.visible;
      return (column.visible = !column.visible);
    } else if (column.name === 'not test' && column.foreignKey === 'not yup') {
      isVisible = !column.visible;
      return (column.visible = !column.visible);
    } else if (column.name === 'dynamic visible col' && column.foreignKey === 'make me visible') {
      isVisible = !column.visible;
      return (column.visible = !column.visible);
    }
  });

  if (isExpanded) {
    if (headerVals === 'test') {
      // show test column in grid
      // functionality to accomplish this is used with another library
    } else if (headerVals === 'not test') {
      // show not test column in grid
      // functionality to accomplish this is used with another library
    } else if (headerVals === 'dynamic visible col') {
      // show dynamic visible col in grid
      // functionality to accomplish this is used with another library
    }
  } else {
    if (headerVals === 'test') {
      // hide test column in grid
      // functionality to accomplish this is used with another library
    } else if (headerVals === 'not test') {
      // hide not test column in grid
      // functionality to accomplish this is used with another library
    } else if (headerVals === 'dynamic visible col') {
      // hide dynamic visible col in grid
      // functionality to accomplish this is used with another library
    }
  }
}

Any help would be appreciated.

How to use react-xarrows for only particular data points

I have a data Records which is an array of dictionaries. Only two samples have two unique spanids and I want to draw two arrows, one from first instance to the second and vice-versa, using react-xarrows. I want to draw one arrow from spanid 1 to spanid 2 and another from spanid 2 to spanid 1 but I am getting the following warning:

Warning: Failed prop type: Invalid prop end supplied to Xarrow, expected one of type [string].
Xarrow@http://localhost:3000/static/js/bundle.js:58667:31
Relation@http://localhost:3000/static/js/bundle.js:70:1

I have tried the following code:

import React from 'react';
import './App.css';
import Xarrow, {useXarrow, Xwrapper} from 'react-xarrows';
    Records = [
  { "tid": 1, "token_text": "Canis Familiaris", "spanid": 1, "label": "Name" },
  { "tid": 3, "token_text": "is" },
  { "tid": 4, "token_text": "the" },
  { "tid": 5, "token_text": "scientific" },
  { "tid": 6, "token_text": "name" },
  { "tid": 7, "token_text": "of" },
  { "tid": 8, "token_text": "dog", "spanid": 2, "label": "species" },
  { "tid": 9, "token_text": "." }
]
     
    
    class Relation extends React.Component {
        
        render () {
           const tokens_to_render = [];
           const input_tokens = Records;
           const span_cntr = [];
          
          // console.log(spanid);
           var cntr = 200;
      
           input_tokens.forEach(tk => {
               const span = tk['spanid'];
               if (!tk['spanid']) {
                   tokens_to_render.push(
                       <div key={cntr} index={tk['spanid']}> 
                           {tk['token_text']} 
                      </div>
                  );
                  
               } else {
                  tokens_to_render.push(
                      <div
                        key={cntr} id = {cntr}
                        index={tk['spanid']}> 
                          {tk['token_text']} 
                      </div>
                  );
                  span_cntr.push(cntr);
               };
               cntr = cntr + 1;
          });
          console.log(span_cntr);
        
          return (
            <Xwrapper>
              <div key="id" className="control-box">
                 {tokens_to_render}
                 <Xarrow  start ={span_cntr[0]} end ={'span_cntr[1]'}/>
                 <Xarrow  start ={span_cntr[1]} end ={span_cntr[0]}/>
              </div> 
            </Xwrapper>
          )
        }
      }
    export default Relation;

How can I keep the value written in the input?

i would like keep the value written in the input, but antd always modify the number

for example,
case 1: if write 3.5 should be 3.5
case 2: if write 3,5 should be 3,5

this is the code:


import React from 'react';
import { InputNumber } from 'antd';
const onChange = (value) => {
  console.log('changed', value);
};
const App = () => <InputNumber min={1} max={10} defaultValue={3} onChange={onChange} />;
export default App;

when i written 3.5 is keeping 3.5 its ok
but when i typed 3,5 the value is changing to 10

Vue global properties with composables / onScopeDispose() is called when there is no active effect scope to be associated with

I am trying to write a composable that uses vue-query to fetch some data, it has a function that accepts string as argument and returns a piece of data based on that (it’s translations).

When used as a normal composable in a component it’s working well.

But I wanted to add this getter function as a global property with vue.use and that causes problems.

Here’s a simple version of my code:

Composable:

export const useComposable= () => {
    const { data } = useQuery<TranslationsAPIResponse>({ options })

    const t = (key: string) => {
        return data[key];
    }

    return { t }
}

There are steps in between where I am typing the key object but I think it’s irrelevant.

Main vue file:

vue
    .use({
        install(app) {
            app.config.globalProperties.$t = (key) => useComposable().t(key);
        },
    });

My main question is this even a possible pattern since I am using reactive objects in my composable?

When I use $t in component I get these errors:

onScopeDispose() is called when there is no active effect scope to be associated with,
Maximum recursive updates exceeded in component.

I am failing to understand why this code wouldn’t work when it’s working if I use the same composable directly in component.