Foursquare API – query by location

I am trying to make some fetch calls to the Foursquare Place Api. For instance, if I provide the following link as an API call:

 var url ="https://api.foursquare.com/v3/places/search?radius=100000&limit=25&ll=42.433633,9.208001";
    

It will correctly fetch the data for the given latitude and longitude. Now, on the other side, I would like to fetch for the data providing some location, like “London”. As the documentation states, it should be inserted as a string for the “near” query parameter, so this would be the url:

var url ="https://api.foursquare.com/v3/places/search?radius=100000&limit=25&near=London"

It fails. Im not sure what im doing wrong, or if I have read wrongly the documentation.

Why do JavaScript’s settimer/setInterval drop when there is an identical timer in the task queue?

I’m studying JS timer and recently I read this page
https://johnresig.com/blog/how-javascript-timers-work/

Please note the following in this article.

Note that while mouse click handler is executing the first interval
callback executes. As with the timer its handler is queued for later
execution. However, note that when the interval is fired again (when
the timer handler is executing) this time that handler execution is
dropped.
If you were to queue up all interval callbacks when a large
block of code is executing the result would be a bunch of intervals
executing with no delay between them, upon completion. Instead
browsers tend to simply wait until no more interval handlers are
queued (for the interval in question) before queuing more.

And in Commnets, we can see below:

Abhi (February 25, 2008 at 2:16 pm) Just to make sure I understood let
me reiterate. If an interval handler is already queued up for
execution and before it gets a chance to execute another interval
fires, then the newly fired interval’s handler will be dropped. But if
an interval handler is executing and while it is executing another
interval fires then the newly fired handler will be executed
immediately after the currently executing interval handler is done
executing. Sorry if I sound too convoluted.

John Resig (February 25, 2008 at 3:29 pm) @Abhi: Yes, that’s correct.

Just to note that in your second example “But if an interval handler
is executing and while it is executing another interval fires then the
newly fired handler will be executed immediately after the currently
executing interval handler is done executing.” it may not be the
absolute next thing to execute (since another timer or event may be
already queued) but it’ll certainly occur after no artificial delay.

But, yes, you are correct in your assumption – and, yes, this is quite
convoluted.

If my understanding is correct, in JavaScript it seems to be dropped when the same timer is pushed while the timer is on the task queue (not yet running, just waiting). Can anyone explain why this is happening? I checked the HTML spec about timer(https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html), but couldn’t find anything like this.

Async function not running some code even inside await

I have a Node.js AWS Lambda function created via the serverless framework. I have multiple helper functions inside it. I am having an issue with one of them due to being async. The function runs and logs out all parts I put comments next to however it doesn’t update callDuration. I think that the code is having an issue due to async where it finishes in the wrong order. My goal is to be able to return the callDuration to my main function for further processing. How can I get all code to process/run and be able to meet my goal and have the code run in the right order

Here is the function:

const callAggregate = async (billingData, billingDB) => {
    const accountSid = process.env.TWILIO_ACCOUNT_SID
    const authToken = process.env.TWILIO_AUTH_TOKEN
    const client = require('twilio')(accountSid, authToken)
    // Setup model
    const Billing = billingDB.model('Billing')
    await Billing.findOne({_id: billingData._id}).exec().then(bill => {
      const callArray = bill.callSid
      console.log(bill) // This logs out
      let callDuration = 0
      for (const call of callArray) {
        console.log(call) // This logs out
        client.calls(call)
        .fetch()
        .then(callDetails => {
          console.log(callDetails) // This logs out
          callDuration += callDetails.duration
        })
      }
      console.log(`Billing for ${callDuration} minutes of voice calling for ${billingData._id}`) // This logs out
      Billing.findOneAndUpdate(
        {_id: billingData._id},
        { $inc: { call_duration: callDuration }, callSid: []},
        (err, doc) => {
            if(err) {
                console.log(err)
            }
        }
      )
      return callDuration
    })
}

Datatables issue on reloading div

