JsonResponse from django app not showing in html table or console.log

I have a django app that parses a csv and stores the data in sqlite which works great and i can see the data in the admin panel. Now i’m having trouble displaying the data either in the front end as a table or in the console.

views.py

def airpollution_table_data(request):
    table_data = {}
    pollutant_list = [pollutant for pollutant in Pollutant.objects.all()]
    country_list = [country for country in Country.objects.all()]
    for pollutant in pollutant_list:
        table_data[pollutant.name] = {}

        for i, country in enumerate(country_list):
            total = PollutantEntry.objects 
                .aggregate(total=Sum('pollution_level', filter=Q(pollutant=pollutant,
                                                                 country=country)))['total']

            minimum = PollutantEntry.objects 
                .aggregate(min=Min('pollution_level', filter=Q(pollutant=pollutant,
                                                               country=country)))['min']
            maximum = PollutantEntry.objects 
                .aggregate(max=Max('pollution_level', filter=Q(pollutant=pollutant,
                                                               country=country)))['max']
            count = PollutantEntry.objects.filter(pollutant=pollutant, country=country).count()
            units = PollutantEntry.objects.filter(pollutant=pollutant, country=country).first()
            units = units.units if units else ''
            if total is not None and count:
                table_data[pollutant.name][country.iso_code] = {'avg': total / count, 'min': minimum,
                                                                'max': maximum,
                                                                'limit': pollutant.limit_value, 'units': units}
    return JsonResponse(table_data)

URLs.py

from django.urls import path
from . import views

app_name = 'supplychain'

urlpatterns = [
    path('', views.airpollution, name='airpollution'),
    path('airpollution_table_data', views.airpollution_table_data, name='airpollution_table_data'),
    path('temp_country_creator', views.temp_country_creator, name='temp_country_creator')
]

welcome.html table code

<!-- Table Section-->
 <section class="page-section mt-5" id="data-table">
  <div class="container">
      <!-- Heading-->
      <h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Data Table</h2>
      <!-- Icon Divider-->
      <div class="divider-custom">
          <div class="divider-custom-line"></div>
          <div class="divider-custom-icon"><i class="fas fa-star"></i></div>
          <div class="divider-custom-line"></div>
      </div>
      <!-- Table-->
      <div class="row">
          <div class="col-lg-8 mx-auto">

              <table id="our-table" class="table">
                  <thead>
                  <tr>
                      <th scope="col">Pollutant</th>
                      <th scope="col">Country</th>
                      <th scope="col">Avg</th>
                      <th scope="col">Min</th>
                      <th scope="col">Max</th>
                      <th scope="col">Limit</th>
                      <th scope="col">Units</th>
                  </tr>
                  </thead>
                  <tbody id="table-body">

                  </tbody>
              </table>

          </div>
      </div>
  </div>
</section>


{% endblock %} 

{% block js %}
    <!-- Page level plugins -->
    <script src="{% static 'vendor/datatables/jquery.dataTables.min.js' %}"></script>
    <script src="{% static 'vendor/datatables/dataTables.bootstrap4.min.js' %}"></script>

    <script>
        $(document).ready(function () {
          
            $.get("airpollution_table_data", function (data) {
              console.log(data)
            });
        })
    </script>
{% endblock %}

Initially I was trying to show the data in a html table using javascript but that wasn’t working so i tried to do console.log and I’m still unable to see anything in the network console in google chrome.

Any ideas what’s wrong? I’ve been stuck in this for the last couple of days lol

Why don’t the buttons work? How do I fix these problems?

i have this functions

I need them to work when the buttons are clicked

