JCrop: How to upload Image from client side in a canvas?

PS: Not a duplicate as it has multi cropping feature.

I am make a Image crop app with multiple sections cropping areas, after lot of try and research I found Jcrop useful.
Now I am trying to make interface where client can upload their image by itself and then crop easily.

  • In below HTML there is static image as of now and upload button too where user can upload and replace static image in a canvas.

HTML code:

  <div style="padding:0 5%;">
<h1 style="font-family:Helvetica,sans-serif;">
  Jcrop Example <span style="color:lightgray;">- draw some crops!</span>
</h1>

<img id="target" src="https://d3o1694hluedf9.cloudfront.net/market-750.jpg">


 <div class="file btn btn-lg btn-primary">
  Upload
   <input type="file" name="file" />
 </div>
</div>

JavaScript:

  var jcp;
Jcrop.load('target').then(img => {
  jcp = Jcrop.attach(img, { multi: true });
  const rect = Jcrop.Rect.sizeOf(jcp.el);
  jcp.newWidget(rect.scale(.7, .5).center(rect.w, rect.h));
  jcp.focus();
});



function setImage(tag) {
  document.getElementById('target').src =
    'https://d3o1694hluedf9.cloudfront.net/' + tag;
}

How to give anchor position in rich marker google map?

Hi I am using richmarker for custom image markers on google map in ASP.net MVC web app.
It’s working fine for normal markers. But I have some scenarios in which there are two markers at same location . Using default marker I am handling this by using Roadside LHS or RHS and specifying different anchors for LHS and RHS.And it works fine. But for rich marker, how to specify anchor so that I can see 2 separate LHS and RHS customized marker?

This is my code for rich marker.

           var marker = new RichMarker({
                                    position: myLatlng,
                                    label: data.RoadSide,
                                    map: map,
                                    title: data.title,                                         
                                    content: '' +
                                        '<div class="customMarker"style="float:left"><img class="" src="' + image+ '"/></div>'
                                });

Default marker for LHS and RHS:

    if (data.RoadSide == 'LHS') {
                                var marker = new google.maps.Marker({
                                    position: myLatlng,
                                    label: data.RoadSide,
                                    map: map,
                                    title: data.title,
                                    icon: {
                                        url: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
                                        size: new google.maps.Size(39, 40),
                                        scaledSize: new google.maps.Size(39, 40),
                                        anchor: new google.maps.Point(15, 0),
                                        labelOrigin: new google.maps.Point(-20, 20)
                                    }
                                });
                            }
                            else {
                                var marker = new google.maps.Marker({
                                    position: myLatlng,
                                    label: data.RoadSide,
                                    map: map,
                                    title: data.title,
                                    icon: {
                                        url: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
                                        size: new google.maps.Size(39, 40),
                                        scaledSize: new google.maps.Size(39, 40),
                                        anchor: new google.maps.Point(-20, 0),
                                        labelOrigin: new google.maps.Point(60, 20)
                                    }
                                });

                            }

Change URl tabs without page refresh NEXT.JS

Im using material ui tabs, and Im pushing the tabs to url. I want to push the tab but not refresh the page every-time I change the tab. Here is my code, and Im using shallow:true but the problem remains:

const tabs = [
  { label: 'Details', value: 'details' },
  { label: 'Purchases', value: 'purchases' },
  { label: 'Money Transfer', value: 'moneyTransfer' },
  {label:'User Activity',value:'userActivity'},
  {label:'User Logs',value:'userLogs'}
];
const {
    query: { UsersId,tab },
  } = router
const handleTabsChange = (event: ChangeEvent<{}>, value: string): void => {

  router.push({
    pathname: `/dashboard/twigUsers/${UsersId}`,query: { tab:value}},undefined,{ shallow: true });
};

             <Tabs
              indicatorColor="primary"
              onChange={handleTabsChange}
              scrollButtons="auto"
              sx={{ mt: 3 }}
              textColor="primary"
              value={tab}
              variant="scrollable"
            >
              {tabs.map((tab) => (
                <Tab
                  key={tab.value}
                  label={tab.label}
                  value={tab.value}
                />
              ))}
            </Tabs>

