polkit policy, restrict the parameters of an application when running with pkexec

I should be able to restrict the parameters when running an application without asking for password (debian 12, systemd 256, polkit 122-3).
For example:

app foo
app foo ...

should work, but

app bar
app bar ...

should be blocked.

This would be my approach, but it did not work:

polkit.addRule(function(action, subject) {
    var program = action.lookup("program");
    var args = action.lookup("command_line");

    if (action.id == "org.freedesktop.policykit.exec" &&
        subject.isInGroup("some ldap group") &&
        program == "/usr/bin/app" &&
        args[1] == "foo") {
                return polkit.Result.YES;
        }
});

Does anyone have an idea?

How to query in firebase with OR operator, whose query parameters are different?

I am trying to implement OR operator in firebase query. I searched but couldn’t find similar usage that I intend, for example this answer doesn’t apply to mine. I want all occurences to get returned in my query. I am trying to do something like this:

query(collection(db, "users"),
  where("town", "==", user.town) OR
  where("city", "==", user.city) OR
  where("country", "==", user.country), (snapshot) => { ... }

As can be seen, I am trying to return all instances, and the query parameters are not the same. Is there a way to do this in firebase?

Woocommerce – How to setup new order email distribution based upon customer country, state, and zip / postal code

I’m trying to setup a way for new orders in Woocommerce upon submission from my site to be copied on different emails based upon geographic location in addition to the admin email.

For example: For an order submitted from Alabama with a Zip Code of 35976 in the United states, it will email an individual in that region as well as the admin email as usual. This would be similar to other countries as well since we sell globally.

I’m familiar how to do this in Javascript as I’ve done it for Adobe pdf forms but I’m vaguely familiar with PHP.

I would presume, if this is possible, it would be within email-order-details.php

I have been unsuccessful trying to find a plugin to work for what we need.

Any assistance would be welcome and appreciated.

I have not attempted a solution at this time.

Regex for separating strings that include whitespace with commas [duplicate]

I’m trying to achieve something very simple. I’m writing a Tampermonkey script where I want to be able to input Test, test test, Test 1, T.est 2, te#st 3, test 4 and get as a result ["Test", "test test", "Test 1", "T.est 2", "te#st 3", "test 4"], to be used as an array. Ideally it should be compatible letters, numbers, and special characters (that aren’t commas). The result shouldn’t be ["Test", "testtest", "Test1", "T.est2", "te#st3", "test4"].

The current solution I have is

const TESTOUTPUT = 'Test, test test, Test 1, T.est 2, te#st 3, test 4'.match(/[^,s?]+/g);
console.log(TESTOUTPUT);

The output is ["Test", "test", "test", "Test", "1", "T.est", "2", "te#st", "3", "test", "4"], so it’s inserting commas after every word and erasing every whitespace between them.

Other solutions I’ve found (like this one and this one) are separating elements that don’t have any space between them before or after the commas (so their input is Test, testtest, Test1, T.est2, te#st3, test4)

How to render nodes incrementally using cytoscapejs’ layout method?

I am currently using cytoscapejs for my UI to render a graph. I have a big graph that I want to render on-demand or incrementally to avoid performance bottleneck issues. My server sends the graphs in chunks as and when requested.

What I want to do:

  1. Fetch the first chunk from the backend and render it with dagre layout or any layout that is easier for the user to understand. We can call this graph as G0
  2. Fetch the next chunk when the user requests neighbouring subgraph. (Assume that the size of the subgraph is fixed as of now) The fetched graph can be referred as G1
  3. Render G1 with respect to G0 such that the overall result is consistent and looks like as if both G1 and G0 were rendered together.

What is happening:

When I render the G1 graph using the answer given on this page: Cytoscape: apply layout only to newly added nodes
the new nodes overlap the nodes of G0. In other words, the layout function is not taking the previously rendered graph G0 into consideration.

What have I tried:

I looked around and came across this library: https://github.com/iVis-at-Bilkent/cytoscape.js-layout-utilities?tab=readme-ov-file which has been developed for the exact same purpose (incrementing layout adjustments). But when I tried this library (by referencing demo.html, I did not get the expected results. The nodes of G1 still overlap G0 nodes. Here is the snippets of my code:

  1. The api initialisation:
 api = cy.layoutUtilities({
                desiredAspectRatio: 1.0,
                polyominoGridSizeFactor: 1.0,
                utilityFunction: 1,
                componentSpacing: 80
            })
  1. Rendering the initial chunks (3 chunks):
        async function loadInitialChunks() {
            for (let i = 0; i < 3; i++) {
                // this function fetches an object containing two arrays
                // {nodes, edges} and stores it in a variable `preloadedchunks`
                await getChunk(chunkIndex++, chunkSize); 
            }
            renderChunks();
        }

        function renderChunks() {

            preloadedChunks.forEach(chunk => {
                chunk.nodes.forEach(node => {
                    cy.add({
                        group: 'nodes',
                        data: node.data,
                        position: node.position
                    });
                });
                cy.add(chunk.edges);
            });

           // This code has been referred from the demo.html file I mentioned above
           // More specifically, this code is present at line 299 in demo.html 
            var subgraphs = []
            cy.$().forEach(chunk => {
                var subgraph = {}
                subgraph.nodes = []
                subgraph.edges = []
                chunk.nodes().forEach(node => {
                    var boundingBox = node.boundingBox();
                    subgraph.nodes.push({
                        x: boundingBox.x1,
                        y: boundingBox.y1,
                        width: boundingBox.w,
                        height: boundingBox.h
                    })
                });

                chunk.edges().forEach(edge => {
                    subgraph.edges.push({
                        startX: edge.sourceEndpoint().x,
                        startY: edge.sourceEndpoint().y,
                        endX: edge.targetEndpoint().x,
                        endY: edge.targetEndpoint().y
                    })
                });
                subgraphs.push(subgraph);
            })

            var result = api.packComponents(subgraphs, true);
            cy.$().forEach((component, index) => {
                component.nodes().layout({
                    name: 'fcose',
                    animate: 'true',
                    fit: false,
                    transform: (node) => {
                        let position = {};
                        position.x = node.position('x') + result.shifts[index].dx;
                        position.y = node.position('y') + result.shifts[index].dy;
                        return position;
                    }
                }).run();
            });

            let currentZoom = cy.zoom();
            let currentPan = cy.pan();

            const layout = cy.layout({
                name: 'fcose',
                avoidOverlap: true,
                nodeDimensionsIncludeLabels: true
            });
            layout.run();

        }    

  1. Requesting additional chunks:
function renderAdditionalChunks(chunk, chunkIndex) {
            try {
                // This approach is given at line #398 in the demo.html file
                var newNodes = cy.collection();
                chunk.nodes.forEach(node => {
                    if (!loadedNodes.has(node.data.id)) {
                        node.data.chunkId = chunkIndex
                        var newEles = cy.add({
                            group: 'nodes',
                            data: node.data,
                        });
                        newNodes.merge(newEles.nodes());
                        loadedNodes.add(node.data.id);

                    }
                });

                chunk.edges.forEach(edge => {
                    edge.data.chunkId = chunkIndex
                    cy.add({
                        group: 'edges',
                        data: edge.data,

                    });
                });
                let elementF = cy.elements("node[chunkId=" + chunkIndex + "],edge[chunkId=" + chunkIndex + "]");
                console.log("Elements filtered out: ", elementF)

                elementF.layout({
                    name: 'fcose',
                    // fit: false,
                    animate: true,
                    avoidOverlap: true,
                    nodeDimensionsIncludeLabels: true
                }).run();

                api.placeNewNodes(newNodes);

                cy.zoom(currentZoom);
                cy.pan(currentPan);

            } catch (error) {
                console.log(chunk)
                console.error('Error:', error);
            }

        }

It would be really great if anyone can help me figure out what am I missing here or if there are any other better alternatives to do so. Thanks.

File upload service with moleculer

I have a service file, and I’m sending a file to the http://localhost:4000/uploads URL using the “file” field via POST in Postman. However, in my code, context.meta.$multipart is coming out as undefined, and the file is not being saved to the public directory.

api.service
`

const ApiGateway = require("moleculer-web");

module.exports = {
  name: "api",
  version: 1,
  mixins: [ApiGateway],

  settings: {
    port: 8080,
    path: "/upload",
    routes: [
      {
        path: "",
 
        bodyParsers: {
          json: false,
          urlencoded: false
        },

        mappingPolicy: "restrict",
        aliases: {
         
          "POST /multi": {
            type: "multipart",
            // Action level busboy config
            busboyConfig: {
              limits: {
                files: 3
              }
            },
            action: "v1.assets.upload"
          },
          // File upload from HTML multipart form
          "POST /": "multipart:v1.assets.upload",

          // File upload from AJAX or cURL
          "PUT /": "stream:v1.assets.upload"
        },
        // Route level busboy config.
    
        busboyConfig: {
          limits: {
            files: 1
          }
        }
      }
    ],

    assets: {
      folder: "./public"
    }
  }
};

`

assets.service.js
`

module.exports = {
    name: "assets",
    version: 1,
    actions: {
      upload: {
        handler(context) {
          console.log("params", context.params.meta);
          console.log("context.meta.$multipart", context.meta.$multipart);
        }
      }
    }
  };

`

I tried both POST and PUT, and even tested it by creating a website, but I still couldn’t resolve the error. It returns 200 OK in Postman, but the file is not uploaded, and both console.log statements in the assets.service.js file are returning undefined.

getCSSProperty returns different values each time I run autotest

Here’s my code:

async $checkCSSProperty(getElement, cssProperty, expectedValue) {
  const element = await handleLocator(getElement);
  const value = await element.getCSSProperty(cssProperty);
  await expect(value.value).toBe(expectedValue);
}

await assertions.$checkCSSProperty(PassportPage.dateOfIssue, 'border', '1px solid rgb(250, 85, 85)');

Every time I run autotest, it returns the different value of border. Why do this happen and how to fix it?
When I run test I see that the color of the border matches the color I set in assertion, but it returns different color.

I tried to change function to

async $haveAttr(getElement, attr, attrValue) {
  const element = await handleLocator(getElement);
  await expect(element).toHaveAttr(attr, attrValue);
}

It returns null.

react google maps clustering for one marker

I faced a problem using a @googlemaps/markerclusterer and @vis.gl/react-google-maps libraries that I cant cluster only one marker no matter what approach I used. Right now clustering part looks like this:

  useEffect(() => {
    if (!map) return;

    clusterer.current = new MarkerClusterer({
      map,
      markers: [],
      algorithm: new SuperClusterAlgorithm({
        minPoints: 1,
      }),
    });

    return () => {
      if (clusterer.current) {
        clusterer.current.clearMarkers();
        clusterer.current = null;
      }
    };
  }, [map]);

  const memoizedMarkers = useMemo(() => markers, [markers]);

  useEffect(() => {
    if (!clusterer.current || !map) return;

    const markerElements = Object.values(markersRef.current);
    clusterer.current.clearMarkers();
    clusterer.current.addMarkers(markerElements);
  }, [map, memoizedMarkers]);

Can someone help me please to find a way how to cluster only one marker.

I went to documentation and havent found the correct answer, I tried:

  clusterer.current = new MarkerClusterer({
    map,
    markers: [],
    algorithm: new SuperClusterAlgorithm({
      minPoints: 2, // Changed from 1 to 2
    }),
  });

but it didnt work

Why can component names in Vue only be shadowed by non-default exports?

I have a simple App, that only renders my TestComp. In the setup context of App.vue, there is also a ref called testComp. Even though I am not using the recommended Template Expression of <TestComp /> (and instead <test-comp />), everything renders fine.

<!-- App.vue -->

<script setup>
import { ref } from 'vue'
import TestComp from './TestComp.vue'

const testComp = ref(null)

</script>

<template>
  <div>
    <test-comp />
    <!-- Recommended is <TestComp />, and this avoids the issue, but not the focus here -->
  </div>
</template>
<!-- TestComp.vue -->
<script setup>

</script>
<template>
  <div>
    I am a test component.
  </div>
</template>
// components.ts
import TestComp from './TestComp.vue'
// supposed to group multiple component definitions together
export {
  TestComp
}

Vue SFC Playground

So the Template Expression <test-comp /> is evaluated as the imported component TestComp and not my variable testComp.

Instead of importing TestComp directly, we can use a file that is grouping my component definitions by importing and re-exporting them in an object. We can achieve that by replacing the import:

from: import TestComp from './TestComp.vue'

to: import { TestComp } from './components.ts'.

Now the Template Expression <test-comp /> seems to be evaluated to the ref testComp, and I get a warning: [Vue warn]: Invalid vnode type when creating vnode: null – the component is not rendered.


Why is there a difference between TestComp being imported directly, and being part of another files non-default export?

how to detect click in dom programatically [closed]

I have an input field with an onBlur event that triggers a temp() method when the user leaves the field. There’s also a Save button, and when the Save button is clicked manually, the input field loses focus (triggers blur) automatically, which calls the temp() method, followed by the Save operation.

However, when using a keyboard shortcut, I cannot call the Save method directly. Instead, I have to simulate a button click programmatically. In this case, the input field does not lose focus, so the onBlur event is not triggered, and the temp() method doesn’t execute. How can I ensure the onBlur event is triggered when the Save button is clicked programmatically via a keyboard shortcut?
in angular

i only tried this way

Issues with Handling setupIntervalButton() in refreshFetch() Function for Weather Map API

I’m currently working on a weather map API and encountering an issue with my setupIntervalButton() function when trying to use it in the refreshFetch() function. Specifically, I’m having trouble ensuring that the button is properly rendered and the interval is correctly set up before the refreshFetch() function is executed.

Here’s the code for setupIntervalButton():

function setupIntervalButton(input,select,button){
    console.log('Setting up event listener'); // Debugging line
    console.log('Button element inside setup:', button); // Debugging line
    
    button.addEventListener('click', () =>{
        const intervalValue = input.value;
        const selectedInterval = select.value

        if (!intervalValue && !selectedInterval) {
            alert("Please provide numeric value and select interval type");
        } else if (!intervalValue) {
            alert("Please provide numeric value for interval");
        } else if (!selectedInterval) {
            alert("Please select interval type");
        } else{
            console.log(`Interval set to ${intervalValue} ${selectedInterval}`);
            
        }

        if(selectedInterval === "Seconds"){
            console.log(intervalValue)
            return intervalValue * 1000
        }
        else if(selectedInterval === "Minutes"){
            console.log(intervalValue)
            return intervalValue * 60000
        }
        else if(selectedInterval === "Hours"){
            console.log(intervalValue)
            return intervalValue * 60 * 60 * 1000
        }else{
            return intervalValue * 1000
        }

    })
}
function refreshFetch(){
    window.setInterval(() =>{
        fetchData()
        console.log('url fetched')
    },setupIntervalButton())

}

Issue: The main problem is that setupIntervalButton() is not rendering the button before the refreshFetch() function is executed. Consequently, the interval is not being set correctly.

You can see the JS Fiddle code here: https://jsfiddle.net/blaze92/u9zs2qy8/

Dev console Error

Questions:

1.How can I ensure that setupIntervalButton() properly sets up the interval before refreshFetch() is executed?

2.Is there a way to make setupIntervalButton() return the interval time so it can be used in refreshFetch()?

NPM Command Not Recognized Despite Installation-‘CALL “C:Program Filesnodejsnode.exe””C:Program Filesnodejsnode_modulesnpmbinnpm-prefix.js”‘

I’m encountering an issue with npm on my Windows machine. When I run npm –version in the command line, I get the following output:
C:Usersnares>npm –version
‘CALL “C:Program Filesnodejsnode.exe” “C:Program Filesnodejsnode_modulesnpmbinnpm-prefix.js”‘ is not recognized as an internal or external command,
operable program or batch file.
10.8.2

Reinstalling Node.js and npm multiple times.
Checking the PATH environment variable to ensure it includes the paths to Node.js and npm.
Running the command prompt as an administrator.
Clearing the npm cache with npm cache clean –force

Has anyone encountered this issue before? Any advice or solutions would be greatly appreciated.

Thank you!

Micro Frontend with React and a normal html/css/js

I am trying to implement Micro Frontend Architecture where the html/css/js application is the main application and the React application must be embedded inside it.
I don’t want to implement it using iframes.

const App = () => {

    const navigate=useNavigate();
    const location=useLocation();
    
    const logout=()=>{
        localStorage.removeItem("name");
        Cookies.remove("token");
        localStorage.removeItem("groupId");
        navigate("/");
    }

    return (
        <>
            {location.pathname!=="/" && location.pathname!=="/register" && 
                <>
                    <button onClick={logout}>Logout</button>
                    <select name='mytenants' id='mytenants'>
                        
                    </select>
                </>// marked
            }
            <Routes>
                <Route path="/" element={<Login></Login>}></Route>
                <Route path="/message" element={<ProtectedRoute><WebSocketComponent></WebSocketComponent></ProtectedRoute>}></Route>
                <Route path="/register" element={<SignUp></SignUp>}></Route>
                <Route path='/message/:reciver' element={<ProtectedRoute><WebSocketComponent></WebSocketComponent></ProtectedRoute>}></Route>
                <Route path="/message/group" element={<ProtectedRoute><GroupChat></GroupChat></ProtectedRoute>}></Route>
                <Route path="/message/group/:group" element={<ProtectedRoute><GroupChat></GroupChat></ProtectedRoute>}></Route>
                <Route path="/registeruser" element={<ProtectedRoute><RegisterUser></RegisterUser></ProtectedRoute>}></Route>
            </Routes>
        </>
    );
};

export default App;

This is my App.js of my react application.

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

This is my Index.js

I tryed to wrap the App.js using the Web Component and the use it in my html/css/js application but it didn’t work out.

class ReactMicroFrontend extends HTMLElement
{
    connectedCallback()
    {
        const shadowRoot=this.attachShadow({mode:"open"});

        const mountPoint=document.createElement('root');
        shadowRoot.appendChild(mountPoint);

        ReactDOM.render(
            <React.StrictMode>
            <BrowserRouter>
                <App />
            </BrowserRouter>
            </React.StrictMode>
            ,
            mountPoint
        );
    }

    disconnectedCAllback()
    {
        ReactDOM.unmountComponentAtNode(this.shadowRoot.querySelector('root'));
    }
}

customElements.define('react-microfrontend', ReactMicroFrontend);

This was the wrapper component.

I don’t want to use any frameworks like Single-SPA to implement it.
I want to implement it using plain javascript.
Is there any possible way to achieve it?