async function Ghash(name){
    let res = await fetch(`https://account.imperiomc.click/${name}.json?`+new Date().getTime()), json = await res.json(), hash, skin;
    if (json.skins.slim != null){
        hash = await json.skins.slim
        skin = "Alex"
    } else {
        hash = await json.skins.default
        skin = "Steve"
    }
    console.log("Skin model is "+skin)
    return hash
}
function populateAuthAccounts(){
    const authAccounts = ConfigManager.getAuthAccounts()
    const authKeys = Object.keys(authAccounts)
    if(authKeys.length === 0){
        return
    }
    const selectedUUID = ConfigManager.getSelectedAccount().uuid

    let authAccountStr = ''
    authKeys.map((val) => {
        const acc = authAccounts[val]
        const hash = Ghash(acc.displayName)
        .then(function(hash) {
            const settingsCurrentAccounts = document.getElementById('settingsCurrentAccounts')
            let url = `https://account.imperiomc.click/preview/hash/${hash}?`+new Date().getTime();
            authAccountStr += `<div class="settingsAuthAccount" uuid="${acc.uuid}">
                <div class="settingsAuthAccountLeft">
                    <img class="settingsAuthAccountImage" alt="${acc.displayName}" src="${url}">
                </div>
    //[...]cropped code
                    <div class="settingsAuthAccountActions">
                        <button class="settingsAuthAccountSelect" ${selectedUUID === acc.uuid ? 'selected>Selected Account &#10004;' : '>Select Account'}</button>
                        <div class="settingsAuthAccountWrapper">
                            <button class="settingsAuthAccountLogOut">Log Out</button>
                        </div>
                    </div>
                </div>
            </div>`
            settingsCurrentAccounts.innerHTML = authAccountStr
        })  
    })
}

if the html code is outside the .then the function const hash = ghash(acc.displayName) does not return what I want
And if the code is inside the .then the buttons are invalid

Cypress and cypress-metamask plugin issue (connect ECONNREFUSED 127.0.0.1:9222)

