Sequelize where issue with 6.19.1 version

With braking changes that sequelize introduced in new version 6.19.1

async findByUuid(uuid: string, options?: Omit<FindOptions<T>, 'where'>): Promise<T | null> {
return this.model.findOne<T>({ where: { uuid }, ...options });

}

I am getting error for “where”

No overload matches this call.
Overload 1 of 2, ‘(this: ModelStatic, options: NonNullFindOptions<Attributes>): Promise’, gave the following error.
Type ‘{ uuid: string; }’ is not assignable to type ‘WhereOptions<Attributes>’.
Types of property ‘uuid’ are incompatible.
Type ‘string’ is not assignable to type ‘WhereAttributeHashValue<Attributes[string]>’.
Overload 2 of 2, ‘(this: ModelStatic, options?: FindOptions<Attributes>): Promise’, gave the following error.
Type ‘{ uuid: string; }’ is not assignable to type ‘WhereOptions<Attributes>’.
Types of property ‘uuid’ are incompatible.
Type ‘string’ is not assignable to type ‘WhereAttributeHashValue<Attributes[string]>’.ts(2769)
model.d.ts(52, 3): The expected type comes from property ‘where’ which is declared here on type ‘NonNullFindOptions<Attributes>’
model.d.ts(52, 3): The expected type comes from property ‘where’ which is declared here on type ‘FindOptions<Attributes>’

How to pass data from WebAssembly OpenGL application to JavaScript?

I want to create a simple dialog in a browser that takes button click as input using WebAssembly.

I have succeeded creating an application using OpenGL, SDL2, and imGui and ported it to JavaScript using Emscripten.
But I have problems passing data from the WebAssembly OpenGL application to JavaScript.

How can I pass data from C++ to Javascript to acknowledge the web page that users have done some actions (ex: Clicking “OK” button)?

I’ve tried to stop the Emscripten run loop using emscripten_cancel_main_loop. And the application just freezes on the web page.
I’m trying to emit events from C++ to JavaScript but couldn’t figure out how it works.

HOC inside react hook, causes infinite rerenders

Im attempting to return a HOC component from within the hook.

Let’s say I have a top level component as…

function Component(props){
  //do something with props;
  return <h1>Hello {props.title}</h1>
}

And a hook which knows some props, and wants to free the user from providing those props

function useHook(){
  //somehow get prop values at runtime(say title)
  const title = //get from API call;
  return (props) => <Component title={title} {...props}/>
}

Any idea why infinite rerendering happens here?
Should I be using useCallback?

How can I download generated PDF by html-pdf-node library, node and React JS and graphQL

I am getting response from the backend now how can I download the generated PDF from the frontend by clicking on the Export button.
My Export button click handler as follows;

const handleExportProjectData = () => {
const changeStatusProjectData = JSON.stringify(project);
dataProvider
  .postRequest("ExportAllProjectChangeStatus", {
    queryType: "retrieve",
    data: { changeStatusProjectData },
  })
  .then((response) => {
    console.log(response.data, "data posted");
    saveChangeReport(response.data);
  })
  .catch((error) => {
    notify("No change status data found to export");
  });
 };

and my backend code is;

const downloadChangeStatusPDF = async (root, { changeStatusProjectData },{ user }) => {
  const html_to_pdf = require("html-pdf-node");
  let options = { format: "A4" };
  let today = new Date();
  let dd = String(today.getDate()).padStart(2, "0");
  let mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
  let yyyy = today.getFullYear();
  today = dd + "/" + mm + "/" + yyyy;


 let file = { content: "<h1>Welcome to html-pdf-node</h1>" };



 let generatedPDF = await html_to_pdf.generatePdf(file, options)
    .then((pdfBuffer) => {
        return JSON.stringify(pdfBuffer);
    });
 return generatedPDF;
};

I am getting the following response in my console as follows;
console.log(response.data)

now my question is how can I download the generated PDF using saveChangeReport function?

React Native Expo: Custom Fonts Not Loading Along With Google Fonts

I’m trying to load downloaded fonts along with google fonts using Font.loadAsync but it is giving me error:

Unable to resolve module ../../assets/fonts/sf-ui-text/SFUIText-Bold.ttf from /Users/bilal/Work/datumbrain/erp-app/src/utils/useFonts.js:

None of these files exist:
  * SFUIText-Bold.ttf
  * assets/fonts/sf-ui-text/SFUIText-Bold.ttf/index(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json|.android.svg|.native.svg|.svg)

Here is my code in App.js:

import { useCallback, useEffect, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Provider } from 'react-redux';
import colors from './src/constants/colors';
import AppNavigator from './src/navigation/AppNavigator';
import { store } from './src/redux/store';
import * as SplashScreen from 'expo-splash-screen';
import * as Font from 'expo-font';
import {
  FiraSans_300Light,
  FiraSans_400Regular,
  FiraSans_500Medium,
} from '@expo-google-fonts/fira-sans';
import { useFonts } from './src/utils/useFonts';

