node.js discord bot wont ready

I’ve recently gotten interested in discord bots so I started coding one however now about a day in everything stopped working kick, ban, clear everything I coded isn’t working the discord bot won’t ready theirs no response in the terminal once so even if I try to run it
here’s my code

const mySecret = process.env[`TOKEN`]
const Discord = require("discord.js");
const prefix = '!';
const fs = require('fs');
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "GUILD_MEMBERS"], partials: ["MESSAGE", "CHANNEL", "REACTION"] });

client.commands = new Discord.Collection();

const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
  const command = require(`./commands/${file}`);

  client.commands.set(command.name, command);

}

const welcome = require("./welcome");

client.on('ready', () => {
  console.log("Our Discord bot is online");

  welcome(client);
});

client.on('message', message => {

  if (!message.content.startsWith(prefix) || message.author.bot) return;
  const args = message.content.slice(prefix.length).split(/ +/);
  const command = args.shift().toLowerCase();

  if (command === 'clear') {
    client.commands.get('clear').execute(message, args);
  } else if (command === 'kick') {
    client.commands.get('kick').execute(message, args);
  } else if (command === 'ban') {
    client.commands.get('ban').execute(message, args);
  } else if (command === 'mute') {
    client.commands.get('mute').execute(message, args);
  } else if (command === 'unmute') {
    client.commands.get('unmute').execute(message, args);
  }
});

client.on("message", msg => {
  if (msg.content === "i love snick") {
    msg.reply("Me too!");
  }
})


client.login(process.env.TOKEN);

Resolver con closure

tengo este problema que necesito resolver con un closure, no me sale y no se
que estoy declarando mal

Closures

EJERCICIO 5

Enunciado:

Implementar la función telefonoDescompuesto que recibe un string
y que debe retornar otra función que devuelva las consonantes del string
Si el parámetro es igual a null o undefined debería devolver false

   function telefonoDescompuesto(string) {
    
        function quitarvocales(string){ 
            return function(){ 
           if(typeof string !== 'string'){return "string debe ser una cadena de texto"}
           var sinVocales = string.replace(/[aeiou]/gi, "")
           return sinVocales
        
        
            }
        }  var cons = quitarvocales("cadena")
    

La terminal me arroja este error:
sinVocales = string.replace(/[aeiou]/gi, “”)
TypeError: Cannot read properties of undefined (reading ‘replace’)

Tambien probe colocando una verificacion type of para string

 function quitarvocales(string){ 
       if(typeof string !== 'string'){return "string debe ser una cadena de texto"}
       return function(){ 
      
       var sinVocales = string.replace(/[aeiou]/gi, "")
       return sinVocales
    
    
        }
    }  var cons = quitarvocales()
    console.log(cons("cadena"))

Este fue el error que me dio la terminal console.log(cons(“cadena”)) ^
TypeError: cons is not a function

Si podrian ayudarme a entender como funciona este closure

Access Token found in Javascript file?

Hey I am Mehul a Begineer to Bug Bounty Hunting
I have found an Access token in a javascript file while i was searching for any confidential information I want to ask whether it is a confidential thing so that i can report about it…
Thanks

Function still raises exception even with catch statement [duplicate]

Im suffering from a weird issue

basically I have the function

msg.guild.members.unban(userID)

This function returns a promise

I then use a .then statement for further code after the promise has been fulfilled

msg.guild.members.unban(element)
         .then(function() {console.log("worked")})

Anyways this function will in certain cases raise an Exception

Therefore I use the .catch statement to handle it

msg.guild.members.unban(element)
         .catch(console.log("Not banned"))
         .then(function() {})

However this does not seem to work

as a discord api error will still be raised and the program terminated

The error is an DiscordAPIError

Node JS -Telegram bot works locally but not on heroku

My telegram bot working perfectly on local machine but when I deploy it to heroku it become unresponsive and dynos are also set to npm start even when I declared start script in package.json.Here is the log file:-

2022-06-04T15:45:02.232005+00:00 app[web.1]: at Promise._settlePromiseFromHandler (/app/node_modules/bluebird/js/release/promise.js:547:31)
2022-06-04T15:45:02.232006+00:00 app[web.1]: at Promise._settlePromise (/app/node_modules/bluebird/js/release/promise.js:604:18)
2022-06-04T15:45:02.232006+00:00 app[web.1]: at Promise._settlePromise0 (/app/node_modules/bluebird/js/release/promise.js:649:10)
2022-06-04T15:45:02.232006+00:00 app[web.1]: at Promise._settlePromises (/app/node_modules/bluebird/js/release/promise.js:729:18)
2022-06-04T15:45:02.232006+00:00 app[web.1]: at _drainQueueStep (/app/node_modules/bluebird/js/release/async.js:93:12)
2022-06-04T15:45:02.232007+00:00 app[web.1]: at _drainQueue (/app/node_modules/bluebird/js/release/async.js:86:9)
2022-06-04T15:45:02.232007+00:00 app[web.1]: at Async._drainQueues (/app/node_modules/bluebird/js/release/async.js:102:5)
2022-06-04T15:45:02.232008+00:00 app[web.1]: at Immediate.Async.drainQueues [as _onImmediate] (/app/node_modules/bluebird/js/release/async.js:15:14)
2022-06-04T15:45:02.232011+00:00 app[web.1]: at processImmediate (node:internal/timers:466:21)
2022-06-04T15:45:02.521059+00:00 heroku[web.1]: State changed from starting to up

Aligning items side by side in css

I have the code:

$(window).scroll(function() {
  $('.container p').each(function() {
    var scrollTop = $(window).scrollTop(),
      elementOffset = $(this).offset().top,
      distance = (elementOffset - scrollTop),
      windowHeight = $(window).height(),
      breakPoint = windowHeight * 0.9;

    if (distance > breakPoint) {
      $(this).addClass("more-padding");
    }
    if (distance < breakPoint) {
      $(this).removeClass("more-padding");
    }
  });
});
.wrap {
  position: relative;
  font-size: 18px;
  color: black;
  z-index: -1;
}

h1 {
  font-size: 2em;
  text-align: center;
  margin: 20px 0 40px;
  padding: 0;
}

.container {
  background: transparent;
  right: 100%;
  margin: 0 auto;
  overflow: auto;
  padding: 2%;
}

.right-content,
.left-content {
  float: left;
  display: block;
  width: 40%;
  padding: 1% 2%;
}

.left-content {
  border-right: 5px dotted #666;
  text-align: right;
}

.left-content p {
  margin: 150px 0 0;
}

.right-content p {
  margin: 80px 0 150px;
}

.container p {
  -webkit-transition: all 0.7s ease-in-out;
  -moz-transition: all 0.7 ease-in-out;
  -ms-transition: all 0.7s ease-in-out;
  -o-transition: all 0.7s ease-in-out;
  transition: all 0.7s ease-in-out;
}

.left-content .more-padding {
  padding-right: 100px;
}

.right-content .more-padding {
  padding-left: 100px;
}

.icon-wrapper {
  display: flex;
  width: 200px;
  height: 200px;
  background: orange;
  padding: 2.9em;
  margin: 2em auto;
  border-radius: 50%;
  overflow: hidden;
}

h1 {
  text-align: center;
}

.cls-1 {
  fill: #fff;
}

.cls-2 {
  fill: none;
  stroke: #fff;
  stroke-linecap: round;
  stroke-linejoin: round;
  stroke-width: 2px;
}

.icon-wrapper #air {
  stroke-dashoffset: 66;
  stroke-dasharray: 33;
  transition: all 2s ease;
}