I am trying to integrate cypress tests into my app, but in order to perform e2e tests I need to interact with metamask. I am using the cypress-metamask plugin (https://www.npmjs.com/package/cypress-metamask), but cannot get it to work.

Running the tests returns the following error:

cy.task(‘setupMetamask’) failed with the following error:

request to http://localhost:9222/json/version failed, reason: connect ECONNREFUSED 127.0.0.1:9222

This is the test:

describe('NFTicket', () => {
  beforeEach(() => {
    cy.setupMetamask();
    cy.changeMetamaskNetwork('localhost')
    cy.visit('/')
  });

  it('is expected to display a sussess message', () => {
    cy.get('[data-cy=title]').should('contain.text', 'MetaMask Detected')
  });
  
});

This is how my cypress/plugins/index.js is configured:

module.exports = (on, config) => {
  require('cypress-metamask/plugins')(on);
  on('before:browser:launch', (browser = { isHeaded: true }, arguments_) => {
    if (browser.name === 'chrome') {
      arguments_.args.push('--remote-debugging-port=9222')
      arguments_.args.push('--disable-background-timer-throttling');
      arguments_.args.push('--disable-backgrounding-occluded-windows');
      arguments_.args.push('--disable-renderer-backgrounding');
    }
  })
}

MySQL – Insert rows date and time between all intervals

I have a mysql database like this

---------------------------------------------------------------------------
|   startdate   |   starttime  |    enddate    |    endtime   |   status  |
---------------------------------------------------------------------------
|  2020-03-04   |   04:30:00   |  2020-03-04   |   09:00:00   |  running  |
|  2020-03-04   |   11:30:00   |  2020-03-04   |   19:30:00   |  running  |
|  2020-03-05   |   05:00:00   |  2020-03-05   |   11:15:00   |  running  |
|  2020-03-05   |   12:30:00   |  2020-03-05   |   22:08:00   |  running  |

---------------------------------------------------------------------------

I want know if is possible, create a php(or something like that) script to insert all intervals between date/time and create a row with status “stopped”.

Example:

---------------------------------------------------------------------------
|   startdate   |   starttime  |    enddate    |    endtime   |   status  |
---------------------------------------------------------------------------
|  2020-03-04   |   00:00:00   |  2020-03-04   |   04:30:00   |  stopped  | *created by this script
|  2020-03-04   |   04:30:00   |  2020-03-04   |   09:00:00   |  running  |
|  2020-03-04   |   09:00:00   |  2020-03-04   |   11:30:00   |  stopped  | *
|  2020-03-04   |   11:30:00   |  2020-03-04   |   19:30:00   |  running  |

etc.

---------------------------------------------------------------------------

Is this possible?

Sorry my english

automatically change height to content of

At the moment, I am working on a website that works with WordPress and Elementor (latest versions). I’m trying to implement an iframe using an html widget in the Elementor editor. The iframe works via an external website link (of a client) and I would like the iframe to automatically adjust in height to the content of the iframe. However, I am currently not getting this to work with the code below. In the Elementor editor itself it looks good, but on the website itself it is barely visible (due to the limited height) and it does not work. I have tried the following codes as well: height=”auto”, height=”100%”, but they didn’t work either.

Does anyone know how I can fix this, please? I did try some solutions on other topics, but these didn’t work either (and I’m not that good at coding). That’s why I created a new topic.

The code used:

<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/4.2.11/iframeResizer.min.js"></script><script
type="text/javascript">iFrameResize({ inPageLinks: true },
'#externallinkname')</script><iframe id="externallinkname"
src="https:// externallink.com/"
width="100%" scrolling="no"></iframe>

– Note: The names of the following codes are changed, due clients privacy: #externallinkname, id=”externallinkname”, src=”https:// externallink.com/”

Is it possible to embed a full “spotify” app inside a html document?

Now, this is something I can’t find info about…
There is a Spotify API, and playlist/song embeds, however, I would like to embed a full Spotify “app” inside my HTML document, I am trying to make an HTML5 Vehicle Interface, that logically supports music streaming, and I have not had any luck in getting Spotify working, apart from using Bluetooth and a phone.

I am asking if there is a way to get Spotify support/embed Spotify somehow into the HTML document iframes don’t work, Spotify has some protection in place to stop embedding.

This can also be some other music streaming service, just that something plays music.

Thanks in advance

how i am going to clearInterval when i press stop btn?

i am truly new with programing with javaScript so i just start to learn it, it will be good you are going to reply using a simple js code
my code does’nt stop when i press stop i want to clear the interval that i named with myTimer if i didn’t put setInterval inside the function it just work directly and if there is any way to make my code more short please mentiot it.

const // my variable
  myHour = document.getElementById("hours"),
  myMin = document.getElementById("min"),
  mySecond = document.getElementById("second"),
  myMiliSecond = document.getElementById("dsecond"),
  startchrono = document.getElementById("start"),
  getLap = document.getElementById("lap"),
  stopchrono = document.getElementById("stop"),
  resetchrono = document.getElementById("reset"),
  result = document.getElementById("result");
let // variable
  milisecond = 0,
  second = 0,
  minute = 0,
  hour = 0,
  chronoRun = false,
  round = 0;

function decoration(item) // this function is for add 0 if second or minute less than 10
  {
  if (String(item).length < 2) {
    item = "0" + item;
  }
  return item;
}

function lapset() // function that create a new row in the table to save rounds
 {
  round++;
  let // decoration add 0 if number under 10
    ds = decoration(milisecond),
    s = decoration(second),
    m = decoration(minute),
    h = decoration(hour);
  if (round <= 10) {
    const // insert the row in table
      tr = result.insertRow(-1);
    tr.insertCell(0).innerHTML = round;
    tr.insertCell(-1).innerHTML = h + ":" + m + ":" + s + ":" + ds;
  } else if (round <= 11) {
    tr = result.insertRow(-1);
    tr.insertCell(-0).innerHTML = "-";
    tr.insertCell(-1).innerHTML = "you can't add any more laps";
    getLap.setAttribute("disabled", "true");
  }
}

function chrono() //chrono start 
  {
  // chrono
  milisecond++;

  // make sure that minute, second have to be less than 60
  if (milisecond > 10) {
    milisecond = 0;
    second++;
  }
  if (second > 59) {
    second = 0;
    minute++;
  }
  if (minute > 59) {
    minute = 0;
    hour++;
  }
  let // decoration add 0 if number under 10
    ds = decoration(milisecond),
    s = decoration(second),
    m = decoration(minute),
    h = decoration(hour);

  myMiliSecond.innerHTML = ds;
  mySecond.innerHTML = s;
  myMin.innerHTML = m;
  myHour.innerHTML = h;
  startchrono.setAttribute("disabled", "true");
}
// function chronoStarts() {}
const myTimer = () => {
  setInterval(chrono, 100);
};

const test = () => {
  return clearInterval(myTimer);
};
startchrono.addEventListener("click", myTimer);
getLap.addEventListener("click", lapset);
stopchrono.addEventListener("click", test);
<!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" />
    <title>Document</title>
  </head>
  <body>
    <div id="chrono">
      <div id="timer">
        <span id="hours" class="time">00</span>
        <span class="sep">:</span>
        <span id="min" class="time">00</span>
        <span class="sep">:</span>
        <span id="second" class="time">00</span>
        <span class="sep">:</span>
        <span id="dsecond" class="time">00</span>
      </div>
      <div id="btnarea">
        <button id="start" class="btnevent">start</button>
        <button id="lap" class="btnevent">lap</button>
        <button id="stop" class="btnevent">stop</button>
        <button id="reset" class="btnevent">reset</button>
      </div>
      <table id="result">
        <caption>saved lap</caption>
        <tbody>
          <tr>
            <th class="round">round</th>
            <th class="laptime">time</th>
          </tr>
        </tbody>
      </table>
    </div>
    <script src="newpagescript.js"></script>
  </body>
</html>

and that is my html code i think every is ok with my code but if there any issue i am looking for adives

how can i put base64 image file into opencv? (javascript)

I’m trying to get random image from input video file, and then put the image into opencv to get grayScale image on the webpage.

Getting random image from video is solved by below-solution.

Javascript how to extract frame from video?

but now i’m stuck to the problem, Is it impossible to give base 64 source image file into opencv(imread, imshow, cv.cvtColor)? Please help me.

'''
//const cv = require("./js/opencv");
var video = document.createElement("video");
var image = new Image();

var canvas = document.getElementById("prevImgCanvas");
var canvas_after = document.getElementById("canvas_after");

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

video.addEventListener('loadeddata', function() {
  reloadRandomFrame();
}, false);

video.addEventListener('seeked', function() {

  var context = canvas.getContext('2d');
  context.drawImage(video, 0, 0, canvas.width, canvas.height);

  const dataurl = canvas.toDataURL("image/jpeg")
  image.src = dataurl;

  image.onload = function(){
  console.log(image);
  let mat = cv.imread(image);
  cv.imshow('canvasOutput', mat);

  mat.delete();
  };

}, false);

var playSelectedFile = function(event) {
  var file = this.files[0];
  var fileURL = URL.createObjectURL(file);
  video.src = fileURL;
}

var input = document.getElementById('fileinput');
input.addEventListener('change', playSelectedFile, false);

function reloadRandomFrame() {
  if (!isNaN(video.duration)) {
    var rand = Math.round(Math.random() * video.duration * 1000) + 1;
    video.currentTime = rand / 1000;
  }
}

'''

CSS Animation Cant Transform/Translate object to original location

so i am currently working on a animation for an error message. So my idea is when an error occurs that the error message will “fly in” from above to its desired location and fades in linear. If the Error Message is dismissed with the X Symbol on the Left it should leave as it entered. So fly up and fade out linear. So the first part the flying in works an looks as planned. But flying away dosent work at all although its animation just literally does the opposite as the flying in animation.

Working Flying In Animation:

enter image description here

But when i set the animation of the div from the message to fade out animation, nothing at all happens.

Heres the CSS:

.message{
    border: 0.2em black solid;
    padding: 1em 1em 1em 1em;
    display: flex;
    animation-name: messageMoveIn;
    animation-duration: .7s;
    animation-fill-mode: forwards;
}
.message p{
    float: left;
    margin-right: 1em;
}
.message p:hover{
    color: grey;
    cursor: grab;
}
@keyframes messageMoveIn { /* works */
    from{transform: translateY(-1em); opacity: 0;};
    to{transform: translateY(0em); opacity: 1;};
}
@keyframes messageMoveOut { /* dosent works */
    from{transform: translateY(0em); opacity: 1;};
    to{transform: translateY(+1em); opacity: 0;};
}

HTML:

    <div class="message">
        <p v-on:click="error = ''; success = ''" class="cancel-button">X</p>
        <div class="message-content">
            {{success || error}}
        </div>
    </div>

Btw since i use Vue JS and the div loads conditionally i dont have to bother about overflow after its gone. I really appreciate your help 🙂

How to add a transition/animation effect while changing position of a div using javascript

umm im making something which will hide my navbar on scroll and display it again accordingly which works well but was curious if i could make it more like an animation or transition.

Here’s my code so far

var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("bottom-navigation").style.bottom = "0";
   
  } else {
    document.getElementById("bottom-navigation").style.bottom = "-100px";
  }
  prevScrollpos = currentScrollPos;
}

