Using a chrome profile does not work in WebdriverIO

I am trying to avoid handling signing in by signing in beforehand in my profile.

I am using this code:

const browser = await remote({ capabilities: { browserName: 'chrome', 'goog:chromeOptions': { args: [ `user-data-dir=C:/Users/rudra/AppData/Local/Google/Chrome`, `profile-directory=Avg` ] } }, });
But it still does not load in the profile I have specified. How do I fix this?

Github API post works locally, but gets a 401 in a remote server

Hi I use the github API to send a file to a repo, I tested in postman in local and is working but when I deploy to my server it always return a 401 status, so I need t create another token, but when I deploy again ,I got the same error:
Any one has a solution for this?
I read here, and don’t find anything useful:
https://docs.github.com/en/rest/overview/troubleshooting-the-rest-api?apiVersion=2022-11-28

here is the call and working in postman:

curl –location –request PUT ‘https://api.github.com/repos/MY_ACCoUNT/JavaAsyncGraphql/contents/player/src/main/resources/example2.md’
–header ‘Authorization: Bearer mytoken’
–header ‘Accept: application/vnd.github+json’
–header ‘Content-Type: application/json’
–data-raw ‘{
“message”: ” tets api file”,
“content”: “LS0tCnRpdGxlOiAiV3JpdGUgYSBoaWdoIENUUiBtZXRhIGRlc2NyaXB0aW9uICYgdGl0bGUiCmRhdGU6ICIyMDIzLTA3LTA4VDIzOjExOjM4Ljg1MVoiCnRodW1iOiAiV3JpdGVfYV9oaWdoX0NUUl9tZXRhX2Rlc2NyaXB0aW9uXyZfdGl0bGUucG5nIgp0YWdzOiBbQ29udGVudCwgU0VPLCBNYXJrZXRpbmcsIE90aGVyc10KLS0tCgojIFdyaXRlIGEgaGlnaCBDVFIgbWV0YSBkZXNjcmlwdGlvbiAmIHRpdGxlCgpbTGlua10oaHR0cHM6Ly90d2l0dGVyLmNvbS9oZXlsb3Zpc2gvc3RhdHVzLzE2MzgxNjQ0MDM2NTU2OTYzODQpCioqRHVlIHRvIG5ldyB0d2l0dGVyIHBvbGljeSB5b3UgbmVlZCB0byBsb2dpbiB0byB2aXN1YWxpemUgdGhlIHRocmVhZCoqCg==”
}’

in my program:

var markdown_encode = btoa(markdown);
 var headers = { 
'Authorization': 'Bearer mytoken',
'Accept': 'application/vnd.github+json'
  }



  var body = {
        "message": "adding " + filename,
        "content": markdown_encode
    }
    const url = `${url_base}${repoName}/contents/${pathFile}/${filename}.md`;

fetch(url, {
    method: 'PUT',
    headers,
    body: JSON.stringify(body)
  })
  .then(response => response.json())
  .then(data => {
        const sha = data.content.sha;
        console.log(sha);
        alert("success ith a sha " + sha);
        
        })
  .catch(error => {
        console.log(error);
        alert(JSON.stringify(error.message))
  });

the result after trying from deploy:
enter image description here
Regards

Convert Angular template into a name.html file

I have a lot of Angular templates which contains mostly html and css. Those templates are actually designed slides. Now I want to get rid of Angular, because I want to use HTML, CSS and JavaScript.

Is there a fast way to convert all those templates into HTML CSS and Javascript files? It mainly concerns the transfer from Angular to HTML.

