Zoho Mail – replaceAll() Regex Script [duplicate]

I am trying to apply the regular expression /<.*?>/ in a Zoho Mail script with the replaceAll() function.

enter image description here

It never seems to work even though I can do it just fine on for example JSFiddle. See sample here:

console.log("to: <[email protected]> from: test <wef> wfw".replace(/<.*?>/, 'email'))

My goal is to replace all occurrences of to hide e-mail addresses.

Any idea what I am doing wrong?

Bootstrap required JS is not loaded

I’ve got an Elixir Phoenix project in which I am using Webpack and Bootstrap.

Bootstrap CSS works fine and I can use however there is a problem with the JS Bootstrap requires. How I think there’s a problem with JS is that on the page when I click on the burger menu toggle it doesn’t expand to show menu items.

enter image description here

If I manually insert these two scripts below into the DOM. Then the burger menu toggle functions as expected.

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>

I am not sure what the problem is because I am not really familiar with Webpack and how the front-end related stuff is handled.

Here’s my webpack.config.js:

const path = require('path');
const glob = require('glob');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = (env, options) => {
  const devMode = options.mode !== 'production';

  return {
    optimization: {
      minimizer: [
        new CssMinimizerPlugin()
      ]
    },
    entry: {
      'app': glob.sync('./vendor/**/*.js').concat(['./js/app.js'])
    },
    output: {
      filename: '[name].js',
      path: path.resolve(__dirname, '../priv/static/js'),
      publicPath: '/js/'
    },
    devtool: devMode ? 'eval-cheap-module-source-map' : undefined,
    module: {
      rules: [
        {
          test: /.js$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader'
          }
        },
        {
          test: /.[s]?css$/,
          use: [
            MiniCssExtractPlugin.loader,
            'css-loader',
            'sass-loader',
          ]
        },
        {
          test: /.(woff|woff2|eot|ttf|otf)$/i,
          type: 'asset/resource',
        }
      ]
    },
    plugins: [
      new MiniCssExtractPlugin({ filename: '../css/app.css' }),
      new CopyWebpackPlugin({ patterns: [{ from: 'static/', to: '../' }] })
    ]
  }
};

Here’s my package.json

{
  "repository": {},
  "description": " ",
  "license": "MIT",
  "scripts": {
    "deploy": "webpack --mode=production",
    "watch": "webpack --mode=development --watch"
  },
  "dependencies": {
    "@popperjs/core": "^2.11.5",
    "bootstrap": "^5.1.3",
    "bowser": "^2.11.0",
    "jquery": "^3.6.0",
    "phoenix": "file:../../../deps/phoenix",
    "phoenix_html": "file:../../../deps/phoenix_html",
    "phoenix_live_view": "file:../../../deps/phoenix_live_view"
  },
  "devDependencies": {
    "@babel/core": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "autoprefixer": "^10.4.2",
    "babel-loader": "^8.0.0",
    "copy-webpack-plugin": "^10.2.4",
    "css-loader": "^6.6.0",
    "css-minimizer-webpack-plugin": "^3.4.1",
    "mini-css-extract-plugin": "^2.5.3",
    "node-sass": "^7.0.1",
    "sass-loader": "^12.4.0",
    "webpack": "^5.68.0",
    "webpack-cli": "^4.9.2"
  }
}

I am sorry if the title is too vague but I just don’t really know how to describe it in short, if you have a better title please let me know so I can update.

Why i can’t add and remove class with classList.add and classList.remove to some objects?

I can’t add and remove here – menu.classList.add(‘menu–shrink’);
And here – menu.classList.remove(‘menu–shrink’);
Why? And how i can fix this?

Whait a second, i cant add my js code.

<nav class="header" id="header">
<div class="container">
    <div class="navbar">
        <div class="logo" id="logo"> <a href="#" class="logo__a" id="logo_a">ZI</a> </div>
        <ul class="menu">
            <li class="menu__item">
                <a href="#" class="menu__item-link" id="menu__item-link" data-scroll>&#60;Main page/&#62;</a>
            </li>
            <li class="menu__item">
                <a href="#" class="menu__item-link" id="menu__item-link2" data-scroll>&#60;About/&#62;</a>
            </li>
            <li class="menu__item">
                <a href="#" class="menu__item-link" id="menu__item-link3" data-scroll>&#60;Portfolio/&#62;</a>
            </li>
            <li class="menu__item menu__item-red">
                <a href="#" class="menu__item-link" id="menu__item-link4" data-scroll>&#60;Price/&#62;</a>
            </li>
            <li class="menu__item">
                <a href="#" class="menu__item-link" id="menu__item-link5" data-scroll>&#60;Contacts/&#62;</a>
            </li>
        </ul>
        <div class="burger" id="burger">
            <span class="burger__span" id="burger__span"></span>
        </div>
    </div>
