Electron: how to change current input language in forms programmatically

We have a desktop app built using Electron and it contains many forms where our users are switching the keyboard language between (English & Arabic) for specific text fields (which are many).

I’m planning to switch keyboard input language for those text fields programmatically, but I’m not able to find an API in Electron to do so.

I found similar solutions for other frameworks, but not Electron

Thanks!

How can I check if a particular submenu item already exists using the Cytoscape Context Menus library?

In my Next.js application, I am using the Cytoscape Context Menus library and have implemented functionality to dynamically add items to a submenu depending on the kind of node that has been selected using appendMenuItems(). However, when I open the context menu immediately back-to-back for the same node, I am running into the following runtime error:

Error: There is already an element with id=swagSauce in the context menu

I understand that I am seeing this error because appendMenuItems() is trying to create submenu items that already exist by running again with the same parameters from earlier. I believe what I need to do is wrap appendMenuItems() inside of a conditional statement so that it will only run if one of the parameters being passed into appendMenuItems() doesn’t already exist; however, I am not sure how I can check for that.

Is it possible to see whether there is already an element with the same id in the context menu? If so, I’d really appreciate it if someone could explain how I can do that. I’ve included my code below:

Code:

const options = {
    evtType: 'cxttap',
    menuItems: [
        {
            id: 'one',
            content: 'This is the first option in the menu',
            selector: 'node',
            onClickFunction(evt) {
                genericFunctionName(evt, 'one')
            },
        },
        {
            id: 'two',
            content: 'This is the second option in the menu',
            selector: 'node',
            onClickFunction(evt) {
                genericFunctionName(evt, 'two')
            },
        },
        {
            id: 'three',
            content: 'This is the third option in the menu',
            selector: 'node',
            submenu: [],
        },
    ],
};

let instance = cyRef.current.contextMenus(options);