Let me know (:

I have only try to search for a answer, but I didn’t find a fasted way to do this.

Vimeo Oauth Authorization – 401 Unauthorized

I am attempting to obtain an authorization token from Vimeo and am using an approach highlighed on the following Vimeo page: https://developer.vimeo.com/api/authentication. The problem I am having is I am constantly getting a 401 Unauthorized message from Vimeo for some reason. Vimeo is configured to accept requests from this source domain.

Currently trying to get this POST to https://api.vimeo.com/oauth/authorize/client to return an access token given both the headers I am sending and the JSON in the POST. Two parameters to the Authorization headers that are supplied are from the Vimeo application setup: Client Identifier and the Client Secret.
Unfortunately, currently getting a 401 Unauthorized response on each request. Again, all of this is documented on the following Vimeo Web Page. https://developer.vimeo.com/api/authentication which I have followed to the best of my ability.

 var access_token_data;

 function Authorize() {

     var authorize_data = {
         "grant_type": "client_credentials", "scope": "public"
     };

     $.ajax({
         type: 'POST',
         url: "https://api.vimeo.com/oauth/authorize/client",
         headers: {
             "Authorization": "basic base64_encode({Client Identifier}:{Client Secret})", "Content-Type": "application/json", "Accept": "application/vnd.vimeo.*+json;version=3.4"
         }, 
         data: JSON.stringify(authorize_data),
         cache: false,
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         processData: false,
         success: function (data) {
             console.log("success");
             console.log(data);
             access_token_data = data.access_token;    

             alert("!!Access Token " + access_token_data)
         },
         error: function (data) {
             console.log("error");
             console.log(data);
         }
     });
 };

how to create a React login page with existing SQL database/server?

I’m absolutely brand new to React (as in, I learned what React was for the first time last week) and I’m pretty new to web dev as well, so bear with me here a little. I’ve been charged with converting an ASP.NET login page to a React web app, and I’m having a lot of trouble.

I’ve been looking at tutorials online, which are great for creating the actual PAGE for logging in (aka like the HTML and CSS and stuff), but they often get into using express for servers and making their own databases and such, and those already exist at my office, and to a noob like me, it’s too confusing to parse out what I should and shouldn’t use. Does anyone have a good walkthrough/template for how to create a login page with an already existing server and SQL Database?

Thank you! I can post the ASP.NET code if you want to see it.

What I tried: I tried creating a Login.js page, with a basic form that just grabs the email and password, and doesn’t do anything with it, and I’ve routed to it from the landing page. I’m not really sure what to do next, hence the question.

looking modification on security.properties files [closed]

If/when someone is assigned to check/update the security.properties files, Engineering would recommend making sure that the following exist. While Engineering doesn’t have evidence of an immediate need, it wouldn’t hurt to add this to glb.properties as well – as these two properties files are often used interchangeably.

prmEnvironment=prm essEnvironment=ess basEnvironment=bas ejpEnvironment=ejp adsEnvironment=ads

Why does the function run 2 times if I export the async function of another file?

I’m making a program using the async function, but I tested it because there was something I didn’t know.

This file is promis1.js

const A = async function(){
    console.log("promis1 : A")
    return "promis1 : B"
};

const B = async function(){

    let i = await A();
    console.log(i)
    return "promis1 : C"
};

const C= async function(){
    let i = await B();
    console.log(i)
    return "promis1 : D"
};

C().then(a => {console.log(a);})

module.exports = { A,B,C };

and this file is promise2.js

var {B} = require("./promise1");

const D = async function(){
    let i = await B()
    console.log('promis2 :',i)
};

D()

and this is console

promis1 : A
promis1 : A
promis1 : B
promis1 : B
promis1 : C
promis2 : promis1 : C
promis1 : D

I thought ‘A’, ‘B’, and ‘promise1: C’ would be printed once in a while, but it’s being printed twice, I don’t know why, and I’d like to know if there’s a way to make it printed once in a while.

Keycloak 502 Bad Request

I have a problem with my Keycloak version 22, so this is when I login to my project with Keycloak it’s safe to enter my project application but when I try to reload automatically 502 bad request why is that? after I traced it I checked the network the results when I first logged in there was a token in the network but when I reloaded the web the token disappeared on the network like that do you have a solution?

I have tried to set the token as in this code that I will provide but still can’t, what I expect is that when the Web Reload is not 502 Bad Request

UseAuth.js
enter image description here

App.js
enter image description here

api.service.js
enter image description here

The error you get when reloading the web

enter image description here

Jest cannot read property of undefined?

I am working with Auth0 and i have written a function that looks at the appMetadata of a user and if the user has an accountProperties set to have an email type, it asks the user to authenticate via email.

Here is the function:

exports.onExecutePostLogin = async (event, api) => {
  // 1. Sync user.app_metadata and retrieve for other steps
  const appMetadata = await syncMetadata(event, api);
  // 2. If Roles are different, Sync Roles in Auth0
  await syncRoles(event, appMetadata.roles);
  // 3. Set Claims from user.app_metadata
  api.accessToken.setCustomClaim(
    'https://example.com/name',
    event.user.name
  );
  api.accessToken.setCustomClaim(
    'https://example.com/email',
    event.user.email
  );
  api.accessToken.setCustomClaim(
    'https://example.com/accountId',
    appMetadata.accountId
  );
  api.accessToken.setCustomClaim(
    'https://example.com/userId',
    appMetadata.userId
  );
  api.accessToken.setCustomClaim(
    'https://example.com/accountIds',
    appMetadata.accountIds
  );
  const hasMfaTypeEmail = appMetadata.accountProperties.some(prop => prop.mfa_type === 'email');
  if (hasMfaTypeEmail) {
    api.authentication.challengeWith({ type: 'email' });
  }
};

And i wrote a unit test for this as follows :

import Sinon from 'sinon';
import rewiremock from 'rewiremock/node.js';
import { ManagementClient } from 'auth0';
import _ from 'lodash';
import jsonWebToken from 'jsonwebtoken';
import { fetchMock } from '../fetch-mock.js';
import { onExecutePostLogin } from '../../src/actions/post-login.cjs';


// Rest of the tests

describe('onExecutePostLogin', () => {
    it('should call api.authentication.challengeWith with type email if MFA type is email', async () => {
      // Mocking the necessary objects and functions
      const event = {
        user: {
          name: 'John Doe',
          email: '[email protected]'
        }
      };
      const appMetadata = {
        accountId: '123',
        userId: '456',
        accountIds: ['789', '101112'],
        accountProperties: [
          { mfa_type: 'phone' },
          { mfa_type: 'email' },
          // Add more properties as needed for your specific case
        ],
        roles: ['role1', 'role2']
      };
      const api = {
        accessToken: {
          setCustomClaim: jest.fn(),
        },
        authentication: {
          challengeWith: jest.fn(),
        }
      };
      // Mocking syncMetadata and syncRoles functions
      jest.mock('../../src/actions/post-login.cjs', () => ({
        ...jest.requireActual('../../src/actions/post-login.cjs'),
        syncMetadata: jest.fn(() => appMetadata),
        syncRoles: jest.fn()
      }));
      // Calling the function to be tested
      await onExecutePostLogin(event, api);
      // Assertion using Jest's expect and toHaveBeenCalledWith
      expect(api.authentication.challengeWith).toHaveBeenCalledWith({ type: 'email' });
    });
    it('should not call api.authentication.challengeWith if MFA type is not email', async () => {
      // Mocking the necessary objects and functions
      const event = {
        user: {
          name: 'John Doe',
          email: '[email protected]'
        }
      };
  
      const appMetadata = {
        accountProperties: [
          { mfa_type: 'phone' }
        ]
      };
      const api = {
        accessToken: {
          setCustomClaim: jest.fn()
        },
        authentication: {
          challengeWith: jest.fn()
        }
      };
      // Mocking syncMetadata and syncRoles functions
      jest.mock('../../src/actions/post-login.cjs', () => ({
        ...jest.requireActual('../../src/actions/post-login.cjs'),
        syncMetadata: jest.fn(() => appMetadata),
        syncRoles: jest.fn()
      }));
      // Calling the function to be tested
      await onExecutePostLogin(event, api);
      // Assertion using Jest's expect and not.toHaveBeenCalled
      expect(api.authentication.challengeWith).not.toHaveBeenCalled();
    });
  });

But when i run it using npm run test, i keep running into the following errors

TypeError: Cannot read property 'challengeWith' of undefined
ReferenceError: jest is not defined
TypeError: Cannot read property 'some' of undefined

I am very new to this so any help will be appreciated if someone can explain what i’m doing wrong. Thank you.

How can i zoom the background to the center point without using background position in css?

Html

<div class="board"></div>

JS Drag function

var mouseProperties = {
    mouseState: false,
    prevX: null,
    prevY: null,
}

var debugMode = {
    appDebug: false,
    isDrawEnabled: false,
    isAnchorEnabled: false,
    isEraserEnabled: false,
    fpsAlreadyRunnin: false,
    eraserRadius: 20,
}

// triggers when the mouse is pressing
document.addEventListener("mousedown", () => {
    mouseProperties.mouseState = true;
});

// and triggers when mouse isn't pressing
document.addEventListener("mouseup", () => {
    mouseProperties.mouseState = false;
    mouseProperties.prevX = null;
    mouseProperties.prevY = null;
});

//theres a mouse down eventlistener and an if state to check if mouse is pressing and if true then
//it will run the if below (debugmode is binded to a button in my html file it's not that important)
if (!debugMode.isDrawEnabled && !debugMode.isEraserEnabled) {
            const currentX = e.screenX;
            const currentY = e.screenY;
        
            if (mouseProperties.prevX !== null && mouseProperties.prevY !== null) {
                const deltaX = currentX - mouseProperties.prevX;
                const deltaY = currentY - mouseProperties.prevY;
        
                const lastPosX = parseInt(board.style.backgroundPositionX || 0);
                const lastPosY = parseInt(board.style.backgroundPositionY || 0);
        
                const anchedElements = document.querySelectorAll('.anch');
                const bypassElements = document.querySelectorAll('.bypass');

                anchedElements.forEach(nailed => {
                    const anchX = parseInt(nailed.style.left || 0);
                    const anchY = parseInt(nailed.style.top || 0);
                    nailed.style.left = `${anchX + deltaX}px`;
                    nailed.style.top = `${anchY + deltaY}px`;
                });
        
                board.style.backgroundPosition = `${lastPosX + deltaX}px ${lastPosY + deltaY}px`;

                bypassElements.forEach((el) => observer.observe(el))
            }
        
            mouseProperties.prevX = currentX;
            mouseProperties.prevY = currentY;
        }

JS Zoom function

const board = document.querySelector(".board")
var boardScale = 40

// unzoom
function unzoom() {
    if (boardScale > 10) {
        boardScale -= 5
    } else if (boardScale < 10 || boardScale == 10) {
        boardScale = 10 
    }

    board.style.backgroundSize = `${boardScale}px ${boardScale}px`
}

// zoom
function zoom() {
    if (boardScale < 70) {
        boardScale += 5
    } else if (boardScale > 70 || boardScale == 70) {
        boardScale = 70 
    }

    board.style.backgroundSize = `${boardScale}px ${boardScale}px`
}

This is where I’m having the problem. Normally I’d prefer using background-position: center center but in my project I’m using it to drag the boards background around so I can’t use it. I tried some math thing etc. but they didn’t work either. I tried to scale the board. It worked very well when I zoomed the board but not when I made it unzoom.

When I drag the board around it changes the center of the background then when i zoom in and the zoom was on that point. So I tried to subtract the board width and height with the background position but I couldn’t do it.

Finding and updating JSON values with unknown path but known key

The problem: I have thousands of JSONs with wildly different levels of nesting. I need to insert data into a specific key on each of them.

While I always know said key’s name, I don’t know the path to it.

A few (simplified) examples:

// Example 1
{
    "fruits": {
        "apple": { "color": "red" },
        "orange": { "color": "orange" }
    }
}

// Example 2
{
    "fruits": {
        "round": {
            "apple": { "color": "red" },
            "orange": { "color": "orange" }
        }
    }
}


// Example 3
{
    "apple": { "color": "red" },
    "orange": { "color": "orange" }
}

I need to figure out a way to modify the value of, for example, “apple” across all 3 JSONs without knowing their specific nesting/path.

Notes:

  • I already know how to access the value of this key. I need to modify the value.

  • The key is always unique.

I had a similar issue in the past, and after digging around came upon this implementation to search for the path I need. The problem is that it works on object value, not key.

getPath(object: any, value: any) {
  return Object
    .keys(object)
    .reduce((r: any, k: any) => {
      const kk = Array.isArray(object) ? `[${k}]` : `${k}`;
      if (object[k] === value) {
        r.push(kk);
      }
      if (object[k] && typeof object[k] === 'object') {
        r.push(...this.getPath(object[k], value).map((p: any) => kk + (p[0] === '[' ? '' : '.') + p));
      }
      return r;
    }, []);
}

How can I work around this?

Model.getAttributes is not a function

I have an array of objects (docs) and a sequelize model(model) i’m building this objects into. The process looks something like this:

let mappedChunk = await Promise.all(
        docs.map(async (item) => {
            const pg_item: any = await model.build({
                _pg_key: uuidv4(),
                _source: JSON.stringify(item),
            }).dataValues

            await baseMapping(item, pg_item)

            if (extraMapping) {
                const status = await extraMapping(item, pg_item)
            }
            return pg_item
        }),
    )


await model.bulkCreate(mappedChunk, bulkCreateOptions)

baseMapping and extraMapping are just functions that pass data from attributes of those objects in the array to their corresponding attributes in sequelize models.

There’s no problem here, the items get mapped into their corresponding pg_items.

However, when working on creating OneToMany and ManyToMany relations, i want to check if the foreign key even exists on the model like so:

const Model = pg_item.constructor

if (!(foreignKeyName in Model.getAttributes())) {...}

while executing the program just quits randomly saying “Model.getAttributes is not a function”

I’ve tried to console.log the pg_item, the constructor and the attributes by just using Object.keys(pg_item) to see if maybe some of the pg_items come in empty or even undefined (i don’t even know how can they be undefined, but one can never be 100% sure i guess)

console.log('1')
console.log('pg_item <---------  ' + pg_item)
const Model = target.constructor
console.log('2')
console.log('Model <---------  ' + Model)

if (!(foreignKeyName in Model.getAttributes())) {...}

but the log just looks like this:


pg_item <---------  [object Object]
2
Model <---------  function Object() { [native code] }
1
pg_item <---------  [object Object]
2
Model <---------  function Object() { [native code] }
1
pg_item <---------  [object Object]
2
Model <---------  function Object() { [native code] }
TypeError: Model.getAttributes is not a function
    at /home/ulkash/Desktop/Cloned/mgn-sequelize/build/seeders/scripts/utils/relationsBinding.js:26:49
    at Generator.next (<anonymous>)

I understand that the “native code” means that the implementation of the Object function is written in a language other than JavaScript. Understandable.

However i just don’t understand why at some point of execution it seems content with using this getAttributes() function on a sequelize object and then suddenly not so content anymore…

Do you have any suggestions on what i should do in this situation? Maybe some other checks to conduct?
It’s all very new to me and i’m just stumped… Thank you)