{tab === 'details' && (
             <UsersDetailsContainer user={user} userId={UsersId}/>
            )}
            {tab === 'purchases' && <PurchasesListTable userDetailsId={userDetailsId}/>}
            {tab === 'moneyTransfer' && <MoneyTransferListTable userDetailsIdMT={userDetailsIdMT} />}
            {tab==='userActivity' &&<UserActivity/>}
            {tab==='userLogs' &&<UserLogs user={user} userId={twigUsersId}/>}

How to encode output json data with charset windows1251 using node.js API?

I want to encode the data to windows1251.

My output json data is not good like that:

API

This is my node.js API code:

    // Create express app
var express = require("express")
var app = express()
var mysql = require('mysql')
var express = require("express")
var cors = require('cors')

app.use(cors())

const utf8 = require('utf8');


// Server port
var HTTP_PORT = 3002

var pool = mysql.createPool({
  connectionLimit: 10,
  host: '',
  user: '',
  port: '',
  password: '',
  database: '',
  charset: 'cp1251_bulgarian_ci'
});

var HQdataAHS = '';
var HQstationsAHS = '';

function formatDate(date) {
  var d = new Date(date),
    month = '' + (d.getMonth() + 1),
    day = '' + d.getDate(),
    year = d.getFullYear();

  if (month.length < 2)
    month = '0' + month;
  if (day.length < 2)
    day = '0' + day;

  return [year, month, day].join('-');
}

var dateNow = formatDate(Date());

app.route('/HQstationsAHS')
  .get(function (req, res) {
    // omitted
    res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate');
    pool.query(`SELECT Station, Ime FROM auto_q_stations;`, function (error, result2, fields) {
      if (error)
        return res.status(500).json({ error: "Грешна заявка. Опитай отново !" })
        HQstationsAHS = result2.map((item) => {
          item.Ime = utf8.encode(item.Ime);
          return item;
        });
    
       res.json({ HQstationsAHS })
     });
    });


// Start server
app.listen(HTTP_PORT, () => {
  console.log("Server running on port %PORT%".replace("%PORT%", HTTP_PORT))
});

pool.on('error', function (err) {
  console.log(err.code); // 'ER_BAD_DB_ERROR'
});

app.use(function (req, res) {
  res.status(404);
});

I installed from npm windows1251 library from here:

https://www.npmjs.com/package/windows-1251

After installation I try to encode this line like that:

item.Ime = utf8.encode(item.Ime);

item.Ime = windows1251.encode(item.Ime);

But I receive error: windows1251 is not defined..

How to encode my output json data to windows1251 ?

React debouncing problem with useCallback

Inside my React component, I have these:

const [vendor,setVendor] = useState("");
const [taggedWith,setTaggedWith] = useState("");

function updateQuery () {
  const filters = [];
  if(vendor) {
    filters.push({
      label: `Vendor: ${vendor}`
    })
  }
  if(taggedWith) {
    filters.push({
      label: `Tagged with: ${taggedWith}`
    })
  }
  props.onUpdate(filters);
}

function debounce (func,delay){
  let timer;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(()=>{
      func();
    },delay);
  };
};

const updateQueryWithDebounce = useCallback(debounce(updateQuery,300),[]);

useEffect(()=>{
  updateQueryWithDebounce();
},[taggedWith,vendor]);

Debouncing works, but the problem is, the stateful variables inside updateQuery function stays the same, because of useCallback. If I pass those states to the dependency array of useCallback, the debouncing function gets redeclared at every render, thus, new function with its closure is created which leads to debouncing not working. How can I fix that ?

Chart JS For Working With A REST API Using JavaScript

//This is the app.js code and there issue in map function line

async function getDummyData(){
const apiUrl = “http://localhost:8080/api/v1/soilchart/cultyvatesoilchart”

const response = await fetch(apiUrl)
const BarChart = await response.json()

 const fc = BarChart.soil.map( (x) => x.Fieldcapacity)
 const wp = BarChart.soil.map( (x) => x.wiltingpoint)

   
console.log(BarChart)    

}

How to add reference id in mongodb when we upload csv file data in mongodb

