TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension “.jpg”

I am trying to create an api in my server.js file for a react app. I connected the server and as soon as I imported data.js and set it to the api/products page it gave me the error.

    import express from 'express';
    import data from '../src/data.js';

    const app = express();

    app.get('/api/products', (req, res) => {
        res.send(data.products);
});

app.get('/', (req, res) => {
    res.send('Server is ready');
});

app.listen(5000, () => {
    console.log('Serve at http://localhost:5000');
});

How to Render Fetched Object Items in React Component

How do I render an object that I’ve fetched in React?

Here is my code:

const PrayerTimesByCity = () => {
  // Initiate array for fetching data from AlAdhan API
  const [data, setPrayerTimes] = useState({});

  useEffect(() => {
    fetch(
      "http://api.aladhan.com/v1/timingsByCity?city=Helsingborg&country=Sweden&method=0"
    )
      .then((resp) => resp.json())
      .then((data) => setPrayerTimes(data));
  }, []);

  console.log(data);

  return <div> // Here is where I want my objects to return </div>;
};

Here is what the fetched data returns:

{
  "code": 200,
  "status": "OK",
  "data": {
    "timings": {
      "Fajr": "06:42",
      "Sunrise": "09:00",
      "Dhuhr": "12:13",
      "Asr": "13:17",
      "Sunset": "15:27",
      "Maghrib": "16:00",
      "Isha": "17:29",
      "Imsak": "06:32",
      "Midnight": "00:13"
    }
}

I want to extract “data” and then “timings” and then each respective item and its key. How do I do this in my return statement in my component?

Thanks for any answer in advance

make a function globally available via webpack

I have a .ts file that contains a function, and I want to compile this file into .js file via webpack to be loaded in index.html.

I need this function to be globally available in index.html

index.html

<script src="./myfile.js"></scrit>
<script>
  console.log(myfunction);
// ----> error: myfunction is not defined
</scrit>


<script type="module">
  import myfunction from './myfile'
  console.log({myfunction})
// ----> error: requested module './myfile.js' does not provide an export named 'myfunction'
</script>

myfile.ts

export myfunction = function(){}

webpack.config

{
    mode: 'development',
    devtool: false,
    target: [ 'web', 'es5' ],
    profile: false,
    resolve: {
      roots: [Array],
      extensions: [Array],
      symlinks: false,
      modules: [Array],
      mainFields: [Array],
      plugins: [Array],
      alias: [Object]
    },
    resolveLoader: { symlinks: true, modules: [Array] },
    context: '/home/sh_eldeeb_2010/@eng-dibo/dibo/projects/ngx-cms',
    entry: {
      main: [Array],
      'polyfills-es5': [Array],
      polyfills: [Array],
      styles: [Array],
      scripts: './scripts.ts'
    },
    output: {
      clean: true,
      path: './dist',
      publicPath: '',
      filename: '[name].js',
      chunkFilename: '[name]-es2015.js',
      crossOriginLoading: false,
      trustedTypes: 'angular#bundler',
      library: undefined,
      libraryTarget: 'commonjs2'
    },
    watch: false,
    watchOptions: { poll: undefined, ignored: '**/$_lazy_route_resources' },
    performance: { hints: false },
    ignoreWarnings: [
      /System.import() is deprecated and will be removed soon/i,
      /Failed to parse source map from/,
      /Add postcss as project dependency/
    ],
    module: {
      strictExportPresence: true,
      rules: [Array],
      noParse: //native-require.js$/
    },
    experiments: { syncWebAssembly: true, asyncWebAssembly: true },
    cache: false,
    optimization: {
      minimizer: [Array],
      moduleIds: 'deterministic',
      chunkIds: 'deterministic',
      emitOnErrors: false,
      runtimeChunk: 'single',
      splitChunks: [Object]
    },
    plugins: [
      [ContextReplacementPlugin],
      [DedupeModuleResolvePlugin],
      [ProgressPlugin],
      [LicenseWebpackPlugin],
      [CommonJsUsageWarnPlugin],
      [AnyComponentStyleBudgetChecker],
      [Object],
      [MiniCssExtractPlugin],
      SuppressExtractedTextChunksWebpackPlugin {},
      [NgBuildAnalyticsPlugin],
      [AngularWebpackPlugin],
      [FilterErrors]
    ],
    node: false,
    stats: {
      all: false,
      colors: true,
      hash: true,
      timings: true,
      chunks: true,
      builtAt: true,
      warnings: true,
      errors: true,
      assets: true,
      cachedAssets: true,
      ids: true,
      entrypoints: true
    },
    externals: []
  },
  entry: {
    myfile: './myfile.ts'
  }
}