.icon-wrapper:hover #air {
  stroke-dashoffset: 0;
}

.icon-wrapper #ball {
  transition: all 1.5s ease;
  transform: rotate(0);
  transform-origin: center;
}

.icon-wrapper:hover #ball {
  transform: rotate(360deg);
}
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,900&amp;amp" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700&amp;subset=latin,latin-ext" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.6/animate.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.min.js"></script>

<div class="wrap">
  <div class="container">
    <h1>Hobbies</h1>
    <div class="left-content">
      <p>Content 01</p>
      <p>Content 02</p>
      <p>Content 03</p>
      <p>Content 04</p>
      <p>Content 05</p>
      <p>Content 06</p>
      <p>Content 07</p>
      <p>Content 08</p>
      <p>Content 09</p>
      <p>Content 10</p>
    </div>
    <div class="right-content">
      <p>Content 01</p>
      <p>Content 02</p>
      <p>Content 03</p>
      <p>Content 04</p>
      <p>Content 05</p>
      <p>Content 06</p>
      <p>Content 07</p>
      <p>Content 08</p>
      <p>Content 09</p>
      <p>Content 10</p>
    </div>
  </div>
</div>

<div class="icon-wrapper">
  <svg id="netball-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
      <title>Netball</title>
      <path id="ball" class="cls-1" d="M70.44,32.78A32,32,0,0,0,55.28,24.3l-.37-.08A32.57,32.57,0,0,0,42.09,24l-.32,0A32,32,0,1,0,70.44,78a32.26,32.26,0,0,0,5.47-7.3l.27-.5h0A32.24,32.24,0,0,0,70.44,32.78Zm-1.77,1.77A29.19,29.19,0,0,1,77,51.28a11,11,0,0,1-5.38,5.39,47.16,47.16,0,0,0-.71-12.11,30.91,30.91,0,0,0-4.55-11.45c-.35-.5-.71-1-1.08-1.48A31.27,31.27,0,0,1,68.67,34.55ZM54.54,26.69c7.42,3,12.1,9.14,13.91,18.33A44.25,44.25,0,0,1,69,57.52a19.92,19.92,0,0,1-5,.38A95,95,0,0,0,59.5,41.82a43.19,43.19,0,0,0-6.65-11.93,19,19,0,0,0-4.43-4A30,30,0,0,1,54.54,26.69Zm-12.35-.24c7.23.33,12.13,9,15,16.27a91.23,91.23,0,0,1,4.31,15,56.07,56.07,0,0,1-13-3.78l-.76-.3c-.8-11.8-3.87-19.55-9.12-23a11.46,11.46,0,0,0-3.74-1.65A29.24,29.24,0,0,1,42.19,26.45ZM27,34.55a29.23,29.23,0,0,1,4-3.32,8,8,0,0,1,1.31-.1,8.84,8.84,0,0,1,4.67,1.32,36.37,36.37,0,0,0-8.6,5.09A32.06,32.06,0,0,0,18.9,49.75,29.53,29.53,0,0,1,27,34.55Zm-5.5,34.08a29.12,29.12,0,0,1-2.67-8A29.16,29.16,0,0,1,29.86,39.52a33.11,33.11,0,0,1,9.28-5.24A16.1,16.1,0,0,1,41.7,38.1,75.82,75.82,0,0,0,29,50.24a34.87,34.87,0,0,0-6.94,12.68A18.6,18.6,0,0,0,21.47,68.63Zm8.63,3.09c0,.23-.08.49-.13.79l-.06.33A12.59,12.59,0,0,0,30,78.9a30.79,30.79,0,0,1-3-2.66l-.62-.62C22,69.06,23.54,61,31,51.82A74.15,74.15,0,0,1,42.72,40.47a48.19,48.19,0,0,1,2.5,13.19,19.72,19.72,0,0,0-5,2.94c-3,2.35-7.1,6.83-10.12,15ZM47.82,84.86a29.67,29.67,0,0,1-13.41-3.21,8.54,8.54,0,0,1-2.17-7.48,67.13,67.13,0,0,0,8.58,4.07,44.67,44.67,0,0,0,15.47,3.22,26.2,26.2,0,0,0,5.72-.6c.4-.09.8-.19,1.19-.3A29.24,29.24,0,0,1,47.82,84.86Zm25.9-15.37a19.06,19.06,0,0,1-12.25,8.92,23.25,23.25,0,0,1-5.18.55c-10.12,0-20.21-5.42-23.5-7.37a38.69,38.69,0,0,1,2.3-4.89,96.31,96.31,0,0,0,17.6,4.59,43.78,43.78,0,0,0,14.67.1,19.35,19.35,0,0,0,6.73-2.6C74,69,73.84,69.26,73.72,69.49Zm-6.84-.56a41.32,41.32,0,0,1-13.81-.11,94.1,94.1,0,0,1-16.64-4.3,26.25,26.25,0,0,1,5.33-5.92,16.32,16.32,0,0,1,4.83-2.77l.78.31.19.07c2.68,1.08,9,3.61,15.28,4.12s11.31-1.13,14.45-4.89a29.3,29.3,0,0,1-1,7.61C74.47,66.07,71.3,68,66.88,68.93Z" />
      <g id="air">
          <line class="cls-2" x1="68.86" y1="27.95" x2="86.42" y2="10.4" />
          <line class="cls-2" x1="73.42" y1="31.34" x2="85.74" y2="19.02" />
          <line class="cls-2" x1="76.68" y1="36.31" x2="82.13" y2="30.86" />
      </g>
  </svg>
