Download files automatically through firefox with nodeJS and webdriverio

I want to verify file download using NodeJS and Webdriverio. The file to download is of PDF format. When WebDriverIO clicks on “Download” Firefox opens up the following download confirmation window:download confirmation pop-up

I want Firefox to download the file automatically without showing above confirmation window, so I used the below code:

 conf_firefox.js file
require('dotenv').config();
const path = require('path');
const merge = require('deepmerge');
const baseConfig = require('./wdio.conf_base');

exports.config = merge(baseConfig.config, {
  services: ['selenium-standalone'],
  capabilities: [
    {
      maxInstances: 2,
      browserName: 'firefox',
      'moz:firefoxOptions': {
        prefs: {
          'browser.download.dir': path.join(__dirname, '../test-data/tmp/download/firefox'),
          'browser.helperApps.neverAsk.saveToDisk': 'application/pdf',
        },
      },
      acceptInsecureCerts: true,
    },
  ],
});

but still Firefox shows the same window. How can I set Firefox profile so that PDF files are downloaded automatically without showing the confirmation dialogue?
For chrome everything works correctly. Thanks!

Vue JS setting image through file uploader on v-model applies empty object

I’m using Vue JS 2 to create an image uploader. My input has a change function which runs a function and sets my file on v-model property.

When I console.log my data, all what’s set is an empty object rather than the image, this is also causing my Vee Validate rule to fail as it thinks it’s empty.

What am I missing?

My HTML for uploading a logo

<div>
  <validation-provider
    name="base64_logo"
    rules="mimes:image/jpeg,image/png"
    v-slot="{ errors, classes, validate }"
  >
    <label for="base64_logo" class="block text-sm font-medium text-gray-500 mb-2">
      Brand logo <em>(PNG or JPG)</em>
    </label>
    <div class="mt-1 relative rounded-md shadow-sm">
      <input @change="selectFilesToUpload('base64_logo', $event.target.files[0]); validate()" type="file" name="base64_logo" id="base64_logo" :class="classes" class="focus:ring-green-500 focus:border-green-500 block w-full py-3 px-4 sm:text-sm border border-gray-300 rounded-md" accept="image/png, image/jpeg">
    </div>
    <span class="text-xs text-red-500">{{ errors[0] }}</span>
  </validation-provider>
</div>

The following function runs:

/*
** Select files to upload (file uploader)
*/
selectFilesToUpload (model, file) {
  try {
    this.form[model] = file
  } catch (err) { }
},

Which form should now contain everything associated with my image, but when adding an image, it shows as an empty object (see attached)

enter image description here

I’ve also tried a JSON.stringify before setting my model, no luck here either.

How to use wildcard characters in ts typeorm?

I’m coding a query in my NestTs project, so I would like to retrieve information matched with LIKE clause values. the problem with my query is the table has three types of records ‘_INFORMED’, ‘_UNINFORMED’ and ‘WITHOUT’. If I use the sentence .where(“user.firstName like :name”, { name:%_INFORMED% }) It matches with _INFORMED and _UNINFORMED records, then I tried to use the wildcard character as to standard SQL ‘%_INFORMED%’ but it looks wrong. Do you have any idea? Thanks!

Few utf-8 characters are not being decoded properly in linux OS

I have a javascript file where i encode, decode and remove/modify some characters from the url. I have been recently facing some issues during the decoding of this particular character (“ and ”). When this character is parsed it throws a Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to repeat error. When i commented the decoding it parsed the file without an issue. I want to know why this character is being not parsed by the browser.

This is my function for reference:

