CSS Position Material UI Menu item below its parent

I’ve got a Material UI dialog that contains nothing but some text and an Icon with a Menu options dropdown. The demo can be seen here: https://codesandbox.io/s/prod-rain-1rwhf?file=/src/App.js

I’m trying to position the Menu component so that it appears just below the Settings component. I’ve specified a position: relative on the parent element (i.e. the Settings Icon) as well as a position: absolute with top: -10px to the child element (i.e the Menu component), but that doesn’t seem to work.

How can I set it up so that when the Settings icon is clicked, the Menu appears directly below the Settings, as well as when the window is resized so that the Menu follows?

How to get list of files in directory in git repo hosted on GitHub? [duplicate]

I have a repo jcubic/gaiman on GitHub. And I need to get a list of examples as a list (files in directory):

https://github.com/jcubic/gaiman/tree/master/examples

I’ve searched but was not able to find anything on how to get a list of files on GitHub. it should be a pretty common task to do.

I need this inside JavaScript hosted on GitHub pages at https://gaiman.js.org/ so I can list examples in a dropdown.

Add div below the td.button that called it [closed]

I have a table with a column that has an animated button.

When clicking on this animated button, an ajax request occurs to load information regarding the id of that entity.

The information is stored and added in div which has a table!

My problem is: I would like this div to appear just below the td.button that invoked it, at the moment I just put it below the main table as you can see in the images below.

enter image description here

enter image description here

How could I put this div below the td.button that called it? using js and/or jquery

Window is not defined in node.js, sigma.js and typescript environment

I try to setup a sigma.js project with node.js written in TypeScript. The following reference error occurs after starting the node.js server with:

ts-node index.ts

The error seems to occur directly within the sigmautilsindex.js.

<nodejsproject>node_modulessigmautilsindex.js:125
    if (typeof window.devicePixelRatio !== "undefined")
    ^
ReferenceError: window is not defined
    at getPixelRatio (<nodejsproject>node_modulessigmautilsindex.js:125:5)
    at Object.<anonymous> (<nodejsproject>node_modulessigmasigma.js:52:45)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (<nodejsproject>node_modulessigmaindex.js:14:31)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)

I tried to setup the typescript configuration as follows:

package.json

{
  ...
  "main": "index.ts",
  "scripts": {
    "dev": "nodemon ./index.ts",
    "test": "echo "Error: no test specified" && exit 1",
    "start": "ts-node index.ts"
  },
  "dependencies": {
    "@types/sigmajs": "^1.0.28",
    "express": "^4.17.2",
    "fs": "^0.0.1-security",
    "graphology": "^0.23.2",
    "graphology-components": "^1.5.2",
    "graphology-layout": "^0.5.0",
    "graphology-layout-forceatlas2": "^0.8.1",
    "papaparse": "^5.3.1",
    "path": "^0.12.7",
    "sigma": "^2.1.3",
    "xhr": "^2.6.0"
  },
  "devDependencies": {
    "@types/express": "^4.17.13",
    "tslint": "^6.1.3",
    "typescript": "^4.5.5"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist",
    "lib": ["dom"]
  },
  "lib": [
    "es2015"
  ],
  "exclude":[
    "./node_modules"
  ]
}

The error is raised after instantiation of Sigma to draw the graph:

