Leaflet Contextmenu open on double-click event

i have an array of markers and every marker has a contextmenu. I want to open the marker contextmenu if someone double-click the marker (for more mobile friendly usage).

marker.on('dblclick', function(e) {
  // Open the context menu
  map.contextmenu.showAt(e.latlng, { contextmenuItems: contextMenuItems });
});

This example only opens the default contextmenu and not the marker one. How can I change this to the marker one?

I asked chatGPT but it only returned code with unknown functions.

How to make this parallax scrolling effect?

Hey there SO community!

I have to divs and I want it so that when the user scrolls the second div will scroll quicker and start to cover up the first one I have somewhat accomplished this; however, my way is innefficient and doesn’t work when the user tries to scroll back up. Further details are listed below.

HTML:

<body>
    <div class="first-div"></div>

    <div class="second-div"></div>

    <script src="Script.js"></script>
</body>

CSS:

* {
    padding: 0;
    margin: 0;
}
body {
    --red: #DE0000;
    background-color: black;
    position: relative;
}

.first-div {
    width: 100%;
    height: 500px;
    position: relative;
    display: flex;
    align-items: center;
    position: absolute;
    top:0;
}
.second-div {
    width: 100%;
    height: 50em;
    background-color: white;
    z-index: 2;
    position: absolute;
    top: 500px;
}

JS:

let second-div = document.getElementsByClassName("second-div")[0];
window.addEventListener('scroll', function() {
    let a = parseInt(this.getComputedStyle(second-div)['top']);
    let b = window.scrollY;
    let c = a - b;
    second-div.style.top = c + 'px';
});

How it currently looks (ignore that it’s about Hitler it’s for a school coding project):

https://streamable.com/afdkpa

If you couldn’t tell at the end I was stuck in white because I couldn’t go up further because my code don’t work.

Honestly a lot of stuff but I think my math is just wrong. Mainly stuff with margin-top, top, adding offsets, multiplying, etc. Just random stuff but im sure my code was wrong.

Mocking react custom hook with sinon stub

I have a custom hook with that returns api calls. It looks like this:

export const useApiData = () => {
    const queryClient = useQueryClient();
    const [networkError, setNetworkError] = useState<string>(null);

    const getCase = (caseId: number) =>
        useQuery({
            queryKey: `case-${caseId}`,
            queryFn: (): Promise<AxiosResponse<CaseDto>> => CASE_API.api.getCase(caseId),
            staleTime: Infinity,
            suspense: true,
        });

    const api = {
        getCase,
    };

    return { api, networkError };
};

I would like to stub this custom hook with a sinon stub:

export function mockGetCase(sinonSandbox: SinonSandbox = sinon.createSandbox()) {
    const { api } = useApiData();
    sinonSandbox.stub(api, "getCase").callsFake(() => {
        return () => Promise.resolve(caseMockApiData);
    });

    return sinonSandbox;
}

But, this won’t work since I am calling hook outside of react component:

Warning: Invalid hook call. Hooks can only be called inside of the
body of a function component. This could happen for one of the
following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug

How can I stub a custom react hook with sinon?

and fix this problem.

I am using this hook like this in my components:

const { caseId } = useCase();
const { api } = useApiData();
const {
    data: { data: case },
} = api.getCase(caseId);

The CASE_API looks like this:

export const CASE_API: CaseApi<CaseDto> = useApi(
    new CaseApi({ baseURL: environment.url.case }),
    "case",
    "gcp"
);

And the hook useApi looks like this:

export function useApi<T extends AxiosClient>(api: T, app: string, cluster: string): T {
    api.instance.interceptors.request.use(
        async (config: InternalAxiosRequestConfig) => {
            const secHeaders = await createDefaultHeaders(app, cluster);
            Object.assign(config.headers, secHeaders);

            return config;
        },
        function (error) {
            // error handling here
            return Promise.reject(error);
        }
    );

    api.instance.interceptors.response.use(
        function (response) {
            return response;
        },
        function (error) {
            return Promise.reject(error);
        }
    );

    return api;
}

const createDefaultHeaders = async (app: string, cluster: string) => {
    const idToken = await SecuritySessionUtils.getSecurityTokenForApp(app, cluster);
    const correlationId = SecuritySessionUtils.getCorrelationId();
    return {
        Authorization: "Bearer " + idToken,
        "Content-type": "application/json; charset=UTF-8",
        "X-Correlation-ID": correlationId,
        "Call-Id": correlationId,
        "Consumer-Id": SecuritySessionUtils.getAppName(),
    };
};