convertCsv()
.fromFile(uploads/csv_Employee/${req.body.file})
.then((csvData) => {
const obj = { createdById: req.body.createdById };
csvData.obj;
const finalData = Employee.insertMany(csvData);
if (finalData) {
return res.json(
Response(
constants.statusCode.ok,
constants.attendanceMsg.attendanceSuccess,
finalData
)
);
} else {
return res.json(
Response(
constants.statusCode.unauth,
constants.messages.internalServerError
)
);
}
});

Why does optional chaining allows rendering when fetching data through useEffect in an app that uses context?

I’m new to the webdev world and want to learn ReactJS. I followed a tutorial I found on YouTube made by Traversy where he makes a task tracker and now I want to make some changes to it to learn and practice some more.

I want to use context for the appointments (originally named tasks in the tutorial), add a calendar with react-calendar and use react-router-dom.
I got stuck for a while trying to make the list render, because it only rendered “empty”. Later on found this post with a similar issue to mine: Only run a useEffect fetch after first useEffect fetch has fired and setUser in context

I changed bits of my code based on that post and now it does render the appointment list, but I don’t know why it didn’t work before and I’m unsure on why it does work now. I don’t even know if I’m using context correctly or just prop-drilling. Help would be greatly appreciated. Thank you.

Also, sorry if my code is a mess, I’m new at this.

App.js

import { createContext, useState, useEffect } from "react";
import Dashboard from "./views/Dashboard";
import './App.css';
import { BrowserRouter as Router, Route, Routes} from "react-router-dom";
import AddAppointmentForm from "./views/AddAppointmentForm";

export const AppContext = createContext();
export const AppUpdateContext = createContext();

function App() {
  const [appointments, setAppointments] = useState([])
  const updateAppointments = (apptList) => {
    setAppointments(apptList)
  }

  return (
    <AppContext.Provider value={ appointments }>
      <AppUpdateContext.Provider value={ updateAppointments }>
        <Router>
          <Routes>
            
              <Route path="/" element={<Dashboard appointments={appointments} />} />
              {/* <Route path="/add" element={<AddAppointmentForm />} />  TBA */} 
            
          </Routes>
        </Router>
      </AppUpdateContext.Provider>
    </AppContext.Provider>
  );
}

export default App;

Dashboard.js

import { useEffect, useContext} from "react";
import { AppContext } from "../App";
import { AppUpdateContext } from "../App";
import AppointmentList from "../components/AppointmentList";
import Header from "../components/Header";

// function Dashboard() {  // this is how it used to be
  function Dashboard(props) {
  const appointments = useContext(AppContext)
  const setAppointments = useContext(AppUpdateContext)

  const fetchAppointmentList = async () => {
    const res = await fetch("http://localhost:5000/appointments");
    const data = await res.json();

    return data;
  }

  useEffect(() => {
    const getAppointments = async () => {
      const appointmentsFromServer = await fetchAppointmentList();
      setAppointments(appointmentsFromServer);
    }

    getAppointments();
    console.log("ñññññ",appointments)
  }, []);
  
  console.log("aagh",appointments)
  
  return (
    <div style={dashboardStyle}>
      <Header />
      {/* {appointments.lenght>0 ? (<AppointmentList />) : <p>empty</p>} this is how it used to be */}
      <AppointmentList appointments={props?.appointments}/>
    </div>
  );
}

const dashboardStyle = {
  maxWidth: "31.25rem",
  overflow: "auto",
  minHeight: "18.75rem",
  border: "1px solid steelblue",
  margin: "1.875rem auto",
  padding: ".5rem",
  boxSizing: "border-box",
}

export default Dashboard;

AppointmentList.js

import Appointment from "./Appointment";
import { AppContext } from "../App";
import { useContext } from "react";

function AppointmentList({ appointments }) {
// function AppointmentList() {  // this is how it used to be
  // const { appointments, setAppointments } = useContext(AppContext)
  console.log("appList",appointments)  // this is how it used to be

  return (
    <>
      {
        appointments.map(appt => (
          <Appointment key={appt.id} appointment={appt} />
        ))
      }
    </>
  );
}

export default AppointmentList;

Cannot build/run DevServer cause of babel-loader

At before, there was no issue with build & run dev server.
But it doesn’t work from some point.