const App = () => {
  const [appIsReady, setAppIsReady] = useState(false);
  const prepare = async () => {
    try {
      const customFonts = await useFonts();
      await SplashScreen.preventAutoHideAsync();
      await Font.loadAsync({
        'Fira Sans 300': FiraSans_300Light,
        'Fira Sans 400': FiraSans_400Regular,
        'Fira Sans 500': FiraSans_500Medium,
        ...customFonts,
      });
    } catch (e) {
      console.warn(e);
    } finally {
      setAppIsReady(true);
      console.log('Loaded fonts...');
    }
  };
  const onLayoutRootView = useCallback(async () => {
    if (appIsReady) {
      await SplashScreen.hideAsync();
    }
  }, [appIsReady]);
  useEffect(() => {
    prepare();
  }, []);
  useEffect(() => {
    onLayoutRootView();
  }, [onLayoutRootView]);

  if (!appIsReady) {
    return null;
  }

  return (
    <Provider store={store} style={styles.container}>
      <AppNavigator />
    </Provider>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.light,
    alignItems: 'center',
    justifyContent: 'center',
  },
});
export default App;

and useFonts.js:

import * as Font from 'expo-font';

export const useFonts = async () => {
  await Font.loadAsync({
    SF: require('../../assets/fonts/sf-ui-text/SFUIText-Bold.ttf'),
  });
};

Ag-grid editable grid adding new row dynamically

I have an editable AgGrid in my functional component as below.
On the last column, I have buttons to Add/Remove rows.
Now I want the Add row to be displayed only for the last row. I am using cellRenderer for the last column.

With the below change, I get the Add button for the last row (i.e. on 2nd row in my case) on initial render. But if I click on Add for this 2nd row, while I get the Add button for the new 3rd row, but it does not get removed for the 2nd row. not sure if I am implementing this in the wrong way.

const MyCmp = (props) => {

    const getData = () => {
        return [{
            id: 0,
            firstName: 'F1',
            lastName: 'L1'
        }, {
            id: 1,
            firstName: 'F2',
            lastName: 'L2',
        }];
    }

    const [myCols, setMyCols] = useState(null);
    const [gridData, setGridData] = useState(getData());

    const [gridApi, setGridApi] = useState('');  

    let cellRules = {
        'rag-red': params => {
            if (params.data.lastName === 'INVALID_VAL') {
                return true;
            }
        }
    };

    const handleGridReady = (params) => {
        setGridApi(params.api);
        setMyCols([{
            headerName: 'F Name',
            field: 'firstName',
            editable: true
        }, {
            headerName: 'L Name',
            field: 'lastName',
            cellClassRules: cellRules,
            editable: true
        }, {
            headerName: '',
            field: 'buttonCol',
            cellRenderer: 'customColRenderer',
            cellRendererParams: {
                addItems: addItems
            }
        }]
        );
    };

    const createNewRowData = () => {
        const newData = {
            id: newCount,
            firstName: '',
            lastName: ''
        };
        newCount++;
        return newData;
    }

    let newCount = getData().length;

    const addItems = (addIndex, props) => {
        const newItems = [createNewRowData()];
        const res = props.api.applyTransaction({
            add: newItems,
            addIndex: addIndex,
        });

        setGridData(...gridData, res.add[0].data); // IS THIS CORRECT ?

        if (props.api.getDisplayedRowCount() > props.api.paginationGetPageSize()) {
            props.api.paginationGoToPage(parseInt((props.api.getDisplayedRowCount() / props.api.paginationGetPageSize())) + 1);
        }
    }

    const onCellClicked = (e) => {
    }

    const frameworkComponents = () => {
        return {customColRenderer: customColRenderer}
    }

    return (
        <>
            <MyAgGrid
                    id="myGrid"
                    columnDefs={myCols}
                    rowData={gridData}
                    frameworkComponents={{customColRenderer: customColRenderer}}
                    {...props}
                />
        </>
    )
}

My customColRenderer is as below;

export default (props) => {
        let isLastRow = (props.rowIndex === (props.api.getDisplayedRowCount() -1)) ? true: false;
        const addItems = (addIndex) => {
            props.addItems(addIndex, props);
        }

        return (
            <span>
                {isLastRow ? <button onClick={() => addItems()}>Add</button> : null}
                <span><button onClick={() => props.api.applyTransaction({remove: props.api.getSelectedRows()})}>Remove</button>
            </span>
        );
};

Add a class to an element if it matches a specific ID

Thanks in advance for your help. I am not too savvy with JS and I am trying to use it to dynamically change a navigation.

