Ajax JSON Respone took much time

First: Sorry for my Bad English. I hope you understand me anyway.

So. I have an Ajax request and the JSON file is always rewritten from somewhere else. The new data arrives but at the first change it takes 20-30 seconds until the change is visible (I think this is because of the caching, more about this below). After that, after the first request, it takes only 2 seconds or often shorter. And if I don’t change anything for a while the same process begins again.

I think it is either because of the caching or because I use a local HTTP server for the request. And this server I set up with Python, here the code from the server:

class ServerHandler(http.server.SimpleHTTPRequestHandler):

def do_GET(self):
    logging.error(self.headers)
    http.server.SimpleHTTPRequestHandler.do_GET(self)

def do_POST(self):
    logging.error(self.headers)
    form = cgi.FieldStorage(
        fp=self.rfile,
        headers=self.headers,
        environ={'REQUEST_METHOD': 'POST',
                 'CONTENT_TYPE': self.headers['Content-Type'],
                 })
    for item in form.list:
        logging.error(item)
    http.server.SimpleHTTPRequestHandler.do_GET(self)

    with open("data.txt", "w") as file:
        for key in form.keys():
            file.write(str(form.getvalue(str(key))) + ",")

def start_localhost():
Handler = ServerHandler

httpd = socketserver.TCPServer(("", 2029), Handler)

print("serving at port", 2029)
httpd.serve_forever()

And that it is the caching would also be funny, because I have the following in my head tag of the HTML file:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

What might be worth mentioning, I have this html file open in an Edge WebView window.

And here is my JavaScript Code:

          var cur_width;
      var cur_height;
      var cur_pos;
      var cur_right;
      var cur_bottom;
      var cur_brightness;
      var cur_blur;
      var cur_zoom;
      var cur_contrast;
      var cur_invert;
      var cur_sepia;
      var cur_saturate;
      var cur_grayscale;

      function checker() {
        vid = document.getElementById("bg_div");
        $.ajax({
                type: "GET",
                url: 'http://localhost:2029/backgrounds/asus/video_settings.json',
                contentType: "application/json",
                dataType: "json",
                success: function(json_infos) {

          var width = json_infos.width;
          var height = json_infos.height;
          var pos = json_infos.position;
          var right = json_infos.right;
          var bottom = json_infos.bottom;
          var blur = json_infos.blur;
          var brightness = json_infos.brightness;
          var zoom = json_infos.zoom;
          var contrast = json_infos.contrast;
          var invert = json_infos.invert;
          var sepia = json_infos.sepia;
          var saturate = json_infos.saturate;
          var grayscale = json_infos.grayscale;

          var new_filter = "brightness("+brightness+") blur("+blur+") contrast("+contrast+") invert("+invert+") sepia("+sepia+") saturate("+saturate+") grayscale("+grayscale+")";

          if(width != cur_width) {
          cur_width = width;
          vid.style.width = width;
          }

          if(cur_pos != pos) {
          cur_pos = pos;
          vid.style.position = pos;
          }

          if(cur_height != height) {
          cur_height = height;
          vid.style.height = height;
          }

          if(cur_right != right) {
          cur_right = right;
          vid.style.right = right;
          }

          if(cur_bottom != bottom) {
          cur_bottom = bottom;
          vid.style.bottom = bottom;
          }

          if(cur_brightness != brightness) {
          cur_brightness = brightness;
          vid.style.filter = new_filter;
          }

          if(cur_blur != blur) {
          cur_blur = blur;
          vid.style.filter = new_filter;
          }

          if(cur_zoom != zoom) {
          cur_zoom = zoom;
          vid.style.transform = zoom;
          }

          if(cur_contrast != contrast) {
          cur_contrast = contrast;
          vid.style.filter = new_filter;
          }

          if(cur_invert != invert) {
          cur_invert = invert;
          vid.style.filter = new_filter;
          }

          if(cur_sepia != sepia) {
          cur_sepia = sepia;
          vid.style.filter = new_filter;
          }

          if(cur_saturate != saturate) {
          cur_saturate = saturate;
          vid.style.filter = new_filter;
          }

          if(cur_grayscale != grayscale) {
          cur_grayscale = grayscale;
          vid.style.filter = new_filter;
          }
        }
        
      });
      }

      checker();
      var t = setInterval(checker, 400);