</div>

Iterate through scalar values to make viridis heat-map in canvas javascript

First, my javascript skills are very limited. My code takes an array of scalar values (applies a filter with a html slider) and tuns it into a canvas img. I like the greysacle image it produces. The img isn’t created until the slider is moved, but I can work on that later.

I would like to apply a viridis heat map inside the javascript loop below. I really have no knowledge how heatmaps are applied to greyscale values.

I imagine that i can apply the appropriate values into the rgb values (left as zero below) that would map a viridis heat map to the values.

// ***** NEED TO APPLY HEATMAP *****
var inc = 0
for(var y = 0; y < height; y++) {
    for(var x = 0; x < width; x++) {
        inc++
        var pos = (y * width + x) * 4; // position in buffer based on x and y
        buffer[pos  ] = 0;           // some R value [0, 255]
        buffer[pos+1] = 0;           // some G value
        buffer[pos+2] = 0;           // some B value
        buffer[pos+3] = fltarray[inc];           // set alpha channel
    }
} 

full code below. Uses python flask, I upload a pic from unsplash so people can give it a try. It’s not crucial to the code. I have a matplotlib slider example below that im trying to mimic with canvas.

python:

import matplotlib.pyplot as plt
from flask import Flask, render_template
import requests
from PIL import Image
from io import BytesIO

img_src = 'https://unsplash.it/500/300'
response = requests.get(img_src)
imgarray = Image.open(BytesIO(response.content))
imgarray = np.asarray(imgarray.convert('L'))

fltarray = imgarray.ravel()
n = np.sort(fltarray).tolist()


# attempt to make a heat map to potentially pass the html with flask
from matplotlib import cm
idx = np.argsort(fltarray)
viridis = cm.get_cmap('viridis', len(idx))
A = viridis.colors
A= 255*A[idx]
A=A.tolist()

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def main():  
    return render_template('clip.html',
                           Lsort = n,
                           fltarray = fltarray.tolist(),
                           heightP=[imgarray.shape[0]],
                           widthP=[imgarray.shape[1]])

if __name__ == '__main__':
    app.run()
    
#%%

# want web version to look like matplotlib version below

from matplotlib.widgets import Slider

fig,ax = plt.subplots(figsize = (5,3))
zlims = (np.percentile(imgarray, .1), np.percentile(imgarray, 100 - .1))
im = ax.imshow(imgarray, aspect='auto',vmin=zlims[0], vmax=zlims[1])
print(zlims)
threshold = 0.
axthreshold = plt.axes([0.2, 0.01, 0.65, 0.03])
sthreshold = Slider(axthreshold, 'z-clip', -.1, 3., 
                    valinit=threshold, valstep=None)

def update(val):
    ax.clear()
    zlims = (np.percentile(imgarray, .1+val), np.percentile(imgarray, 100 - (.1+val)))
    print(zlims)
    ax.imshow(imgarray, aspect='auto',vmin=zlims[0], vmax=zlims[1])
    fig.canvas.draw_idle()
    
sthreshold.on_changed(update)
update(threshold) 

html:

<html class="no-js" lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="ie=edge" /> 
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        
    <style>
    .container {
        display: flex;
        align-items: center;
        justify-content: center;
    }
    </style>    
    </head>
<body>


<br><br><br><br><br>


    <h4>img element.</h4>    
    <div class="container">
        <input style="width:50%" id="slide" type="range" min="0" max="5" step="0.025" value=".1" name="name_of_slider">
    </div>
    <div class="container" id="sliderAmount"></div>
    
<script>

//flask data assignment

    const fltarray = JSON.parse('{{ fltarray | tojson }}');
    const source = structuredClone(fltarray);
    const z1 = JSON.parse('{{ Lsort | tojson }}');
    var size = z1.length 
    const widthP = JSON.parse('{{ widthP | tojson }}');
    const heightP = JSON.parse('{{ heightP | tojson }}');