Photoshop script to put an image into a local file to replace a layer image and export as a new JPEG?

We are working on downloading finished product photo for a website and put it into a custom layer in photoshop. It takes a long time to do manually so i’m trying to see if we can automate the process by downloading the JPEG into a local folder and output the final product into another folder as a JPEG.

Workflow –
-Download JPEG into folder
-Move to Photoshop file
-Replace layer image in photoshop with new downloaded JPEG
-Export new photoshop file as a JPEG in output folder (possibly into google drive)

A screenshot of the photoshop file is here. enter image description here

I’m not a coder so I used ChatGPT to do try and build an introductory code and I’m just seeing if it will work.

// Load required modules
const request = require('request');
const fs = require('fs');

// Download the JPEG file from a URL and save it in a local folder
const imageUrl = 'https://example.com/image.jpg';
const downloadFolder = '/path/to/download/folder';
const fileName = 'downloaded_image.jpg';

request(imageUrl)
  .pipe(fs.createWriteStream(`${downloadFolder}/${fileName}`))
  .on('close', function() {
    console.log('JPEG downloaded successfully');
    
    // Open the Photoshop file
    const photoshopFile = '/path/to/your/photoshop/file.psd';
    const docRef = app.open(new File(photoshopFile));
    
    // Replace the layer image in Photoshop with the new downloaded JPEG
    const layerName = 'Layer 1';
    const layerRef = docRef.layers.getByName(layerName);
    const newLayerRef = docRef.artLayers.add();
    newLayerRef.name = layerName;
    docRef.activeLayer = newLayerRef;
    docRef.selection.selectAll();
    docRef.paste();
    docRef.selection.deselect();
    layerRef.remove();

    // Export the new Photoshop file as a JPEG and save it in the output folder
    const outputFolder = '/path/to/output/folder';
    const outputFileName = 'new_file.jpg';
    const jpegOptions = new JPEGSaveOptions();
    jpegOptions.quality = 8; // adjust the quality as needed
    docRef.saveAs(new File(`${outputFolder}/${outputFileName}`), jpegOptions);
    docRef.close(SaveOptions.DONOTSAVECHANGES);

    console.log('New Photoshop file saved as JPEG');
    
    // Upload the new file to Google Drive (assuming you have authenticated and authorized access)
    const { google } = require('googleapis');
    const drive = google.drive({ version: 'v3', auth: YOUR_AUTH_TOKEN });
    const fileMetadata = { name: outputFileName };
    const media = { body: fs.createReadStream(`${outputFolder}/${outputFileName}`) };
    drive.files.create({ resource: fileMetadata, media: media, fields: 'id' }, function (err, file) {
      if (err) {
        console.error('Error uploading file to Google Drive:', err);
      } else {
        console.log(`New file uploaded to Google Drive with ID: ${file.data.id}`);
      }
    });
});

I haven’t tried it yet I’m just seeing if it’s even possible and if i’m on the right track.

Share the package.json scripts configuration across multiple projects

Share the package.json scripts configuration across multiple projects

common-scripts

modules.export = {
  "dev": "npm run",
  "build": "run-p",
}

project 1


  "scripts": {
    "dev": "The dev command derived from common-scripts is executed here",
    "build": "The build command derived from common-scripts is executed here",
  },

project 2

  "scripts": {
    "dev": "The dev command derived from common-scripts is executed here",
    "build": "The build command derived from common-scripts is executed here",
  },

How can I share package.json scripts configuration across multiple projects

I need help solving the multiple radio button selection (html/javascript)

<script type="text/javascript">

x = "1.html";
y = "2.html";

function redirectPage(f){
   for(var i=0; i<f.length; i++) {
      if(f.answerq[i].checked && f.answerw[i].checked && f.answere[i].checked) {
         if (f.answerq[i].value == 'a' && f.answerw[i].value == 'a' && f.answere[i].value == 'a') {
            window.location = x;
         }else {
            window.location = y;
         }
      }
   }    
}
</script>
<form method="post" action="#">
    
*ARE YOU 18+ YEARS OLD?
<label><input type="radio" name="answerq" value="a"> Yes</label>
<label><input type="radio" name="answerq" value="b"> No</label>