ReactJS child components import resolution along with their parent component prefix

Hi folks I’m very curious to find a way for importing parent/child components with the prefix of their parent component using dot notation.

Before taking your much time I would like to show you guys an example from the react-bootstrap components import style.

import Modal from "react-bootstrap";

# usage

function Example() {
  return (
      <Modal show={show} onHide={handleClose}>
        <Modal.Header closeButton>
          <Modal.Title>Modal heading</Modal.Title>
        </Modal.Header>
        <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
        <Modal.Footer></Modal.Footer>
      </Modal>
  );
}

render(<Example />);

I’m trying to have this kind of a similar approach.

I have a Layout component and within that, I have 3 more child components Header, Body, and Footer.

Right now I’m using them like this

Layout.js

export const Header = ({ children }) => (
  <div className="header">{children}</div>
);

export const Body = ({ children }) => <div className="body">{children}</div>;

export const Footer = ({ children }) => (
  <div className="footer">{children}</div>
);

export const Layout = ({ children }) => {
  return <section>{children}</section>;
};

const _default = {
  Header: (props) => <Header {...props} />,
  Body: (props) => <Body {...props} />,
  Footer: (props) => <Footer {...props} />
};

export default _default;

App.js

import { Layout, Header, Body, Footer } from "./Layout";
import ParentLayout from "./Layout";

