set Dynamic Default Value for select dropdown in react

I have a form, where I need to set the default value of the select dropdown in formik.

SelectDropDown.js

{props.options.map((option) => {
    return (
        <option key={option.id} value={option.id} title={option.title}>
            {option.name}
        </option>
    );
})}

Code Sandbox LINK

App.js

<SelectDropdown
    control="select"
    name="episodeType"
    data-testid="episodeType"
    id="episodeType"
    label="Episode Type"
    options={dropDownValues} // how to pass defualt a props
/>

How to pass the default values as props so the page is loaded the values is selected.

Thank you.

How to select variant class in styled components?

In styled-components we can have contextual styles using component selector patterns. But how do we parents variant to contextual the child component? For example, we have three components here, Child, NoteWrapper, and Note.

const Child = styled.div<{ editing?: boolean }>`
  ${props => props.editing && css`some styles`}
`

const NoteWrapper = styled.div<{ compact?: boolean }>`
  ${props => props.compact && css`some styles`}
`

const Note = styled.input`

/* How do I style this when Child is editing and NoteWrapper is compact */

`

const App = () => {
  return (
   <Child editing>
    <NoteWrapper compact>
     <Note/>
    </NoteWrapper>
   </Child>
  )
}

`

With plain CSS we could do something like this


.child.editing .note-wrapper.compact .note {
  /* Contextual styles here */
}

My question is how do I style Note when Child is editing and NoteWrapper is compact in styled components selector pattern ?

how to retrieve key and value from object search?

I want to find a page url searching by an input. I have an object that contains keywords and urls. Then when press enter it will do a check, if the keywords are the same or exist, it will display the url, if not it will display not found.

So for example in the input I type “home”, when I enter it will display the url “/homepage” because the keywords are exist, if I type “contact” it will show not found because the keywords doesn’t exist.

I’ve made the code like below but why the map doesn’t work? can anyone help me?

$(document).ready(function(){
  $("#searchKeywords").on("keypress", function(e){
    if(e.which == 13){     
      const pageKeywords = {
        "home" : "/homepage",
        "about" : "/about-us"
      }

      pageKeywords.map((key,value) => {
        console.log(key)

        if($(this).val() == key){
          console.log(value)
        }else{
          console.log('not found')
        }
      })
    }
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="searchKeywords">

populate items from promotion node express js

promotion Modele

    const mongoose = require("mongoose");

const PromotionSchema = mongoose.Schema({
    name: { type: String, required: true },
    item1: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "itemPromotion",
        required: true,
    },
    item2: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "itemPromotion",
        required: false,
    },
    item3: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "itemPromotion",
        required: false,
    },
    

    startDate: { type: Date, required: false },
    endOfDate: { type: Date, required: false },
    status: { type: Boolean, required: false },
    totalPrice: { type: Number, required: false },
    discount: { type: Number, required: false },
});
module.exports = new mongoose.model("Promotion", PromotionSchema);

promotion Items its item with price and quantity and discount pourcent in promotion

    const mongoose = require("mongoose");

const ItemPromotionSchema = mongoose.Schema({
    item: { type: mongoose.Schema.Types.ObjectId, ref: "Item", required: true },
    price: { type: Number, required: true },
    quantity: { type: Number, required: true },
    discount: { type: Number, required: true },
});

module.exports = new mongoose.model("itemPromotion", ItemPromotionSchema);

items its the orginal item

const mongosse = require("mongoose");

const ItemSchema = mongosse.Schema({
code: {
type: String,
required: true,
},
label: {
type: String,
required: true,
},

itemCategory: {
    type: mongosse.Schema.Types.ObjectId,
    ref: "ItemCategory",
    required: false,
},
// category: {
//     type: CategorySchema,
//     required: false,
// },
itemFamilly: {
    type: mongosse.Schema.Types.ObjectId,
    ref: "ItemFamilly",
    required: false,
},
description: {
    type: String,
    required: false,
},
picture: {
    type: String,
    required: false,
},

Price: [{
    type: mongosse.Schema.Types.ObjectId,
    ref: "Price",
    required: false,
}, ],
tempPrice: { type: Number, required: false },

active: {
    type: Boolean,
    required: true,
},

});

module.exports = new mongosse.model(“Item”, ItemSchema);

and I have also the methode get (route)
where I need to get my data
promotion with itemsPromotions with label of item

   router.get("/config", async(req, res) => {
    try {
        const PromotionInDataBase = await Promotion.find().populate("item1").populate("item1.item");

        res.json(PromotionInDataBase);
    } catch (error) {
        res.json({ message: error });
    }
});

Detect pixelated images by using opencv and javascript

I’m trying to find out whether user uploaded photo is blur/pixelated. For that i’m using OpenCV4Nodejs package. It only detects blur not the pixelated one. So i found a python code to detect pixelated images but i wanted to do it in node/javascript. I tried converting it but couldn’t as i’m new to python. Can someone help me convert it. if cannot then could you please suggest is there any other way we can detect pixelated images?

Python Code:

import numpy as np
import Image, ImageChops

im = Image.open('fireworks-pixelate-02.gif')    
im2 = im.transform(im.size, Image.AFFINE, (1,0,1,0,1,1))
im3 = ImageChops.subtract(im, im2)
im3 = np.asarray(im3)
im3 = np.sum(im3,axis=0)[:-1]
mean = np.mean(im3)
peak_spacing = np.diff([i for i,v in enumerate(im3) if v > mean*2])
mean_spacing = np.mean(peak_spacing)
std_spacing = np.std(peak_spacing)
print 'mean gap:', mean_spacing, 'std', std_spacing

How to insert a javascript file in another javascript at build time file using a comment

Is there something on npm or in VS Code or anywhere that can bundle or concatenate Javascript files based on comments, like:

function myBigLibrary(){
    //@include util.js
    //@include init.js

    function privateFunc(){...}

    function publicFunc(){
      //@include somethingElse.js
      ...
    }

    
    
    return {
        init, publicFunc, etc
    }
}

Or something like that? I would think that such a thing is common when your javascript files get very large. All I can find are complicated things like webpack.

Optimize Angular Distribution

I have an Angular project and it uses a bunch of Javascript Libraries, starting with jQuery, going through Modal Forms, Tooltips and many more, mostly from third party providers. The thing is that, even when my Angular website makes use of these Libraries, the Website does not make exactly FULL use of the complete Libraries, but at the moment of Building the Dist files, the styles.xx.css and main.js are quite big files containing all these Libraries and Styles inside.

So, I was thinking there must be a way to only include in the final Distribution, only the “actual” code that is used by the Website and not the complete Libraries that includes the used and unused code. There are many features in those Libraries that the Website actually does not use, but these are at the same time, big files that make it difficult to just get in there and remove code by hand.

If there would be some sort of Code Coverage test that I can run on the complete website, just to “mark” all the actual used code and remove/discard from Dist compilation, all the unused code, that would be just awesome. This would be no-doubt a very efficient way to put on diet the Production compilations on any website.

Anyone knows if something like this exists?

How to print page exactly it looks on screen using window.print()?

I have designed a form for my project and I want to print the form. The form looks like below:
Actual Form

I was trying to use window.print() method to print it. But it changed the style in print preview like below: print preview

Here’s my code that I’ve done. Let me know if there any possible way to solve this issue and print exactly it shown in the window. Thanks in advance.

<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8">
    <title></title>
    
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    
    <link rel="stylesheet" type="text/css" href="Registrationform.css">
</head>
<body>



<div style="width:670px; padding:30px; box-shadow: 5px 5px 5px 5px #888888;" class="container">
        <table style="margin: auto;">
            <tr>
                <td><img width="60px" height="60px" src="imagesNSTU-logo.png"></td>
                <td>
                <div class = "header-name">
                <h6 style="text-align: center; margin: 0 auto;">NOAKHALI SCIENCE AND TECHNOLOGY UNIVERSITY</h6>
                <p style="text-align: center; margin:auto;">Noakhali-3814, Bangladesh</p>
                <h6 style="text-align: center;margin: auto;">COURSE REGISTRATION FORM</h6>
                </div>
            </td>
            </tr>
        </table>
        <hr>
        

    
        <form action="" method="POST">
            <!-- <div style=" align-content: center;" class = "std-header-info"> -->
                 <div>
                     <label>Name</label>
                     <input class="text" style = "width: 365px; text-align: center;" type="text" id = 'name' placeholder="" value="Khair" readonly>
                     <label>Roll</label>
                     <input class="text" style = "width: 160px; text-align: center;" type="text" id = 'roll' placeholder="" value="12" readonly> <br>
                 </div>
                 <div>
                    <label>Department</label>
                     <input class="text" style = "width: 230px; text-align: center;" type="text" id = 'department' placeholder="" value="IIT" readonly>
                     <label>Institute/Faculty</label>
                     <input class="text" style = "width: 165px; text-align: center;" type="text" id = 'institute' placeholder="" value="IIT" readonly>
                     <br/>
                 </div>

                 <div>
                     <label>Year</label>
                     <input class="text" style = "width: 120px; text-align: center;" type="text" id = 'year' placeholder="" value="2012" readonly>
                     <input type="hidden" name="year" value="" />

                     <label>Term</label>
                     <input class="text" style = "width: 150px; text-align: center;" type="text" id = 'term' placeholder="" value="2" readonly>

                     <label>Session</label>
                     <input class="text" style = "width: 200px; text-align: center;" type="text" id = 'session' placeholder="" value="2017" readonly>
                 </div>
                 <br/>


            


                 <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>Course Code</th>
                                <th>Course Title</th>
                                <th>Credits</th>
                                <th>Remarks</th>
                            </tr>
                        </thead>
                        <tbody>
                            
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            
                        </tbody>
                    </table>
                 </div>
                 
                 <div>
                     <table style="font-size: 10px;" class="table table-bordered" id="table">
                        <tr class="borderless">
                            <td style="border: none;"></td>
                            <td style="border: none;"></td>
                            <td colspan="2">Year 1</td>
                            <td colspan="2">Year 2</td>
                            <td colspan="2">Year 3</td>
                            <td colspan="2">Year 4</td>
                            <td colspan="2">Year 5</td>
                        </tr>
                        <tr style="font-size: 8px">
                            <td style="border: none;"></td>
                            <td style="border: none;"></td>
                            <td>Term-I</td>
                            <td>Term-II</td>
                            <td>Term-I</td>
                            <td>Term-II</td>
                            <td>Term-I</td>
                            <td>Term-II</td>
                            <td>Term-I</td>
                            <td>Term-II</td>
                            <td>Term-I</td>
                            <td>Term-II</td>
                        </tr>
                     
                        <tr>
                            <td colspan="2">Credit <br> Completed </td> 
                            
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                        </tr>
                        <tr>
                            <td colspan="2">GPA</td>
                            <td>3.23</td>
                            <td>3.21</td>
                            <td>3.43</td>
                            <td>3.52</td>
                            <td>3.12</td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>

                        </tr>

                     </table>
                 </div>
</form>
</div>

<script type="text/javascript">
    window.print()
</script>
</body>
</html> 

threejs 3d model textures not loading

hey guys i am new to threejs and i am trying to load a 3d animated model with textures, but i am facing issues trying to do so as the textures are not loading into gltf. both the files are in textures folder while index.html is in the main folder. thanks in advance!

textures/Material_diffuse.png:1 Failed to load resource: the server responded with a status of 404 (Not Found)

textures/Material_specularGlossiness.png:1 Failed to load resource: the server responded with a status of 404 (Not Found)

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>3d model</title>
    <style>
      body {
        margin: 0;
      }
      canvas {
        display: block;
      }
    </style>
  </head>
  <body>
    <!-- <script src="three.js"></script> -->
    <!-- <script type="module" src="GLTFLoader.js"></script>  -->
    <script type="module">
      import * as THREE from 'https://cdn.skypack.dev/[email protected]/build/three.module.js';
      import { GLTFLoader } from 'https://cdn.skypack.dev/[email protected]/examples/jsm/loaders/GLTFLoader.js';

      var scene = new THREE.Scene();

      var camera = new THREE.PerspectiveCamera(
        75,
        window.innerWidth / window.innerHeight,
        0.01,
        1000
      );
      var renderer = new THREE.WebGLRenderer();
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);

      var loader = new GLTFLoader();

      var obj;
      loader.load("scene.gltf", function (gltf) {
        obj = gltf.scene;
        scene.add(gltf.scene);
      });
      scene.background = new THREE.Color(0xffffff);
      var light = new THREE.HemisphereLight(0xffffff, 0x444444);
      scene.add(light);
      // camera.position.set(0, 5, 30);
      camera.position.set(0, 5, 20);

      function animate() {
        requestAnimationFrame(animate);
        renderer.render(scene, camera);
      }
      animate(); 

      function rotateFunction() {
        obj.rotation.y += 0.01;
      }

     document.addEventListener('scroll', function(e) { rotateFunction() });
    </script>
    <div>
      
    </div>
  </body>
</html>

Make fake multilanguage subfolders for website

I’d like to know if it is possible to make fake subfolders for my multilanguage website, right now I use this code to switch between the two languages I have (Italian and English)

<?php
session_start();

$langs = [ "en", "it" ];

$current_lang = "en";

if (isset($_GET["lang"]))
{
    $lang = $_GET["lang"];
    if (in_array($lang, $langs, true))
        $current_lang = $lang;
    
}
elseif (!isset($_SESSION["lang"]))
{
    
    if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"]))
    {
        $acceptLang = $_SERVER["HTTP_ACCEPT_LANGUAGE"];
        if (strlen($acceptLang) > 2)
        {
            $acceptLang = strtolower(substr($acceptLang, 0, 2));
            if (in_array($acceptLang, $langs, true))
                $current_lang = $acceptLang;
        }
    }
}
else
    $current_lang = $_SESSION["lang"];

$_SESSION["lang"] = $current_lang;


require_once "languages/$current_lang.php";
?>

So whenever I want to switch language I add to the end of the URL ?lang=neededLanguage.php

I also use these rewrite rules to hide the .php

Options +SymLinksIfOwnerMatch 

RewriteEngine on

RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
RewriteRule . %1/%2 [R=301,L]

RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]

This is what I have to do to switch language right now:
https://example.com/?lang=en
https://example.com/blog?lang=en

I’d like to know if it’s possible to make the previous two URLs look something like these:
https://example.com/en/
https://example.com/en/blog

Nodejs error “Callback was already called error.”

For some reason, this part of the code is causing a callback is already called issue, if it does not enter the “if” loop, it returns accurately. Unable to figure out why it partially works.
Why are the return statements acting differently?

   **if (!args.is_table) {
      return cbk(null, {peers: forwards.peers});
    }**

Here’s the error:

***if (fn === null) throw new Error("Callback was already called.");
                         ^
Error: Callback was already called.***



module.exports = (args, cbk) => {
  return new Promise((resolve, reject) => {
    return asyncAuto({

      // Final forwards table
      allForwards: ['forwards', ({forwards}, cbk) => {
        if (!args.is_table) {
          return cbk(null, {peers: forwards.peers});
        }

        const isWideSize = !size || size.get().width > wideSizeCols;

        return cbk(null, {
          peers: forwards.peers,
          rows: []
            .concat([notNull([
              'Alias',
              'Earned In',
              'Earned Out',
              'Inbound',
              'Outbound',
              !!isWideSize ? 'Public Key' : null,
            ]).map(n => !args.is_monochrome ? bold(n) : n)])
            .concat(forwards.peers.map(peer => {
              return notNull([
                chartAliasForPeer({
                  alias: peer.alias,
                  icons: peer.icons,
                  is_disconnected: peer.is_disconnected,
                  is_forwarding: peer.is_forwarding,
                  is_inactive: peer.is_inactive,
                  is_pending: peer.is_pending,
                  is_private: peer.is_private,
                  public_key: peer.public_key,
                }).display,
                formatTokens({
                  is_monochrome: args.is_monochrome,
                  tokens: peer.liquidity_outbound,
                }).display,
                !!isWideSize ? peer.public_key : null,
              ]);
            })),
        });
      }],
    },
    returnResult({reject, resolve, of: 'allForwards'}, cbk));
  });
};

Trying to get the SearchBar to get data from the API

Forgive me if the formatting didnt work. I am trying to use the SearchBar to get the data from the API. (left the AAPL symbol as an example) I would like I am missing something and cant quite figure it out. How can I get this to work? Any assistance to my first post is greatly appreciated.

import axios from "axios";

function SearchBar() {
  const [value, setValue] = useState("");
  // const [data, setData] = useState([]);

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log("form submitted", value);
  };
useEffect(() => {
   
      .get(`https://api.twelvedata.com/symbol_search?symbol=AAPL`)
      .then((response) => {
        console.log(response.data);
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);


  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label>Search:</label>
        <input type="text" value={value} onChange={handleChange}></input>
        <button type="submit" value={handleSubmit}>
          Submit
        </button>
      </form>
      {/*value from form so that works from display*/}
      <div>{value}</div>
    </div>
  );
}

export default SearchBar;```

Forward console to channel discord.js

I am trying to forward my bot’s console to a channel in Discord. I assume I would use process.stdout to get the console output, and client.channels.cache.get(id).send() to send the message, but how do I combine the two and send that to a channel?

Any help is appreciated, cheers!

Getting a bytecode error when packaging javascript

Hey so I am trying to package my node javascript application with pkg on my mac, but I keep getting met with a codesign utility error?

**Error! Cannot generate bytecode

pkg fails to run “codesign” utility. Due to the mandatory signing
requirement of macOS, executables must be signed. Please ensure the
utility is installed and properly configured.**

Also only trying to get this as a runnable file, not put it on the mac store or anything.