*ARE YOU A U.S CITIZEN?
<label><input type="radio" name="answerw" value="a"> Yes</label>
<label><input type="radio" name="answerw" value="b"> No</label>

*ARE YOU MARRIED? 
<label><input type="radio" name="answere" value="a"> Yes</label>
<label><input type="radio" name="answere" value="b"> No</label>

<button type="button" class="btn btn-primary" value="Submit" onclick="redirectPage(this.form)">Submit!</button>

<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

 </form>

Selecting yes,yes,yes or no,no,no is working perfectly fine and redirect to the correct link. However, when selecting yes,yes,no, no,yes,no or yes,no,yes doesn’t work after clicking the submit button.

And one more thing anyone here can help me put a validation if they do not select a radio button like an alert of prompt?

Thank!

How to align for loop of items and database items messages?

So, basicly i have this python chat flask application, and i am on the final stages of the project and encountered in issue. For some reason the socket messages are not aligning with the database messages.

Heres what i mean: https://imgur.com/a/vPU2mua

The message that is not inline is the socket message and the messages that are inline is the HTML.

Does anyone know how i can fix this problem?

<html>
<head>
  <title>Chat Room</title>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <link rel="stylesheet" href="/static/css/styles.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js" integrity="sha512-pumBsjNRGGqkPzKHndZMaAG+bir374sORyzM3uulLV14lN5LyykqNk8eEeUlUkB3U0M4FApyaHraT65ihJhDpQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.6.1/socket.io.js"></script>
  <style>
    .message-container {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
    }

    .message-container .username {
      font-weight: bold;
      margin-right: 10px;
    }

    .message-container .message-text {
      font-style: italic;
    }
    .row:last-child {
  position: relative;
  z-index: 1;
}

#messages {
  position: relative;
  z-index: 1;
}

  </style>
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col-md-8">
        {% for username, message in messages %}
        <div class="message">
          <div class="message-row">
            <span class="message-text">{{ message }}</span>
          </div>
        </div>
        {% endfor %}
        <ul id="messages"></ul>
        <div class="input-group">
          <input type="text" id="myMessage" class="form-control">
          <button class="btn btn-primary" id="sendbutton">Send</button>
        </div>
      </div>
    </div>
  </div>
  <script type="text/javascript">
    $(document).ready(function() {
      var socket = io.connect('http://127.0.0.1:3000');

      socket.on('message', function(msg) {
  var message = '<div class="message">';
  message += '<div class="message-row">';
  message += '<span class="message-text">' + msg + '</span>';
  message += '</div></div>';
  $("#messages").append(message);
});
      $('#sendbutton').on('click', function() {
          socket.send('{{ username1 }}: ' + $('#myMessage').val());
          $('#myMessage').val('');
      });
    });
  </script>
</body>
</html>

CSS:


body {
    background-color: #2b2b2b !important;
    color: white !important ;
}
.username {
    position: relative;
    bottom: -25pc;
    left: 45pc;
    width: 500px;
    height: 50px;
}
.password {
    position: relative;
    bottom: -30pc;
    left: 13.6pc;
    width: 500px;
    height: 50px;
}
.submit {
    position: relative;
    bottom: -34pc;
    left: -4pc
}
#myMessage {
    position: fixed;
    width: 1000;
    height: 30px;
    border-radius: 1pc;
    bottom: 0pc;
}
input[type="text"] {
  background-color: #f2f2f2;
  border-radius: 5px;
  padding: 10px;
  border: none;
}

#sendbutton {
    position: fixed;
    left: 83pc;
    bottom: 0pc;
    border-radius: 2pc;
}
.message {
  margin-bottom: 10px;
}

.message-text {
  display: inline-block;
  padding: 5px;
  border-radius: 5px;
  background-color: #f2f2f2;
  color: black;
}

.username {
  font-weight: bold;
  margin-right: 5px;
}

.message-row {
  display: flex;
  align-items: center;
}

.message-row .message-text {
  margin-left: 10px;
}

.message-row:nth-child(even) .message-text {
  background-color: #e6e6e6;
}

How to store UTM parameters in a cookie using google tag manager

Hi I’m running Facebook ads with visitors landing on a calendly booking page(embedded on my website) with UTM parameters in the URL.

When they book in they are redirected to another page which is where the issue happens. Because of the nature of calendly with how I’m having to use the redirect it removes all of the utm parameters which I need on the page they land on to send to google analytics.

