Chrome extention to MySQL

I am currently making a Chrome extention, where I can input my current mood and it should write my mood in my MySQL Database. I have the GUI all set up, but now only the backend part is missing. I know how to make it in PHP, but since a Chrome extention is on the client site. PHP isn’t a choise. So I made a PHP script, which updates the DB acording to the input its given. But how can I “Send” the Button clicks to the PHP server? I tried it with AJAX but with no success.

This is the html code for the buttons:

<div id="buttons">
                <input type="button" id="bad" value="bad"></button>
                <input type="button" id="normal" value="normal"></button>
                <input type="button" id="great" value="great"></button>
            </div>

And this is the js code for one button(I dont think I have to send all three here):

document.getElementById("normal").addEventListener("click", function() {
  xhr.send("feeling=normal")
  if (xhr.status === 200) {
    alert(xhr.responseText);
  } else {
    alert('Request failed.  Returned status of ' + xhr.status);
  }

  alert("Thank you for your feedback");
});

And this is my PHP script:

<?php
if (isSet($_POST['feeling'])) {
    $con = mysqli_connect('localhost', 'NoUsernameNamed', 'YouWontGetMyPassword', 'JustADatabase');
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    else {
        echo "Connected to Server";
    }
    $stmt = mysqli_prepare($con, 'INSERT INTO moods VALUES (?)');
    mysqli_stmt_bind_param($stmt, 'i', $_POST['feeling']);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
    mysqli_close($con);
}
?>

When I click one of the tree Buttons, then the Database should Add the mood(Can be stored as an INT(bad=1,normal=2, great=3) or as a String)

Loop Scroll WordPress Elementor

I found some interesting code here https://codepen.io/rileyjshaw/pen/nLqgpx which will loop the page when scrolling.

But incorporated in my website it works when scrolling down, but when i scroll up it doesn’t jump back to the bottom of the page, to make it seem like a loop.

See page for example: https://www.moschalkx.com/test/

I’m not at all experienced with Java so i used to code as is:

var docHeight = 9999,
  windowHeight = -1,
  thisY = 0,        
  lastY = 0,
  blocker = true,
  IE = document.all?true:false;

setDocHeight = function() {
  var d = document;
  window.setTimeout(function() {
    docHeight = Math.max(
      Math.max(d.body.scrollHeight, d.documentElement.scrollHeight),
      Math.max(d.body.offsetHeight, d.documentElement.offsetHeight),
      Math.max(d.body.clientHeight, d.documentElement.clientHeight))
  }, 0);
}
setWindowHeight = function() {
  window.setTimeout(function() {
    if (document.body && document.body.offsetWidth)
      windowHeight = document.body.offsetHeight;
    if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth )
      windowHeight = document.documentElement.offsetHeight;
    if (window.innerHeight && window.innerWidth)
      windowHeight = window.innerHeight;
  }, 0);
}
getYPosition = function() {
  if (self.pageYOffset) return self.pageYOffset;
  if (document.documentElement && document.documentElement.scrollTop)
    return document.documentElement.scrollTop;
  if (document.body.scrollTop) return document.body.scrollTop;
    return 0;
}
infiniteScroll = function() {
  thisY = getYPosition();

  if(thisY != lastY && blocker) 
    blocker = false;

  lastY = thisY;

  if(!blocker) {
    if(windowHeight + thisY >= docHeight) {
      blocker = true;
      window.scroll(0, 0);
      lastY = 0;
    } else if(thisY === 0) {
      blocker = true;
      window.scroll(0, windowHeight);
      lastY = windowHeight;
    }   
  }
}
initialize = function() {
  setDocHeight();
  setWindowHeight();
  setInterval("infiniteScroll()", 1);
}

if(IE) {
  window.attachEvent('onresize', setWindowHeight);
  window.attachEvent('onload', initialize);
} else {
  window.addEventListener('resize', setWindowHeight, false);
  window.addEventListener('load', initialize, false);
}

Does anyone have an idea of why it works scrolling down, but not upwards?

Using chrome.declarativeNetRequest to update the First Document (HTML) Fetch request call

We have an array of tab ids stored in chrome storage, using those I wanted to modify the user-agent of the First Document Fetch call on a webPage of those tabs.

i am using chrome.declarativeNetRequest API to dynamically update the rules with new Tab Ids whenever there is an update on any tab (chrome.tabs.onUpdated). But the first call always seems to bypass the eventListener because tabs.onUpdated are triggered after the first fetch call has been made. All the other requests after that are updated as intented. How can I modify the First request.

