Node.js middleware create a proxy service

I’m trying to code a proxy service like iproyal. But I couldn’t figure out the rotating proxy logic. My proxy database is ready. Each time I return a different proxy, but if I return these proxies with the api, the user must first get the information from the api and then use it. However, what I need to do is when the user connects to the proxy with the only information I have given, the request is executed using any proxy I have chosen from the database.

Host:port:username:password when a request is sent with
1- Fetch a random proxy from database (done)
2- Ensuring the request is executed through this proxy (failed to complete)

How can I ensure that the incoming request is executed through the proxy I have specified? I searched Node.js libraries for this but it either uses a single proxy or returns a random proxy from a list. I could not find a library that allows the incoming request to be executed directly through the proxy I specified. Can you please suggest a library that provides this functionality? I couldn’t solve the issue of connecting with single information in the rotating proxy service. Thanks.

Tooltip- how can I make it taller not wider?

I have a question regarding the tooltip I have used from w3schools.com

I have it entirely in CSS but have the problem, that when it shows at the edge of a side, it cuts the tooltip off.

My ideal thing would be, that it detects when the side is stopping and it makes the given div taller, not wider.

the code is

.tooltip {
    position: relative;
    display: inline-block;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    font-size: 20px;
    color: darkslategrey;
}

    .tooltip .tooltiptext {
        visibility: hidden;
        width: 260px;
        background-color: darkslategrey;
        color: #fff;
        text-align: center;
        border-radius: 6px;
        padding: 16px 0;
        position: absolute;
        z-index: 1;
        bottom: 125%;
        left: 50%;
        margin-left: -80px;
       
        position: absolute;
        z-index: 1;
        font-size: 16px;
        
    }

    .tooltip:hover .tooltiptext {
        visibility: visible;
       
    }
     .tooltiptext {

         text-shadow:none;
     }

.tooltip .tooltiptext:after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: darkslategrey transparent transparent transparent;
    
}

Thank you for any kind of help, where I could begin.

Share via WeChat in Javascript

I’m trying to find a way to share some content from the website via WeChat (the same as we can do for the Twitter, Facebook, etc). Not the whole website, just copied link or selected good.

I’ve found the official docs with JS SDK: https://developers.weixin.qq.com/doc/offiaccount/en/OA_Web_Apps/JS-SDK.html#10 , but according to the answer it works only with the WeChat browser.

So the question is there any possibilities to share content via WeChat from non-WeChat browser (like Chrome, Safari, etc)? And if so, is there a way to customise the content we share (add title, put some description, etc)?

Adding array of value in javascript

I’m asking this question again and hope I get the answer this time, I have an array of number that adds and subtract on button click which works withonclick and a function created. I will like the sum up of the array 21998 and 11999 when this same button is click and will like to display the value in <p id=""sumTotal></p> find screenshot of what my array looks like:

enter image description here

I have an onClick function that multiple quantity with total every time - and + are clicked. I will like the sum-up of 21,998 and 11,999 when - and + are clicked. Below is what my HTML code and PHP script look like:

<p id = "sumTotal"></p>
    <table class="table table-cart table-mobile">
        <thead>
            <tr>
                <th>Quantity</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
        <? for($i=0;$i<count($_SESSION['img_src']);$i++){ ?>
        <tr>
            <td>
                <div onclick="clickMe(<?php echo  $_SESSION['id'][$i]; ?>)">
                    <input type="number" value="1" min="1" max="10" step="1" data-decimals="0" required id = "<? echo $_SESSION['id'][$i].'_quantityCount' ?>">
                </div><!-- End .cart-product-quantity -->
            </td>
            <td id = "<? echo $_SESSION['id'][$i].'_totalPrice' ?>">&#8358;<?php echo $_SESSION['price'][$i] ?></td>
        </tr>
    
    <?
        }
    ?>
<tbody>
    </table>