router.get('/', (request, response) => {
    
    response.sendFile(path.join(__dirname+'/views/index.html'));
    
    const file = fs.createReadStream(fileLocation);
    
    //Metadata were loaded and parsed
    Papa.parse<{ original_table: string; referenced_table: string }>(file, {
      download: true,
      header: true,
      delimiter: ';',
      complete: (results) => {
        const graph: Graph = new Graph();
            
        //Build the node with their entities as nodes
        results.data.forEach((line) => {

        /* process loaded data to create the graph */

        //Draw the graph within the browser
        const container = document.getElementById("network-container") as HTMLElement;
        
        new Sigma(graph, container); //error occurs right here
      },
    });
});

SVELTE how to fix page flicker

In the app below I am encountering the notorious page flick effect that usually is a result of AJAX request. In my situation it is not due to AJAX it is due to a conditional that results in rendering different versions of the same page.

https://workflow-magic-svelte.vercel.app/

I have included a gif image video so you can see the problem.

Code is below.

enter image description here

<script>
  import { onMount } from "svelte";
  import Dexie from "dexie";
  import SearchAndCreateField from "../components/SearchAndCreateField.svelte";
  import {
    createClient,
    getAllClients,
    deleteClient,
  } from "../storageAPI/indexedDB";
  import { showNav } from "../store/nav_animation.js";
  import { animateNav } from "../store/nav_animation.js";
  import { fade, fly } from "svelte/transition";
  import { spring } from "svelte/motion";
  import BackButton from "../components/BackButton.svelte";

  //  import downloadjs from "downloadjs";

  let clients = [];
  let firstUseCookieBool;

  onMount(function () {
    firstUseCookieBool = document.cookie.split(";").some(function (item) {
      return item.trim().indexOf("workflow-magic=") == 0;
    });

    getAllClients().then((result) => {
      let list = result.reverse();
      clients = [...list];
    });
  });

  async function submitToDatabase(item) {
    try {
      let id = await createClient(item); // create new client
      // let result = await getAllClients(); // get all clients
      getAllClients().then((result) => {
        clients = [...result.reverse()]; // store new state to page
        // show nav if
        if (result.length > 1) {
          showNav.set(true);
          animateNav.set(false);
        }

        if (result.length === 1 && !firstUseCookieBool) {
          animateNav.set(true);
          document.cookie = "workflow-magic=user-first-submit-true";
        }
      });
    } catch (error) {
      throw error;
    }
  }

  function goToRoute(item) {
    console.log(item);

    window.location.href = "#/client/" + item.id + "/dashboard";
  }

  async function onDelete(id) {
    let clientID = clients[id].id;
    await deleteClient(clientID);
    await getAllClients().then((result) => {
      let list = result.reverse();
      clients = [...list];
      console.log(clients);
    });
  }
</script>

{#if $showNav || $animateNav}
  <div class="logo-form-container">
    <div class="container">
      <div class="row">
        <div class="col-0" />

        {#if $animateNav && !$showNav}
          <div class="col-12">
            <div
              class="background-image"
              in:fade={{ x: 0, y: 0, duration: 500 }}
            />

            <h2 class="logo-title">Workflow Magic</h2>
            <h3 class="app-is-ready-text">Your app is ready!</h3>
            <p class="get-started-text" in:fly={{ y: -50, duration: 900 }}>
              Add all the clients you want.<br /> Use the up and down arrows on
              your keyboard. <br />
              To go to the next step, select a client!
            </p>
          </div>
        {/if}

        {#if !$animateNav && $showNav}
          <div class="col-12">
            <div class="background-image" />

            <h2 class="logo-title">Workflow Magic</h2>
            <h3 class="app-is-ready-text">Your app is ready!</h3>
            <p class="get-started-text">
              Add all the clients you want.<br /> Use the up and down arrows on
              your keyboard. <br />
              To go to the next step, select a client!
            </p>
          </div>
        {/if}

        <div class="col-0" />
      </div>
      <div class="row">
        <div class="col-0" />
        <div class="col-12">
          <SearchAndCreateField
            arrayOfObjects={clients}
            keyToRender="name"
            buttonText="Create Client"
            onSubmit={submitToDatabase}
            {onDelete}
            onSelectionEvent={goToRoute}
            placeholder="Type the name of a company or client you work with"
          />
        </div>
        <div class="col-0" />
      </div>
    </div>
  </div>
{:else}
  <div class="logo-form-container">
    <div class="container">
      <div class="row">
        <div class="col-0" />
        <div class="col-12">
          <h2 class="logo-title">Workflow Magic</h2>

          <h2 class="top-text">
            Workflow Magic is an organizer tool for work-from-home contractors
            and freelancers.
            <br />
            Get Started Now!
          </h2>
        </div>
        <div class="col-0" />
      </div>

      <div class="row">
        <div class="col-0" />
        <div class="col-12">
          <SearchAndCreateField
            buttonText="Create Client"
            placeholder="Type the name of a company or client you work with"
            arrayOfObjects={clients}
            keyToRender="name"
            onSubmit={submitToDatabase}
            {onDelete}
            onSelectionEvent={goToRoute}
          />
        </div>
        <div class="col-0" />
      </div>
    </div>
  </div>
{/if}

<style>
  .get-started-text {
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #787878db;
    font-size: 1.2em;
    position: relative;
    top: 20px;
    margin-bottom: 50px;
  }

  .top-text {
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #000db;
    font-size: 1.8em;
    position: relative;
    top: 0px;
    margin-bottom: 0px;
  }

  @font-face {
    font-family: logoFont;
    src: url(/fonts/next.ttf);
  }

  .logo-title {
    font-family: logoFont;
    font-size: 2.5em;
    color: #be3ebc91;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .background-image {
    background-image: url(/background_image/background.png);
    background-repeat: no-repeat;
    background-size: auto;
    background-size: cover;
    background-size: 43% 60%;
    bottom: 60px;
    top: -190px;
    width: 150%;
    left: 8px;
    height: 1000px;
    position: absolute;
    opacity: 0.2;
  }

  .logo-form-container {
    position: relative;
    top: 100px;
  }

  .app-is-ready-text {
    color: #819dc2;
    text-align: center;
    font-size: 2em;
  }
</style>



  [1]: https://i.stack.imgur.com/FBSym.gif

pass parameter in jsp fails

I need to pass a parameter in javascript function so I do this:

<af:textBox name="date" id="date" type="date"
                    value="<%=startDate%>" 
                    title="" onKeyUp="fieldChanged()"
                    
                    onChange="load('cod','<%=startDate%>'))
                />

The method javascript is this:

function ricaricaDescrizione908(idComponente,value_pass) {
        console.log("Value "+value_pass);
     
     
        }

The problem is the console.log is never called when onchange is called.
In my console there are some erors. Anyone can help me?

Trying to prevent duplicate entries not working

I am fetching data from an API (array of objects) and I want to then check in the database if any of the records exist, using the url as the basis for duplicates. When it comes to inserting the new records, I get this monogoDB error:

MongoBulkWriteError: E11000 duplicate key error collection: news.news
index: sourceUrl_1 dup key: { sourceUrl:
“https://example.com/article-abc123” }

  try {
    const covidDbArticles = await News.find({ category: "Coronavirus" });
    const filterCovidDuplicates = covidData.data.news.filter(
      (covidApiSource) =>
        !covidDbArticles.some(
          (covidDatabaseSource) =>
            covidApiSource.link === covidDatabaseSource.sourceUrl
        )
    );
    if (filterCovidDuplicates.length) {
      try {
        await News.insertMany(covidNewsObj);
      } catch (err) {
        console.log("Error inserting covid data: " + err);
      }
    }
  } catch (err) {
    console.log("saving data failed: " + err);
  }

Why did the browser never update itself from zombie service worker?

In this brillant talk Alexander Pope: ServiceWorkers Outbreak: index-sw-9a4c43b4b47781ca619eaaf5ac1db.js | JSConf EU 2017:
The presenter has a situation where a broken service worker gets installed, and its stuck in the broken state. The presenter tries a kill switch and an empty service worker to remedey it, but there are still some browsers permantely infected. I am trying to understand why it happened, and not do a similar thing.

Here is his code (from 22m:57s):

function onInstall(event) {
    event.waitUntil(
        install(config.version, config.assets)
            .catch((err) => {
                reportError(err);
                // Ok, you know what you're doing, Installing now....
            })
    );
}

It gets stuck because within the call to install he uses cache.addAll(), but long ago Chrome didnt support cache, so this error never bubbled up, and the browser thought it was installed correctly.

Now the browser is reponsible for fetching the sw.js file and checking if its byte different to the currently installed worker. The code to register the new sw.js file is outside of the service worker file. This means even if a service worker is broken, the browser should be able to fetch the new one, determine its different, register it, and activate it (eventually). The newer sw.js file could then check for the presence of cache API. So why are there some clients still in a broken state?

ReferenceError: Cannot access ‘AuthProvider’ before initialization

Can someone explain why I am getting this error in next js? The auth.js file is also not being run but it used to run before when I import.

ReferenceError: Cannot access ‘AuthProvider’ before initialization
This error happened while generating the page. Any console logs will be displayed in the terminal window.

This is my _app.js file

import React from "react";
import { AuthProvider } from "contexts/auth";
import { ProtectRoute } from "contexts/auth";
import Nav from "components/Nav";

function MyApp({ Component, pageProps }) {
  return (
    <AuthProvider>
      <Nav />
      <ProtectRoute>
        <Component {...pageProps} />
      </ProtectRoute>
    </AuthProvider>
  );
}

export default MyApp;

And this is my contexts/auth.js file

import React, { createContext, useState, useContext, useEffect } from "react";
import Cookies from "js-cookie";
import { fetchWrapper } from "helpers";

const AuthContext = createContext({});

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadUserFromCookies = async () => {
      // authenticate code
    };
    loadUserFromCookies();
  }, []);

  const login = async (email, password) => {
   // login code
  };

  const logout = () => {
    // logout code
  };

  return (
    <AuthContext.Provider
      value={{ isAuthenticated: !!user, user, login, loading, logout }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => useContext(AuthContext);

export const ProtectRoute = ({ children }) => {
  const { isAuthenticated, isLoading } = useAuth();
  if (
    isLoading ||
    (!isAuthenticated && window.location.pathname !== "/login")
  ) {
    return () => {
      "Loading...";
    };
  }
  return children;
};

How to bind correct s to dynamic columns created based on dynamic arrays?

I get an array of objects from API that contain, among other data, a targets_and_rewards array that can vary with a minimum of one occurence.
I created a material table showing these values, using static columns and dynamic columns based on the maximum length of targets_and_rewards array for each offer.
I need to bind tds correctly based on these dynamic columns.

Here is how it looks like:

app.component.ts

import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';

const dataReceivedFromAPI = [
  {
    id: 4000,
    name: 'My awesome offer',
    targets_and_rewards: [
      {
        reward: {
          max: 3.6,
          mean: 0.48,
          min: 0.4,
        },
        target: {
          max: 30,
          mean: 3.71,
          min: 3,
        },
      },
      {
        reward: {
          max: 5.7,
          mean: 1.17,
          min: 1,
        },
        target: {
          max: 5.7,
          mean: 5.88,
          min: 5,
        },
      },
      {
        reward: {
          max: 7.5,
          mean: 3.38,
          min: 3.3,
        },
        target: {
          max: 30,
          mean: 13.35,
          min: 13,
        },
      },
    ],
  },
  {
    id: 5000,
    name: 'My awesome second offer',
    targets_and_rewards: [
      {
        reward: {
          max: 3.5,
          mean: 0.55,
          min: 0.3,
        },
        target: {
          max: 35,
          mean: 5.67,
          min: 4,
        },
      },
      {
        reward: {
          max: 6.8,
          mean: 2.12,
          min: 2,
        },
        target: {
          max: 7.9,
          mean: 4.12,
          min: 3,
        },
      },
      {
        reward: {
          max: 8.2,
          mean: 5.24,
          min: 4.87,
        },
        target: {
          max: 32,
          mean: 17.13,
          min: 15.65,
        },
      },
      {
        reward: {
          max: 9,
          mean: 6.66,
          min: 5.87,
        },
        target: {
          max: 50,
          mean: 34.45,
          min: 21.12,
        },
      },
      {
        reward: {
          max: 8.2,
          mean: 5.24,
          min: 4.87,
        },
        target: {
          max: 32,
          mean: 17.13,
          min: 15.65,
        },
      },
    ],
  },
  {
    id: 6000,
    name: 'My awesome third offer',
    targets_and_rewards: [
      {
        reward: {
          max: 6.1,
          mean: 5.54,
          min: 4.13,
        },
        target: {
          max: 100,
          mean: 45.12,
          min: 31.1,
        },
      },
    ],
  },
];

interface Targeting {
  id: number;
  name: string;
  targets_and_rewards: Array<{
    reward: {
      max: number;
      mean: number;
      min: number;
    };
    target: {
      max: number;
      mean: number;
      min: number;
    };
  }>;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  public dataSource: MatTableDataSource<Targeting>;
  public displayedColumns: Array<string> = ['id', 'name'];
  public targetAndRewardColumns: Array<string> = [];

  ngOnInit(): void {
    // API call binding data variable... (here `dataReceivedFromAPI`)
    // Populate columns with static part (basic `displayedColumns`) and dynamic part (`targetAndRewardColumns`)
    this.populateColumns(dataReceivedFromAPI);
    this.dataSource = new MatTableDataSource(dataReceivedFromAPI);
  }

  populateColumns(data: Array<Targeting>): void {
    let maxTargetsAndRewards: number = 0;
    data.map((offer: Targeting) => {
      const targetsAndRewardsLength: number = Object.keys(
        offer.targets_and_rewards
      ).length;
      if (targetsAndRewardsLength > maxTargetsAndRewards) {
        maxTargetsAndRewards = targetsAndRewardsLength;
      }
    });
    for (let i: number = 0; i < maxTargetsAndRewards; i++) {
      this.targetAndRewardColumns.push(
        `Min Target (${i})`,
        `Min Reward (${i})`,
        `Mean Target (${i})`,
        `Mean Reward (${i})`,
        `Max Target (${i})`,
        `Max Reward (${i})`
      );
    }
    this.displayedColumns = [
      ...this.displayedColumns,
      ...this.targetAndRewardColumns,
    ];
  }
}

app.component.html

<table mat-table [dataSource]="dataSource">
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef>Id</th>
    <td mat-cell *matCellDef="let offer">
      {{ offer.id }}
    </td>
  </ng-container>

  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef>Name</th>
    <td mat-cell *matCellDef="let offer">
      {{ offer.name }}
    </td>
  </ng-container>

  <ng-container
    *ngFor="let column of targetAndRewardColumns"
    [matColumnDef]="column"
  >
    <th mat-header-cell *matHeaderCellDef>
      {{ column }}
    </th>
    <!-- How to dynamically bind tds here ? -->
    <!-- Min target (0) should be equal to first offer.targets_and_rewards[0].target.min for example -->
    <td mat-cell *matCellDef="let offer">
      <!-- Just to populate with something by default -->
      {{ offer.targets_and_rewards[0].target.min }}
    </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let offers; columns: displayedColumns"></tr>
</table>

And here is a stackblitz snippet to make everything more clear.

Using IFrame to check if a NVR is online or not

I have a group of around 10 NVRs that I would like to be able to display on one page whether they are online or not.

Currently I do this with a HTML page containing 10 iframes each trying to load the default page of the NVR via their IPs, this either displays the default menu or just has a white error page.

Is it possible to interrogate what is in the iframe and display a green page if the connection is made and red page if not? or even to do away with the iframe and check if the IP of the NVR is live or not and display this as a visual list.

Javascript Reduce, missing values

I’ve been struggling with this all day and have finally given up as I see no reason why its not working.

I have the following code:

let groupedEvents: any[] = events.reduce((processedEvents: any[], event: Event) => {
    const day: string = dayjs(event.startDateTime).format('YYYY-MM-DD');
    const matchingDateIndex: number = processedEvents.findIndex(group => group.day === day);
    console.log(matchingDateIndex)

    if (matchingDateIndex > -1) {
        processedEvents[matchingDateIndex].events.push(event);
    } else {
        processedEvents.push({ day, events: new Array(event) })
    }
    return processedEvents;
}, []);
console.log(groupedEvents)

This takes an events array with calendar entries, then should group them by day. However what happens is the first day always ends empty, with subsequent days being fine as below:

enter image description here

There should be a total of 5 events but the 3 from the 21st are not showing, anyone know why this is happening?

Lerna version remove commit links

I’m using lerna version for the private gitlab repository, my CHANGELOG.MD will be visible on npm after publish, but commit links won’t be accessible for users, so I want to remove commit links altogether.
One way to do it is to add --no-push option, undo commit, then manually remove the links. Another option is the same as the first, but with the bash script, which will remove links automatically.

I was wondering if the same operation could be done using only lerna version configuration? Couldn’t find anything helpful in lerna docs.