cyRef.current.on('cxttap', "node", function(evt) {
    for (const variable in evt.target.data('properties')) {
        submenuItems.push(new Object(variable, evt.target.data('properties')[variable]));
    }

    instance.appendMenuItems(submenuItems, "three");
}

FWIW, I am using Cytoscape Context Menus v4.1.0.

CSP policy with ASP.NET 4.8

https://csp-evaluator.withgoogle.com/ shows the classic ASP.net site I’m working on with the following results:

object-src 'none'; img-src 'self'; script-src 'self'; require-trusted-types-for 'script'

but it looks like none of my code that uses __DoPostback JS are working. Here’s a snippet from web.config:

<rule name="CSP"> <match serverVariable="RESPONSE_Content-Security-Policy" pattern=".*" /> <action type="Rewrite" value="object-src 'none'; img-src 'self'; script-src 'self'; require-trusted-types-for 'script'" /> </rule>

Removing the require-trusted-types-for and script-src stanzas makes the JS work again, but also makes the site vulnerable to XSS.

Anyone aware of a solution? I’ve tried script-src url-of-base-site’` .

What’s the proper way to generate dynamic routes for a social media app using Next.js?

I’m building a social media app using Next.js + Sanity.

In a social media app, the data is in constant change as users add comments, likes, etc so it would make sense to use getServerSideProps for SSR since the data displayed should be updated on each request right?

But how can I handle the dynamic routes for let’s say, a user’s profile Page, a post, etc? The docs explain that for dynamic routes I should use getStaticPaths and getStaticProps but that doesn’t guarantee that the data for a user’s profile or post will be updated since it’s statically generated.

What’s the proper way to work this out?

Does useCallback accept an object from props in react?

i have a reusable component which receives an object prop in react, in this reusable component i have a useCallback, but i am not sure if it’s correct since it’s an object, and since there’s referential equality thing I am confused.

const SukiCustomer = ({ contact, source, sukiPhoneNumbers, isCreditFlow }) => {
  const appTheme = useThemeContext();
  const navigation = useNavigation();

  const isSukiCustomer = sukiPhoneNumbers.includes(contact.phone_number);
  const isAllCustomers = source === ALL;
  const isCredit = source === CREDIT;
  const isPromo = source === PROMO;
  const dueAmount = contact.totalDebit - contact.totalCredit;
  const displayDueAmount = getFormattedPesos(dueAmount);

  const onPress = useCallback(() => {
    const handleIsCredit = async () => {
      try {
        const parameters = {
          id: contact.id,
          first_name: contact.first_name,
          last_name: contact.last_name,
          phone_number: contact.phone_number,
          totalCredit: contact.totalCredit,
          totalDebit: contact.totalDebit,
          'Screen Name': 'SukiCustomers',
        };
        await selectSukiContact({ parameters });
        await viewSukiTransactionHistory({ parameters });
        timeToInteractionUtils.setTTIStartTime({
          key: keys.TTI_START_SUKI_TRANSACTION_HISTORY,
        });
        navigation.navigate('TransactionHistory', {
          contact,
          fromScreen: leanPlumConstants.screenNames.SukiListaActivity,
        });
      } catch (error) {
        console.error(FILE_PATH, error);
      }
    };

    const handleIsNotSukiCustomer = async () => {
      const parameters = {
        ...contact,
        button_name: 'Add',
      };
      await addSukiContact({ parameters }).catch(error => {
        console.error(FILE_PATH, error);
      });
      timeToInteractionUtils.setTTIStartTime({
        key: keys.TTI_START_ADD_CONTACT_ACTIVITY,
      });
      const origin = isCreditFlow ? CREDIT : SUKI;
      navigation.navigate('AddSukiCustomer', {
        contact,
        source: origin,
      });
    };

    if (!isSukiCustomer) {
      handleIsNotSukiCustomer();
    } else if (isCredit) {
      handleIsCredit();
    }
  }, [contact, navigation, isCreditFlow, isCredit, isSukiCustomer]);

This actually works but i am just not sure if this is correct way or maybe i should deconstruct on top of component:

 const { id, first_name, last_name, phone_number, totalCredit, totalDebit } =
    contact;

and on useCallback pass them?

[
    id,
    first_name,
    last_name,
    phone_number,
    totalCredit,
    totalDebit,
    active_services,
    suki_id,
    id,
    navigation,
    isCreditFlow,
    isCredit,
    isSukiCustomer,
  ]);

Pls help me improve my code

Converting a RegExp constructor to be Safari-compatible

I have this regexp constructed pattern I’m passing a string variable to. This works perfectly in Chrome, but won’t work in Safari.

Is there a way I might be able to convert this code to be compatible across browsers? Thank you!

(e = e
  .split(new RegExp("(?<!\w)" + t[l] + "(?!\w)(?![^\[\]]*\])", "gm"))
  .join(n)),
  1 == caseinsensitive &&
    (e = e.replace(
      new RegExp("(?<!\w)" + t[l] + "(?!\w)(?![^\[\]]*\])", "gmi"),
      "[$&](" + n + ")"
    ));

Proper media query for iphone 11?

simply as the title states:

What is the actual correct media query for responsive design for a iphone 11?

Im using the Mobile Simulator chrome extension that suggest its 414×896 resolution however it doesnt seem to work.

Having a problem where my portfolio looks good on basically every other phone then my Iphone 11.

Thank you.

How to use override in package.json to update child dependencies

I am seeing a vulnarability in async and want to update it to 3.2.2
This is the dependency tree if i do npm list async

└─┬ [email protected]
  └─┬ [email protected]
    └── [email protected]

So looking at the npmdocs I tried to add override in package.json as follows.

{
  "name": "some application",
  "scripts": {...},
  "dependencies": {...},
  "overrides": {
    "webpack-dev-server": {
      "portfinder": {
        "async": "3.2.2"
      }
    }
  },
  "devDependencies": {...}
}

But when I do npm install it didn’t update async version to 3.2.2 and still shows older version in pacakge-lock.json.
Any idea what am i doing wrong?

How to connect to mysql server with electron?

I’m trying to connect my electron app to a database, but I keep getting the same error

ETIMEOUT
or that the user don't have access

But if I try with my local database works fine, any ideas of why is this happening?

var mysql = require(‘mysql’);

    // Add the credentials to access your database
    var connection = mysql.createConnection({
        host     : 'xxx.xxx.xxx',
        user     : 'xxxxx',
        password : 'xxxxxxx', 
        database : 'xxxxx',
        pool: { 
            max: 1000,
            min: 0,
            idleTimeoutMillis: 30000000
          },
          options: {
            "enableArithAbort": false,
            "encrypt": false
        }, 
          debug: true
    });

    // connect to mysql
    connection.connect(function(err) { 
        if(err){
            console.log(err.code);
            console.log(err.fatal);
        } else {
            console.log("OK");
        }
    });

Predefined functions for extracting “work hours” from two timestamps in JavaScript?

I have two timestamps and I must find the “working hours” in between these two timestamps where “working hours” is defined as 9:00 to 17:00 (9AM to 5PM).

Given the timestamps 2022-04-25 01:00:00 and 2022-04-27 10:00:00:

2022-04-25 15:00:00 -> 2 hours

2022-04-26 -> 8 hours (full day)

2022-04-27 10:00:00 -> 1 hour

So the total would be 11 working hours.

I know how to do this in SQL with the EXTRACT function but I’m not as adept in JavaScript and my search hasn’t returned anything useful. Alternatively, I could add up the time that falls in the “work hours” given two timestamps but I want to check if there’s some pre-defined function for this.

SQL equivalent: SQL extract hour from timestamp

How can I use JavaScript Google Translation API in html.erb Rails?

I want to integrate Google Translation API into my Rails project using JavaScript. But I don’t know how to do it correctly. For example, I have an image_tag:

      <div id="google_icon_div">
        <%= image_tag "google-icon.png", id: "google_icon", onclick: "test_transl()"%>
      </div>

And now I want translate a string ‘hello’ from English to German and log it console by pressing the button and calling function ‘test_transl’. How can I do it? I already have Google Translation API key.

SpeechRecognition API not stopping on React application

I am trying to add speech recognition to my web application. I am using Web Api’s speech recognition. This is my react’s code:

import logo from './logo.svg';
import './App.css';
import React from 'react';
import { Typography, Button, Box } from '@mui/material';

function App() {
  const [values,setValues] = React.useState("Click on the start button and start speaking.");
  var SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
  var recognition = new SpeechRecognition();
  recognition.continuous = true;
  recognition.lang = 'en-US';
  recognition.interimResults = true;
  
  recognition.onresult = function(event) {
    console.log("Value is "+event.results[0][0].transcript)
    setValues(event.results[0][0].transcript)
  }
  return (
    <React.Fragment>
      <Typography align='center' variant="h1">
        Filler word helper
      </Typography>

      <Box sx={{
        backgroundColor:'gray',
        maxWidth:'md',
        margin:'auto',
        minHeight:200,
      }}>
        <Typography style={{
          paddingLeft:'2%',
          paddingRight:'2%'
        }} color="white">
          {values}
        </Typography>
      </Box>

      <Box sx={{
        display:'flex',
        justifyContent:'space-around',
        paddingTop:'2%'
      }}>
        <Button 
        onClick={()=>{
          recognition.start()
        }}
        variant="contained"
        >Start</Button>

        <Button 
        onClick={()=>{
          setValues("Click on the start button and start speaking.")
        }}
        variant="contained"
        >Clear</Button>

        <Button 
        onClick={()=>{
          recognition.abort()
          recognition.stop()
          console.log("Stop pressed")
        }}
        variant="contained"
        >Stop</Button>

      </Box>
    </React.Fragment>
  );
}

export default App;

The problem is that after I start the process I cannot stop it. It keeps on going. I did try stopping and aborting and trying various combinations.

Can anyone help me with this issue ?

change value of tom select after rendering it

I’m working on an update function that uses tom-select (https://tom-select.js.org/).

The process goes as follows:
1- the user clicks on the edit button
2- a bootstrap modal will open and the data of the selected row will show so he can update them.

the problem:
after rendering the selector I want to change it’s value to select the value of the selected item, I tried this code:
$('#select-beast-update').val(response.data.book.author_id).change()

but it’s not working, then I tried using the onInitialize:function() -refer to this link at the callbacks section to get more details https://tom-select.js.org/docs/ – and it also did not work.

this is my AJAX function :

            $.ajax({
                url: "{{ route('books.edit',['%book%']) }}".replace('%book%',id),
                type: "GET",
                success: (response)=>{

                    $('#book-id-update').val(response.data.book.id)
                    $('#book-name-update').val(response.data.book.name)
                    // $('#book-pdf-update').val(response.data.book.pdf_file)
                    // $('#book-mobi-update').val(response.data.book.mobi_file)

                    let authors = response.data.authors.map(item => {
                        return {
                            value: item.id,
                            text: item.name
                        };
                    });

                    var input = document.getElementById('select-beast-update');
                    new TomSelect(input,{
                        create: true,
                        plugins: ['change_listener'],
                        sortField: {
                            field: "text",
                            direction: "asc"
                        },
                        options:authors,
                    })

                    input.value = response.data.book.author_id;
                    var evt = document.createEvent('HTMLEvents');
                    evt.initEvent('change', false, true);
                    input.dispatchEvent(evt);

                    $('#select-beast-update').attr('name','author_id')
                },
                error: (e)=>{
                    Swal.fire('Error','Please Try Again Later','error' )
                }
            }).done(function(){
                $('#edit_book_modal').modal('show')
            }); ```
note: I'm using Laravel as my backend and vanilla JS and bootstrap along with the tom-select. I'm also open to changing tom-select and using other libraries that implement search in its options **other than select 2**.
            

Javascript Books challenge

I tried to complete a javascript assessment for a job interview but failed

My plan was to process the user object inside findPotentialLikes function but it’ll always throw undefined.

It is made using Mocha and Chai testing framework and promises.

class SocialNetworkQueries {

    constructor({ fetchCurrentUser }) {
        this.fetchCurrentUser = fetchCurrentUser;
    }

    findPotentialLikes({ minimalScore } = { }) {
        
     console.log(this.fetchCurentUser);
     // I tried here to get the user in order to process the findPotentialLikes function with no luck

        return Promise.resolve();
        
    }

}


describe('SocialNetworkQueries', () => {
  describe("example from README", () => {

    it("should find potential likes", async () => {
      // given
      const user = {
        id: "mrouk3",
        likes: {
          books: ["Moby Dick", "Ulysses"],
        },
        friends: [{
          id: "YazL",
          likes: {
            books: ["Ulysses", "War and Peace"],
          }
        }],
      };

      // when
      const potentialLikes = await new SocialNetworkQueries({
        fetchCurrentUser: () => Promise.resolve(user),
      }).findPotentialLikes({ minimalScore: 0.3 });

      // then
      expect(potentialLikes).toEqual({
        books: [
          "The Great Gatsby",
          "Don Quixote",
          "War and Peace",
        ],
      });
    });

  });
});