And my javascript onclick looks like below code:

    <script>
        function clickMe(id) {
           var price = document.getElementById(id+"_price").innerHTML;
           let finalPrice =  price.replace(/[^a-zA-Z0-9]/g, '')
           var quantity = document.getElementById(id+"_quantityCount").value;
           var totalPrice = quantity * finalPrice;
           document.getElementById(id+"_totalPrice").innerHTML = "u20A6"+totalPrice.toString().replace(/B(?=(d{3})+(?!d))/g, ",");


          
        }
    </script>

I will like to get the sum total of 21,998 and 11,999to <p id = "sumTotal"></p>

I have a transparent image that I downloaded from google, but when I placed it into my html file in VScode. It doesn’t have a transparent background

I have a transparent image that I downloaded from google, but when I placed it into my HTMLA white and gold transparent circular zodiac wheel downloaded from google. file in VScode. It doesn’t have a transparent background. It appears with a white square background. I want it to appear as a circular image with no square background.

    <img src="./ZodiacLogoPics/Zodiac_Wheel_2.png" class="zodiac_wheel_1">

string.substring() in Javascript

    const removeParenth = function (str) {
  // your code here - don't forget to return a string!
  let start;
  let finish;
  for ( let i in str) {
      if (str[i] === '(') {
          start = i;
      }
      if (str[i] === ')') {
          finish = i;
      }
  }
//   console.log(start, finish);
//   console.log(str);
  let omitStr = str.substring(start, finish+1);
  console.log(omitStr);
  return str.replace(omitStr, "");
};

console.log(removeParenth('ido(not)liketocode'));

I’m trying to slice the ‘(not)’ part from the input string, but somehow the ‘omitStr’ gives me ‘(not)liketocode’ instead of ‘(not)’.

Anyone knows why this happens?

Why do these unresolved promises not get stuck?

I am looking at a lib that makes HTTP requests to an API. They all eventually call this one request function. It returns a Promise that wraps an old npm package called request. But it never resolves the promise, it only calls a callback. Yet, these promises never seem to get stuck. What am I missing?? Is callback a magical word in Promises that let’s it get resolved?

  return new Promise(function (resolve, reject) {
    request(settings, function (error, result, body) {
      if (error || result.statusCode >= 400) {
        var err = new Error(JSON.stringify(body));
        if (callback) {
          // callback always exists, reject is never called
          callback(err);
        } else {
          reject(err);
        }
      } else {
        if (callback) {
          // callback always exists, resolve is never called
          callback(null, body);
        } else {
          resolve(body);
        }
      }
    });
  });

And I found this returns undefined..

const result = await libraryCall()

Programmatically how to transfer ownership of Googlesheet from service account to my own account gmail? [duplicate]

I’m trying to create a GoogleSheet through the Google API.