I am trying to add classes to an element only if it matches a specific ID.

For example add the classes ‘active’ & ‘show’ to an element with the ID ‘tab2’.

Is this straightforward? Let me know if it is and how I would go about it.

Thank you!

Match values from two array into a new array using id

So I have an array that has this structure

[{id:'bitcoin', change:-5.5}]

Again I have another array that has cryptos in this format

[{
            id: 'bitcoin',
            symbol: 'BTC',
            name: 'Bitcoin',
            img: 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/46/Bitcoin.svg/1200px-Bitcoin.svg.png',
            addr: '0xECe365B379E1dD183B20fc5f022230C044d51404'
        },]

That is just but an example, the arrays have multiple data objects.
I am transforming the crypto array into a new array because I am calculating their real-time market price using each coin address like this

for (let i = 0; i < this.assets.length; i++) {
            coinValue = await getPrice(this.assets[i].addr);
            this.transformedAssets.push({
                id: this.assets[i].id,
                symbol: this.assets[i].symbol,
                name: this.assets[i].name,
                img: this.assets[i].img,
                addr: this.assets[i].addr,
                value: numberWithCommas(coinValue)
            });
        }

Now I also want to pass coin_24h_percentage_change to the new array because the crypto array and the percentage change array have common id that can link them together but I am stranded on how to do that

I did something like this but its not working How am I suppose to make this happen

for (let i = 0; i < this.assets.length; i++) {
            coinValue = await getPrice(this.assets[i].addr);
            const price_change_percentage_24h = JSON.parse(JSON.stringify(this.coinPerfomance[0].change));
            window.console.log(price_change_percentage_24h);
            this.transformedAssets.push({
                id: this.assets[i].id,
                symbol: this.assets[i].symbol,
                name: this.assets[i].name,
                img: this.assets[i].img,
                addr: this.assets[i].addr,
                daychange: this.coinPerfomance[this.assets[i].id].change,
                value: numberWithCommas(coinValue)
            });
        }

Icon overlapping on progress bar

I am trying to find a solution on how to prevent the icons overlapping in a progress bar.

Tried Methods

I played around and added zIndex to each reminder object but seems like it did not have any effect

Context

I am actually receiving some reminderDates and I have to place them on a progress bar based on their reminder dates.
The progress Bar has a startDate and an endDate.

Code

I am mapping the reminderDates :

mappedReminders: () => {
      return reminderDates.map((reminder) => {
        let percentage: number = 0
        let right: string = ''
        let left: string = ''

        const diffWithReminders = moment(reminder.reminderDate).diff(
          startDate,
          'days',
        )

        percentage = Math.round((diffWithReminders * 100) / contractLengthInDays)

        if (percentage >= 0 && percentage <= 49) {
          left = `${percentage}%`
          right = 'auto'
        } else if (percentage >= 50 && percentage <= 100) {
          left = 'auto'
          right = `${100 - percentage}%`
        }

        return {
          position: 'absolute',
          bottom: '0',
          left,
          right,
          icon: <InvertedDropPinWithBell fill={colors.blue.dark} size={24} />,
          date: moment(reminder.reminderDate).format(DATE_MONTH_YEAR_FORMAT),
        }
      })
    },

Explanation

  1. I am trying to find the day difference with the startDate
  2. I am calculating the percentage equivalent based on the contractLengthInDays (calculated on the upper scope)
  3. I am adjusting their css based on the percentage value , either left or right
  4. At the end I am returning the property for each reminder in order to map them on the index file

Index File

    mappedReminders().map((reminder, key) => (
        <span style={{position: reminder.position,left: reminder.left,right:reminder.right,bottom: reminder.bottom}}>
{reminder.icon}</span>
     ))

Screenshot

Reminder Bar with Icons

How to change p-dropdown values on condition using json file in angular

My website uses three languages:

  1. English
  2. Sindhi
  3. Arabic

I am using PrimeNG p-dropdown for selecting languages and want to change the values of p-dropdown according to if the user selects Arabic, Sindhi, or English. The default language is English.

The problem is how to change the p-dropdown values when clicking on co-responding language.

languages.json:

{
    "english": [
        
        {
            "name": "English",
            "mod": "mod3"
        },
        {
            "name": "Sindhi",
            "mod": "mod1"
        },
        {
            "name": "Arabic",
            "mod": "mod2"
        }
    ],

    "arabic": [
        
        {
            "name": "إنجليزي",
            "mod": "mod3"
        },
        {
            "name": "سنڌي",
            "mod": "mod1"
        },
        {
            "name": "عربي",
            "mod": "mod2"
        }
    ],

    "sindhi": [
        
        {
            "name": "انگريزي",
            "mod": "mod3"
        },
        {
            "name": "سنڌي",
            "mod": "mod1"
        },
        {
            "name": "عربي",
            "mod": "mod2"
        }
    ]
}