export default function App() {
  return (
    <div className="App">
      <Layout>
        <Header>Header goes here</Header>
        <Body>Body goes here</Body>
        <Footer>Footer goes here</Footer>
      </Layout>
      {/* as you can see from this example i can't use ParentLayout as a componet */}
      <Layout>
        <ParentLayout.Header>Header goes here</ParentLayout.Header>
        <ParentLayout.Body>Body goes here</ParentLayout.Body>
        <ParentLayout.Footer>Footer goes here</ParentLayout.Footer>
      </Layout>
      {/* so i was wondering if it can be done in this way */}
      {/* 
        <ParentLayout>
          <ParentLayout.Header>Header goes here</ParentLayout.Header>
          <ParentLayout.Body>Body goes here</ParentLayout.Body>
          <ParentLayout.Footer>Footer goes here</ParentLayout.Footer>
        </ParentLayout> 
      */}
    </div>
  );
}

I have created this playground so you can quickly hit and try.

jquery load page only work in first click

I use jquery to upload part of the code in PHP on changing or uploading data
it works fine in the first click but if I try to do it again not working

I use the same code for the first dropdown and it work so I did the same for the second one
the first one working fine and I can do change as many times

but the second one first click work if I try again nothing happen I need to refresh the page to make it work
There isn’t anything on the console
so I think I did something wrong with jquery

HTML