We previously in MV2 architecture used to do the same using chrome.webRequest.onBeforeSendHeaders event directly, but in Mv3 blocking request is not allowed.

background.js :

chrome.tabs.onUpdated.addListener(function (request, sender, callback) {
    chrome.storage.local.get(["tabs"], (tabs) => {
        const ruleId = 1;
        const rules = {
            removeRuleIds: [ruleId],
            addRules: [{
                id: ruleId,
                priority: 1,
                condition: {
                    tabIds: tabs,
                    resourceTypes: ["main_frame", "sub_frame", "xmlhttprequest"],
                },
                action: {
                    type: "modifyHeaders",
                    requestHeaders: [{
                        header: "user-agent",
                        operation: "set",
                        value: MY_USER_AGENT            
}],
                }
            }],
        };

        chrome.declarativeNetRequest.updateSessionRules(rules);
    });
});

How to filter array of objects using customized input as filters

Using a multi select dropdown where i have an array of objects where i want to filter it out based on user input such as

[{
        "ServiceArea": "NON-CIO",
        "ManagingDirector": "qwe",
        "Lead": "abc",
        "Manager": "xyz"
    },
    {
        "ServiceArea": "NON-CIO",
        "ManagingDirector": "dfg",
        "Lead": "hgf",
        "Manager": "lkj"
    },
    {
        "ServiceArea": "NON-CIO",
        "ManagingDirector": "qwe",
        "Lead": "poi",
        "Manager": "uyt"
    },
    {
        "ServiceArea": "4500-CIO",
        "ManagingDirector": "yhh",
        "Lead": "trr",
        "Manager": "nbb"
    }
]

Custom user input 1st time-

array = ["NON-CIO"]

I should be getting first three records.
Second time user inputs

array = ["dgf","qwe"]

Here i should be getting first two records.
I am using this function but it seems to append the array not replace.

//airData is main array

array.forEach((item)=>{
 var name = this.airData.filter( el=>el.ManagingDirector == item );
 this.airData.push.apply(this.finalArr,name);
});

Why an error “connect ECONNREFUSED 127.0.0.1:8080” occurs when testing firestore rules with npm

I wanted to test a firestore rule. Below is firestore.rules. I wanted to check that these security rules are valid. Then I tried to use jest and firebase testing. However when executing “npm test”, an error, “connect ECONNREFUSED 127.0.0.1:8080” occured.

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /clubUsers/{uid} {
      allow read: if request.auth != null
        && request.auth.uid == uid;
      allow create: if request.auth != null
        && request.auth.uid == uid;   
      allow update: if request.auth != null
        && request.auth.uid == uid;  
    }
  }
}

And my test script is here.

const firebase = require('@firebase/testing/');
const fs = require('fs');

const project_id = "PROJECT ID";

describe("testing firestore rules", () => {

    beforeAll(
        async () => {
            await firebase.loadFirestoreRules({
                projectId: project_id,
                rules: fs.readFileSync('../../firestore.rules', 'utf8'),
            });
        }
    );

    afterEach(
        async () => {
            await firebase.clearFirestoreData({ projectId: project_id });
        }
    );

    afterAll(
        async () => {
            await Promise.all(
                firebase.apps().map((app) => app.delete())
            );
        }
    );

    function authedApp(auth) {
        return firebase.initializeTestApp({
            projectId: project_id,
            auth: auth,
        }).firestore();
    }

    describe("testing get and write", () => {

        test("testing get", async () => {
            const db = authedApp({ uid: 'UID' });
            const message = db.collection("clubUsers").doc("UID");
            await firebase.assertSucceeds(message.get());
        })

        test("testing write", async () => {
            const db = authedApp({ uid: "UID" });
            const message = db.collection("clubUsers").doc("UID");
            await firebase.assertSucceeds(
                message.set({ text: "hoge" })
            );
        })
    })

})

I tried the test while firebase emulator is opened.

I checked what is using port 8080 by executing sudo lsof -P -i:8080 on terminal.
However, nothing has used port 8080.

Datatable column time sorting not working properly

I have primeng datatable which have sorting for each column everything was sorting fine until i formated my time column to ‘shortime’ through DatePipe and now my column is sorting wrong like this instead of normal 1-2-3…:

1:00AM
1:00PM
10:00AM
10:00PM
11:00AM
11:00PM
...

how can i fix that ? do i need some kind of custom sort ?