app.component.ts What I have tried and gotten from this answer here

ngOnInit() {
 this.httpClient.get<any>('../assets/data/languages.json')
        .toPromise()
                
   
     .then((res: any) => {
            this.languages = res.english;
            localStorage.setItem('selectedLanguage', JSON.stringify(this.languages[0]));
            if(this.selectedLanguage.name === "Arabic"){
                this.languages = res.arabic;
                localStorage.setItem('selectedLanguage', JSON.stringify(this.languages[1]));
            }
            else if(this.selectedLanguage.name === "Sindhi"){
this.languages = res.sindhi;
localStorage.setItem('selectedLanguage', JSON.stringify(this.languages[2]));
}                
            
        });

 this.selectedLanguage = JSON.parse(localStorage.getItem("selectedLanguage")!);
}

app.component.html

<p-dropdown [options]="languages" [(ngModel)]="selectedLanguage" optionLabel="name"
                (onChange)="changeLanguage(selectedLanguage)"></p-dropdown>

karate.org.apache.http.conn.HttpHostConnectException: Connection timed out: Http call failed after 21407 milliseconds

I see the below error when I run my script to retrieve token data using Karate framework –

karate.org.apache.http.conn.HttpHostConnectException: Connection timed out: connect, http call failed after 21407 milliseconds.

Below is the Gherkin syntax written to extract token data –

* configure charset = null
* configure cookies = null
* header Content-Type = 'application/json'
* header Cookie = 'SMSESSION=' + SMSESSION
* header Connection = 'keep-alive'
Given path 'main-controller/v1/tokens'
When request ''
And method POST
And karate.waitForHttp(url)
Then status 200
And def token = response
And print 'NEW GENERATED TOKEN = ' + token

– Please be informed that url and SMSESSSION have been defined already in Background.

I have already tried the below configuration settings –

* configure proxy = 'http://my.proxy.host:8080'
* configure ssl = true

But none of these configurations resolved my issue.

I have even used karate.waitForHttp(url) in my feature file to try and wait for the Token API to respond back. Karate reports show that it waits for 72987 ms but still ends up with the same error again.

Can somebody help me resolve this issue? Thanks in advance!

Downloaded File not supported from laravel using vue.js

My function can download the exact file I want using laravel and vue.js, but when I try to open the downloaded file, it show unsupported file type.

My vue.js function to get the file info:

downloadFile(file){
  this.$axios.post(`file/download`, file).then(({data}) => {
    this.download(data, file)
  })
},

My Laravel controller:

$file = public_path() . "/images/" . $request['file_name'];
$headers = ['Content-Type' => 'application/jpeg'];
return response()->download($file, $request['file_name'], $headers);

And finally, my vue.js function to download the image creating the URL link:

download(data, file) {
    const url = window.URL.createObjectURL(new Blob([data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', file.file_name);
    document.body.appendChild(link);

    link.click();
}

is there a css property to change javascript functions for different screen sizes (in media queries)?

can we cancel out the javascript functions in specified screen sizes?

I’m working on a project in which I need certain js functions on desktop view only. I don’t need those in mobile-view. What I did is created same element twice and set js functions to one and hid it on mobile-view. Is there a way by which this can be implemented using css, without having to replicate elements…? can the js functions be turned off or something;p…?

Accessing parent prototype method via child object like a normal child method

It seems like I don’t understand prototypes correctly once again.

If you call a method on an object, and it doesn’t exist – does it not check the prototype for the method can run it?

like

Array.prototype.myArrayMagic = function () { ... }

Then on any array you can call arr.myArrayMagic() ?

That was my understanding, but I am now running into issue where calling a prototype method wont work unless I explicitly call it through .prototype

Also: I am restricted to ES5 code

The base module setup

function Wall() {}

Wall.prototype = {

    shouldShowWall: function() {
        return true;
    },

    show: function () {
        if (!this.shouldShowWall()) {
            return;
        }

        // Do other stuff here
    }
}

module.exports = Wall;

The child object

function OtherWall() {
    this.item = 'my_tracking_id',
    this.minutes = 30
    // ...
}

OtherWall.prototype = {
    constructor: Object.create(Wall.prototype),

    /**
     * Override wall.prototype.shouldShowWall method for deciding if the wall should be shown at this time
     */
    shouldShowWall: function() {
        // return true or flase here
    }.bind(this)
}

module.exports = OtherWall;

So following other answers and trying to understand as best as possible, this should be set up in a way where I can call

new OtherWall().show();

but it doesn’t work, it only works if I call

new OtherWall().prototype.show();

Is this normal, or have I set it up wrong?

What do I need to change to get it to work with OtherWall().show();