//slider data
    var slide = document.getElementById('slide'),
    sliderDiv = document.getElementById("sliderAmount");


//empty pic array
var width = widthP[0],
    height = heightP[0],
    buffer = new Uint8ClampedArray(width * height * 4); // have enough bytes    
    var image=new Image();

//create pic with slider
slide.onchange = function() {
    sliderDiv.innerHTML = this.value;  
    var perc = this.value;  
    var qlower = z1[Math.ceil(size * perc / 100) - 1];
    var qupper = z1[Math.ceil(size * (100-perc) / 100) - 1];


//javascript version of numpy percentile
for(var j = 0; j < size; j++) {
    fltarray[j] = 255*(source[j]-qlower)/(qupper-qlower)
}


//creates img
// ***** NEED TO APPLY HEATMAP *****
var inc = 0
for(var y = 0; y < height; y++) {
    for(var x = 0; x < width; x++) {
        inc++
        var pos = (y * width + x) * 4; // position in buffer based on x and y
        buffer[pos  ] = 0;           // some R value [0, 255]
        buffer[pos+1] = 0;           // some G value
        buffer[pos+2] = 0;           // some B value
        buffer[pos+3] = fltarray[inc];           // set alpha channel
    }
}
 


// create off-screen canvas element
var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d');

canvas.width = width;
canvas.height = height;

// create imageData object
var idata = ctx.createImageData(width, height);

// set our buffer as source
idata.data.set(buffer);

// update canvas with new data
ctx.putImageData(idata, 0, 0);


// set the img.src to the canvas data url
image.src=canvas.toDataURL();

// append the new img object to the page
document.body.appendChild(image);
}


</script>