this is html

 <tr class="cols">
          <th pSortableColumn="time">Time <p-sortIcon field="time"></p-sortIcon>
            <p-columnFilter *ngIf="filterSwitch" display="menu" type="text" field="time"></p-columnFilter></th>
          <th pSortableColumn="temperature">Temperature <p-sortIcon field="temperature"></p-sortIcon>
...
...code

here is ts where i formatted the time

const times = historicalWeatherData.hourly.time.map((time) =>
          this.datePipe.transform(time, 'shortTime')
        );

I want use a child theme to change wordpress dashboard by code

  1. I want to customize the display of the red box and add some listening events on the green box check box.
    my want page

I try to write my own js file to control the above listening event, but my js file doesn’t work
my php code :

add_action('wp_enqueue_scripts', 'multi_child_style');
function multi_child_style(){
    wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css');
    wp_enqueue_script( 'script', get_stylesheet_directory_uri() . '/admin/script.js', array( 'jquery' ),'',true );
}

my js code


jQuery(document).ready(function () {
console.log(‘hello world’);

})

how do correct loop in loop

hi I try to do loop of array inside loop of array but the result I get is now whet I want
I have one array of books id and one array of quantity
now whet I try is foreach book in the quantity field decrease by the value in the array quantity
but whet I get is take all the quantity array sum all the values and decrease from every book

booksId = ['63761881ec1e2022c0d9e987','637e262ea6fd0c1c544e9a19','637a2798b661e13c40433698']
quantity = [ '1', '2', '1' ]

const updateQuantityBooks = async (booksId, quantity) => {
    quantity.map(async (que, i) => {
        booksId.map(async (el, i) => {
            await Book.findByIdAndUpdate(el, { $inc: { quantity: -que } }, {
                new: true,
                runValidators: true
            })
        })
    })
}

now whet happen is decrease foreach book 4 in the quantity

How to get Primereact DataTable column width after resized

I’m using Primereact DataTable component in my react project.
After resized column I’m trying to get resized width but always get initial fix width.

Initially style applied to TH element in DataTable

element.style {
  width: 150px;
  position: sticky;
 }

After column resized style applied to TH by CSS class

 .p-datatable[pr_id_1] .p-datatable-thead > tr > th:nth-child(1), .p-datatable[pr_id_1] .p- 
  datatable-tbody > tr > td:nth-child(1), .p-datatable[pr_id_1] .p-datatable-tfoot > tr > 
  td:nth-child(1) {
     flex: 1 1 498px !important;
  }

I can see updated width un Dev tool in above style but how to read it using java script code.

If anyone used primereact DatataTable please suggest me Is there any way in Primereact DataTable to get actual column width after resized.

Minimise/optimized code for toggling layers in Leaflet JS Maps

I developed a map displaying a large number of datasets (around 70 different layers at this point) using leaflet. To toggle each of these layers I am using a Javascript function and switch case within that to add/remove layers based on checkbox status. To toggle 3 layers I had to write 6 case statements (two lines of code for each layer), for 70 layers in my primary project I had to write 140 case statements. Tried different things like loops, variable switching and others to reduce this code but couldn’t crack it just wanted to know if there is an efficient way of doing this. I consciously named my layers to match the name with checkbox IDs and the argument passed when the function toggleLayer() from HTML is called to take advantage of it.

Below is a basic example of what I am doing in my primary project. Here is my HTML part of the code

<!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Simple Example</title>
      <link href="https://fonts.googleapis.com/css2?family=Nunito+Sans:wght@200&display=swap" rel="stylesheet">
      <link rel="stylesheet" 
            href="https://unpkg.com/[email protected]/dist/leaflet.css"
            integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ=="
            crossorigin=""/>
      <link rel="stylesheet" href="style.css">    
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  </head>

  <body>
      <main>
          <div class="address-list">
            <p>Use checkboxs to toggle layers</p><br>
            <div class="inputs" id="years">
              <input type="checkbox" id="layer_points_state" onclick='toggleLayer("layer_points_state")' checked="true">States<br>
              <input type="checkbox" id="layer_points_territory" onclick='toggleLayer("layer_points_territory")' checked="true">Territories<br>
              <input type="checkbox" id="layer_polygon" onclick='toggleLayer("layer_polygon")' checked="true">State Polygons
            </div>
          </div>
          <div id="map"></div>
      </main>

      <!-- Leaflet js Packages/libraries -->
      <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
              integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ=="
              crossorigin=""></script>
      <script src="./leaflet-providers.js"></script>

      <!-- data files -->
      <script src="state_points.js"></script>
      <script src="state_polygons.js"></script>
      <script src="script.js"></script>

  </body>