</div>
<h1>Netball Icon Animation</h1>

When you run the code and scroll down, you will see a sports logo animation. I would like that sports logo to be displayed at this position:

enter image description here

How can I achieve this? I would like the logo to be displayed on the side, so how can I edit the CSS of the logo animation accordingly?

Any suggestions would greatly help. Thanks.

deep hierarchy data tree

hi i have been facing an issue from weeks and not able to solve , I have an array of objects in which i have few properties like fullName and reportingTo , then i have another object which is of ceo, the final data structure is to be every object has a fullName now if in any other object if the reportingTo matches with their name that object must be removed from array and added in children property, i have been able to do it only for a few levels but i need it dynamic so even if there is 100 parents it must work, i am putting the data below and what ever i have been able to do so far



let data = [
  {
    department: "development",
    designation: "lead",
    employeeId: "2",
    fullName: "Kashif",
    reportingTo: "Rashid",
    workEmail: "[email protected]",
    workPhone: "2222222222",
  },

  {
    department: "development",
    designation: "UI Developer",
    employeeId: "3",
    fullName: "Sharif",
    reportingTo: "Rashid",
    workEmail: "[email protected]",
    workPhone: "3333333333",
  },
  {
    department: "development",
    designation: "UX Developer",
    employeeId: "4",
    fullName: "Naveen",
    reportingTo: "Rashid",
    workEmail: "[email protected]",
    workPhone: "4444444444",
  },
  {
    department: "development",
    designation: "Developer",
    employeeId: "5",
    fullName: "Mani",
    reportingTo: "Kiran",
    workEmail: "[email protected]",
    workPhone: "5555555555",
  },

  {
    department: "development",
    designation: "Developer",
    employeeId: "6",
    fullName: "Joseph",
    reportingTo: "kiran",
    workEmail: "[email protected]",
    workPhone: "6666666666",
  },
  {
    department: "development",
    designation: "Developer",
    employeeId: "7",
    fullName: "Waseem",
    reportingTo: "Mani",
    workEmail: "[email protected]",
    workPhone: "6666666666",
  },
  {
    department: "development",
    designation: "Developer",
    employeeId: "8",
    fullName: "Munir",
    reportingTo: "Waseem",
    workEmail: "[email protected]",
    workPhone: "6666666666",
  },
  {
    department: "development",
    designation: "Developer",
    employeeId: "9",
    fullName: "Maaz",
    reportingTo: "Munir",
    workEmail: "[email protected]",
    workPhone: "6666666666",
  },
  {
    department: "development",
    designation: "Developer",
    employeeId: "10",
    fullName: "Hazma",
    reportingTo: "Maaz",
    workEmail: "[email protected]",
    workPhone: "6666666666",
  },
  {
    department: "development",
    designation: "Developer",
    employeeId: "11",
    fullName: "Muhammad",
    reportingTo: "Maaz",
    workEmail: "[email protected]",
    workPhone: "6666666666",
  },
  {
    department: "development",
    designation: "Developer",
    employeeId: "11",
    fullName: "Kiran",
    reportingTo: "Rashid",
    workEmail: "[email protected]",
    workPhone: "6666666666",
  },
];