dropdown list displaying problems

I have 2 problems in my code , as you see I have a navbar that contain 6 items 2 of them should display a dropdown list when clicked .

I was able to make them display a dropdown list but there is a problem .

problem 1 : when I click on on of the 2 items both drop down list shows up , but what i want is that each item shows its dropdown list , plus I want when clicking outside the list for it to close.

problem 2 : when clicking on the other 4 items there is a path that i put to them , but it seem to work with the two item that shows a dropdown list , and i dont want that i want them with no path .

this is my navitem.js :

export const navItems = [
 {
      id: 1,
      title: "mybook",
      path: "./mybook",
      cName: "navitem",
    },
    {
      id: 2,
      title: "mylab",
      path: "./mylab",
      cName: "navitem",
    },
    {
      id: 3,
      title: "marks",
      path: "./marks",
      cName: "navitem",
    },
    {
      id: 4,
      title: "trash",
      path: "./trash",
      cName: "navitem",
    },
    {
        id: 5,
        title: "mywork",
        path: "./mywork",
        cName: "navitem",
      },
      {
        id: 6,
        title: "set",
        path: "./set",
        cName: "navitem",
      },
  ];
  
  export const mybookDropdown = [
    {
      id: 1,
      title: "fav",
      path: "./fav",
      cName: "submenu-item",
    },
    {
      id: 2,
      title: "continue",
      path: "./continue",
      cName: "submenu-item",
    },
  ];
  export const mylabDropdown = [
    {
      id: 1,
      title: "dailycheck",
      path: "./dailycheck",
      cName: "submenu-item",
    },
    {
      id: 2,
      title: "recommendation",
      path: "./recommendation",
      cName: "submenu-item",
    },
    {
        id: 3,
        title: "popular",
        path: "./popular",
        cName: "submenu-item",
      },
  ]; 

and here is my Dropdown.js :

import React, { useState } from "react";
import { mybookDropdown , mylabDropdown } from "./NavItems";
import { Link } from "react-router-dom";
import "./Dropdown.css";

function Dropdown() {
  const [dropdown, setDropdown] = useState(false);

  return (
    <>
      <ul
        className={dropdown ? "mybook-submenu clicked" : "mybook-submenu"}
        onClick={() => setDropdown(!dropdown)}
      >
        {mybookDropdown.map((item) => {
          return (
            <li key={item.id}>
              <Link
                to={item.path}
                className={item.cName}
                onClick={() => setDropdown(false)}
              >
                {item.title}
              </Link>
            </li>
          );
        })}
      </ul>
      <ul
        className={dropdown ? "mylab-submenu clicked" : "mylab-submenu"}
        onClick={() => setDropdown(!dropdown)}
      >
        {mylabDropdown.map((item) => {
          return (
            <li key={item.id}>
              <Link
                to={item.path}
                className={item.cName}
                onClick={() => setDropdown(false)}
              >
                {item.title}
              </Link>
            </li>
          );
        })}
      </ul>
    </>
  );
}

export default Dropdown;

lastly here is what I added to the navbar.jsx :

import { navItems } from "./NavItems";
import Dropdown from "./Dropdown";

export default function navbar() {
  const [dropdown, setDropdown] = useState(false);

 return (
<ul className={[styles.navitem]}>
              {navItems.map((item) => {
                if (item.title == "mybook")
                return(
                  <li key={item.id} className={item.cName}
                    onClick={() => setDropdown(true)}
                  >
                    <Link to={item.path}>{item.title}</Link>
                  </li>
                );
                else if (item.title == "mylab")
                return(
                  <li key={item.id} className={item.cName} 
                    onClick={() => setDropdown(true)}
                  >
                    <Link to={item.path}
                    >{item.title}</Link>
                  </li>
                );
                return(
                  <li key={item.id} className={item.cName}>
                    <Link to={item.path}>{item.title}</Link>
                  </li>
                );
              }
              )}
            { dropdown && <Dropdown />}
            </ul>
 );
}

How to pass data on django ajax?

how to pass filter data from Django model/view to ajax? I tried to pass the data but, it’s showing no result. The ajax return field is blank. From the request get method I tried to post the data, that’s working fine. With the ajax method, I tried to do as follows, but it’s throwing just a blank area. I tested on console, the filter value is correctly passed to views but from views, it’s not fetching correctly. Is it an ajax success problem or do my views has any other issue? Please help me