</html>

and JS file

var osmMapHum = L.tileLayer.provider('OpenStreetMap.HOT');
var baseMaps = {'OSM Humanitarian':osmMapHum,}
var map = L.map('map', {
    center: [-26.750867654966356, 136.22808234118338],
    zoom:4.8,
    worldCopyJump: false,
    layers:[osmMapHum]
});

// Start of States Points
function filter_state(feature){
    if (feature.properties.type === 'State')
        return true
}
var layer_points_state = new L.GeoJSON(json_state_point, {filter: filter_state}).addTo(map);
function filter_territory(feature){
  if (feature.properties.type === 'Territory')
      return true
}
var layer_points_territory = new L.GeoJSON(json_state_point, {filter: filter_territory}).addTo(map);
// Start of States Polygon
var layer_polygon = new L.GeoJSON(json_state_polygon, {}).addTo(map);

var overlayMaps = {
                    "States": layer_points_state,
                    "Territories": layer_points_territory,
                    "State Polygon": layer_polygon,
                  };

var layerControl = L.control.layers(baseMaps, overlayMaps, {collapsed:false}).addTo(map);

//toggle layers with checkbox status
function toggleLayer(layer_toggled){
  id_to_check = '#' + layer_toggled
  const cb = document.querySelector(id_to_check);  
  if (cb.checked === true){
      switch (layer_toggled){
                                  case 'layer_points_state': return map.addLayer(layer_points_state);
                                  case 'layer_points_territory': return map.addLayer(layer_points_territory);
                                  case 'layer_polygon': return map.addLayer(layer_polygon);
                            }
  }else{
      switch (layer_toggled){       
                                case 'layer_points_state': return map.removeLayer(layer_points_state);
                                case 'layer_points_territory': return map.removeLayer(layer_points_territory);
                                case 'layer_polygon': return map.removeLayer(layer_polygon);                             
                              }
  }
}

This is how the map looks

enter image description here
Thanks in advance for the suggestions

FilePond,Laravel restore uploaded temporary files on validation failure

after searching a lot here and there I am going to put my question here . If any body can help out in this regard . Let me explain the things I am working on Laravel and Filepond .
Filepond upload and revert is working perfectly but I am facing problem in restoring the file back if the validation gets failed i-e restore the file on filepond.

                
                 files: [{
                     source: 'filename', 
                     options: {
                       type: 'limbo',
                    },

                }, ],

the source is coming from laravel controller function

FilePond.setOptions({
                server: {

                    process: './filepond-upload',
                    revert: './filepond-delete',
                    restore: './filepond-restore',
                    // restore: {
                    //     url    :'./filepond-restore/?id=',
                    //     method :'GET',

                    // },
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Access-Control-Expose-Headers': 'Content-Disposition,'
                        // 'Access-Control-Expose-Headers': 'Content-Disposition',
                    }

                }

            });

but either get 302 redirection or 500 server error.
If any body have implemented such kind of functionality I ll be thankful for sharing.
Thanks in advance.
Happy Coding

I want to close the react-select menu when scrolled outside of menu list

There is a closeMenuOnScroll prop in the official react-select documentation which states the following: closeMenuOnScroll prop

However, when I set closeMenuOnScroll={() => true} prop on the component, it closes the menu even if I scroll inside of it (I can’t scroll the menu options, because it is automatically closed).
What I try to achieve is to go through (scroll) the menu items when I scroll inside the react-select component and close the menu if I scroll out of it.

Thanks.

<Select
   options={options}
   onChange={handleChange}
   closeMenuOnScroll={() => true}
/>

How can I call gmail api’s method without authentication everytime?

I want to use access token instead of authorization. I have get my token and stored it in local storage. Now I am saying, if user has token then do not need of authorization. just call the required method. But it says “API keys are not supported by this API. Expected OAuth2 access token or other authentication credentials that assert a principal. See https://cloud.google.com/docs/authentication”. How can I use access token in every Gmail method calling. Like for adding label, getting email messages in my DOM and all this stuff.
In short, I wanna get rid of every time authentication.

Cannot read properties of undefined (reading ‘call’)

If you have this error with [email protected]

this error is caused when you use the link component or image, etc. The lastest version of next ( 13.0.7 ) is inestable but you can move to the version 13.0.6 with this comands in the root of your next.js aplication ( i use pnpm but if you use another package manager like yarn or npm the comands are different):

1: pnpm remove next
2: pnpm install [email protected]
3: pnpm run dev

I dont have idea that why this is caused but this fix the error you can have with this lastest version.