Cannot build / run Webpack-Dev-Server with this exception.

ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module './ast-types/generated'
Require stack:
- {myProject}/node_modules/@babel/types/lib/index.js
- {myProject}/node_modules/@babel/core/lib/transformation/file/file.js
- {myProject}/node_modules/@babel/core/lib/index.js
- {myProject}/node_modules/babel-loader/lib/index.js
- {myProject}/node_modules/loader-runner/lib/loadLoader.js
- {myProject}/node_modules/loader-runner/lib/LoaderRunner.js
- {myProject}/node_modules/webpack/lib/NormalModuleFactory.js
- {myProject}/node_modules/webpack/lib/Compiler.js
- {myProject}/node_modules/webpack/lib/webpack.js
- {myProject}/node_modules/webpack/lib/index.js
- {myProject}/node_modules/webpack-cli/lib/webpack-cli.js
- {myProject}/node_modules/webpack-cli/lib/bootstrap.js
- {myProject}/node_modules/webpack-cli/bin/cli.js
- {myProject}/node_modules/webpack/bin/webpack.js
 babel-loader@8 requires Babel 7.x (the package '@babel/core'). If you'd like to use Babel 6.x ('babel-core'), you should install 'babel-loader@7'.
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> ({myProject}/node_modules/@babel/types/lib/index.js:629:19)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:999:19)

webpack 5.66.0 compiled with 1 error in 454 ms

package.json :

{
  "type": "module",
  "scripts": {
    "dev": "NODE_ENV=development webpack serve",
    "build": "NODE_ENV=build webpack --mode production",
    "start": "NODE_ENV=start node ./server/server.cjs"
  },
  "dependencies": {
    "@rails/webpacker": "^5.4.3",
    "css-loader": "^6.5.1",
    "express": "^4.17.2",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-svg": "^14.1.6",
    "style-loader": "^3.3.1"
  },
  "devDependencies": {
    "@babel/core": "^7.16.7",
    "@babel/preset-env": "^7.16.8",
    "@babel/preset-react": "^7.16.5",
    "@webpack-cli/info": "^1.4.1",
    "@webpack-cli/serve": "^1.6.1",
    "babel-loader": "^8.2.3",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^5.5.0",
    "webpack": "^5.66.0",
    "webpack-cli": "^4.9.1",
    "webpack-dev-server": "^4.7.1"
  }
}

webpack.config.js is like:

import path from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import { fileURLToPath } from 'url';
import webpack from 'webpack';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

export default {
  entry: path.join(__dirname, "src", "index.js"),
  output: {
    path:path.resolve(__dirname, "dist"),
  },
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        use:  ["babel-loader"]
      },
      {
        test: /.(png|svg|jpg)$/,
        use: ["file-loader"]
      },
      {
        test: /(.css)$/,
        use: ["style-loader", "css-loader"],
      },
    ]
  },
  resolve:{
    extensions : [".js"],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, "src", "index.html"),
    }),
    new webpack.EnvironmentPlugin({
      NODE_ENV: 'development'
    }),
  ],
}

(NO ‘.babelrc’)

I thought auto update option(version with ^) makes issue that roll back modules to before version, but it makes same issue.

I found this exception during few days, but i cannot found real reason of this issue.

what’s the wrong with this config?

Why is my Axios POST request returning Error 400

I’ve got a problem with sending POST request to a backend server (managed by Swagger UI).
Below is the code snippet of POST function:

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        const employee: IEmployee = {
          age: newEmployeeData.age,
          id: newEmployeeData.id,
          name: newEmployeeData.name,
          position: newEmployeeData.position,
        };

        axios
          .post("http://34.140.193.23/api/employees", JSON.stringify(employee), {
            headers: {
              "Content-Type": "application/json",
            },
          })
         .then((res) => setEmployeesData([...employeesData, res.data]))
         .catch((error) => {
           console.log("Error:", error);
         });
    };

When I call handleSubmit function, it throws me an error to the console like this:

Failed to load resource: the server responded with a status of 400 ()
createError.js:16 Uncaught (in promise) Error: Request failed with status code 400
at createError (createError.js:16:1)
at settle (settle.js:17:1)
at XMLHttpRequest.onloadend (xhr.js:66:1)