</body>
</html> ```

Angular using setTimeout delays the view update

Due to the apps database updates being so quick we have added a material progress bar to help with visual cues to indicate that something has happened.

Our logic is that we set the progressbar to a minimum delay of say 500ms. We set the showLoading to start the progressbar and we then perform the task and then call hideLoading to turn off the progressbar. If the minimum delay is surpassed the progressbar stops if not it will wait until the minimum delay time has elapsed and the setTimeout will take care of the stop. To be clear this part is working.

The issue we have is that when we perform the task and we want to update the ui ie. display the results in a table it doesnt update until the setTimeout has completed.

I have put console.log(s) in the appropriate places and the task is running and returning results it is purley the view is not updating.

Loader Service

export class LoaderService {

private _isLoading = false;
private _inProgress = false;
private _delayFinished = false;

private minimumProgressDelay: number = 200;

public get isLoading() {
    return this._isLoading;
}

public showLoading(delay?: number) {
    this._isLoading = true;
    this._inProgress = true;
    this._delayFinished = true;
    delay = delay ? delay : this.minimumProgressDelay;

    setTimeout(() => {
        this._delayFinished = false;
        if (!this._inProgress) {
            this._isLoading = false;
        }
    }, delay);
}

public hideLoading() {
    this._inProgress = false;
    if (!this._delayFinished) {
        this._isLoading = false;
    }
}

}

Progress Bar in Header component

<div *ngIf="showLoading">
  <mat-progress-bar mode="indeterminate"></mat-progress-bar>
</div>

Typical use of the loader

async search(): Promise<void> {
    this.uiService.loader.showLoading(500);

    await this.getResults();

    this.uiService.loader.hideLoading();
}

The getResults function basically does an async httprequest to get the results and then sets the data property for the table.

As previously explained the code all works excpet the update to the table is not updated until the delay is completed. eg. if we set it to 10000ms it does wait until the 10secs to show the results.

How to get LocalStorage data from a dataset I have got after running a specific analysis to get all flows in many websites

after running analysis on many websites. I got two datasets that contain all the flows from the websites crawled. I need a script that take only LocalStorage from each dataset and put it in a new file to carry on with my analysis. Those datasets files contain information that irrelevent for me such as SessionStorage, timestamps etc.. .I have tried to make script in JavaScript to do that but just didn’t work. Does anyone have an idea how it should be done. Thanks in advance.

Php Signup page alert on button click at first attempt

Soo..I have a Signup button on my index.htmland when i click it for the first time it shows this js alert “Username not supported !” which is obvious because the inputs are empty. If i click ok and then type username,password and submit the form the account is registered normally.I want the if condition to be executed when i click on the submit of the form or something like that..

signup.php

<?php 
session_start();

    include("connection.php");
    include("../functions.php");
    


    if($_SERVER['REQUEST_METHOD'] == "POST")
    {
        //something was posted
        $user_name = $_POST['user_name'];
        $password = $_POST['password'];
        
             
    }
        if(!empty($user_name) && !empty($password) && !is_numeric($user_name) )
        {

            //save to database
            $user_id = random_num(8);
            $query = "insert into users (user_id,user_name,password) values ('$user_id','$user_name','$password')";

            mysqli_query($con, $query);

            header("Location: login.php");
            die;
        } else
        {
            ?>  
                    
                    <script>                     
                         alert("Username not supported !");
                       </script>
                       
                     <?php  
            
        }
    
?>

<!DOCTYPE html>
<html>
<head>  
    
     <link rel="stylesheet" type="text/css" href="style.css"> 
     <title></title>
    <link rel="icon" type="images/x-icon" href="../images/favicon.png">
    
</head>
<body>

    <div class="center">
      <h1>Signup</h1>
      
      <form method="post">
      
        <div class="txt_field">
          <input type="text" required
          name="user_name">
          <span></span>
          <label>Username</label>
        </div>
        
        <div class="txt_field">
          <input type="password" required
          name="password">
          <span></span>
          <label>Password</label>
        </div>
        
        <input type="submit" value="Signup">
        
        <div class="signup_link">
          Already a member;  <a href="login.php">Login</a>
        </div>
        
      </form>
    </div>
    

functions.php

function random_num($length)
{
    
    $text = "";

    for ($i=0; $i < $length; $i++) { 

        $text .= rand(0,9);
    }

    return $text;
} 

?>

Estoy usando XMLHttpRequest, para coger un JSON de una API Rest, imprime en consola el JSON pero no logro sacar esa info por HTML en mi web [closed]

Estoy usando XMLHttpRequest, para coger un JSON de una API Rest, imprime en consola el JSON pero no logro sacar esa info por HTML en mi web

Pero por alguna razon no puedo sacar la informacion en la web…

JSON

{
    "success": true,
    "response": {
        "ico": "running",
        "total": "100,000,000 RIDY",
        "total_amount": "2,500,000 EUR",
        "sold": "0 RIDY",
        "sold_amount": "0 EUR",
        "progress": 0,
        "price": 0.025,
        "start": "2022-06-03 19:05:00",
        "end": "2022-07-03 19:05:00",
        "min": 100,
        "max": 100000,
        "soft": 0,
        "soft_amount": "0 EUR",
        "hard": 0,
        "hard_amount": "0 EUR"
    }
}
      function JSONRequest(){

          let request = new XMLHttpRequest();
          request.open('GET', 'https://ridery.es/public/api/stage?secret=Fpx7WJZhuH9FofuBP3poAfS6');
          request.onload = function() {debugger;
             let todo = JSON.parse(this.responseText);
             document.getElementById("output").innerHTML = todo.total_amount;
          }
          request.send();
      }

      JSONRequest();
<div id="output"></div>

El suelta undefined en el navegador.

JavaScript global variables not updating in functions [duplicate]

I am very new to JS and this is my very first post on Stack Overflow. I hope I’m doing it right.

I am currently coding a site that uses several APIs. I would like to enter the data received via these APIs into global variables so that I can reuse it in my other functions. However, I’ve come across several topics talking about the same issue, but I haven’t found a solution for my specific case. I am very sorry if the answer is already on this site but I did not find it.

When I place console.log to debug my code, my global variables are displayed with their initial values, as if they had not been modified. But when I enter console.log myself in my browser’s console, my variables are displayed with the updated value.

Here is a part of my code that does not work as I expected:

/* Here I initialise my global variables */
let cityName=" ", countryName=" ";
let lat=0, long=0;

function onload(){ //function called with body onload attribute
    getCurrentLocation();
    getTheWeatherChannel();
}

function getCurrentLocation(){
    /* API Call for IP based Location */
    $.post("https://ipapi.co/json", getLocation);

    function getLocation(data){
        cityName=data.city;
        countryName=data.country;
        lat=data.latitude;
        long=data.longitude;
        console.log(lat) //it returns the good latitude
    }
    console.log(lat) //still working
}

console.log(lat) //it returns 0 while I expected it to return the new latitude

function getTheWeatherChannel(){
    console.log(lat) //it returns 0...

    /* API Call for Weather */
    const key="*****";
    const urlCurrentInfo="https://api.weather.com/v1/geocode/"+lat+"/"+long+"/observations.json?language=en-US&units=m&apiKey="+key;
    //Here it stops working because API returns error with zero coordinates
    //...
}

I hope I have given enough information about my issue

Problem 1: replace all internal whitespace in a string value with underscores * (‘_’), and makes it UPPERCASE [closed]

We want to be able to convert a string to Upper normalizeVariable Case style, so that all

  • leading/trailing whitespace is removed, and any internal spaces, tabs, or dots,
  • are converted to ‘_’ and all letters are UPPER cased.

The normalizeVariable() function should work like this:
*

  • normalizeVariable(‘abc’) –> returns ‘ABC’
  • normalizeVariable(‘ ABC ‘) –> returns ‘ABC’
  • normalizeVariable(‘ABC’) –> returns ‘ABC’
  • normalizeVariable(‘A BC’) –> returns ‘A_BC’
  • normalizeVariable(‘ A bC ‘) –> returns ‘A_BC’
  • normalizeVariable(‘A BC’) –> returns ‘A_BC’
  • normalizeVariable(‘A.BC’) –> returns ‘A_BC’
  • normalizeVariable(‘ A.. B C ‘) –> returns ‘A_B_C’

@param {string} value – a string to be converted
@return {string}

  function normalizeVariable(value) {

value = value.replace(/s+/g, ‘-‘).toUpperCase();
console.log(value);

    return value;
  }

If I call a function in the head section of JavaScript for-of loop, is it guarantied to be called only once?

I have tried the code below in Firefox and Chrome:

function test() {
    console.log("***")
    return [1,2,3]
}

for (const t of test()) {
    console.log(t)
}

The test function was called only once. Is it the standard behavior for this kind of loop? Is it like the initialization part of for ([initialization]; [condition]; [final-expression]) loop? I didn’t find the explanation on MDN and I didn’t understand much from ECMA standard.

Remove Domain Name and Backslash from AD User

I have a user name that comes in like this domainuser123. I need to remove domain and on have the username. I have tried the following:

var input = "domainuser123";

var str =  input.replace(/\//g, '')

and

var input = "domainuser123";

var str = input.replace('\', '');

and

var input = "domainuser123";

var str = input.split('\', '');

All come back with the backslash removed, but also the character after the backslash domainser123.

I need it to look like this user123.

codewars optimization of solution 4 kyu js

I can’t done the huge numbers tests. Help me optimize my code. My solution:

    const dontGiveMeFive = (start, end) => {
  let res = []
  for (let i = start; i <= end; i++) {
    if (!i.toString().includes('5')) res.push(i)
  }
  return res.length
}

  dontGiveMeFive(40076, 215151422963990)
  dontGiveMeFive(-206981731, 223575697903165)
  dontGiveMeFive(-249022878360451, -249022878219653)   
  dontGiveMeFive(-90000000000000, 900000000000000)

Task: `This kata is the performance version of Don’t give me five by user5036852.