How to make a flow in directus with the following function

I have a custom (coded) hook that works like:

  • a collection is updated
  • is it the collection “events”?
  • is one of the updated fields one of these: time_show_start, time_show_end, …
  • get all contacts from a collection who want to recieve mails
  • send a mail to these contacts with some info about the event (icluding old and new times)

it should look something like this, but i just can’t get it to work
enter image description here


module.exports = function registerHook({ action }, { services, exceptions }) {
  const { MailService, ItemsService } = services;
  const { ServiceUnavailableException, ForbiddenException } = exceptions;

  // Send mail to admin when event time is updated
  action('items.update', async ({ keys, collection, payload }, { schema, accountability }) => {
    if (collection !== 'events') return;
    if (
      !payload.time_get_in &&
      !payload.time_setup_start &&
      !payload.time_setup_end &&
      !payload.time_soundcheck_start &&
      !payload.time_soundcheck_end &&
      !payload.time_dinner &&
      !payload.time_doors &&
      !payload.time_show_start &&
      !payload.time_show_end &&
      !payload.time_curfew_live_music &&
      !payload.time_curfew_guests
    ) {
      return;
    }

    const eventsService = new ItemsService('events', { accountability: accountability, schema: schema });
    const contactsService = new ItemsService('contacts', { accountability: accountability, schema: schema });
    const mailService = new MailService({ schema });

    const contacts = await contactsService.readByQuery({ filter: { getsmailon_eventtimechange: { _eq: true } } });

    contacts.forEach(async (contact) => {
      keys.forEach(async (el) => {
        // get event
        let event = null;
        try {
          event = await eventsService.readOne(el, { fields: ['*'] });
        } catch (error) {
          console.error(error);
          throw new ServiceUnavailableException(error);
        }

        // send mail
        try {
          await mailService.send({
            to: contact.email,
            subject: 'Zeit der Veranstaltung ' + event.name + ' geändert',
            text: 'Zeit der Veranstaltung <b>' + event.name + '</b> geändert',
            template: {
              name: 'event-time-update',
              data: {
                collection: collection,
                event: event,
                payload: payload,
              },
            },
          });
          console.log('mail sent for event', event.id);
        } catch (error) {
          console.error(error);
          throw new ServiceUnavailableException(error);
        }
      });
    });

    return;
  });
};

Merge duplicates in array of objects and mutate some properties javascript

I have this complex scenario in which I need to find duplicates in an array of objects, and merge them mutating some property values.

The data comes from an excel file which has reservations for an hotel, each reservation has a reservationNumber which is unique, when the array contains 2 or more reservations with the same reservationNumber it means that it’s the same reservation but with multiple rooms, so I need them to be merged, but the first item should remain as the roomNumber (which is the main room) and the rest of the duplicates should aggregate to extra_rooms (which is a simple array containing the remaining room numbers, excluding the main room); Also it needs to aggregate to extraRoomsAges property with the following structure:

extraRoomsAges: [
   {
     room: 34, // We get this from the roomNumber property
     // We get this from the mainRoomDistribution property
     adults: 0,
     infants: 0,
   },
],

So to get a wider view of the problem this is an example of the data I need to process:

