How I center my HTML iframe in Android webivew?

I have an iframe in my Android webview that I am loading like this:

     String folderPath = "file:android_asset/";
     String fileName = "index.html";
     String file = folderPath + fileName;
     webView.loadUrl(file);

The iframe is loaded via HTML and CSS files located in my android/assests folder. The HTML and CSS look like this. HTML:

<!DOCTYPE html>
<html lang="en">
<body>
<link rel="stylesheet" type="text/css" href="default.css"  />
    <div class="abs-frame-container">
    <iframe 
      id="my_frame"
      src="my web page link"
      scrolling="no"
      allowtransparency="true" 
      style="border:none;overflow:hidden">
    </iframe>
    </div>
</body>
</html>

and my CSS

#my_frame {
  position: absolute;
  top: 0%;
  bottom: 0%;
  right: 0%;
  width: 117%;
  height: 100%;
}

#abs-frame-container{
    top: 10%;
    bottom: 0%;
    position: relative;
}

The webpage in iframe shows fine in the webview. I want to center (vertical alignment) my iframe in the webview so that it aligns automatically based on the webview dimensions (height). Would appreciate a lot if someone could help me how this can be achieved?

How to make the content of a div go from left to right, then drop e continue going left to right

I have a code where I want to make the content inside the div, go from left to right (wich I did using Flex-direction: row) and when it gets to the limit of the div, goes down and continues this order. It should look like this (https://i.stack.imgur.com/L97y0.png) with the elements inside going in this order.

I’m using MVC core, and its a system wich accepts requests and shows then in the screen.

Heres the HTML of the div

<div class="pedido-tudo">
            @foreach(var pedido in Model)
        {
            <div class="pedido-quadrado">
                @pedido.IdPedido
                @pedido.NomeCliente
                @pedido.TelCliente
                @pedido.DataEntrada
                @pedido.HoraEntrada
                @pedido.HoraSaida
                @pedido.TextoStatus
                @pedido.TextoTipoPedido
                    
                @if (@pedido.TextoStatus == "Andamento" && @pedido.HoraSaida == "")
                {
                <div class="botoes-cad">
                    <a href="/Pedidos/Update/@pedido.IdPedido" class="btn btn-sm btn-primary" id="finalizar">Finalizar</a>
                </div>
                }
            </div>
        } 
        </div>

the css of the div

.pedido-tudo {
    margin-left: 1.5rem;
    width: 60rem;
    max-width: 60rem;
    display: flex;
    flex-direction: row;
}

.pedido-quadrado{
    margin-top: 1rem;
    margin-left: 5.7rem;
    width: 18rem;
    height: 20rem;
    border: 1px rgb(170, 0, 0) solid;
    color: black;
    font-size: 16px;
}

Heres how currently its

https://i.stack.imgur.com/KIdhq.png

Conditionally Rendering Material UI Elements in React

I want to render Material UI Elements like Menu Items of a AppBar Conditionally if some conditions are true. In my example menu items should only be rendered for specific users. But it doesnt work like the way it would work with normal html in react.

                  {context.token && context.userRole === "USER" && (
                    <MenuItem key="submission" onClick={handleCloseNavMenu}>
                      <Typography textAlign="center">Submission</Typography>
                    </MenuItem>
                  )}
                  {context.token && context.userRole === "JUDGE" && (
                    <MenuItem key="submissions" onClick={handleCloseNavMenu}>
                      <Typography textAlign="center">Submissions</Typography>
                    </MenuItem>
                  )}

Its rendering this Items all the time anyways and seems to ignoring the conditions.

The full code:

import React from "react";
import { NavLink } from "react-router-dom";
import AuthContext from "../context/auth-context.js";
import AppBar from "@mui/material/AppBar";
import Box from "@mui/material/Box";
import Toolbar from "@mui/material/Toolbar";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import Menu from "@mui/material/Menu";
import MenuIcon from "@mui/icons-material/Menu";
import Container from "@mui/material/Container";
import Avatar from "@mui/material/Avatar";
import Button from "@mui/material/Button";
import Tooltip from "@mui/material/Tooltip";
import MenuItem from "@mui/material/MenuItem";
import ComputerIcon from "@mui/icons-material/Computer";

const ResponsiveAppBar = (props) => {
  const pages = ["Conditions", "Winner", "Submission", "Submissions", "Login"];
  const settings = ["Profile", "Settings", "Logout"];

  const [anchorElNav, setAnchorElNav] = React.useState(null);
  const [anchorElUser, setAnchorElUser] = React.useState(null);

  const handleOpenNavMenu = (event) => {
    setAnchorElNav(event.currentTarget);
  };
  const handleOpenUserMenu = (event) => {
    setAnchorElUser(event.currentTarget);
  };

  const handleCloseNavMenu = () => {
    setAnchorElNav(null);
  };

  const handleCloseUserMenu = () => {
    setAnchorElUser(null);
  };

  return (
    <AuthContext.Consumer>
      {(context) => (
        <AppBar position="static">
          <Container maxWidth="xl">
            <Toolbar disableGutters>
              <Typography
                variant="h6"
                noWrap
                component="div"
                sx={{ mr: 2, display: { xs: "none", md: "flex" } }}
              >
                <ComputerIcon />
              </Typography>

              <Box sx={{ flexGrow: 1, display: { xs: "flex", md: "none" } }}>
                <IconButton
                  size="large"
                  aria-label="account of current user"
                  aria-controls="menu-appbar"
                  aria-haspopup="true"
                  onClick={handleOpenNavMenu}
                  color="inherit"
                >
                  <MenuIcon />
                </IconButton>
                <Menu
                  id="menu-appbar"
                  anchorEl={anchorElNav}
                  anchorOrigin={{
                    vertical: "bottom",
                    horizontal: "left",
                  }}
                  keepMounted
                  transformOrigin={{
                    vertical: "top",
                    horizontal: "left",
                  }}
                  open={Boolean(anchorElNav)}
                  onClose={handleCloseNavMenu}
                  sx={{
                    display: { xs: "block", md: "none" },
                  }}
                >
                  {context.token && context.userRole === "USER" && (
                    <MenuItem key="submission" onClick={handleCloseNavMenu}>
                      <Typography textAlign="center">Submission</Typography>
                    </MenuItem>
                  )}
                  {context.token && context.userRole === "JUDGE" && (
                    <MenuItem key="submissions" onClick={handleCloseNavMenu}>
                      <Typography textAlign="center">Submissions</Typography>
                    </MenuItem>
                  )}
                  <MenuItem key="conditions" onClick={handleCloseNavMenu}>
                    <Typography textAlign="center">Conditions</Typography>
                  </MenuItem>
                  <MenuItem key="winner" onClick={handleCloseNavMenu}>
                    <Typography textAlign="center">Winner</Typography>
                  </MenuItem>
                </Menu>
              </Box>
              <Typography
                variant="h6"
                noWrap
                component="div"
                sx={{ flexGrow: 1, display: { xs: "flex", md: "none" } }}
              >
                LOGO
              </Typography>
              <Box sx={{ flexGrow: 1, display: { xs: "none", md: "flex" } }}>
                {pages.map((page) => (
                  <Button
                    key={page}
                    onClick={handleCloseNavMenu}
                    sx={{ my: 2, color: "white", display: "block" }}
                  >
                    {page}
                  </Button>
                ))}
              </Box>

              <Box sx={{ flexGrow: 0 }}>
                <Tooltip title="Open settings">
                  <IconButton onClick={handleOpenUserMenu} sx={{ p: 0 }}>
                    <Avatar
                      alt="Remy Sharp"
                      src="/static/images/avatar/2.jpg"
                    />
                  </IconButton>
                </Tooltip>
                <Menu
                  sx={{ mt: "45px" }}
                  id="menu-appbar"
                  anchorEl={anchorElUser}
                  anchorOrigin={{
                    vertical: "top",
                    horizontal: "right",
                  }}
                  keepMounted
                  transformOrigin={{
                    vertical: "top",
                    horizontal: "right",
                  }}
                  open={Boolean(anchorElUser)}
                  onClose={handleCloseUserMenu}
                >
                  {settings.map((setting) => (
                    <MenuItem key={setting} onClick={handleCloseNavMenu}>
                      <Typography textAlign="center">{setting}</Typography>
                    </MenuItem>
                  ))}
                </Menu>
              </Box>
            </Toolbar>
          </Container>
        </AppBar>
      )}
    </AuthContext.Consumer>
  );
};

export default ResponsiveAppBar;

Fetching multiple raw md files from GitHub in React JS

I’m trying to fetch data from multiple raw .md files from Guthub repo. Currently I’m able to fetch only one, yet I need to get to all of them.

I have a github repo and Im looking to fetch data from raw .md file, which is not a problem. The problem is that the repo has bunch of folders and each folder has its own .md file. I need to make some sort of map through all folders and fetch all of the .md files.

Lets say I have a github repo with following folders:

folder1 -> text1.md
folder2 -> text2.md
folder3 -> text3.md

I’m currently being able to fetch only one raw md usinng the following method

let fetchData = () => {    
axios.get("https://raw.githubusercontent.com/user-name/repo-name/master/folder1/text1.md").then(response => {
      console.log(response)
    }).catch(error => {
      console.log(error)
    })
  }

My goal is to fetch all text1, text2, text3.md so I can map through them and display in the table

HTML textarea connect

I have a question. I am making a note-taking/study app for myself as a project to learn CSS HTML and javascript so I am new to all of this, so my question is I have a main text area then another one on top to represent the title and then I have a sidebar to make new pages I’m working on. How can I make it so when I type the title in the text both textbox or just text will change with it?Heres an image of the page right now I want those untitled texts to change togehter

How can I preserve the JSDoc on re-assignment in VSCode?

A project I am on uses plugins, which export objects, and have their properties re-assigned to centralise functions.

Here is an example:

// barPlugin.js
const barPlugin = {
  /**
   * Register a Foo
   * @param {string} name of the foo
   * @param {object} options the options that make this foo special
   * @param {string} options.flavour how the foo tastes
   * @param {boolean} options.levitate if the foo can levitate
   */
  registerFoos: (name, options = {}) => {
     // stuff that registers foos
  }
  // other bar plugin related functions
}
export default barPlugin;

// pluginHub.js
const allPlugins = {};
export const initialisePlugins = () => { // called on app load
  // hovering over 'registerFoos' on the LHS of the assignment does not show the jsdoc
  allPlugins.registerFoos = barPlugin.registerFoo; 
  // LOTS of other examples of the above
}
export default allPlugins;

This is also so that when we need to register/interact with the foos registered via the barPlugin we only need to know it’s foos and not which of the many many plugins it’s from.

The issue, now that we have started using JSDoc is that it seems like importing allPlugins and calling allPlugins.registerFoos no longer has the JSDoc associated with it?

// nonPluginCode.js
import allPlugins from 'pluginsHub';

allPlugins.registerFoos( ... ) // hovering over 'registerFoos' does not show the jsdoc

It feels like this might be an issue with VSCode, but regardless how can I preserve the JSDoc across the reassignment?

It’s not JSDoc broken on `exports.default` in VSCode? as this happens before exporting.

Server Error while using Graphql Playground

I have been following the www.howtographql.com tutorials but i am stuck as i am not able to add authorization token in http headers. As soon as i write the authorization token it gives an error – ‘Server cannot be reached’

index.js

const { ApolloServer } = require('apollo-server');
const { PrismaClient } = require('@prisma/client');
const fs = require('fs');
const path = require('path');
const { getUserId } = require('./utils');
const Query = require('./resolvers/Query');
const Mutation = require('./resolvers/Mutation');
const User = require('./resolvers/User');
const Link = require('./resolvers/Link');

const prisma = new PrismaClient();

const resolvers = {
    Query,
    Mutation,
    User,
    Link
}

const server = new ApolloServer({
    typeDefs: fs.readFileSync(
        path.join(__dirname, 'schema.graphql'),
        'utf-8'
    ),
    resolvers,
    context:({ req }) => {
        return {
            ...req,
            prisma,
            userId: req && req.headers.authorization ? getUserId(req) : null
        };
    }
});

server.listen()
    .then(({ url }) => console.log(`Server is running on ${url}`)
    );

increase textarea size according to the size of the text in the angular

sorry for my English

currently the following code is being used to resize the textarea

    function autoResize(el){
  while (el.scrollHeight > el.offsetHeight){
    el.rows += 1;
  }
}

but it only resizes when I hover over the textarea

<textarea onmousemove="autoResize(this)"></textarea>

I would like to make it resize automatically when I open the screen that has the textarea. I already tried switching to onload but without success

js script for automatic slideshow (html, js)

i’m trying to write a js script for an automatic slideshow of the newest 10 images in a specific folder. It is a folder where every hour a new image is uploaded, so i cant use the name of the image just the time when it was uploaded.

can someone solve this problem?

kind regards

Hide table row based on table cell pure Javascript

I have an form which add the input to an HTML table. I want to do a dropdown where the user can filter for specific table cell elements only in pure Javascript and a filter method.

Let’s say I have an table like this:

Name | Age | ID

Anna | 14 | 3

Herb | 34 | 4

John | 14 | 6

And a dropdown like this:

Select Name

  • Anna
  • Herb
  • John

In the case the user selects Anna only the following table should showed:

Name | Age | ID

Anna | 14 | 3

The tricky part is that every row is created through the input from an form what means that I can’t talk to an specific table row per id or class.

Here is what I tried:

Table

<table id="table" class="tableZebra" border="1">
    <tr>
        <th>Student_Id</th>
        <th>First_Name</th>
        <th>Last_Name</th>
        <th>DOB</th>
        <th>Gender</th>
        <th>Department</th>
        <th>Email_Id</th>
        <th>Joining Date</th>
    </tr>
</table>                           

Form

<form">
    <p>*Staff_Id:</p>
    <div><input type="text" id="Staff_Id" placeholder="Staff_Id"></div>
    <p>*First_Name:</p>
    <div><input type="text" id="First_Name_staff" placeholder="First_Name"></div>
    <p>Last_Name:</p>
    <div><input type="text" id="Last_Name_staff" placeholder="Last_Name"></div>
    <p>DOB:</p>
    <div><input type="text" id="DOB_staff" placeholder="DOB"></div>
    <p>Gender:</p>
    <div><input type="radio" id="GenderFemale_staff" placeholder="Gender" name="test"></div>
    <label for="html">Female</label>
    <div><input type="radio" id="GenderMale_staff" placeholder="Gender" name="test"></div>
    <label for="html">Male</label>
    <p>*Email_Id:</p>
    <div><input type="text" id="Email_Id_staff" placeholder="Email_Id"></div>
    <div class="distance-submit"><input class="submit" type="submit" value="Submit" onclick="onClickCheckFormStaff()"></div>
    <div class="error-staff" id="error-staff">*Fill out all mandatory fields</div>
</form>

Select button

<p>*Department:</p>
<select name="departments" id="Departments">
    <option value="empty">------</option>
    <option value="Department_1">Department_1</option>
    <option value="Department_2">Department_2</option>
    <option value="Department_3">Department_3</option>
    <option value="Department_4">Department_4</option>
</select>

JS

function changeDisplayTable(){
    //here i get all the values from the table cell departments in an array as text
    var dataCellsDepartments = document.getElementsByClassName(" dep"); //if does not work try " dep"
    var listWithTextContentDepartments = [];
    var i = 0;
    len = dataCellsDepartments.length;
    while(i < len){
        listWithTextContentDepartments.push(dataCellsDepartments[i].textContent)
        i++
    }
    console.log(listWithTextContentDepartments);
    //array filtern und dann durch jede row gehen und checken if row contains one of the elem from array
    const result = listWithTextContentDepartments.filter(checkDepartment);
    function checkDepartment(department){
        return department
    }

    //wenn selected elem != elem from table row --> hide table row

}

For the Javascript part I tried to get all the elements from the table cell which should contain the value from the select button and if this element is != the value from the select button I hide the table row. I don’t know how to get the table row through a table cell element.

How to split an array to multiple arrays one by one JS

I need to split an Array into multiple arrays one by one, for example, if I have an array

const input = [1, 2, 3, 4, 5, 6, 7, 8, 9];

And the number of multiple arrays would be 3, the output should be

const arraysNumber = 3;
const result = [[1,4,7], [2,5,8], [3,6,9]];

if multiple arrays = 2,

const arraysNumber = 2;
result = [[1,3,5,7,9], [2,4,6,8]];

if multiple arrays = 4,

const arraysNumber = 4;
result = [[1,5,9], [2,6], [3,7], [4,8]];

I found only ways hot to split on chunks, like [[1,2,3], [4, 5, 6], [7, 8, 9]], but that’s not what I need

Would be grateful for any help!

GitHub API Pagination, possibly without relying on Link Header

I’m trying to paginate Issues’ Comments accordingly to their docs that relies on the Link Header.

I perform the Request using a (Babel) Class’ method, a wrapper routine for the Fetch API, like this:

class MyClass {

  async load( url, method = 'GET', args = {} ) {

    const options = {
      method: method.trim().toUpperCase(),
      redirect: 'follow'
    };

    try {

      const process = await fetch( url, Object.assign( options, args ) );

      if( ! process.ok ) {
        throw new Error( process.statusText );
      }
    
      return process.clone().json().catch( () => process.text() )

    } catch( error ) {
      return Promise.reject( error );
    }
  }

}

(new MyClass).load( 'https://api.github.com/repos/OWNER/REPOSITORY/issues/ISSUE/comments?page=1&per_page=15' );

I’ve suppressed a small bit of the code because, as you can see, I’m not returning the Fetch API Response Promise, only the resolved data, but I’ve tested it returning the thenable Promise itself and the results were the same.

For the sake of simplification, some simple debugging right after the process.ok yields me:

Response Object (console.log( process ))

{ type: "cors", url: "https://api.github.com/repos/OWNER/REPOSITORY/issues/ISSUE/comments?page=1&per_page=15", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false }

The Headers (iterating over process.headers.entries())

cache-control: private, max-age=60, s-maxage=60
content-type: application/json; charset=utf-8
etag: W/"5304658e191e2c59f9a26ca89366de5dcf3801d561b0307b0590282a672c4409"
x-accepted-oauth-scopes:
x-github-media-type: github.v3; param=html.squirrel-girl-preview; format=json
x-oauth-scopes: notifications, public_repo, user
x-ratelimit-limit: 5000
x-ratelimit-remaining: 4973
x-ratelimit-reset: 1638360867
x-ratelimit-resource: core
x-ratelimit-used: 27

x-ratelimit varies depending on the number of Requests performed within one hour

As you can see, no Link Header.

After some research, I’ve found this answer saying that over CORS only a few Headers are available and in its comments, I’ve learned that access-control-expose-headers when configured in the server can expand this list.

Well, this is a screenshot of the Response Data:

enter image description here

Once again, x-ratelimit varies

As you can see, Link is present among access-control-expose-headers, meaning that GitHub (apparently) did their part, and yet I can’t retrieve it.

With the case exposed so, how could I:

  • Get this Link Header using the Fetch API (preferably)
  • Or then build the pagination logic without it. Maybe using some math, perhaps?

What’s bugging me is that I’m 100% positive the very same code I have today was working ’til a few days ago when Firefox was updated. I’m sure of it because the whole implementation was working ’til 11/23, the date on which I’ve committed it to my repository.

In the meantime, Firefox was updated but I couldn’t find any information regarding a change in Fetch API, since I’ve read somewhere that using oldie XHtmlHttpRequest was still possible to get such headers.

‘Routes’ is not defined react/jsx-no-undef

So I was following the React Crash Course on YouTube for Beginners from Academind. I was following everything along and everything was good until I came to the Routing part.
I followed every step, everything just perfectly (for the routing part) but after refreshing the page the following error occurs:

A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

Aaand I did it, I wrapped my Route in Routes :

    import { Route } from 'react-router-dom';


import AllMeetupsPage from './Pages/AllMeetups';
import NewMeetupsPage from './Pages/NewMeetups';
import FavoritesPage from './Pages/Favorites';

function App() {
  return (
    <div>
      <Routes>
        <Route path='/'>
          <AllMeetupsPage />
        </Route>

        <Route path='/new-meets'>
          <NewMeetupsPage />
        </Route>

        <Route path='/favs'>
          <FavoritesPage />
        </Route>
      </Routes>
    </div>
  );
}

export default App;

and then I get this:

‘Routes’ is not defined react/jsx-no-undef

then I :

Tried to import Routes from react-router-dom – No success;

Tried to import Routes from react-router – No success;

Tried to import Routes also in different components – No success;

Trust me I tried every different scenario for Routes but couldnt achieve anything different.
I

Googled, researched and couldnt find the solution for this problem.. Now Im desperate and
stuck here and I cant continue my React learning journey if I dont fix this…

Hovering tooltip position is not proper on ng2-charts (pie chart)

enter image description here

The hovering position is not proper on chart
When I am moving mouse from red color part to green color part, at the starting of green color it is still showing red color hovered and the green color will get hovered only when it reaches little right or center of the green color.
The position hovering is incorrect in this chart

”’

<canvas baseChart 
                    [data]="pieChartData" 
                    [labels]="pieChartLabels" 
                    [chartType]="pieChartType"
                    [options]="pieChartOptions"
                    [plugins]="pieChartPlugins"
                    [legend]="pieChartLegend"
                    [colors]="pieChartColors"
                    (chartClick)="statusClicked($event)">
                </canvas>

”’