<ul class="nav nav-tabs nav-tabs-solid nav-tabs-rounded d-lg-flex justify-content-center">

    <li class="nav-item dropdown p-1">
        <a class="nav-link dropdown-toggle active" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Status </a>
        <div class="dropdown-menu">
            <a class="dropdown-item active" id="all" data-toggle="tab">all</a>
            <a class="dropdown-item " id="new" data-toggle="tab">New</a>
            <a class="dropdown-item" id="connected" data-toggle="tab">Connected</a>
            <a class="dropdown-item" id="canceled" data-toggle="tab">canceled</a>

        </div>
    </li>

    <li class="nav-item  p-1  ">
        <div class="btn-group">
            <button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <!-- <span class="sr-only">Toggle Dropdown</span> -->
                Edit
            </button>
            <div class="dropdown-menu">

                <a class="dropdown-item" id="toconnected">Connected</a>
                <a class="dropdown-item" id="tocanceled">canceled</a>

            </div>
        </div>
    </li>

</ul>
<table class="table table-hover table-center text-center mb-0  resp-table schedule">
    <thead>
        <tr>
            <th class=""> </th>
            .
            .
            .
            <th></th>
        </tr>
    </thead>
    <tbody id="serviceTable">
        <?php foreach ($call as $i) { ?>
            <tr>
                <td>
                    <input type="checkbox" class="checkbox" value="<?php echo $i['Order_id']; ?>" name="Order_id" id="<?php echo $i['Order_id']; ?>">
                </td>
                .
                .
                
            </tr>
        <?php } ?>
    </tbody>
</table>

jqury

$(function(){

    //view base on status of the order 
    $('a[id=new]').on('click', function(){

        $("#serviceTable").load("..//..//forms//load-schedule-communication.php"//)
        , {
            filter: "new"
        });
    })
    //for the edit
    $('a[id=toconnected]').on('click', function(){

        var orderids =document.querySelectorAll('.checkbox');
        for (var orderid of orderids) {
            if(orderid.checked){
                var filterstatus='';
                var statusOrders = document.getElementsByClassName("dropdown-item active");
                for (var statusOrder of statusOrders) {
                    
                        if(statusOrder.id=='new'){
                            filterstatus='new';
                        }
                        else if (statusOrder.id=='connected'){
                            filterstatus='connected';
                        }
                        else if(statusOrder.id=='pending'){
                            filterstatus='pending';
                        }
                        else if(statusOrder.id=='no_response'){
                            filterstatus='no_response';
                        }
                        else if(statusOrder.id=='all'){
                            filterstatus='all';
                        }
                        else if(statusOrder.id=='delete'){
                            filterstatus='delete';
                        }
                }

                $("#serviceTable").load("..//..//forms//load-schedule-communication.php"//)
                , {
                    statusto: "connected",
                    id: orderid.id,
                    statusorder: filterstatus
                });
            }
        }
        
    })
    
    
})

How to do an accordion with HTML and JS

I want an accordion to drop down when a user clicks on the greater than sign.

enter image description here

    <div class="row">
                    <div class="col-2">
                        <p>DEP-08B827E791<button class="accordion"><i class="fa-solid fa-greater-than fa ps-1"></i></button></p>
                    </div>
                    <div class="col-3">
                        <P>Omodeko Divine</P>
                    </div>
                    <div class="col-2">
                        <p>EE</p>
                    </div>
                    <div class="col-3">
                        <p>[ETHIOPE EAST]</p>
                        <P>DELSU HEALTH CENTER ABRAKA</P>
                    </div>
                    <div class="col-2">
                        <button class="btn btn-primary">GENERATE ID</button>
                    </div>
                    <div class="panel" onclick="document.getElementByclassname(panel).style.display='none'">
                      <p>No, but there must be adequate evidence that would help to support your claim.</p>
                    </div>
                </div>

This is the javascript

    var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
/* Toggle between adding and removing the "active" class,
to highlight the button that controls the panel */
this.classList.toggle("activee");

/* Toggle between hiding and showing the active panel */
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
  panel.style.display = "none";
} else {
  panel.style.display = "block";
}});}

On click of the greater than sign, the .panel is supposed to dropdown.