decodeEntities = function(v){
if (v !== null && v !== '' && typeof(v) == 'string') {
v = v.replace(/&gt;/gi,">"); // 62
v = v.replace(/&lt;/gi,"<"); // 60
v = v.replace(/&#38;/g, "&");
v = v.replace(/``/g, " ");
v = v.replace(/“/gi,""");//<-- exception in chrome version 95 and up, works for 94
v = v.replace(/”/gi,""");//<-- exception in chrome version 95 and up, works for 94
}
return v;
};

Following two statements from the function above fails with the error above for chrome versions 95 and above. 94 however has no problem with it. v = v.replace(/“/gi,”””);
v = v.replace(/”/gi,”””); Any help as to how to rewrite the last two lines of the code would be greatly appreciated. Thanks.

Is there a way to use Reacts useLocation to restart Gsaps animation timeline?

I have three links which I am currently animating to slide down when the user clicks the toggle menu button. It works fine when the user clicks the toggle again.

The problem: when the user clicks on a route and navigates away THEN comes back to select another route, the animation doesn’t restart again. The animation should restart to initial position even if the user navigates to another route.

Here is what I currently have:

let linkOne = useRef(null);
let linkTwo = useRef(null);
let linkThree = useRef(null);

const [dropped, setDropped] = useState()

const tl = useRef()
useEffect(() => {
    // tl.current = gsap.timeline({paused: true})
    tl.current = new gsap.timeline()
        .to([linkOne, linkTwo, linkThree], { y: 30, stagger: { amount: .3 } });
    return tl.current.kill()
}, [])

useEffect(() => {
    dropped ? tl.current.play() : tl.current.reverse();
}, [dropped])

HTML:

<Navbar.Toggle onClick={() => setDropped(!dropped)} aria-controls="responsive-navbar-nav" />

<Nav.Link ref={el => linkOne = el} as={Link} to="/About" href="#About">About</Nav.Link>
<Nav.Link ref={el => linkTwo = el} as={Link} to="/TestPage" href="#TestPage">Test Page</Nav.Link>
<Nav.Link ref={el => linkThree = el} as={Link} to="/GsapImageReveal" href="#GsapImageReveal">GsapImageReveal</Nav.Link>

I have tried using useLocation:

let location = useLocation()
useEffect(() => {
    dropped ? tl.current.play() : tl.current.reverse();
    console.log(location)
}, [dropped, location])

This doesn’t work. But i think useLocation is on the right track because it gives me a route change.

Can anyone suggest a work around or a better way to approach this?

How to check for restricted file while uploading in react

if a person renames the file extension to an allowed one let say abc.exe to abc.pdf and try to upload it.

I want to know if there are any open source library available in React/JavaScript to detect the content in the file so that no executable or malicious code is checked in even if the extension of the file is changed to what is allowed in the code

JavaScript – beginner’s excersise [closed]

I have a problem with the task. I would like the easiest way to get the result, which is a tree with all the elements.
The object looks like this:

const bookPages = [
    {
        name: '1',
        content: [
            {
                name: '1.1',
                content: [
                    {
                        name: '1.1.1',
                        content: []
                    }
                ]
            },
            {
                name: '1.2',
                content: []
            }
        ]
    },
    {
        name: '2',
        content: [
            {
                name: '2.1',
                content: []
            }
        ]
    }
]

console.log(bookPages);

After typing this to the console I would like to get a similar result:

// - 1
// -- 1.1
// --- 1.1.1
// -- 1.2
// -2
// --2.1

WHAT would be the easiest way to do it? Thanks

Styled Components with bracket doesn’t work properly in Next.js

Styled Components with bracket doesn’t work properly in Next.js
I’m using typescript, styled-components with Next.js

package.json

    "dependencies": {
             "@reduxjs/toolkit": "^1.6.2",
             "babel-plugin-styled-components": "^2.0.2",
             "next": "12.0.4",
             "react": "17.0.2",
             "react-dom": "17.0.2",
             "react-inlinesvg": "^2.3.0",
             "react-redux": "^7.2.6",
             "redux": "^4.1.2",
             "redux-saga": "^1.1.3",
             "styled-components": "^5.3.3"
    },
    "devDependencies": {
             "@types/node": "^16.11.10",
             "@types/react": "^17.0.37",
             "@types/styled-components": "^5.1.15",
             "eslint": "7.32.0",
             "eslint-config-next": "12.0.4",
             "typescript": "^4.5.2"
    }

.babelrc

    {
    "presets": ["next/babel"],
    "plugins": [
       [
         "babel-plugin-styled-components",
         {
            "ssr": true, 
            "displayName": true, 
            "preprocess": false
         }
       ]
    ]
    }

_document.tsx

import React from "react";
import Document, { Html, Head, Main, NextScript } from "next/document";
import { ServerStyleSheet } from "styled-components";
class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }

  render() {
    return (
      <Html>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

but in a certain situation, like using Styled Components with bracket, and the components in the bracket were imported, styled-components cannot apply any of it.

(it can render the imported component, but cannot apply any additional styles)

RegisterForm.tsx

    import React, { useState } from 'react';
    import styled from 'styled-components';
    import RoundButton from '../../components/common/RoundButton';

    const RoundButtonWithMarginTop = styled(RoundButton)`
        margin-top: 3.75rem;
    `;

    const RegisterForm = () => {
         ...
         <RoundButtonWithMarginTop>Next</RoundButtonWithMarginTop>
         ...
    }

components/common/index.tsx

    export * from './Header';
    export * from './Responsive';
    export * from './RoundButton';

components/common/RoundButton.tsx

import React from 'react';
import styled from 'styled-components';
import palette from '../../lib/styles/palette';

const RoundButtonBlock = styled.button`
    width: 100%;
    background-color: ${palette.Gray[1]};
    border-radius: 30px;
    border: none;
    font-size: 1.1em;
    font-weight: 700;
    height: 3rem;

    cursor: pointer;

    &:hover {
        background-color: ${palette.Gray[0]};
    }
`;

const RoundButton = ({ children }) => {
    return (
        <RoundButtonBlock>
            {children}
        </RoundButtonBlock>
    );
};

export default RoundButton;

how button appears on the page

How can I solve this problem?
Please give me the solution.

Filtering array of objects with nestead array loop

I am trying to filter an array, based on some nested object.
the final value would be the main object.

this is the data I have.

JSonData =  [
        {
            "ID": 1,
            "Name": "0ABCDDDD",
            "Business Profile Owner": "owner ",
            "Folder": "out-of-the-box strategize methodologies",
            "Profile Type": "Greenholt",
            "status": "low"
            "Risk": [
              {
                "ID": 1.1,
                "Name": "Tiaxxxxxnna",
                "Risk Owner": "Lindgren",
                "Risk Taxonomy": "Lindgren",
                "status": "high"
                "Control": [
                  {
                    "ID": 1.2,
                    "Name": "rrrrrrrrrr",
                    "Control Owner": "333333",
                    "Control Hierarchy": "North Laurineshire",
                    "Control Type 3": "Jerde Spring",
                    "status": "high"
                  },
                  {
                    "ID": 1.21,
                      "Name": "cccccccActive",
                    "Control Owner": "333333",
                    "Control Hierarchy": "North Laurineshire",
                    "Control Type 3": "Jerde Spring",
                    "status": "low"
                  }
                ]
              },
              {
                ID: 1.11,
                Name: "Tiaxxxxxnna",
                "Risk Owner": "rRrrrrrrrrrrr",
                "Risk Taxonomy": "rrrrrrrrrrrr",
                "status": "low"
              }
            ]
    
    }, {
            "ID": 2,
            "Name": "dddd0ABCDDDD",
            "Business Profile Owner": "ddddd ",
            "Folder": "strategize methodologies",
            "Profile Type": "ssd",
            "status": "high"
            "Risk": [
              {
                "ID": 2.1,
                "Name": "deeeeeec",
                "Risk Owner": "Lindgren",
                "Risk Taxonomy": "Lindgren",
                "status": "high"
                "Control": [
                  {
                    "ID": 2.2,
                   "Name": "3Active",
                    "Control Owner": "333333",
                    "Control Hierarchy": "North Laurineshire",
                    "Control Type 3": "Jerde Spring",
                    "status": "high"
                  },
                  {
                    "ID": 2.21,
                    "Name": "55555Active",
                    "Control Owner": "333333",
                    "Control Hierarchy": "North Laurineshire",
                    "Control Type 3": "Jerde Spring",
                    "status": "low"
                  }
                ]
              },
              {
                ID: 2.11,
                Name: "33333333",
                "Risk Owner": "eeeeeeee",
                "Risk Taxonomy": "wwwwwwwww",
                "status": "high"
              }
            ]
    
    }, {
            "ID": 3,
            "Name": "WWWW",
            "Business Profile Owner": "Business Profile",
            "Folder": "strategize",
            "Profile Type": "cccccc",
            "status": "high"
            "Risk": [
              {
                "ID": 3.1,
                "Name": "ruchas",
                "Risk Owner": "boss",
                "Risk Taxonomy": "8989889",
                "status": "high"
                "Control": [
                  {
                    "ID": 3.2,
                     "Name": "Active",
                    "Control Owner": "eeeeee",
                    "Control Hierarchy": "North",
                    "Control Type 3": "Jerde",
                    "status": "low"
                  },
                  {
                    "ID": 3.21,
                    "Name": "Active1",
                    "Control Owner": "wwwwww",
                    "Control Hierarchy": "Laurineshire",
                    "Control Type 3": "Spring",
                    "status": "high"
                  }
                ]
              },
              {
                ID: 3.11,
                Name: "EEEE",
                "Risk Owner": "eeeeeeee",
                "Risk Taxonomy": "wwwwwwwww",
                "status": "low"
              }
            ]
        }
    ];

The multiple values which are selected from multi-select are

[{name: 'Business Profile', type: 'bp'}
{name: 'Low', type: 'risk'}
{name: 'Active', type: 'control'}]

here ‘bp’ is the main object (ID’s which are 1,2,3).
risk and control are nested objects/ Array.

it should return the following object since it matches all records.
(selected records should work with && operations)

 {
        "ID": 3,
        "Name": "WWWW",
        "Business Profile Owner": "Business Profile",
        "Folder": "strategize",
        "Profile Type": "cccccc",
        "status": "high"
        "Risk": [
          {
            "ID": 3.1,
            "Name": "ruchas",
            "Risk Owner": "boss",
            "Risk Taxonomy": "8989889",
            "status": "low"
            "Control": [
              {
                "ID": 3.2,
                 "Name": "Active",
                "Control Owner": "eeeeee",
                "Control Hierarchy": "North",
                "Control Type 3": "Jerde",
                "status": "low"
              }
            ]
          },
          {
            ID: 3.11,
            Name: "EEEE",
            "Risk Owner": "eeeeeeee",
            "Risk Taxonomy": "wwwwwwwww",
            "status": "low"
          }
       ]
}

Knex multiple primary key in a identify relationship where id is an auto increment column

I tried to use every single logic in my mind to resolve this problem, but this is the only solution that it worked.

knex.schema.createTable('documents', (table) => {
      table.integer('id').unsigned().notNullable().unique()
      table.string('path')
      table.enum('type', ['CPF', 'RG'])
      table.integer('user_id').unsigned().notNullable()
      table.foreign('user_id').references('id').inTable('users')
      table.primary(['id', 'user_id'])

      table.timestamps(true, true)
    })
    knex.schema.alterTable(this.tableName, (table) => {
      table.increments('id', { primaryKey: false }).alter()
    })
}

TypeScript – Return function value from the callback function

I am using the Error Handling method using the Result type, which I have posted in this question.

Using the Result type, I could easily build a chain of functions like this

Result.combine(result1, result2)
.onFailure(err => doSomethingOnFailure())
.onSuccess(val => doSomethingOnSuccess())

This flow looks good for me, but I have a problem.

function func(a, b) {
// Some code above
const result = Result.comine(aResult, bResult).onFailure(err => {
// I want to return fail result to the func here but do not know how
})

// So I have to do a simple if check
if (result.failure) {
// Return fail result here
}
}

I want to return the fail result to the parent function inside the onFailure function.

Could I somehow achieve this?

HTML: Scroll line by line

I have an unordered list with a variable number of list items. The <ul> is of fixed height (actually the height of a single line of text) and set to overflow-y: scroll.

When I scroll the mouse-wheel, a certain vertical distance is traversed. I would like to have it exatly scroll line by line, to ensure that a <li> is always properly centered in the visible part of the <ul>.

Wrong behaviour:
enter image description here

:root {
  --default-line-height: 24px;
}

.myUl {
  background-color: lightblue;
  height: var(--default-line-height);
  list-style-type: none;
  overflow-y: scroll;
  outline: 1px solid black;
}

.myLi {
  font-size: var(--default-line-height);
}
<ul class="myUl">
  <li class="myLi">Lorem ipsum dolor sit amet</li>
  <li class="myLi">Aenean commodo ligula eget dolor.</li>
  <li class="myLi">Cum sociis natoque penatibus</li>
  <li class="myLi">Donec quam felis, ultricies nec</li>
  <li class="myLi">Nulla consequat massa quis enim.</li>
  <li class="myLi">Donec pede justo, fringilla vel</li>
  <li class="myLi">In enim justo, rhoncus ut</li>
</ul>

<p>Please scroll the blue area.</p>

I played with scroll-snap but to no real success. I “feels” awkward.
It seemed reasonable to be able to scroll line by line under certain conditions. But after spending some hours on the subject, I’m not sure anymore :-/

Thanks in advance
Christian

How to solve Objects are not valid as a React child (found: object with keys {….?

Im trying to map my state , but it allways returns me this error, someone knows how to solve it ?

 const FormScreen = async({route}) => { 
      const [userForm, setuserForm] = useState([]);
      const mounted = useRef(true);
    
      useEffect(async() => {
        let mounted = true; 
        if (mounted && userForm.length > 0 ){
          console.log(userForm,'campos:',userForm.fields);
          return;
        }
        else {
          setuserForm(await JSON.parse(route.params.paramKey));
        }   
        return () => (mounted = false);
    }, [userForm]);
           
      return (
        <SafeAreaView style={{flex: 1}}>
          <View style={styles.container}>
            <Text style={styles.textStyle}>
              COLLECTION :
            </Text>
    
          {
            userForm.length > 0 ? (
              userForm.map(async(item) => (
          <Text keys={await item.fields.toString()}>testtt</Text>        
          )) 
          ): <Text> Loading ...</Text>}
           
          </View>
        </SafeAreaView>
      );
    };

what I’m trying to do is render all my fields and then handle the following types.

Merging two array of objects only when array element contains error

So I have two arrays with objects. And also an array indicating where the replacement should take place(It spots if object contains error)

         const oldData = [
    {
        "index": "01",
        "skuId": "Sarbb-033",
        "name": "Sasko Black",
        "barcode": "843331510012",
        "description": "Nice black bread",
        "brand": "ERROR: No brand matching: Sasko",
        "productLine": "ERROR: No product line matching: line",
        "inputType": "Weight",
        "uom": "ERROR: Invalid UoM type, valid values are: kg,g,mg,kl,l,ml,m,cm,mm",
        "value": "700",
        "capacity": "1",
        "image": ""
    },
    {
        "index": "02",
        "skuId": "ERROR: Empty sku_id is not allowed",
        "name": "Sasko Black1",
        "barcode": "ERROR: Empty barcode is not allowed",
        "description": "Nice black bread",
        "brand": "ERROR: No brand matching: Future Life",
        "productLine": "ERROR: No product line matching: line",
        "inputType": "Weight",
        "uom": "kg",
        "value": "701",
        "capacity": "2",
        "image": ""
    },
    {
        "index": "03",
        "skuId": "Sarbb-099",
        "name": "Sasko Black100",
        "barcode": "843332555614",
        "description": "Nice black bread",
        "brand": "fwfwf",
        "productLine": "naam",
        "inputType": "weight",
        "uom": "g",
        "value": "702",
        "capacity": "3",
        "image": ""
    },
    {
        "index": "04",
        "skuId": "Sarbb-100",
        "name": "Sasko Black101",
        "barcode": "ERROR: Empty barcode is not allowed",
        "description": "ERROR: Invalid description: [] it should not be blank.",
        "brand": "fwfwf",
        "productLine": "fwfwf",
        "inputType": "Weight",
        "uom": "g",
        "value": "703",
        "capacity": "4",
        "image": ""
    },
    {
        "index": "05",
        "skuId": "Sarbb-101",
        "name": "Sasko Black102",
        "barcode": "843332555616",
        "description": "Nice black bread",
        "brand": "fwfwf",
        "productLine": "naam",
        "inputType": "weight",
        "uom": "g",
        "value": "704",
        "capacity": "5",
        "image": ""
    }
]


    const newData = [
    {
        "index": "01",
        "skuId": "Sarbb-033",
        "name": "Sasko Black",
        "barcode": "843331510012",
        "description": "Nice black bread",
        "brand": "fwfwf",
        "productLine": "fwfwf",
        "inputType": "Weight",
        "uom": "g",
        "value": "700",
        "capacity": "1",
        "image": ""
    },
    {
        "index": "02",
        "skuId": "sarb",
        "name": "Sasko Black1",
        "barcode": "124125125",
        "description": "Nice black bread",
        "brand": "fwfwf",
        "productLine": "fwfwf",
        "inputType": "Weight",
        "uom": "kg",
        "value": "701",
        "capacity": "2",
        "image": ""
    },
    {
        "index": "03",
        "skuId": "Sarbb-100",
        "name": "Sasko Black101",
        "barcode": "214214214",
        "description": "Desc",
        "brand": "fwfwf",
        "productLine": "fwfwf",
        "inputType": "Weight",
        "uom": "g",
        "value": "703",
        "capacity": "4",
        "image": ""
    }
]

    const errorRows = [0,1,3]


      const myTerribleAttempt = oldTableData.map((oldData, rowIndex) => {
  return errorRows.map(index => {
    if(rowIndex === index){
     newTableData.map(newData => {
oldData = newData
     })
    }
  })
 })

I have tried multiple maps and just can’t seem to get the right result. The new data objects should replace old data objects at the object containing the error. Please give me some assistance.