My HTML:

<ul class="widget-body filter-items ">
                                            {% for categories in categories%}
                                            <li  class = "sidebar-filter " data-filter="category" data-value="{{categories.id}}" ><a href="#">{{categories.name}}</a></li>
                                            
                                        {% endfor %}
                                        </ul>



<div class="product-wrapper row cols-lg-4 cols-md-3 cols-sm-2 cols-2">


{% for product in products%}

                    <div id = "product-wrapper" class="product-wrap product text-center">
{{product.name}}
{% endfor%}
</div>
</div>

Ajax:

$(document).ready(function () {
  $('.sidebar-filter').on('click', function () {
    var filterobj= {};
    $(".sidebar-filter").each(function(index, ele){
    
     /**var filterval = $(this).attr('data-value');*/
     /**var filterval = $(this).value=this.attr('title');*/
      /**var filterval = $(this).val($(this).text());*/
      var filterval=$(this).data("value");
      var filterkey = $(this).data('filter');
    
      
    filterobj[filterkey]= Array.from(document.querySelectorAll
      ('li[data-filter=' + filterkey+'].active')).map(function(el){
        /**return $(el).data("value");*/
        return $(el).data("value")
        /** return el.getAttribute('data-value');*/
      });
          
  
      
});
console.log(filterobj)   
  $.ajax ({
  url:"/products/filter-data",
  data:filterobj,
  datatype:'json',
  success:function(res){
   
    console.log(res.data)
    var bodyOnly = $(res.data).find('.product-wrapper').html();
    $('.product-wrapper').html(bodyOnly);
    console.log(bodyOnly)
    
  


}

});
});
});

My views.py:

def catfilter(request): 
    categories = request.GET.getlist('category[]')
    brands = request.GET.getlist('brands[]')
    products=Products.objects.filter(is_published=True).order_by('-id')
    
                   
    if len(categories)>0:
        products=Products.objects.filter(is_published=True).order_by('-id')
                        
    if len(brands)>0:
        products=Products.objects.filter(is_published=True).order_by('-id')
   
                      
    json_sort=render_to_string("./ecommerce/shop.html",{'data':products})
    return JsonResponse({'data':json_sort})

TypeError: The ‘compilation’ argument must be an instance of Compilation (React)

I get the following error when I run npm start on my react project. Everything was working fine until I added a few scripts and installed recharts. I’ve tried npm install, npm cache clean --force, removed package-lock.json and installed again, stash my changes but nothing seems to work.

home/bisola/Documents/pro/gitcoin/subquery/explorer/node_modules/react-scripts/scripts/start.js:19
  throw err;
  ^