In Next.js, fetch does not return new data, it returns existing data

I’m trying to use fetch as SSG method in Next.js.

However, the value of ‘content’ that I registered in the mock server is different from the value that is actually displayed.

Below is my code.

import Layout_Mobile from "@/components/Layout/DeviceLayout/Layout_Mobile";
import Layout_PC from "@/components/Layout/DeviceLayout/Layout_PC";
import PostDetailPage from "@/components/PostDetailPage/PostDetailPage";

const fetchPosts = async (params) => {
  const res = await fetch(
    `https://5875183d-18c0-49ad-b99d-8deeb4ded6a9.mock.pstmn.io/posts/${params.slug}`
  )
    .then((response) => response.json())
    .then((data) => {
      return data;
    });

  return res;
};

export const generateStaticParams = async () => {
  const res = await fetch(
    "https://5875183d-18c0-49ad-b99d-8deeb4ded6a9.mock.pstmn.io/posts"
  )
    .then((response) => response.json())
    .then((data) => {
      return data;
    });

  return res.map((post) => ({
    slug: post.id.toString(),
  }));
};

const page = async ({ params }) => {
  const { title, summary, content, author, createdAt } = await fetchPosts(
    params
  );

  return (
    <div>
      <Layout_Mobile></Layout_Mobile>
      <Layout_PC>
        <PostDetailPage
          title={title}
          description={summary}
          content={content}
          author={author}
          date={createdAt}
        />
      </Layout_PC>
    </div>
  );
};

export default page;

The result I expected(The value I entered in postman. That is, a new value)

{
  "content": "test1 "
}

Actual Results(Value previously registered)

{
  ...previous json data
}

How do I solve this problem?

Thank you for reading it.

I tried SSG but it failed… I want to solve this problem.

Nodejs how to get the prototype of a function like the debugger

In Nodejs, I am trying to get the prototype name of a function defined like:

AgreementSchema.statics.saveAgreement = function(){...}

When I check the Web-storm debugger, it can fetch the type of it and display it. I tried different things like prototype.constructor.name etc but since it is defined as an anonymous function it doesn’t work.

You can check the debugger screenshot below, and see that “model.saveAgreement.prototype” is shown with “AgreementSchema.statics.saveAgreement”.

enter image description here

Is there anyway I can get the name of this function as String like the debugger does?