working datable initiallyInitially the Datatables are working properly.
After adding this on button clicked.
$( “#divfortable” ).load(location.href + ” #divfortable>*”,”” );
datatables search, scroll are not visible, button is not working
All elements within the div are not working (datatables, even the button its clickable but not going anywhere)
But the datatables displays the rows it needs to display it just overlaps, the search button,scrolls both x and Y are not visible.

How to display anyone’s keystrokes on a website (so anyone can fly my drone via live video)

I’m developing a fun website where I will fly my drone, and move it according to the keystrokes pressed by anyone viewing the website. For example, if someone presses the ↑ arrow on the keyboard, I will fly the drone upwards, and the user will see a live video from the drone.

To do this, I need to capture the “key down” state, and display it live on the website.

I have experience with saving data to a MySQL database, via JavaScript and PHP, but I can’t find a good way to then display the “key down” state on the website, in a live fashion.

What is the most efficient way to do this?

Using jquery-ui with webpack. Problem with importing

I’m using Jquery and Jquery-ui for creating a datepicker. As module bundler I’m using webpack.
And when I’m trying run my project i get this error:

Uncaught TypeError: jquery__WEBPACK_IMPORTED_MODULE_0___default(...)(...).datepicker is not a function

Here’s my code:

import $ from "jquery";
import { datepicker } from "jquery-ui";
const currentTime = new Date()
const maxDate = new Date(currentTime.getFullYear(), currentTime.getMonth());


$(function () {
  $(".datepicker").datepicker({
    dateFormat: 'yy-mm-dd',
    defaultDate: 1,
    showOtherMonths: true,
    selectOtherMonths: true,
    maxDate: new Date()
  }).datepicker('setDate', new Date());
})

Attempting to reference a firestore document reference type from a column field property

In my code I have a firestore collection and I have passed it into an AG Grid component:

const restaurants = firestore.collection('restaurant');

<AgGridReact
                    columnDefs={RestaurantColumnDefs}
                    rowData={orderBy(restaurants ?? [], 'openingTimes', 'asc')}
                    suppressDragLeaveHidesColumns={true}
                    rowBuffer={20}
                    rowHeight={70}
                    headerHeight={70}
                    getRowId={row => row.data.id}
                    enableBrowserTooltips={false}
                    onCellClicked={(event) => handleRowClick(event.data.id)}
                />

Now inside my collection each document has a field called ‘dataRef’ that is a reference to another collection with various properties such as ‘name’. I need to access them in my columns, but I do not know how to do so. The second column below works, but I am attempting to access the reference in the first one:

   export const restaurantColumnDefs: Array<ColGroupDef | ColDef> = [
{
    headerName: 'Name',
    field: 'dataRef.name',
    sortable: true,
    filter: true,
    minWidth: 200,
    valueFormatter: params => params.value ?? '-',
},
{
    headerName: 'Opening Times',
    field: 'openingTimes',
    sortable: true,
    filter: true,
    minWidth: 250,
    flex: 1,
    cellRendererFramework: timestampRenderer,
},
];

Express.js download works for everything except pdf’s

I have a Node API that serves files by ID, and the web client downloads them. The process works as expected for these file types: .txt, .docx, .xlsx, .png, .ts, .zip, and .tsx. But it doesn’t work for .pdf. I don’t understand it.

My biggest problem is that I don’t really know which side the problem is on, server or client? I’ve checked the source files on the server and they are fine.

The files sizes are different, on one of my test files the server size in 74KB and the client size is only 64KB.

Any assistance would be greatly appreciated.

  • Express Version 4.17.1
  • Axios Version 0.27.2

Express Route

router.get(
  "/:id",
  [...],
  asyncMiddleware(async (req: Request, res: Response) => {
    let filId = req.params.id;
    let result = await prepareForDownload(filId); // Copies the file to a temp directory
    if (!result) return res.status(404).send(errorResponse("File not found", { filId }));
    const { downloadFilePath, file: { fname, mimetype } } = result;
    if (!isNullOrWhitespace(mimetype)) res.type(mimetype);
    files.delayedDelete(downloadFilePath);
    return res.download(downloadFilePath, fname, (err) => {
      if (err) throw err;
    });
  })
);

On the client side, I’ve tried this with both Axios and fetch:

Axios

export const apiDownloadFile = (filId: number) => {
  httpService
    .get(`/files/${filId}`, { responseType: "arraybuffer" }) // Also tried with *blob*
    .then((result) => {
      const contentDisposition: string = result.headers["content-disposition"];
      if (contentDisposition && contentDisposition.indexOf("attachment") > -1) {
        const filenameRegex = /filename[^;=n]*=((['"]).*?2|[^;n]*)/;
        const matches = filenameRegex.exec(contentDisposition);
        if (matches && matches.length > 1) {
          const contentType = result.headers["content-type"];
          const filename = matches[1].replace(/['"]/g, "");
          const blob = new Blob([result.data], { type: contentType });
          var href = (window.URL || window.webkitURL).createObjectURL(blob);
          const a = document.createElement("a");
          a.setAttribute("download", filename);
          a.setAttribute("href", href);
          document.body.appendChild(a);
          a.click();
          a.remove();
        }
      }
      return result;
    })
    .catch((error) => alert(error));
};

Fetch Version

export const apiDownloadFile = async (filId: number) => {
  fetch(`${baseURL}/files/${filId}`, { method: "GET", credentials: "include" }).then((response) => {
    const contentDisposition = response.headers.get("content-disposition");
    if (contentDisposition) {
      const filenameRegex = /filename[^;=n]*=((['"]).*?2|[^;n]*)/;
      const matches = filenameRegex.exec(contentDisposition);
      if (matches && matches.length > 1) {
        const filename = matches[1].replace(/['"]/g, "");
        response.blob().then((blob) => {
          const url = (window.URL || window.webkitURL).createObjectURL(new Blob([blob]));
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", filename);
          document.body.appendChild(link);
          link.click();
          link.remove();
        });
      }
    }
  });
};

setting a condition to hide and show content using React

I am trying to say on submit to hide the dialog box and show my cat images, very new to react and i have gotten this far already and this is the last function i need to set in my app to add the other smaller details like validation etc….

I am having problems getting this change to happen,is there any refactoring i could do as well?

import React from 'react';

import ImageGrid from './ImageGrid';

import '../index.css'

// Material UI 
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import Input from '@material-ui/core/Input'
import Dialog from '@material-ui/core/Dialog';
import Button from '@material-ui/core/Button';
import Grid from '@material-ui/core/Grid';





const DialogBox = () => {
  const [open, setOpen] = React.useState(false);
  
  const handleClickOpen = () => {
    setOpen(true);
  };
  
  const handleClose = () => {
    setOpen(false);
  };

  // function to hide the dialog box and show the ImageGrid
  function showCats() {
    
    // Get the modal
    const startPage = document.getElementsByClassName('modal');

    // get the image elements
    const catImages = document.getElementsByTagName(ImageGrid);

    // target the submit button
    const button = document.getElementsByClassName('toggle');

    if (Input === '') {
      alert('Please enter a valid search')
      button.current.disabled = true;
    } else if (Input === String) {
      startPage.style.display = 'none';
      catImages.style.display = 'show';
    } else {
      button.style.display = 'disabled'
    }

    showCats();
    
  }

  const handleSubmit = () => {
    console.log('i work')
    showCats()
  }

  return (
    <div className='modal'> 
      <Grid container justifyContent='center'>
        {/* Button To Open Dialog Box */}
        <Button 
        style={{border: '1px solid #ebc340', color: '#ebc340'}}
        variant="outlined" 
        color="secondary" 
        onClick={handleClickOpen}>
          Welcome to my Case Study, Click to begin
        </Button>
      </Grid>
        {/* Dialog Box Content */}
        <Dialog
        className='dialog-btn'
        open={open} 
        onClose={handleClose}>
          <DialogTitle>
            To begin the application, please insert your URL below:
          </DialogTitle>
          <DialogContent>
          <Input 
          placeholder="Enter Your Link Here" 
          // inputProps={ariaLabel} 
          fullWidth/>
          </DialogContent>

          {/* Dialog Box Actions */}
          <DialogActions>
            <Button 
            onClick={handleClose} 
            color="secondary">
              Cancel 
            </Button>
            
            <Button 
            className='toggle'
            onClick={handleSubmit}
            color='primary'
            autoFocus
            type='submit'>
              Submit
            </Button>
          </DialogActions>
        </Dialog>
    </div>
  );
}


export default DialogBox

Is there a way to the limit number of API response data display on HTML?

My Get request returns over 1050 pages in the console. I am trying to display in HTML and when I do, the result covers my page and the search bar. Is there any way I can decide to display just 10 per page?

This is my function:

//fetch entities function
function RetrieveEntities(e){
    const nameOfCountries = e.target.value; 
    const url = `http://8000/v1/data/${nameOfCountries}`;
    //http request
    fetch(url)
.then(response => {
    if (!response.ok) {
        throw Error("Error");
    }
    return response.json();
})
.then(data => {
    console.log(data);
    const html = data.map(entity => {
        return `
        <div class="entity">
        <p>ID: ${entity.id}</p>
        <p>ID: ${entity.url}</p>
        <p>ID: ${entity.type}</p>
        <p>ID: ${entity.name}</p>
        <p>ID: ${entity.legal.type}</p>
        <p>ID: ${entity.legal.text}</p>
        <p>ID: ${entity.legal.link}</p>
        </div>
        `;   
    }).join('');
    console.log(html)
    document
    .querySelector("#myData")
    .insertAdjacentHTML("afterbegin", html);
})
.catch(error => {
    console.log(error);
});
}


const input=document.getElementById("input");

input.addEventListener("change", RetrieveEntities);

This is the HTML file that handles the input and display div:

<form class="user-form" id="form">
  <input type="search" id="input" placeholder="Search an Entity">
</form>

<div id="myData"></div>

This is the structure of the response:

[
    {
        "id": "5c02434187bc31589f270ae33efb56cbcc43ac0ffcc80d03b42990a0eb61a168",
        "url": "http://8000/v1/data/country/5c02434187bc31589f270ae33efb56cbcc43ac0ffcc80d03b42990a0eb61a168",
        "type": "country",
        "name": "Afghanistan",
        "legal": [
            {
                "type": "attribution",
                "text": "Data is supplied by Wikipedia",
                "link": "https://en.wikipedia.org/"
            }
        ]

mongodb what is the different $setOnInsert and $set | update and insert data

I understood we need to use $setOnInsert

If an update operation with upsert: true results in an insert of a
document, then $setOnInsert assigns the specified values to the fields
in the document. If the update operation does not result in an insert,
$setOnInsert does nothing.

mongo doc $setOnInsert

Also there is a similar question, but I still don’t get it…

My question is when I want to update and insert data at the same time and both inserting and updating data need to modify title value, how the code will look like?

  modifyQuestion(question) {
    check(question, Object);
    Measures.update(
      {_id: question._id},
      {
        $set: {
          title: question.text,
          type: 'multipleChoice',
        },
        $setOnInsert: {
          title: question.text,
          type: 'multipleChoice',
        },
      },
      {upsert: true},
    );
  }

It might not look like a exact mongodb syntax since I’m using meteor

but I thought when data update

        $set: {
          title: question.text,
          type: 'multipleChoice',
        },

this run and when I insert data

        $setOnInsert: {
          title: question.text,
          type: 'multipleChoice',
        },

this work?

I saw an error saying Updating the path 'title' would create a conflict at 'title'
on my terminal.

Just can’t add title value both in $set and $setOnInsert ?

If I just use one of $set, I could update but not insert.
Is there any way that I could insert and update data at the same time?
Thank you.

Why value of select isn’t showing inside of modal like value of input everything else?

So, basically I have this modal which pop-ups when I click edit button, the thing is I am able to get values of every input, except of select value.

To get you a little bit familiar with situation here, the process of what’s happening is following:

I have one table (which is dynamically populated by the data from database) – works fine and it basically shows value it should show inside of that table.

Now apart from that I have edit and delete button and when I click edit button modal pop-ups and let’s say I’ve clicked EDIT button on first row of the table, <input> fields in modal pop-up are filled in with data from table (database) corresponding to row where edit button is clicked, except this select thing and what I am expecting that, that same value from table replicates inside of first <option value="" id="vlasnik" name="vlasnik" selected disabled hidden></option> value, so one doesn’t have to remember what was initially selected, and here is how my <select> together with <option> looks like:

        <div class="mb-3">
        <select id="vlasnik" name="vlasnik" class="form-control form-control-lg" required> 
        <option value="" id="vlasnik" name="vlasnik" selected disabled hidden></option>
        <?php foreach($users as $user): ?>
        <option value="<?= $user['id']; ?>"><?= "[" . $user['id'] . "]" . $user['username']; ?></option>
        <?php endforeach; ?>
        </select>
        </div>

And it gives me following:
What I get

Also, I must say that I am treating other input’s differently, like this (actually):

// Edit User Ajax Request
tbody.addEventListener("click", (e) => {
  if (e.target && e.target.matches("a.editLink")) {
    e.preventDefault();
    let id = e.target.getAttribute("id");
    editUser(id);
  }
});

const editUser = async (id) => {
  const data = await fetch(`action.php?edit=1&id=${id}`, {
    method: "GET",
  });
  const response = await data.json();
  document.getElementById("id").value = response.id;
  document.getElementById("make").value = response.make;
  document.getElementById("model").value = response.model;
  document.getElementById("godina").value = response.godina;
  document.getElementById("boja").value = response.boja;
  document.getElementById("vin").value = response.vin;
  document.getElementById("engine").value = response.engine;
  document.getElementById("tip").value = response.tip;
  document.getElementById("vlasnik").value = response.vlasnik;
  document.getElementById("regoz").value = response.regoz;
  document.getElementById("istek").value = response.istek;
  document.getElementById("odometer").value = response.odometer;
  document.getElementById("napomena").value = response.napomena;
  document.getElementById("carStatus").value = response.carStatus;

};

Inside of action.php I have this:

// Handle Edit User Ajax Request
if (isset($_GET['edit'])) {
    $id = $_GET['id'];

    $user = $db->readOne($id);
    echo json_encode($user);
}

And inside of db, readOne method is:

public function readOne($id)
    {
        $sql = 'SELECT * FROM vozila WHERE id = :id';
        $stmt = $this->conn->prepare($sql);
        $stmt->execute(['id' => $id]);
        $result = $stmt->fetch();
        return $result;
    }

As I said I get every other value except for option. Does anybody know what is the problem and how can I achieve what I want?

Serial communication won’t print out any results

I am pretty new to all of this and really need to get this working in time for my assessments to come around. Unfortunately, I am completely stuck. I’ve been able to make p5.js read the output of a single button and of a joystick and react accordingly, but I can’t get it to print out the value, I would be getting out of my setup.

Setup: 4 buttons, that all get checked for being on or off and a value variable that tells me if and which buttons are on and off by adding specific numbers together. (Can post the Arduino Code if necessary)

Is there any reason my Code in P5.Js isn’t working right now? (No output whatsoever from serial communication) (probs to Scott Fitzgerald for the code groundwork)

let serial; // variable for the serial object
let value = "waiting for data"; // variable to hold the data


function setup() {
  createCanvas(windowWidth, windowHeight);
  // serial constructor
  serial = new p5.SerialPort();
  // get a list of all connected serial devices
  serial.list();
  // serial port to use - you'll need to change this
  serial.open('/dev/tty.usbmodem1423201');
  // callback for when the sketchs connects to the server
  serial.on('connected', serverConnected);
  // callback to print the list of serial devices
  serial.on('list', gotList);
  // what to do when we get serial data
  serial.on('data', gotData);
  // what to do when there's an error
  serial.on('error', gotError);
  // when to do when the serial port opens
  serial.on('open', gotOpen);
  // what to do when the port closes
  serial.on('close', gotClose);
}

function serverConnected() {
  console.log("Connected to Server");
}

// list the ports
function gotList(thelist) {
  console.log("List of Serial Ports:");

  for (let i = 0; i < thelist.length; i++) {
    console.log(i + " " + thelist[i]);
  }
}

function gotOpen() {
  console.log("Serial Port is Open");
}

function gotClose() {
  console.log("Serial Port is Closed");
  value = "Serial Port is Closed";
}

function gotError(theerror) {
  console.log(theerror);
}

// when data is received in the serial buffer

function gotData() {
  let currentString = serial.readLine(); // store the data in a variable
  trim(currentString); // get rid of whitespace
  if (!currentString) return; // if there's nothing in there, ignore it
  console.log(currentString); // print it out
  value = currentString; // save it to the global variable
}

function draw() {
  background(255, 255, 255);
  fill(0, 0, 0);
  text(value, 10, 10); // print the data to the sketch

  // in this example, we are reciving a 0 and a 1
  // if the button is not pressed we get a 0
  //if (latestData == 0) {
   // ellipse(width / 2, height / 2, 100, 100);
  //} else { // if it is pressed, we get a 1
   // rectMode(CENTER);
    //rect(width / 2, height / 2, 100, 100);
  if (value == 0) {
        console.log("NO SENSOR")
    }
    // Test first bit:
    if (value % 2 == 1) {
        console.log("FIRST SENSOR")
    }
  
    // Test second bit:
    if ((value >> 1) % 2 == 1) {
        console.log("SECOND SENSOR")
    }

    if ((value >> 2) % 2 == 1) {
        console.log("THIRD SENSOR")
    }
    if ((value >> 3) % 2 == 1) {
        console.log("FOURTH SENSOR")
  }
}

How to extend an existing straight line in Three.js

I have an existing line initiated

// material
const material = new THREE.LineBasicMaterial({ color: 0xffffff });
// array of vertices
vertices.push(new THREE.Vector3(0, 0, 0));
vertices.push(new THREE.Vector3(0, 0, 5));
// 
const geometry = new THREE.BufferGeometry().setFromPoints(vertices);
const line = new THREE.Line(geometry, material);

And what I want to do is extend this line following its initiation. I’ve read this page on how to update things and I don’t think it fits this situation because instead of adding vertices to my shape, I want to move them. Then again, it’s very likely I misunderstood. I’ve tried deleting the line and then redrawing it longer, but I can’t get it to work without my browser crashing.

Returning copies of objects with the spread operator and effects on performance with Javascript

I wanted to make an object where you could not directly mutate the variables so I decided to create what is essentially a store with a reducer similar to redux. When I return the store with the get() function I am returning a copy of the store instead of the original store so it cannot be mutated directly. There are variables in the store that I want to remain untouched throughout the controller.

My question is are there any serious performance tradeoffs that I should be aware of when making a copy of the object vs returning the entire object. The get() function will be used a lot so many copies will be made.

Here is a very simple example.

const reducer = (store, action) => {
    switch(action.type) {
    case 'SET_FOO':
        return {
        ...store,
        foo: action.payload
      }
    case 'SET_BAR':
        return {
        ...store,
        bar: action.payload
      }
    default: 
        return store
  }
}



const createController = () => {
    let store = {
    foo: 'foo',
    bar: 'bar'
  }
  
  const get = () => ({...store})
  
  const dispatch = (action) => (store = reducer(store, action)) 
  
  // A bunch of other irrelevant functions here
  
  return {
    get,
    dispatch
  }
} 

As you can see in the get() function I am sending a copy of the store back instead of the actual store. This way it is impossible for the person creating the controller to mutate the store directly. If I just returned the store you could do something like the following and directly mutate the store which I am trying to avoid.

const ctl = createController()

const store = ctl.get()

store.foo = 'baz'

console.log(store.get().foo)

// result would be 'baz'

But if you send back a copy of the store then they could not directly mutate the store but instead you would have to dispatch to the reducer to mutate it. But are there any serious performance concerns that I should take in consideration here. I know adding more objects can use more memory but I don’t think it would make a huge difference.

Any insights would be appreciated. Thanks