When I try to debug in Sources panel in Chrome DevTools it doesn’t even return value for res variable. To be precise, it doesn’t run .then statement at all.

Backend server: http://34.140.193.23/swagger-ui/#/employee-controller

Am I missing something? Thank you a lot for your help.

Quessing game by Object

I am trying to make simple guessing game by object method.I want to practice object method. Everything is working, except one condition. I want compare input with random num. I don’t know why this condition ignore me. How can I fix it? Thank you


let game = {  
  quess: () => {
    const input = document.querySelector('.input').value
     return input
  },
  randomNumber: () => {
    //const x = Math.floor(Math.random() * 10) + 1
    const x = 3   // for testing
    return x
  },
  displayQuess: function() {
      const userNum = document.querySelector('.quess')
      return userNum.innerHTML = this.quess()
  },
 
  clearFields: function() {
    document.querySelector('.input').value = ''
  },
  result: function() {
     const output = document.querySelector('.output')
   
     const input = this.quess()
     const random = this.randomNumber()
     
     
     if(random === input) {         // this condition ignore me , why ? 
       output.innerHTML = ' Winner !!'
     } 

     if(input != random) {
       output.innerHTML = 'correct num was : ' + random
     }
  }
}

 const btn = document.querySelector('.btn')
 const output = document.querySelector('.output')
 const quesss = document.querySelector('.quesses')

 let quesses = 3

 btn.addEventListener('click', function() {
   //console.log( game.displayQuess())
      game.displayQuess()
      game.clearFields()
      game.result()

      quesses--
      quesss.innerHTML = quesses
      if(quesses < 1 ){
          output.style.color = 'red'
          output.innerHTML = 'game over'
          document.querySelector('.input').disabled = true;
          document.querySelector('.btn').disabled = true;
      }  
 })

Use Default IP in axios instead

I need help please.
So, in my react app, I have a function that’s making a request to an external API, The API server requires a stable IP making request to it, instead axios is sending the device’s IP, I tried setting the default IP with x-fawarded-for in the header, but It could not work. Can someone help me with how I can set the default requesting IP in axios?

const getBillerCategories = () => {

    const authorization = {
        "Accept": 'application/json',
        "Content-Type":  "application/json",
        "x-api-key": BAXI_API_KEY // this is the API Key
        "x-forwarded-for": "xxx.xx.x.xxx" // the required IP
    }

    return new Promise((resolve, reject) => {
        //console.log(authorization, 'n', ' chekced ', 'n');
        axios.get(BAXI_BASE_URL+'/billers/category/all', {headers: authorization}).then((response) => {
            resolve({status: true, data: response.data});
        }).catch((error) => {
            console.log(error.response.data, 'response data', BAXI_API_KEY);

            if(error.response){
                resolve({status: false, error: error.response.data.hasOwnProperty('message') ? error.response.data.message: error.response.data.toSting()});
            }else{
                resolve({status: false, error: error.message});
            }
        }); 
    });
   
}

Thank you in advance.

Console is overwriting one console.log with another?

I have an application that queries a mysql database. It starts out:

function init() {
    console.log(`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    What would you like to do?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    `);
    return inquirer
        .prompt({
            type: "list",
            name: "options",
            message: "Select one",
            choices: list,
        })
        .then((data) => {
            return redirectQuestion(data.options);
        })
        .then(() => init())
        .catch(err => {
            console.log(err);
        })
}

init()

The redirectQuestion function takes the user to a function with switch cases to find the correct query, for example:

class View {
    constructor(table = '') {
        this.table = table
        this.statement = `SELECT * FROM ${this.table} ORDER BY id`
    }
    getTable() {
        db.query(
            this.statement, (err, results, fields) => {
                if (err) {
                    console.log("There was an error with your request")
                }
                console.table(results)
            }
        )
    }
}

The problem is, that after this runs, there is a recursive call to init() to bring up the options again. The options, instead of appearing below the data from the database, appear above them, and if I move to select other options, it will then create another table which overwrites the bottom part of the data.

Now, it’s probably a less than desirable way to write the function out, but I need to have a way to recall the table, and still display the data, and I am not sure what is going wrong.

enter image description here

enter image description here

enter image description here