I am very new an inexpereinced with javascript so I’ve been asking for the assistance of chatgpt to help me write the scripts.

Calendly said a good option would be to have a cookie that stores all of the utm parameters which is what my code is for and is triggered using google tag manager (GTM).

The tag I have created is firing correctly however I don’t see any cookies or console log messages in the console window:

<script>
      console.log("Setting cookie: FbAdUTMCookie");  
function getQueryParam(url, param) {

  var queryString = url.split('?')[1];
  if (!queryString) return null;

  var params = queryString.split('&');
  for (var i = 0; i < params.length; i++) {
    var keyValue = params[i].split('=');
    if (keyValue[0] === param) {
      return decodeURIComponent(keyValue[1]);
    }
  }
  return null;
}

function setCookie(name, value, days) {
  var expires = "";
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

function storeUtmParameters() {
  var utmParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'ad_id', 'adset_id', 'campaign_id', 'site_source_name', 'adset_name'];
  var eventData = {};

  for (var i = 0; i < utmParams.length; i++) {
    var paramValue = getQueryParam(window.location.href, utmParams[i]);
    if (paramValue) {
      eventData[utmParams[i]] = paramValue;
    }
  }

  if (Object.keys(eventData).length > 0) {
    console.log("Setting cookie: FbAdUTMCookie");
    setCookie('FbAdUTMCookie', JSON.stringify(eventData), 30); // Store cookie for 30 days
  }
}

</script>

Handsontable component inside a resizable container

I’d like to put a handsontable component inside of a resizable container. I came across the react-resizable component which seemed like a good option for achieving this, however I’m running into an issue where the resize handler scrolls up with the vertical scrollbar:
https://d.pr/i/oJjnep

I’m not firmly set on using react-resizable so if there’s an alternate method to achieve a better result, I’m open to that.

Here’s a codepen:
https://codepen.io/opike99/pen/BaOZVPo?editors=0010

import {ResizableBox} from 'https://cdn.jsdelivr.net/npm/[email protected]/+esm';

class ExampleComponent extends React.Component {
  hotRef = React.createRef();
  
  constructor(props) {
    super(props);
    this.state = {
      settings: {
        data: Handsontable.helper.createSpreadsheetData(50, 30)
      }
    }
  }
// This is a comment
  handleChange(event) {
    const targetId = event.target.id; console.log(this.state);

    switch (targetId) {
      case 'fixed-rows':
        this.setState(new React.addons.update(this.state, {
          settings: {
            fixedRowsTop: {
              $set: event.target.checked ? 2 : 0
            }
          }
        }));
        break;
      case 'fixed-columns':
        this.setState(new React.addons.update(this.state, {
          settings: {
            fixedColumnsLeft: {
              $set: event.target.checked ? 2 : 0
            }
          }
        }));
        break;
      case 'row-headers':
        this.setState(new React.addons.update(this.state, {
          settings: {
            rowHeaders: {
              $set: event.target.checked
            }
          }
        }));
        break;
      case 'column-headers':
        this.setState(new React.addons.update(this.state, {
          settings: {
            colHeaders: {
              $set: event.target.checked
            }
          }
        }));
        break;
    }
  }

  render() {
    return (
      <div id="example-component">
        <div id="hot-options">
          <label for="fixed-rows"><input onChange={(e) => this.handleChange(e)} id="fixed-rows" type="checkbox" />Add fixed rows</label><br/>
          <label for="fixed-columns"><input onChange={(e) => this.handleChange(e)} id="fixed-columns" type="checkbox" />Add fixed columns</label><br/>
          <label for="row-headers"><input onChange={(e) => this.handleChange(e)} id="row-headers" type="checkbox" />Enable row headers</label><br/>
          <label for="column-headers"><input onChange={(e) => this.handleChange(e)} id="column-headers" type="checkbox" />Enable column headers</label><br/>       
        </div>
        <div id="hot-preview">
                      <ResizableBox width={1000}  height={400}
                          onResize={() => {
                            this.hotRef.current.hotInstance.refreshDimensions();
                          }}
                          draggableOpts={{}}
                          minConstraints={[100, 100]}
                          maxConstraints={[1000, 300]}>
                        <div className={'div-wrapper'}>
        <HotTable root="hot" ref={this.hotRef} settings={this.state.settings} />
                        </div>
          </ResizableBox>
          </div>
      </div>
    );
  }
}