const data = [
  {
    reservationNumber: 'RX-0032466',
    fullName: 'John Doe',
    firstName: 'John',
    lastName: 'Doe',
    documentType: 'dni',
    hotel: 'hpp',
    documentID: null,
    extra_rooms: [],
    extraRoomsAges: [],
    mainRoomDistribution: {
      adults: 2,
      infants: 0,
    },
    totalCharges: 1754.28,
    agencyCode: 5,
    roomNumber: '63',
  },
  {
    reservationNumber: 'RX-0032466',
    fullName: 'John Doe',
    firstName: 'John',
    lastName: 'Doe',
    documentType: 'dni',
    hotel: 'hpp',
    documentID: null,
    extra_rooms: [],
    extraRoomsAges: [],
    mainRoomDistribution: {
      adults: 3,
      infants: 1,
    },
    totalCharges: 1954.49,
    agencyCode: 5,
    roomNumber: '64',
  },
  {
    reservationNumber: 'RX-0032466',
    fullName: 'John Doe',
    firstName: 'John',
    lastName: 'Doe',
    documentType: 'dni',
    hotel: 'hpp',
    documentID: null,
    extra_rooms: [],
    extraRoomsAges: [],
    mainRoomDistribution: {
      adults: 1,
      infants: 0,
    },
    totalCharges: 850.30,
    agencyCode: 5,
    roomNumber: '65',
  },
  {
    reservationNumber: 'RX-0032494',
    fullName: 'Jane Foster',
    firstName: 'Jane',
    lastName: 'Foster',
    documentType: 'dni',
    hotel: 'hpp',
    documentID: '123456789',
    extra_rooms: [],
    extraRoomsAges: [],
    mainRoomDistribution: {
      adults: 4,
      infants: 0,
    },
    totalCharges: 1540,
    agencyCode: 13,
    roomNumber: '40',
  },
]

The result should look like this:

  [
    {
      reservationNumber: 'RX-0032466',
      fullName: 'John Doe',
      firstName: 'John',
      lastName: 'Doe',
      documentType: 'dni',
      hotel: 'hpp',
      documentID: null,
      extra_rooms: [64, 65], // aggregates the remaining occurrences from the roomNumber property
      extraRoomsAges: [
        {
          room: 64,
          adults: 3,
          infants: 1
        },
        {
          room: 65,
          adults: 1,
          infants: 0,
        }
      ],
      mainRoomDistribution: {
        adults: 2,
        infants: 0,
      },
      totalCharges: 4559.07, //the sum of all the occurrences
      agencyCode: 5,
      roomNumber: '63', //remains as the main room from the first occurrence
    },
    {
      reservationNumber: 'RX-0032494',
      fullName: 'Jane Foster',
      firstName: 'Jane',
      lastName: 'Foster',
      documentType: 'dni',
      hotel: 'hpp',
      documentID: null,
      extra_rooms: [],
      extraRoomsAges: [],
      mainRoomDistribution: {
        adults: 4,
        infants: 0,
      },
      totalCharges: 1540,
      agencyCode: 13,
      roomNumber: '40',
    },
  ]

So far I’ve tried with this function to merge duplicates:

export function mergeObjectsInUnique<T>(array: T[], property: any): T[] {
  const newArray = new Map();
  array.forEach((item: T) => {
    const propertyValue = item[property];
    newArray.has(propertyValue)
      ? newArray.set(propertyValue, { ...item, ...newArray.get(propertyValue) })
      : newArray.set(propertyValue, item);
  });

  return Array.from(newArray.values());
}

console.log(mergeObjectsInUnique(data, 'reservationNumber'))

As you can see this merges the duplicates correctly, but I just can’t find a way to mutate the data properly as I need it.

Here is a JSFiddle to play around:

https://jsfiddle.net/ou036zwv/

I’d appreciate an explanation with the answer if possible.

Thanks in advance.

How do I save a modified style on Chrome?

So, totally noob question here, but I hope you can help. I work on a tool called SRT, it is from Facebook and it is used for rating content. The page shows me 9 images I need to judge, but they are displayed on 3 rows and 3 columns, but it would work better if it was 5 rows and 2 columns, because the images would be bigger. I asked Facebook to make this change, but who knows when will they actually do something. So I modified the look of the page on the browser console. It was like this:

<div style="display: grid; grid-template-columns: repeat(3, 500px); grid-template-rows: repeat(3, 500px); gap: 60px; height: 100%; margin: 0px;"><div

And I changed to this:

<div style="display: grid; grid-template-columns: repeat(2, 500px); grid-template-rows: repeat(5, 500px); gap: 60px; height: 100%; margin: 0px;"><div

But, every time I go to the next page, it comes back to the previous look, because it is not a permanent change. Is there a way to save this style so, for this page, I will always have this appearance?

Why is my context variable is not changing?

I’m starting to learn React, and I’m breaking my head with a simple problem.

I’ve created a context variable, to store my authentication state, however the value of isAuthenticated is not been updated by setIsAuthenticated as follows:

auth.js

import { createContext, useState } from 'react';

const MyContext = createContext();