While we created automatically the googleSheet in server-side, I needed to auth to google with an account service (https://developers.google.com/identity/protocols/oauth2).

Once, the file is created, the owner is attributed to this account service.
But I would like to be able to have ownership with my own Gmail address, and having the file in my own drive.

So I took a look into permissions. And I tried to transfer ownership on the previously created file from account service to my gmail address.
But go an error :

{
  code: 403,
  errors: [
    {
      domain: 'global',
      reason: 'consentRequiredForOwnershipTransfer',
      message: 'Consent is required to transfer ownership of a file to another user.'
    }
  ]
}

Here is the code :

const { google } = require('googleapis');

const cred = {
  "private_key": "-----BEGIN PRIVATE KEY-----nmyprivateketn-----END PRIVATE KEY-----n",
  "client_email": "[email protected]",
}

/**
 * Authentication
 */
const auth = new google.auth.JWT(
  cred['client_email'],
  null,
  cred['private_key'],
  ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'],
  null
);
google.options({auth});

/**
 * instanciation
 */
const googleSheets = google.sheets({ version: 'v4', auth })
const googleDrive = google.drive({ version: 'v3', auth });

// creation
const file = await googleSheets.spreadsheets.create({/*my params to create googlesheet*/});
// transfer ownership
const fileId = file.data.spreadsheetId;
await drive.permissions.create({
  resource: {
    type: "user",
    role: "owner",
    emailAddress: "[email protected]"  //the email address you want to give the permission.
  },
  fileId: fileId,
  fields: "id",
  transferOwnership: true,
});

According to the docs (https://developers.google.com/drive/api/guides/manage-sharing), I should change the code to

await drive.permissions.create({
      resource: {
        type: "user",
        role: "writer",
        emailAddress: "[email protected]",  //the email address you want to give the permission.
        pendingOwner: true
      },
      fileId: fileId,
      fields: "id",
    });

but I have not idea how to implement the step 2.
“The new owner accepts the ownership transfer request by creating or updating their file permission (from step 1). The permission must include these settings: role=owner and transferOwnership=true”

thanks

React: Banging my head against the Router

I need help setting up a router. Tried many ways, but nothing worked. I don’t think i understand React router and useParams well.
It should work like this:
when you click on a category like “food” or “drink” it should route to /:category. The page doesn’t change, just the visibility of the components gets switched (code below). Then you select a recipe, and it should dynamically link to that recipe, like /food/curry.

Usually i see others put the router into App.js. Mine is just returning the component below atm:

import React, {useEffect, useState} from "react";
import "./Main.scss";
import Header from "./Header";
import CategoryWindow from "./CategoryWindow"
import RecipeSelection from "./RecipeSelection";
import RecipeWindow from "./RecipeWindow";

const Main =()=> {
    const [showElement, setShowElement] = useState("category");
    const [selectedCategory, setSelectedCategory] = useState();
    const [selectedRecipe, setSelectedRecipe] = useState();

    useEffect(()=> {
        if (selectedRecipe) {
            setShowElement("recipe")
            
        } else if (selectedCategory) {
            setShowElement("recipeSelection")
        }
        window.scrollTo(0, 0)
    }, [selectedCategory][selectedRecipe]);

    return (
        <>
            <Header />
            <main className="main">
                <div>
                    <div>
                        {showElement === "category" ?
                                <CategoryWindow
                                    passSelectedCategory={setSelectedCategory}
                                />
                        : ''}
                    </div>
                    <div>
                        {showElement === "recipeSelection" ?
                            <RecipeSelection
                                value={selectedCategory}
                                passSelectedRecipe={setSelectedRecipe}
                            />
                        : ''}
                    </div>
                    <div>
                        {showElement === "recipe" ?
                            <RecipeWindow
                                value={selectedRecipe}
                            />
                        : ''}
                    </div>
                </div>
            </main>
        </>
    )
}

export default Main;

Category component. The array is hardcoded here, but recipies are dynamic, constructed out of a js object. Category is selected with onClick and passed as props to < Main >:

import React from "react";
import "./CategoryWindow.scss"   

const CategoryWindow =(props)=> {
    const categories = ["food", "drink", "dessert", "other"];

    return (
        <div className="categories-div">
            <div className="categories-inner">
                {categories.map(category => 
                    <button className={"category-btn " + `${category}`}
                        key={category}
                        value={category}
                        onClick={() => props.passSelectedCategory(category)}
                    >
                        <h2 className="category-h2">{category}</h2>
                    </button>
                )}
            </div>
        </div>
    )
}

export default CategoryWindow;

And the more dynamic RecipeSelection component:

import React from "react";
import "./RecipeSelection.scss"
import {Recipies} from "./Recipies";

const RecipeSelection =(props)=> {
    const recipies = Recipies.filter(x=>x.type === props.value);

    return (
        <div className="selection-div">
            <div className="selection-inner">
                {recipies.map(selection => 
                <>
                    <img src={require(`../images/${selection.id}.png`)}
                        className="selection-single"
                        key={selection.name}
                        value={selection}
                        onClick={()=> props.passSelectedRecipe(selection.id)}
                        >
                    </img>
                    <div className="container-h3"
                        onClick={()=> props.passSelectedRecipe(selection.id)}
                        >
                        <h3 className="selection-h3">{selection.name}</h3>
                    </div>
                </>
                )}
            </div>
        </div>
    )
}

export default RecipeSelection;

How would i go about this?

ThemeProvider & StyledComponents – Having a problem using a themed variable on pseudo element

So I decided to try to build my portfolio with StyledComponents. I’m using theme provider to implement a “dark” and “light” theme. I am having an issue with one background color on an &:after.. For some reason it is pulling the light theme version of the color regardless of the theme.

My setup looks like this.
I defined 5 variables that change between light and dark theme in theme.js.

import { createGlobalStyle } from "styled-components";

let beige = "#f6d8ae";
let blue = "#083d77";
let pink = "#da4167";
let yellow = "#f4d35e";
let gray = "#2e4057";

export const lightTheme = {
  one: pink,
  two: blue,
  three: beige,
  four: blue,
  five: blue,
};

export const darkTheme = {
  one: blue,
  two: pink,
  three: gray,
  four: yellow,
  five: gray,
};

export const GlobalStyles = createGlobalStyle`

 .typeA{
   background-color: ${(props) => props.theme.one};
    color: #f4d35e;
}
.typeB{
  background-color: ${(props) => props.theme.three};
  color: ${(props) => props.theme.four};
}

 .contact{
  background-color:${(props) => props.theme.five};
}
`;

You’ll notice that ‘two’ in the light and dark theme isnt used in the classes. It’s applied directly in the component.styled sheets as follows..

import styled from "styled-components";

export const JobContainer = styled.div`
  display: flex;
  justify-content: center;
  flex-direction: row;
  position: relative;
  width: 100vw;
  height: 75vh;
  flex-wrap: wrap;
`;

export const MainDiv = styled.div`
  display: inline-flex;
  margin: 25px;
  margin-bottom: 90px;
`;

export const Title = styled.div`
  position: relative;
  width: max-content;
  font-size: 28pt;
  font-weight: 700;
  height: max-content;
  margin: 20px;
  margin-bottom: 20px;
  z-index: 1;

  &:after {
    content: "";
    background-color: ${(props) => props.theme.two};
    height: 12px;
    display: block;
    position: absolute;
    width: 100%;
    left: 0;
    bottom: 15%;
    z-index: -1;
  }
`;
export const TitleB = styled.div`
  position: relative;
  width: max-content;
  font-size: 28pt;
  font-weight: 700;
  height: max-content;
  margin: 20px;
  margin-bottom: 20px;
  z-index: 1;

  &:after {
    content: "";
    background-color: ${(props) => props.theme.two};
    height: 12px;
    display: block;
    position: absolute;
    width: 100%;
    left: 0;
    bottom: 15%;
    z-index: -1;
  }
`;

So the background color on the pseudo element will be the color specified for ‘two’ in the light theme. Maybe it has something to do with the way Im providing themeprovider or globalstyles in the components? The variable works fine in one of the components which is set up like this…

import React, { useState } from "react";
import {
  MainContainer,
  Intro,
  Line,
  LineBox,
  IntroBox,
  Image,
} from "./styles/Home.Styled";

import { ThemeProvider } from "styled-components";
import { lightTheme, darkTheme, GlobalStyles } from "../themes.js";

import { Birds } from "../components/Birds";

export function Home() {
  const [theme, setTheme] = useState("light");

  const themeToggler = () => {
    console.log("holla", theme);
    theme === "light" ? setTheme("dark") : setTheme("light");
  };

  return (
    <>
      <ThemeProvider theme={theme === "light" ? lightTheme : darkTheme}>
        <GlobalStyles />
        <MainContainer className="typeA" onClick={() => themeToggler()}>
          <Birds />
          <IntroBox>
            <Intro>
              <Line>Hello World.</Line>
            </Intro>
            <LineBox>
              <Line>My Name is Dale.</Line>
            </LineBox>
          </IntroBox>
        </MainContainer>
      </ThemeProvider>
    </>
  );
}

The onClick in that component controls the theme for the whole page.

And finally, the component where the variable is not working..

import React, { useState } from "react";
import { ThemeProvider } from "styled-components";
import { lightTheme, darkTheme, GlobalStyles } from "../themes.js";

import {
  JobContainer,
  JobContainerB,
  Card,
  Title,
  TitleB,
  Image,
  Blurb,
  TitleDiv,
  ImageDiv,
  WordDiv,
  MainDiv,
} from "./styles/Projects.Styled";
import heycouldyou from "../assets/projectScreenshots/heycouldyou.png";
import nyet from "../assets/projectScreenshots/nyet.png";
import shoulda from "../assets/projectScreenshots/shoulda.png";

export function Projects() {
  const [theme, setTheme] = useState("light");
  const themeToggler = () => {
    theme === "light" ? setTheme("dark") : setTheme("light");
  };
  return (
    <>
      <ThemeProvider theme={theme === "light" ? lightTheme : darkTheme}>
        <JobContainer className="typeA">
         ......
        </JobContainer>
        <JobContainer className="typeB">
          ......
        </JobContainer>
        <JobContainer className="typeA">
         ......
        </JobContainer>
      </ThemeProvider>
    </>
  );
}

Im sure I could find a workaround but I want to make sure I understand why it’s not working like I am expecting. Thanks for taking the time to read this, even more for any help you may be able to provide!

How to Force Download to use JPEG instead of JFIF

I’m creating a feature to export a graph from my website. On my local machine the images are being downloaded as JFIF’s on my coworkers the images are properly being downloaded as JPEG’s. I am aware that I can configure my local machine to change the extension. However, I don’t want non-technical users to have to go through this process. Is there a way to ensure that images are downloaded on any machine as JPEG’s?

Here is my code

const downloadGraph = () => {
  const element = document.getElementById('unique-id') as HTMLCanvasElement;
  saveImage(element, 'Title');
}

const saveImage = (canvas: HTMLCanvasElement, fileName: string) => {
   const url = canvas.toDataURL('image/jpeg', 1.0);
   download(url, fileName, )
}

const download = (url: string, fileName: string) => {
  const link = document.createElement("a");
  link.setAttribute("href", url);
  link.setAttribute("download", fileName);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}


How to set the value of a combo box by default and get this value in another field in the angular?

There is an object with data:

 ELEMENT_DATA  = [{"shop":[{"Price":11,"seller":"John"},{"Price":22,"seller":"Rick"}]}, {"shop":[{"Price":33,"seller":"Andrew"}]}]

I create a field with a combobox in material-table:

<ng-container matColumnDef="Availability">
    <th mat-header-cell *matHeaderCellDef>Availability</th>
    <td mat-cell *matCellDef="let element">
      <mat-form-field appearance="fill">
        <mat-label >Filter</mat-label>
        <mat-select   [(ngModel)]="element.shop.Price">
          <mat-option  *ngFor="let item of element.shop" [value]="item.Price">
            {{item.seller}} 
          </mat-option>
        </mat-select>
      </mat-form-field>
    </td>
  </ng-container>

How to make here that by default at page opening, in a combobox of the 1st record there was “John”, and in the second “Andrew”. If you use [(ngModel)] = “element.shop.Price” then the combo box starts to dumb.

Then, depending on the seller selected, the value of the other “price” column should change:

  <ng-container matColumnDef="price" >
    <th mat-header-cell *matHeaderCellDef mat-sort-header> price </th>
      <td mat-cell *matCellDef="let element">
        <span *ngFor="let item of element.shop" >
                      {{log(element.shop.Price)}}
        </span>
    </td>
  </ng-container>

The code above does not work, I do not know how to transfer there “item.Price” of the first container.

how can I reduce the complexity of my code

as you can see it is prime number code is it appropriate and will work effectively

var n=prompt("what's is your number")

 var number=parseInt(n);
   console.log(number)
  if(parseInt(number%2)==0){
     console.log("number is not prime")
                          }else {
for(i=3;i<=parseInt(number/2);i=i+1)
{
    console.log(i)
    if(number%i==0){
        console.log("it is not a prime number")
        break;
        /** break statement is used to get out from the code */
    }else{console.log("it is prime number ")

  }