// ReactDOM.render(<ExampleComponent />, document.getElementById('example'));
ReactDOM.createRoot(document.getElementById('example')).render(<ExampleComponent />);

Append a new div element on each button click in javascript

I’m coding a notetaking app and using new divs as notes.
I created a div customized with CSS which I would use as a template whenever I want to create a new note.
However, I can only add a single one when I click the button.

addNote() {
  noteBank.appendChild(newNote);
}

let noteBank = document.querySelector(".note_bank")

newNote = document.createElement("div");
newNote.classList.add("new_note")

let addNew = document.querySelector(".add_note")
addNew.addEventListener('click', () => {
  notebook.addNote()
  notebook.styleNote()
})

I used cloneNode(true) and it worked, but it doesn’t duplicate event listeners so I couldn’t move on with that.
I want a way to add new elements with each button click, while still giving each new element an event listener

fabricJS – Zoom in / out and resize. Clip area and it’s contents always centered

To recreate the issue I’m having, resize one of the black border boxes to extend way outside of the blue clip area and then zoom. You’ll notice it throws off the centering of the blue clip area, which should always be perfectly centered and the objects inside should always maintain their correct position inside of the clip even when canvas size and/ or zoom changes.

Sample: https://codepen.io/dominick/pen/dyqJpoE?editors=0010

The issue is happening here:

const centerObjs = () =>{

const old = canvas.getActiveObjects();

  
canvas.discardActiveObject();
const selection = new fabric.ActiveSelection(canvas.getObjects(), { canvas: canvas });
  selection.viewportCenterV();
  selection.viewportCenterH();
  selection.setCoords();
  selection.destroy();
  setSelectedObjectsHistory(old)
}

The issue is, when an object is extended way outside of the clip area, the activeSelection bounding box is the width of the widest object. This throws off the centering. I would like to always center based on the first object bounding box in active selection (the clipping rect)

I could be approaching this completely wrong, I’m not sure. Any help is appreciated!

How to reference variable I can access from console in firefox extension code?

I’m currently working on a firefox extension for a specific trusted website. I would like access to a variable “ownUsername” that I can access from the console. However, I am unable to access this variable from my extension code, and cannot find it inside the window object. How would I go about accomplishing this?

I’ve tried digging around in dev tools and think I found the function where the variable is defined, but I don’t understand how I can call it from the console when it seems like a local variable. Unfortunately I am unable to share any of the code.

Any help would be appreciated.

Prevent refresh on wordpress page

I have a custom wordpress quiz plugin which creates a quiz with a URL for example

/practice-exam/?customize_autosaved=on&customize_changeset_uuid=random-characters

I am looking to see if i can prevent users from refreshing the page when in this ‘exam mode’ as they go back to the beginning (but if they don’t refresh everything is fine)

I am hoping there is a way to add something to the functions.php and potentially put a message saying “Opps you can’t refresh the page”

But open to suggestions. Any help much appreciated!

Please see above what the issue is

Google Apps Script – Workbook A script onOpen to update Workbook B with email, date/ time, and Workbook A ID – Error with Method Signature Parameter

I am the owner for all reporting google sheets in the company I work for and I would like to make a log of when (and if) people are opening these reports. The idea is that if nobody opens a report in a certain amount of time, we can archive the report and clean up our folders.

I want to put an app script on the reports we’ve built that upon opening the report workbook A, on our master report access workbook B, a new line is created at the top on the sheet named “Access Data” that writes the users email, date/ time, and workbook A ID.

I am getting an error “Exception: The parameters (String) don’t match the method signature for SpreadsheetApp.Spreadsheet.setActiveSheet.
onOpen @ Code.gs:5”

function onOpen(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var now = Utilities.formatDate(new Date(),"GMT-5","yyyy-MM-dd HH:mm:SS");
  var user = Session.getActiveUser().getEmail();
  var destinationSS = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/xxxxxxx').setActiveSheet('Access Data');
  var originSSID = ss.getSheetId;

  destinationSS.insertRowAfter(1)
  destinationSS.getRange('A2').setValue(now)
  destinationSS.getRange('B2').setValue(user)
  destinationSS.getRange('C2').setValue(originSSID)
}

What does this error mean and how can I fix it? It looks like it is having problems finding the workbook and sheet I am trying to make active so I can set the values?

First project in apps script so any advice is appreciated!

I tried different quotes on my sheet name. I expected it to find my sheet name on that workbook who’s URL I provided. It continued to result in this error.