Your mission, should you accept it, is to return the count of all integers in a given range which do not contain the digit 5 (in base 10 representation).
You are given the start and the end of the integer range. The start and the end are both inclusive.

Examples:

1,9 -> 1,2,3,4,6,7,8,9 -> return 8
4,17 -> 4,6,7,8,9,10,11,12,13,14,16,17 -> return 12
The result may contain fives. 😉
The start will always be smaller than the end. Both numbers can be also negative.

The regions can be very large and there will be a large number of test cases. So brute force solutions will certainly time out!
`

How to access kubernetes pods from VS code javascript (for total beginner)

I am trying to write a function that will evaluate kubernetes pods. Function itself is very simple, using object.key.startsWith() and hasOwnProperty. The challenge here is how do I access the kubernetes pods I created from Ubuntu terminal using docker and kind? I have looked into kubernetes specification, but for a total beginner it’s not clear.

Requirements:
Create microservice that evaluates rules for all pods in the cluster, as well as output the results on stdout in json log format one line per pod.

Rules:

  • title: image_name
    description: “check the pod only uses images prefixed with “nigx12/”
    output: boolean
  • title: group_label
    description: “check the pod contains a label “group” with some value”
    output: boolean
  • title: start_time
    description: “check the pod has not been running for more than 5 days according to it’s startTime“

Any help highly appreciated!