let ceo = {
  department: "management",
  designation: "ceo",
  employeeId: "1",
  fullName: "Rashid",
  reportingTo: "null",
  workEmail: "[email protected]",
  workPhone: "1111111111",
};


const renderChildren = (list, reportingTo) => {
  let array = [];
  let dataArray = [...list];

  dataArray.map((item, i) => {
    if (item.reportingTo == reportingTo) {
      array.push(item);
      list.splice(i, 1);
    }
  });
  return array;
};

let ceoChildren = renderChildren(data, "Rashid"); // In this case we are getting all the employees who are reporting to ceo whose name is Rashid

Expected Result should be

let data = {
  department: "management",
  designation: "ceo",
  employeeId: "1",
  fullName: "Rashid",
  reportingTo: "null",
  workEmail: "[email protected]",
  workPhone: "1111111111",
  children: [
    {
      department: "development",
      designation: "lead",
      employeeId: "2",
      fullName: "Kashif",
      reportingTo: "Rashid",
      workEmail: "[email protected]",
      workPhone: "2222222222",
    },
    {
      department: "development",
      designation: "Developer",
      employeeId: "11",
      fullName: "Kiran",
      reportingTo: "Rashid",
      workEmail: "[email protected]",
      workPhone: "6666666666",
      children: [
        {
          department: "development",
          designation: "Developer",
          employeeId: "5",
          fullName: "Mani",
          reportingTo: "Kiran",
          workEmail: "[email protected]",
          workPhone: "5555555555",
          children: [
            {
              department: "development",
              designation: "Developer",
              employeeId: "7",
              fullName: "Waseem",
              reportingTo: "Mani",
              workEmail: "[email protected]",
              workPhone: "6666666666",
              children: [
                {
                  department: "development",
                  designation: "Developer",
                  employeeId: "8",
                  fullName: "Munir",
                  reportingTo: "Waseem",
                  workEmail: "[email protected]",
                  workPhone: "6666666666",
                  children: [
                    {
                      department: "development",
                      designation: "Developer",
                      employeeId: "9",
                      fullName: "Maaz",
                      reportingTo: "Munir",
                      workEmail: "[email protected]",
                      workPhone: "6666666666",
                      children: [
                        {
                          department: "development",
                          designation: "Developer",
                          employeeId: "10",
                          fullName: "Hazma",
                          reportingTo: "Maaz",
                          workEmail: "[email protected]",
                          workPhone: "6666666666",
                        },
                        {
                          department: "development",
                          designation: "Developer",
                          employeeId: "11",
                          fullName: "Muhammad",
                          reportingTo: "Maaz",
                          workEmail: "[email protected]",
                          workPhone: "6666666666",
                        },
                      ],
                    },
                  ],
                },
              ],
            },
          ],
        },

        {
          department: "development",
          designation: "Developer",
          employeeId: "6",
          fullName: "Joseph",
          reportingTo: "Kiran",
          workEmail: "[email protected]",
          workPhone: "6666666666",
        },
      ],
    },
    {
      department: "development",
      designation: "UI Developer",
      employeeId: "3",
      fullName: "Sharif",
      reportingTo: "Rashid",
      workEmail: "[email protected]",
      workPhone: "3333333333",
    },
    {
      department: "development",
      designation: "UX Developer",
      employeeId: "4",
      fullName: "Naveen",
      reportingTo: "Rashid",
      workEmail: "[email protected]",
      workPhone: "4444444444",
    },
  ],
};


my sorting is not working in react-data-table-component

this is the table i have and if i click any one of the heading id dosent sort

when i click on rank, location or deaths on top it used to sort the list before but now it doesn’t work. The data you see is not all of the data i have used there is a few more that would just make the question long so i only added first few. Any help would be appreciated.