TypeError: The 'compilation' argument must be an instance of Compilation
    at Function.getCompilationHooks (/home/bisola/Documents/pro/gitcoin/subquery/explorer/node_modules/webpack/lib/NormalModule.js:193:10)
    at /home/bisola/Documents/pro/gitcoin/subquery/explorer/node_modules/webpack-manifest-plugin/dist/index.js:57:42
    at _next38 (eval at create (/home/bisola/Documents/pro/gitcoin/subquery/explorer/node_modules/tapable/lib/HookCodeFactory.js:19:10), <anonymous>:50:1)
    at _next16 (eval at create (/home/bisola/Documents/pro/gitcoin/subquery/explorer/node_modules/tapable/lib/HookCodeFactory.js:19:10), <anonymous>:97:1)
    at Hook.eval [as call] (eval at create (/home/bisola/Documents/pro/gitcoin/subquery/explorer/node_modules/tapable/lib/HookCodeFactory.js:19:10), <anonymous>:133:1)
    at Hook.CALL_DELEGATE [as _call] (/home/bisola/Documents/pro/gitcoin/subquery/explorer/node_modules/tapable/lib/Hook.js:14:14)
    at Compiler.newCompilation (/home/bisola/Documents/pro/gitcoin/subquery/explorer/node_modules/react-scripts/node_modules/webpack/lib/Compiler.js:1055:26)
    at /home/bisola/Documents/pro/gitcoin/subquery/explorer/node_modules/react-scripts/node_modules/webpack/lib/Compiler.js:1099:29
    at Hook.eval [as callAsync] (eval at create (/home/bisola/Documents/pro/gitcoin/subquery/explorer/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:6:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/home/bisola/Documents/pro/gitcoin/subquery/explorer/node_modules/tapable/lib/Hook.js:18:14)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `react-scripts start`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/bisola/.npm/_logs/2021-12-27T20_51_51_714Z-debug.log

Slot Mpo | Login Slot Mpo | Daftar Slot Mpo | Link Alternatif Slot Mpo

COINMPO >> DAFTAR SEKARANG

AMANMPO >> DAFTAR SEKARANG

DUNIAMPO >> DAFTAR SEKARANG

Selamat datang di slot mpo yang merupakan situs judi online24jam terpercaya dan terbaik di Indonesia dengan bermacam – macam permainan judi online. Slot mpo menyediakan permainan judi bola online, judi casino online, judi poker online, judi slot online, judi togel online dan masih banyak lagi permainan judi online seru lainnya. Dimana hanya dengan 1 user id anda sudah bisa memainkan semua permainan judi yang terdapat di website agen judi online terpercaya slot mpo. Anda juga bisa bermain judi lewat smartphone anda karena situs slot mpo telah mendungkung perangkat android dan ios. Selain menjadi situs judi online terpercaya, slot mpo juga merupakan bandar judi online terpercaya yang sudah terkenal selama bertahun – tahun yang selalu memberikan pelayanan yang baik dan ramah kepada semua masyarakat Indonesia. Slot mpo selalu siap online 24jam untuk semua member setia mereka dan pastinya akan selalu membayar berapapun kemenangan membernya.

Slot Mpo | Agen Slot Mpo | Situs Slot Mpo | Bandar Slot Mpo

Slot mpo adalah situs judi slot online terpercaya dan terbaik di Indonesia yang menyediakan banyak sekali provider judi slot online yang sangat terkenal di Indonesia. Untuk anda yang sedang mencari agen judi slot online kami sangat merekomendasi situs slot mpo sebagai agen slot yang sangat tepat untuk bermain. Slot mpo memiliki sistem keamanan yang sangat aman serta sangat menjaga data – data para member yang bermain di situs judi resmi slot mpo. Selain itu win rate untuk permainan slot online yang terdapat di slot mpo juga sangat besar yaitu 90%, Jadi kemenangan sangat berpihak kepada para member yang bermain di agen slot mpo. Promo bonus yang terdapat disini juga lebih besar diantara agen judi slot online lainnya dan proses deposit dan withdraw sangat cepat hanya butuh hitungan detik. Jadi untuk anda yang sering kalah dalam permainan slot, Anda bisa mencoba bermain di slot mpo yang terkenal sebagai bandar judi slot online gacor gampang menang.

Slot Mpo Situs Judi Online Indonesia Terpercaya

Slot mpo berani menjamin untuk selalu memberikan kemenangan terbesar untuk para pecinta judi online, Baik untuk member baru atau member lamanya. Selain itu slot mpo menyediakan banyak sekali bank lokal indonesia yang bertujuan untuk mempermudah semua member mereka untuk melakukan transaksi. Kami berani menjamin kalau anda tidak akan nyesal jika bergabung bersama slot mpo karena website judi online ini menang tidak ada kurangnya. Slot mpo memberikan minimal deposit yang sangat murah dan minimal bet yang terdapat di situs ini sangat kecil. Jadi untuk anda yang masih ragu untuk bermain di slot mpo anda bisa melakukan deposit kecil terlebih dahulu dan mencoba semua permainan di situs slot mpo. Segera daftar dan bergabung bersama situs judi online terpercaya slot mpo yang selalu siap memberikan palayanan terbaik kepada semua membernya serta permainan judi online yang sangat lengkap. Anda bisa langsung klik link alternatif slot mpo dibawah ini untuk melakukan pendafataran di website resmi slot mpo.

Hide list items when searching

I have a list of items that I would like to filter, at the moment all of the items are visible but how can I make it so that the results only show when a user types a name?

I tried changing the li to be block but did work.

 li[i].style.display = "none";

I am new to JS and currently doing some courses.

function myFunction() {
    var input, filter, ul, li, a, i, txtValue;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    ul = document.getElementById("myUL");
    li = ul.getElementsByTagName("li");
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        txtValue = a.textContent || a.innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}
<h2>Car Directory</h2>

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for Cars" title="Type in a name">

<ul id="myUL">
  <li><a href="#">Volvo</a></li>
  <li><a href="#">BMW</a></li>
  <li><a href="#">Mazda</a></li>
  <li><a href="#">Toyota</a></li>
  <li><a href="#">Yamaha</a></li>
  <li><a href="#">Honda</a></li>
  <li><a href="#">Dodge</a></li>
</ul>

Here is my pen:
https://codepen.io/emmabbb/pen/wvrpqbp

How to setup linting rules for functions calls without brackets ()

Coming from java, I’ve spent many a day debugging what almost inevitably could be summed up as the compiler/linter not warning of function calls made without the brackets.

i.e with a class as such:

export class democlass {

function demofunction(){

    }
}

Very often, in TS/js, on calling demofunction from another class, I’ll do this

instanceOfDemoClass.demofunction

instead of

instanceOfDemoClass.demofunction();

Obviously, in java, the compiler will immediately scream at you, a behaviour which Ts/VScode doesn’t exactly emulate.

I’d like to setup a rule to warn about this call if, of course, the called class doesn’t contain a property named “demofunction”.

Any help/experience with this problem?

Cheers

Dynamic module imports is empty when inside Docker

When I use await import(module) inside Docker the module is just an empty object. Outside of docker everything works as intended.

Node: v16.13.1
Docker: Docker version 20.10.7, build f0df350
Image: node:16

The Code:

import path from "path";

export const WorkerLoader = async () => {
    // import Worker from the public directory => copied from docker
    const here = "file://" + path.resolve("./worker/worker.js"); // worker.wasm.js & worker.wasm don't work in node
    const WorkerModule = await import(here);

    WorkerModule().then(callback); // no, its not a promise
}

If I log WorkerModule I get [Module: null prototype] { }. I’ve also tried to do it with WorkerModule.default but this is undefined.

I can’t just simply change the code to a normal import because it need those exact functions to be present due to a shared code basis for web and nodejs, where I use module-alias to make my own implementations of modules, that were designed for the web.

Edit:
The worker.js file has at the end

if (typeof exports === 'object' && typeof module === 'object')
  module.exports = Worker;
else if (typeof define === 'function' && define['amd'])
  define([], function() { return Worker; });
else if (typeof exports === 'object')
  exports["Worker"] = Worker;

JavaScript – Algorithm To Filter Data On Click

On the frontend the user will click on multiple options and all that will be stored in an array as objects as shown in dataToFilter variable below. Then when user clicks on search button, the array will be sent to the backend and the api route will run the algorithm filtering the data based on the items in the array and return the filtered data to the user. My question – how can I run a filter loop on the data matching the items in the array to search for? One way I can think of is checking the length of the array and setting the number of && accordingly within the filter loop but I dont think that would be the appropriate way to go about it. Thank you for reading this post.

***Dummy Data To Search From***
let data = [
{"name":"Testing", "age":32,"score": 95, "gender":"male"},
{"name":"Testing", "age":22,"score": 85, "gender":"female"},
{"name":"Testing", "age":32,"score": 85, "gender":"male"},
{"name":"Testing", "age":52,"score": 95, "gender":"female"},
]
***Filter Data***
let dataToFilter = [{"age":32},{"score": 95}]
let filteredData = []

filteredData = data.filter((item)=>{
   return item.age === 32 && item.score === 95
)

Node.JS main loop will not return

I am trying to setup a template site using Node.JS. I am new to using Node.JS and am trying to open up an HTML file and a CSS file before continuing towards the rest of the code. However, even upon reaching reponse.end(), the loop continues to run, and in fact goes for a second time, but does not make it to the end again. I threw in some console.log()s in order to demonstrate this. I will throw both my JS code and mode console output down below. I do not know how to fix this, and any help would be appreciated. Thank you all very much!

const server = require('http').createServer()
const markdown = require( "markdown" ).markdown

const fs = require('fs')

server.on('request', (request, response) => {
    response.setHeader('Content-Type', 'text/html')
    var page = fs.readFileSync("html/tb.html", 'utf8')
    console.log("reading html...")
    page+= "<style>"+fs.readFileSync("css/style.css", 'utf8')+"</style>"
    console.log("reading css...")
    const lang = Intl.DateTimeFormat().resolvedOptions().locale
  
    if (request.url === '/') {
        response.end()
    }
    else if (request.url === '/coucou') {
        page+=markdown.toHTML('#Hello world!')
        response.end(page)
        console.log("end")
    }
})

server.listen(4000)

I am sorry for my lack of NodeJS experience, but I could not seem to find an answer to this question anywhere else. Here is my console output when loading ‘coucou’:

reading html...
reading css...
end
reading html...
reading css...

And here it is on the homepage

reading html...
reading css...
reading html...
reading css...

It does not continue after the second round, but the browser never receives an end signal, and therefore continues to load indefinitely. How do I get it to actually process the end of the response and to tell my browser to stop loading?

Again, thank you all very much!!!