function AuthProvider({ children }){
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  async function handleLogin(value){
    setIsAuthenticated(value);
  }
  return (
    <MyContext.Provider value={{ isAuthenticated, handleLogin}}>
      { children }
    </MyContext.Provider>
  )
}

export { MyContext, AuthProvider };

Login.js

const onSubmit = (event) => {
    event.preventDefault();

    const userData = {
        Username: email,
        Pool: UserPool
    };


    const cognitoUser = new CognitoUser( userData );
    const authenticationData = {
        Username: email,
        Password: password
    };
    var authenticationDetails = new AuthenticationDetails( authenticationData );

    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: result => {
            handleLogin(true);
        },
        onFailure: err => {
            handleLogin(false);
        }
    });
}

When I call onSucess or onFailure, the handleLogin function is not changing isAuthenticated, but handleLogin function is invoked.

Why setIsAuthenticated is not changing the value?

How can I use the fetch API instead of XMLhttprequest?

We have a chrome extension that’s been working fine with manifest V2, which we’ve recently tried to migrate to manifest v3 (https://developer.chrome.com/docs/extensions/mv3/intro/). However, I have a single issue, How can I migrate manifest V2 to 3, and we this code I am getting the error of XMLHttpRequest is not defined and uncaught in promise error.

       function HttpRequest(url) {
return new Promise(function(resolve, reject) {

    var badgeText = new String();
    var badgeColor = new String();
    chrome.action.getBadgeText({}, function(result) {badgeText = result;});
    chrome.action.getBadgeBackgroundColor({}, function(result) {badgeColor = result;});
    chrome.action.setBadgeText({text: 'GET'});
    chrome.action.setBadgeBackgroundColor({color: '#3070c0'});

    var req = new XMLHttpRequest();
    req.open('GET', url, true);
    req.timeout = 5000;

    req.onload = function() {
        chrome.action.setBadgeText({text: badgeText});
        chrome.action.setBadgeBackgroundColor({color: badgeColor});
        if (req.status == 200) {
            resolve(req.response);
        }
        else {
            reject(Error(req.statusText));
        }
    };

    req.onerror = function() {
        chrome.action.setBadgeText({text: badgeText});
        chrome.action.setBadgeBackgroundColor({color: badgeColor});
        reject(Error("Unspecified Network Error"));
    };

    req.ontimeout = function() {
        chrome.action.setBadgeText({text: badgeText});
        chrome.action.setBadgeBackgroundColor({color: badgeColor});
        reject(Error("Timeout Error"));
    };

    req.send();

});


 }

// check connection
function checkConnection() {
    return new Promise((resolve, reject) => {
        HttpRequest('http://' + this.fxIP + '/deviceinfo').then(function(response) {
            chrome.action.setBadgeText({text: 'ON'});
            chrome.action.setBadgeBackgroundColor({color: '#70c070'});
            resolve(response);
        }).catch(function(error) {
            chrome.action.setBadgeText({text: 'OFF'});
            chrome.action.setBadgeBackgroundColor({color: '#707070'}); 
            reject(error.toString());
        });
    });
};

// retrieve report
function retrieveReport(serialNumber) {
    return new Promise((resolve, reject) => {
        retrieveReports().then(response => {
            var matchedReports = [];
            try {
                var reports = JSON.parse(response);
            }
            catch (e) {
                reject(e.message);
            }
            reports.forEach(function(report) {
                if (report.snapshot.tags['LM_Pro!PRO_MTR_SERIALNR'].v === serialNumber) {
                    //return resolve(JSON.stringify(report));
                    matchedReports.push(report);
                }
            });
            if (matchedReports.length === 0) {
                reject('S/N not found')
            }
            else {
                resolve(JSON.stringify(matchedReports));
            }
        }).catch(error => {
            reject(error.toString());
        });
    });
}

function retrieveReports() {

    return new Promise((resolve, reject) => {

        let url = 'http://' + this.fxIP + '/snapshots' +
        '?archive=' + this.fxArchive +
        '&count=' + this.fxLogs +
        '&ascending=0' +
        '&type=jsonstream';

        HttpRequest(url).then(function(response) {
            resolve(response);
        }).catch(function(error) {
            reject(error.toString());
        });
    });
}

How to place Glass over the rock?

I am trying to responsive the glass with rock using some custom javascript and TailwindCss. I need to place the glass over the rock on all breakpoints.

Code:

 <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="https://cdn.tailwindcss.com"></script>
    </head>
    
        <body>       
            <div>
                <div class="text-center relative">
                    <div class="mx-auto w-48 h-auto mb-2 relative mb-4 shadow-inset ">
                        <img src="https://i.ibb.co/qjqqmQ0/glass-7-web-removebg-preview-2.png" class="glass_icon object-cover w-full h-96" alt="">
                    </div>
                </div>
            </div>
        </body>
        <script>
            const body = document.querySelector("body");
            body.style.background = `url('https://harvest-selection.netlify.app/assets/background/In-Woods.gif') no-repeat fixed 50% 100%`;
    
            body.style.cssText += `background-size: cover;height:100vh`;
        </script>
    </html>

directUploadWillStoreFileWithXHR is not firing for DirectUpload

I am using rails activestorage

import { DirectUpload } from "@rails/activestorage";

start() {
  this.source.fileUploader = this;
  this.hiddenInput = this.createHiddenInput();
  this.directUpload.create((error, attributes) => {
    if (error) {
      this.hiddenInput?.parentNode?.removeChild(this.hiddenInput);
      this.emitDropzoneError(error);
    } else {
      this.hiddenInput.value = attributes.signed_id;
      this.emitDropzoneSuccess();
    }
  });
}

directUploadWillStoreFileWithXHR(xhr) {
  this.bindProgressEvent(xhr);
  this.emitDropzoneUploading();
}

When I call start it works as expected, but the callback directUploadWillStoreFileWithXHR is not triggering.

All JSON values are undefined

I am currently working on a app that allow me to order some products from a bar, in order to do the order i created a JSON file to pass all the data

Product Screen Code

let keyNum = 1;
let dt = {order: []};

const createTwoButtonAlert = ({item}) => {
        console.warn(item)
            Alert.alert(
                "Warning",
                "your product has been added to the cart",
                [
                    {
                        text: "Continue",
                        onPress: () => {
                            dt.order.push({
                                key: String(keyNum),
                                produtoId: item.produtoId,
                                produtoNome: item.produtoNome,
                                produtoPreco: item.produtoPreco,
                                produtoImagem: item.produtoImagem,
                            });

                            ++keyNum;

                        },
                        style: "cancel"
                    },
                    {
                        text: "Finish Order",
                        onPress: () => {

                            dt.order.push({
                                key: JSON.stringify(keyNum),
                                produtoId: item.produtoId,
                                produtoNome: item.produtoNome,
                                produtoPreco: item.produtoPreco,
                                produtoImagem: item.produtoImagem,
                            });

                            json = dt

                            dt = {order: []};
                            keyNum = 1;

                            navigation.navigate('CartScreen', {
                                json: JSON.stringify(json)
                            });


                        }
                    }
                ]
            );

        };

CartScreen Code

export function CartScreen({route,navigation}) {
    let aux;
    if(route.params === undefined){
        aux = undefined;
    }else{
        aux = route.params.json;
    }
    console.warn('HEYYYYYYYYY'+ aux);

    return(
            <View>
                <FlatList
                    data={[cart]}
                    keyExtractor={({key}) => key}
                    renderItem={({item}) => (
                        <CartProductCard
                            key={item}
                            product={item}
                            setCart={item}
                            onPress={() => {
                                alert(item)
                            }
                            }
                        />
                    )}
                />
            </View>
    )
}

console

HEYYYYYYYYY{"encomenda":[{"key":"1","produtoId":"3","produtoNome":"Compal Uva","produtoPreco":"1.5"}]}

CartProductCard Code

export function CartProductCard({product, onPress}) {
    console.warn('CartProductCard '+ product);
    return (
        <Card key={product.key} style={styles.card} onPress={onPress}>
            <View style={styles.infoContainer}>
                <Text style={styles.name}>{product.produtoNome}</Text>
                <Text style={styles.price}>{product.produtoPreco}€</Text>
            </View>
        </Card>
    );
}

console

CartProductCard {"encomenda":[{"key":"1","produtoId":"3","produtoNome":"Compal Uva","produtoPreco":"1.5"},{"key":"2","produtoId":"4","produtoNome":"Agua 1.5L","produtoPreco":"1.2"}]}

Now the part that i dont understand is why i cant get the value from a specific param, if i try to get aux.produtoNome it returns undefined, the same goes to every other param.

If anyone could help i would appreciate

JSON group elements by value

Good morning,

I’m trying to create a JSON file with all Portuguese parishes inserted in each municipality that is inserted in each respective district – so it’s a pretty basic structure,

The structure I intend to have is as follows:

{
  "district": "Aveiro",
  "OfficialCodeDistrict": "01",
  "municipalities": [
    {
      "municipality": "Arouca",
      "OfficialCodeMunicipality": "0104",
      "parishes": [
        {
          "parish": "Fermedo",
          "OfficialCodeParish": {}
        },
        {
          "parish": "Várzea",
          "OfficialCodeParish": "010420"
        },
        {
          "parish": "Escariz",
          "OfficialCodeParish": "010409"
        },
        {
          "parish": "Mansores",
          "OfficialCodeParish": "010413"
        }
      ]
    },
    {
      "municipality": "Águeda",
      "OfficialCodeMunicipality": "0101",
      "parishes": [
        {
          "parish": "Fermentelos",
          "OfficialCodeParish": "010109"
        },
        {
          "parish": "Préstimo e Macieira de Alcoba",
          "OfficialCodeParish": "010127"
        }
      ]
    }
  ]
}

So each district contains all municipalities which, within each municipality, we have all parishes.

I started working on top of a JSON that was a result of an Excel export which can be found here

Upon reading this question (https://stackoverflow.com/a/54756327) I was able to to transform my JSON to group municipalities inside each district, as you can see in the image below:

JSON Output

The only problem here is that I still need to make a second grouping which is grouping municipalities within each district – as you can see in the image, I’m displaying two results where the parishes are both from the Vale de Cambra municipality whereas I’d like to have each municipality contain all parishes in the same way the districts are holding all results per district.

This is the code that allowed me to group the districts (which has the same format as the StackOverflow question I pasted above)

const result = Object.entries(locations.reduce((acc, { OfficialCodeDistrict, OfficialNameDistrict, OfficialCodeMunicipality, OfficialNameMunicipality, OfficialNameParish, Type  }) => {
        acc[OfficialNameDistrict] = (acc[OfficialNameDistrict] || []);
        acc[OfficialNameDistrict].push({ OfficialCodeDistrict, OfficialCodeMunicipality, OfficialNameMunicipality, OfficialNameParish, Type });
        return acc;
    }, {})).map(([key, value]) => ({ district: key, municipalities: value }));

    console.log(result);

And I’ve tried doing some sort of a loop (this may look super wrong but I’m still learning on how to manipulate objects in JavaScript) to try to loop the municipalities with the same name within each district

let counter = 0;

// I'm going to create a loop to see if I can access all municipalities and them with the method above
while (counter < result.length){

    // Iterating each district on the console - this way we can access each one to make the changes above, I'm hoping
    result2 = Object.entries(result[counter]['municipalities'].reduce((acc, { OfficialCodeMunicipality, OfficialNameMunicipality, OfficialNameParish, Type  }) => {
        acc[OfficialNameMunicipality] = (acc[OfficialNameMunicipality] || []);
        acc[OfficialNameMunicipality].push({ OfficialCodeMunicipality, OfficialNameParish, Type });
        return acc;
    }, {})).map(([key, value]) => ({ municipality: key, parishes: value }));

    console.log(result2);

    // I'm being able to loop the municipalities but what is happening is, it's iterating one JSON object per district
    // example: Portalegre is generating a JSON object with 15 entries and every other district is doing the same, we're on the good but still not working

    counter++;
}

Which is iterating and creating one JSON object per district with its respective municipalities – so it is working well but I don’t know how to push these results to the first object I created in order to have everything organized

Output Per District

Can you help me in arranging the JSON object the way I want it? I know (or it seems like it, at least) there’s only a simple step missing somewhere for me to be able to push these individual iterations into the original object, into each district, but I’m kind of clueless, right now,

Thank you very much in advance!