const

 data = [
        {
            location: 'Texas',
            deaths: '4,164',
            rank: 1
        },
        {
            location: 'California',
            deaths: '3,449',
            rank: 2
        }
    ]



  const columns = [
        {
          name: <h2>Rank</h2>,
          selector:  row => <h3>{row.rank}</h3>,
          sortable: true,
        },
        {
          name: <h2>Location</h2>,
          selector:  row => <h3>{row.location}</h3>,
          sortable: true,
        },
        {
          name: <h2>Deaths</h2>,
          selector:  row => <h3>{row.deaths}</h3>,
          sortable: true,
        }
      ];


  return (
    <div className='table_map'>
        <DataTable  
            data={data}
            columns={columns}
            print='true'
            theme="solarized"
            fixedHeader
            fixedHeaderScrollHeight="700px"
            customStyles = {customStyles }
        />
    </div>
  )
}
 
export default Table
 

node.js – cannot get return value from helper function

i’m very new at node.js, javascript, etc. so i have no experience. I am having a problem when trying to get a return value from a helper function in my controller. The helper function intends to get a value from a mongodb database and return it to the main controller. But when i call the helper function i get undefined as result. I put a console.log inside the helper function and the data from the db is being retrieved correctly. Please Help.
This is my controller code.


var validator = require("validator");
var Necesidad = require("../models/necesidad");
var NecesidadCategoria = require("../models/necesidad_categoria");
var helpers = require("../controllers/helpers/index.js");
const necesidad_categoria = require("../models/necesidad_categoria");

var controller = {
  new: (req, res) => {
    var params = req.body;

    try {
      var validateNombre = !validator.isEmpty(params.nombre);
      var validateCantidad = params.cantidad >= 0;

      if (validateNombre && validateCantidad) {
        var necesidad = new Necesidad();
        necesidad.nece_nombre = params.nombre;
        necesidad.nece_cantidad = params.cantidad;
        necesidad.nece_estado = 0;
        necesidad.nece_imagen = "";
        var args = { cat_nombre: params.cat_nombre };

        var categoria = helpers.getNecesidadCategoria(args);
        console.log("categoria: " + categoria);
        
        necesidad.save((err, necesidadStored) => {
          if (err || !necesidadStored) {
            return res.status(404).send({
              status: "error",
              message: "Los datos no fueron guardados: " + err,
            });
          }

          return res.status(200).send({
            status: "success",
            necesidad: necesidadStored,
          });
        });
      } else {
        return res.status(200).send({
          status: "error",
          message: "Error de validación de datos.",
        });
      }
    } catch (err) {
      return res.status(200).send({
        status: "error",
        message: "Error de validación de datos. Traza completa: " + err,
      });
    }
  },
};

module.exports = controller;

And this is my helper function:

var validator = require("validator");
var NecesidadCategoria = require("/ProyectosAngular/SeminarioFinalBackend/models/necesidad_categoria");
module.exports = {
   getNecesidadCategoria: function (args) {
    var nombre = args.cat_nombre;
    var nombreValidation = !validator.isEmpty(nombre);

    if (nombreValidation) {
      NecesidadCategoria.findOne(
        { cat_nombre: nombre },
        function (err, necesidad_categoria) {
          if (err || !necesidad_categoria) {
            return null;
          } else {
            console.log("categoria function:" + necesidad_categoria);
            return necesidad_categoria;
          }
        }
      );
    }
  },

};

Props values changes when clicked onpress within a Flatlist item

Props values gets changed onpress() event of FlatList Item. I am passing an array but the array gets auto nested again into an array causing issues on Second time onpress event of the same item.

Below is the first time onpress data:

Object {
  "content": "Data",
  "date": "2022-06-04",
  "image": "url",
  "link": "url",
  "pubdate": "2022-06-04T20:00:33.639242+05:30",
  "source": "abc",
  "time": "20:00:33",
  "title": "abc",
}

Below is the Second time onpress Data:

Object {
"item":Object {
  "content": "Data",
  "date": "2022-06-04",
  "image": "url",
  "link": "url",
  "pubdate": "2022-06-04T20:00:33.639242+05:30",
  "source": "abc",
  "time": "20:00:33",
  "title": "abc",
},
}

Below is the FlatList View which has the onpress event:

import React, { useState } from "react";
import { StyleSheet, View, Dimensions, Text, Modal, Share } from "react-native";
import { Icon, Tile } from "react-native-elements";
import {
  Avatar,
  Button,
  Card,
  Title,
  Paragraph,
  Subheading,
  Caption,
} from "react-native-paper";
import moment from "moment";
import { WebView } from "react-native-webview";
import { ActivityIndicator } from "react-native";
import { MaterialCommunityIcons } from "@expo/vector-icons";

// import { Container } from './styles';

const { width } = Dimensions.get("window");
const { webViewHeight } = Dimensions.get("window").height - 56;

const BlockCard = ({ navigation, item }) => {
  const { image, title, source, date, time, link } = item;
  const momentsago = moment(date + " " + time, "YYYY/MM/DD HH:mm:ss").fromNow();
  const source2 = source + " | " + momentsago;
  return (
    <View style={styles.centeredView}>
      <Card>
        <Card.Cover source={{ uri: image }} />
        <Card.Content>
          {/* <Subheading style={{fontWeight:"bold"}}>{title}</Subheading> */}
          <Title>{title}</Title>
          <Caption style={{ fontWeight: "bold" }}>{source2}</Caption>
        </Card.Content>
        <Card.Actions style={{ alignSelf: "flex-end" }}>
          <Button icon="share-variant" color="#E1B72E">
            Share
          </Button>
          <Button
            icon="open-in-new"
            color="#E1B72E"
            onPress={() => navigation.navigate("Details", (item = { item }))}
          >
            Explore
          </Button>
        </Card.Actions>
      </Card>
    </View>
  );
};

Below is the Details Screen:

const Details = ({ navigation, route }) => {
  var { image, title, source, date, time, link, pubdate, content } =
    route.params.item;
  var momentsago = moment(date + " " + time, "YYYY/MM/DD HH:mm:ss").fromNow();
  var source2 = source + " | " + momentsago;

  useEffect(() => {
    console.log(route.params.item);
  });

The Console.log captured the variance in the Data. Kindly provide me any pointers as I am very new to React Native.

Invalid fields warning customisation odoo14

I want to customise invalid fields warning.

I want that user should close the warning instead of automatically disappearing warnings. The reason is suppose there are multiple fields that are required and user clicks on save and got invalid field warning but it disappears after 4-5 second. So user can’t see the required fields properly and he have to again click on the save button and check what are those required fields.

I have tried to customise the below default method but it doesn’t work for me:-

/web/static/src/js/views/basic/basic_controller.js

_notifyInvalidFields: function (invalidFields) {
    var record = this.model.get(this.handle, {raw: true});
    var fields = record.fields;
    var warnings = invalidFields.map(function (fieldName) {
        var fieldStr = fields[fieldName].string;
        return _.str.sprintf('<li>%s</li>', _.escape(fieldStr));
    });
    warnings.unshift('<ul>');
    warnings.push('</ul>');
    this.do_warn(_t("Invalid fields:"), warnings.join(''));
},

Do anyone have any idea how to change this thing or any other method is used to show this warning?

find max Consecutive Ones in array using javascript

I have an array of numbers. I need to find the maximum number of consecutive 1s in the array.

var arr = [1, 1, 3, 2, 3, 1, 1, 1];

const maxOne = (arr) => {
  for (var i = 0; i < arr.length; i++) {
    let count = 0;
    let result = 0;
    if (arr[i] ==1) {
      count += 1;
      result = Math.max(result, count);
    } else {
      count = 0
    }
  console.log("<<<",result)
  }
}

console.log(maxOne(arr));

desired output: 3

my output : 1

I am not sure where I am going wrong

Implement live markdown rendering using slate.js

I’m writing a markdown text editor using slate.js. I’m trying to implement the following live-rendering effect (from Typora):

Live Markdown rendering

As you can see,

  1. When I’m typing, the text is turning to bold automatically.
  2. When I hit the space key, the four asterisks disappeared, only the text itself is visible.
  3. When I focus the cursor back to the text, the asterisks shows up again (so I can modify them).

I’ve already implemented the first item thanks to the example of MarkdownPreview, here is the code of it (take from the slate repository):

import Prism from 'prismjs'
import React, { useCallback, useMemo } from 'react'
import { Slate, Editable, withReact } from 'slate-react'
import { Text, createEditor, Descendant } from 'slate'
import { withHistory } from 'slate-history'
import { css } from '@emotion/css'

// eslint-disable-next-line
;Prism.languages.markdown=Prism.languages.extend("markup",{}),Prism.languages.insertBefore("markdown","prolog",{blockquote:{pattern:/^>(?:[t ]*>)*/m,alias:"punctuation"},code:[{pattern:/^(?: {4}|t).+/m,alias:"keyword"},{pattern:/``.+?``|`[^`n]+`/,alias:"keyword"}],title:[{pattern:/w+.*(?:r?n|r)(?:==+|--+)/,alias:"important",inside:{punctuation:/==+$|--+$/}},{pattern:/(^s*)#+.+/m,lookbehind:!0,alias:"important",inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^s*)([*-])([t ]*2){2,}(?=s*$)/m,lookbehind:!0,alias:"punctuation"},list:{pattern:/(^s*)(?:[*+-]|d+.)(?=[t ].)/m,lookbehind:!0,alias:"punctuation"},"url-reference":{pattern:/!?[[^]]+]:[t ]+(?:S+|<(?:\.|[^>\])+>)(?:[t ]+(?:"(?:\.|[^"\])*"|'(?:\.|[^'\])*'|((?:\.|[^)\])*)))?/,inside:{variable:{pattern:/^(!?[)[^]]+/,lookbehind:!0},string:/(?:"(?:\.|[^"\])*"|'(?:\.|[^'\])*'|((?:\.|[^)\])*))$/,punctuation:/^[[]!:]|[<>]/},alias:"url"},bold:{pattern:/(^|[^\])(**|__)(?:(?:r?n|r)(?!r?n|r)|.)+?2/,lookbehind:!0,inside:{punctuation:/^**|^__|**$|__$/}},italic:{pattern:/(^|[^\])([*_])(?:(?:r?n|r)(?!r?n|r)|.)+?2/,lookbehind:!0,inside:{punctuation:/^[*_]|[*_]$/}},url:{pattern:/!?[[^]]+](?:([^s)]+(?:[t ]+"(?:\.|[^"\])*")?)| ?[[^]n]*])/,inside:{variable:{pattern:/(!?[)[^]]+(?=]$)/,lookbehind:!0},string:{pattern:/"(?:\.|[^"\])*"(?=)$)/}}}}),Prism.languages.markdown.bold.inside.url=Prism.util.clone(Prism.languages.markdown.url),Prism.languages.markdown.italic.inside.url=Prism.util.clone(Prism.languages.markdown.url),Prism.languages.markdown.bold.inside.italic=Prism.util.clone(Prism.languages.markdown.italic),Prism.languages.markdown.italic.inside.bold=Prism.util.clone(Prism.languages.markdown.bold); // prettier-ignore

const MarkdownPreviewExample = () => {
  const renderLeaf = useCallback(props => <Leaf {...props} />, [])
  const editor = useMemo(() => withHistory(withReact(createEditor())), [])
  const decorate = useCallback(([node, path]) => {
    const ranges = []

    if (!Text.isText(node)) {
      return ranges
    }

    const getLength = token => {
      if (typeof token === 'string') {
        return token.length
      } else if (typeof token.content === 'string') {
        return token.content.length
      } else {
        return token.content.reduce((l, t) => l + getLength(t), 0)
      }
    }

    const tokens = Prism.tokenize(node.text, Prism.languages.markdown)
    let start = 0

    for (const token of tokens) {
      const length = getLength(token)
      const end = start + length

      if (typeof token !== 'string') {
        ranges.push({
          [token.type]: true,
          anchor: { path, offset: start },
          focus: { path, offset: end },
        })
      }

      start = end
    }

    return ranges
  }, [])

  return (
    <Slate editor={editor} value={initialValue}>
      <Editable
        decorate={decorate}
        renderLeaf={renderLeaf}
        placeholder="Write some markdown..."
      />
    </Slate>
  )
}

const Leaf = ({ attributes, children, leaf }) => {
  return (
    <span
      {...attributes}
      className={css`
        font-weight: ${leaf.bold && 'bold'};
        font-style: ${leaf.italic && 'italic'};
        text-decoration: ${leaf.underlined && 'underline'};
        ${leaf.title &&
          css`
            display: inline-block;
            font-weight: bold;
            font-size: 20px;
            margin: 20px 0 10px 0;
          `}
        ${leaf.list &&
          css`
            padding-left: 10px;
            font-size: 20px;
            line-height: 10px;
          `}
        ${leaf.hr &&
          css`
            display: block;
            text-align: center;
            border-bottom: 2px solid #ddd;
          `}
        ${leaf.blockquote &&
          css`
            display: inline-block;
            border-left: 2px solid #ddd;
            padding-left: 10px;
            color: #aaa;
            font-style: italic;
          `}
        ${leaf.code &&
          css`
            font-family: monospace;
            background-color: #eee;
            padding: 3px;
          `}
      `}
    >
      {children}
    </span>
  )
}

const initialValue: Descendant[] = [
  {
    type: 'paragraph',
    children: [
      {
        text:
          'Slate is flexible enough to add **decorations** that can format text based on its content. For example, this editor has **Markdown** preview decorations on it, to make it _dead_ simple to make an editor with built-in Markdown previewing.',
      },
    ],
  },
  {
    type: 'paragraph',
    children: [{ text: '## Try it out!' }],
  },
  {
    type: 'paragraph',
    children: [{ text: 'Try it out for yourself!' }],
  },
]

export default MarkdownPreviewExample

My question is, how can I implement the second and third items? I’ve been thinking about it for a long time, but didn’t find any good way to achieve them.

Text is not converting to svg properly – Opentype Javascript

I am trying to convert text to svg in my React web app, but the resulted svg code which i am getting is not right, t’s not showing svg.
Code:

import opentype from "opentype.js"

async function textToPath(){
    const text = "Hello"
    const size = {x: 50, y: 25}
    const fontFile = "https://fonts.gstatic.com/s/firasans/v15/va9E4kDNxMZdWfMOD5Vvl4jO.ttf"
    let params = {
        string: text,
        font: fontFile,
        fontSize: size.x,
        decimals: 1,
        singleGylyphs: false
    }
    const font = await opentype.load(params.font);

    let options = params.options;
    let unitsPerEm = font.unitsPerEm;
    let ratio = params.fontSize / unitsPerEm;
    let ascender = font.ascender;
    let descender = Math.abs(font.descender);
    let ratAsc = ascender / unitsPerEm;
    let ratDesc = descender / unitsPerEm;
    let yOffset = params.fontSize * ratAsc;
    let lineHeight = params.fontSize + params.fontSize * ratDesc;
    let singleGylyphs = params.singleGylyphs;

    let teststring = params.string.split("");

    let glyphs = font.stringToGlyphs(params.string);
    let leftSB = glyphs[0].leftSideBearing * ratio;
    let textPath = "";

    //individual paths for each glyph
    if (singleGylyphs) {
        let paths = font.getPaths(
            params.string,
            -leftSB,
            yOffset,
            params.fontSize,
            options
        );
        paths.forEach(function (path, i) {
            let pathEl = path.toSVG(params.decimals);
            textPath += pathEl.replaceAll(
                "d=",
                'class="glyph glyph-' + teststring[i] + '" d='
            );
        });
    }
    //word (all glyphs) merged to one path
    else {
        let path = font.getPath(
            params.string,
            -leftSB,
            yOffset,
            params.fontSize,
            options
        );
        textPath += path
            .toSVG(params.decimals)
            .replaceAll("d=", 'class="glyph" d=');
    }

    // render
    let fontSvgWrp = document.createElement("div");
    fontSvgWrp.classList.add("fontSvgWrp");
    let fontSvg = document.createElementNS(
        "http://www.w3.org/2000/svg",
        "svg"
    );
    fontSvg.classList.add("svgText");
    fontSvg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
    fontSvg.innerHTML = textPath;
    fontSvgWrp.appendChild(fontSvg);

    // adjust bbox
    let bb = fontSvg.getBBox();
    let stringWidth = Math.ceil(bb.width + bb.x);
    fontSvg.setAttribute("viewBox", "0 0 " + stringWidth + " " + lineHeight);
    fontSvg.setAttribute("width", size.x);
    fontSvg.setAttribute("data-asc", ratAsc);
    console.log(fontSvg); // getting svg code

    let textPathSvg = fontSvg.querySelector(".glyph");
    let textPathLength = textPathSvg.getTotalLength();
    
    return textPathLength
}

It’s generating this svg which is not working:

<svg class="svgText" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 0 5013.25" width="50" data-asc="0.935"><path class="glyph" d="M24 46.8L19.3 46.8L19.3 30.6L4.8 30.6L4.8 46.8L0 46.8L0 12.3L4.8 12.3L4.8 26.7L19.3 26.7L19.3 12.3L24 12.3L24 46.8ZM53.7 32.8Q53.7 34.0 53.5 35.1L53.5 35.1L36.8 35.1Q37.0 39.5 39.0 41.5Q40.9 43.6 43.9 43.6L43.9 43.6Q45.8 43.6 47.4 43.0Q49.0 42.5 50.7 41.3L50.7 41.3L52.7 44.0Q48.5 47.4 43.5 47.4L43.5 47.4Q38 47.4 34.9 43.8Q31.9 40.1 31.9 33.9L31.9 33.9Q31.9 29.8 33.2 26.6Q34.5 23.4 37.0 21.6Q39.5 19.8 42.8 19.8L42.8 19.8Q48.0 19.8 50.9 23.3Q53.7 26.7 53.7 32.8L53.7 32.8ZM49.1 31.8L49.1 31.4Q49.1 27.5 47.5 25.5Q46 23.4 42.9 23.4L42.9 23.4Q37.3 23.4 36.8 31.8L36.8 31.8L49.1 31.8ZM66.3 47.4Q63.7 47.4 62.2 45.8Q60.8 44.3 60.8 41.5L60.8 41.5L60.8 9.8L65.3 9.3L65.3 41.5Q65.3 42.5 65.7 43.0Q66.1 43.5 67 43.5L67 43.5Q68.0 43.5 68.7 43.3L68.7 43.3L69.9 46.5Q68.3 47.4 66.3 47.4L66.3 47.4ZM80.9 47.4Q78.4 47.4 76.9 45.8Q75.4 44.3 75.4 41.5L75.4 41.5L75.4 9.8L80 9.3L80 41.5Q80 42.5 80.4 43.0Q80.8 43.5 81.7 43.5L81.7 43.5Q82.6 43.5 83.4 43.3L83.4 43.3L84.6 46.5Q82.9 47.4 80.9 47.4L80.9 47.4ZM100.2 19.8Q105.8 19.8 108.8 23.5Q111.9 27.2 111.9 33.5L111.9 33.5Q111.9 37.6 110.5 40.8Q109.1 43.9 106.5 45.6Q103.8 47.4 100.2 47.4L100.2 47.4Q94.6 47.4 91.5 43.6Q88.4 40.0 88.4 33.6L88.4 33.6Q88.4 29.5 89.8 26.4Q91.2 23.3 93.9 21.5Q96.5 19.8 100.2 19.8L100.2 19.8ZM100.2 23.5Q93.4 23.5 93.4 33.6L93.4 33.6Q93.4 43.6 100.2 43.6L100.2 43.6Q107.0 43.6 107.0 33.5L107.0 33.5Q107.0 23.5 100.2 23.5L100.2 23.5Z"></path></svg>

I tried & searched a lot but i didn’t get anything to fix this thing and why the converted svg is not working. Can someone help?