I have a script that downloads a urls.txt with a list of urls to images on google. How do i execute this from a .js file

if i paste this into the browser console, it works 100% – as long as i am on google images in my browser. How can i execute this from just a .js file alone and using a variable as the term to search for?

I would ideally like to call this script from the cli in vscode and pass in an argument with the search term, the script then opens google in the background and downloads images related to the search term for the first x amount of search result pages.

This is for a TensorFlow dataset – i am trying to automate the process of collecting relevant image data.

function simulateRightClick(element) {
  var event1 = new MouseEvent('mousedown', {
    bubbles: true,
    cancelable: false,
    view: window,
    button: 2,
    buttons: 2,
    clientX: element.getBoundingClientRect().x,
    clientY: element.getBoundingClientRect().y,
  })
  element.dispatchEvent(event1)
  var event2 = new MouseEvent('mouseup', {
    bubbles: true,
    cancelable: false,
    view: window,
    button: 2,
    buttons: 0,
    clientX: element.getBoundingClientRect().x,
    clientY: element.getBoundingClientRect().y,
  })
  element.dispatchEvent(event2)
  var event3 = new MouseEvent('contextmenu', {
    bubbles: true,
    cancelable: false,
    view: window,
    button: 2,
    buttons: 0,
    clientX: element.getBoundingClientRect().x,
    clientY: element.getBoundingClientRect().y,
  })
  element.dispatchEvent(event3)
}

function getURLParam(queryString, key) {
  var vars = queryString.replace(/^?/, '').split('&')
  for (let i = 0; i < vars.length; i++) {
    let pair = vars[i].split('=')
    if (pair[0] == key) {
      return pair[1]
    }
  }
  return false
}

function createDownload(contents) {
  var hiddenElement = document.createElement('a')
  hiddenElement.href = 'data:attachment/text,' + encodeURI(contents)
  hiddenElement.target = '_blank'
  hiddenElement.download = 'urls.txt'
  hiddenElement.click()
}

function grabUrls() {
  var urls = []
  return new Promise(function (resolve, reject) {
    var count = document.querySelectorAll('.isv-r a:first-of-type').length,
      index = 0
    Array.prototype.forEach.call(
      document.querySelectorAll('.isv-r a:first-of-type'),
      function (element) {
        // using the right click menu Google will generate the
        // full-size URL; won't work in Internet Explorer
        // (http://pyimg.co/byukr)
        simulateRightClick(element.querySelector(':scope img'))
        // Wait for it to appear on the <a> element
        var interval = setInterval(function () {
          if (element.href.trim() !== '') {
            clearInterval(interval)
            // extract the full-size version of the image
            let googleUrl = element.href.replace(/.*(?)/, '$1'),
              fullImageUrl = decodeURIComponent(
                getURLParam(googleUrl, 'imgurl'),
              )
            if (fullImageUrl !== 'false') {
              urls.push(fullImageUrl)
            }
            // sometimes the URL returns a "false" string and
            // we still want to count those so our Promise
            // resolves
            index++
            if (index == count - 1) {
              resolve(urls)
            }
          }
        }, 10)
      },
    )
  })
}

grabUrls().then(function (urls) {
  urls = urls.join('n')
  createDownload(urls)
})

Should I render to an image to draw onto a , and how would I go about doing it?

Hard to fit all of the relevant information in the title, so here’s the gist of it:

I’m working on a sprite editor that will hopefully be able to spit out usable tile sheets/palettes for the GameBoy Advance for another project I’m working on (and thus, I have committed the cardinal sin of programming). Since I’m already going to be keeping track of the tile data, palettes, and sprites separately, I figured it might be more efficient to render the tile sheet to an image, then have a <canvas> context draw sections of the tile sheet into the editing frame, rather than using context.fillRect or similar to draw directly to the canvas. Part of the reason I had this idea was because I was concerned about zooming in/out in the editor, which would expand/shrink the sprite. Instead of having to write my own aliasing code, I could draw the tile sheet to an image buffer at a known size, then use context.drawImage to actually display the required tiles and reaping the benefits of the already-existing aliasing algorithm.

As such, my question is two-fold: should I actually write the tile sheet to an image then draw parts of the image to a canvas or should I just fillRect the “””pixels”””? And if I should generate an image, how would I go about doing such?

Note: I’m preferring not to use jQuery here. It seems like a pretty hefty library that wouldn’t gain me much in this context.

Javascript console.log on the same line

I need to print results on the same line of code without using .innerHTML(“”).
I could do it by overwriting original console.log function. This code bellow does it. However, this code prints every console.log text to next line.

(function () {
if (!console) {
    console = {};
}
var old = console.log;
var logger = document.getElementById('log');
console.log = function (message) {
    if (typeof message == 'object') {
        logger.innerHTML += (String(message)) + '<br>';
    } else {
        logger.innerHTML += message + '<br>';
    }
}
})();

Do you know how could I modify this to print text of console.log to next line only if user writes command console.log(“textn”);, and if it’s written console.log(“text”); the default should be to write inline text. (like function printf in C for example)

setInterval Not Repeating Function using Discord.js

I’m trying to make a discord bot that gives you weekly reminders. Im using momentjs to get the time. As well as using discord.js-commando. I found the best way to call a function multiple times is to use setInterval.

const moment = require('moment');
const Commando = require('discord.js-commando');
const bot = new Commando.Client();

bot.on('ready', function () {
  var day = moment().format('dddd');
  var time = moment().format('h:mm a');

  function Tuesday() {
    if (day == 'Tuesday' && time == '6:30 pm') {
      const channel = bot.channels.get('933047404645724234');
      console.log('Sending Message');
      channel.send('Reminder: You have a week to complete your To-Do List!');
    } else {
      console.log('Not Sending Message');
    }
  }

  console.log('Bot is now ready!');
  setInterval(Tuesday, 100);
});

I noticed the problem with the setInterval is that it is only called once. I also tried using an async function but that failed as well.

Set an inline style with javascript click [duplicate]

I’m trying to change the position of an element with some simple javascript. This isn’t working and I’ve no idea what I’ve got wrong or if what I expect is not possible. This doesn’t need to be pretty, it’s for internal use only.COT

<div id="container">
    <div id="maps"> 
        <div class="frida">CONTENT</div> 
        <div class="dolores">CONTENT</div>
    </div>
    <a href="" onclick = document.getElementById("maps").style.left = "0"; >FRIDA</a> 
    <a href="" onclick = document.getElementById("maps").style.left = "-100vw"; >DOLORES</a>
</div>

My bcrypt.js hash returns null while all other inputs are fine

This code below returns the input password as null, but all other inputs are fine. I don’t know what to do, if anyone can help please do.

I am using bcrypt with knex for psql.

app.post("/register", (req, res) => {
  const { email, name, password } = req.body;
  let salt = bcrypt.genSaltSync(10);
  let hash = bcrypt.hashSync(password, salt);
  
  knex
    .transaction((trx) => {
      trx
        .insert({
          hash: hash,
          email: email,
        })
        .into("login")
        .returning("email")
        .then((loginEmail) => {
          return trx("users")
            .returning("*")
            .insert({
              email: loginEmail[0].email,
              name: name,
              joined: new Date(),
            })
            .then((user) => {
              res.json(user[0]);
            });
        })
        .then(trx.commit)
        .catch(trx.rollback);
    })
    .catch((err) => res.status(400).json("E-mail is already in use"));
});

Having some issues with Edge. Would like to ask a couple basic questions

Opened 2 tabs on Edge and then another popped up that wanted me to verify through authentication without me doing anything that would call it to prompt. A little suspicious. Opened up Visual Studio 2022 to debug the authorization window that would not go away. I find that there is actually 7 instances of Webview, 6 instances of Windows.Client.WebExperience, and 11 general processes for Microsoft Edge (with no specific title). There is also an additional window that has the name of a window title attributed to it. Looking at the type of file, all of the Edge processes are listed as 64-bit, Javascript. Should I assume that there are several hidden Edge windows each running javascript?

Upon choosing a random windows, debugging fails with error message “Cannot connect to the target: connect ECONNREFUSED 127.0.0.1:9222” Why is visual studio trying to connect as a remote debugger through a TCP port?

All the connections for all of these processes have destinations listed as * in Sysinternals TCPView. I went to try wireshark and netstat. Some time while running those, I went back to TCPView and all the process IDs had changed to the same PID, even though I know they each had a unique PID before. How would a program be able to do this? What would be a foolproof way to track my destination IP address should this happen again?

How to make a template css can be call with specific condition?

I design start layout with width 320px, my target is mobile device first > tablet > desktop. I check in developer mode in chrome, iphone 6/7/8 give me different result whereas iphone 6/7/8 still a mobile device, same as galaxy s4. what i need to set same setting by type device?

<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
      body { margin: 0; }
      .container {
        width: 100%;
        height: 20px;
        background-color: gray;
      }
      
      .container > div {
        width: 320px;
        height: inherit;
        background-color: pink;
        margin: auto;
        font-size: 1em;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div>
        Responsive By Type Devices
      </div>
    </div>
  </body>
</html>

grid-template-columns – items not in center

I am trying to create my own grid using “grid-template-columns”, in result when i resize the view items not centered.

I use this documentation https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns

I am stuck and need some advice, what i am doing wrong.

P.S In normal desktop view looks ok, but in mobile …
Below i attached screenshot and my code example.

enter image description here

Here code example what i am using:

<!DOCTYPE html>
<html lang="en">
    
    <head>
        <meta charset="utf-8">
        <title>Profile Card</title>
        <link rel="stylesheet" href="css/font-awesome.min.css">       
        <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,600,700' rel='stylesheet'>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
        <style>

.my-grid {
    display: flex;
    justify-content: center;
    align-content: center;
}

.my-container{
    position: relative;
    width: 1200px;
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    grid-gap: 20px;
    padding: 20px;
}

.my-container .my-card{
    width: 100%;
    background: #fff;
    border-radius: 20px;
    max-width: 250px;
    box-shadow: 0px 20px 70px 0px rgb(0 0 0 / 21%);
}

.my-container .my-card .imgBx {
    position: relative;
    width: 100%;
    height: 310px;
    overflow: hidden;
}

.my-container .my-card .imgBx img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: 0.5s ease-in-out;
    transform-origin: right;
}

.my-container .my-card:hover .imgBx img {
    transform: scale(1.5);
}

.my-container .my-card .my-content{
    padding: 10px;
}

.my-container .my-card .my-content .my-product-name h3{
    font-size: 18px;
    font-weight: 500;
    color: #333;
    margin: 5px 0;
    text-align: center;
}

.my-container .my-card .my-content .my-rating {
    display: flex;
    justify-content: space-between;
    align-items: center;
    text-align: center;
    padding: 15px;
}

.my-container .my-card .my-content .my-rating h2{
    font-size: 20px;
    color: #333;
    font-weight: 500;
}

.my-action{
    position: absolute;
    top: 10px;
    right: 10px;
}

.my-action li{
    position: relative;
    list-style: none;
    width: 40px;
    height: 40px;
    background: #fff;
    border-radius: 6px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 4px;
    cursor: pointer;
    transition: transform 0.5s;
    transform: translateX(60px);
}

.my-action li:nth-child(2){
    transition-delay: 0.15s;
}

.my-action li:nth-child(3){
    transition-delay: 0.3s;
}

.my-container .my-card:hover .my-action li{
    transform: translateX(0px);
}

.my-action li:hover{
    background: #a7389d;
    color: #fff;
}

.my-action li span{
    position: absolute;
    right: 50px;
    top: 50%;
    transform: translateY(-50%) translateX(-20px);
    white-space: nowrap;
    padding: 4px 60px;
    background: #fff;
    color: #333;
    font-weight: 500;
    font-size: 12px;
    border-radius: 4px;
    pointer-events: none;
    opacity: 0;
    transition: 0.5s;
}

.my-action li:hover span{
    opacity: 1;
    transform: translateY(-50%) translateX(0px);
}

.my-action li span::before{
    content: ' ';
    position: absolute;
    top: 50%;
    right: -4px;
    width: 8px;
    height: 8px;
    background: #a7389d;
    transform: translateY(-50%) rotate(50deg);
}

.app{
    text-align: center;
}

.app h6{
    display: inline-block;
}

.verified-label{
    text-align: center;
}

.verified-label h6{
    display: inline-block;
}

</style>
    </head>

    <body>



<div class="my-grid">
<div class="my-container">

    <div class="my-card">
        <div class="imgBx">
            <img src="/test.jpg">
            <ul class="my-action">
                <li>
                    <i class="fas fa-external-link-alt"></i>
                    <span>View more</span>          
                </li>
                <li>
                    <i class="fas fa-camera"></i>
                    <span>2</span>          
                </li>
                <li>
                    <div class="f32">
                        <a class="flag ru"></a>
                   </div>           
                </li>
            </ul>
        </div>
        <div class="my-content">
            <div class="my-product-name">
                <h3>Test Name</h3>
            </div>
            <div class="app">
                <span class="fas fa-mobile-alt">
                        <h6></h6>
                </span>
            </div>
            <div class="verified-label">
                <span class="fas fa-gem">
                        <h6></h6>
                </span>
            </div>
            <div class="my-rating">
                <div class="rating">
                    <i class="fas fa-fire"></i>
                    <h2>168</h2>
                </div>
                <div class="rating">
                    <i class="fas fa-eye"></i>
                    <h2>168</h2>
                </div>
                <div class="rating">
                    <i class="fas fa-heart"></i>
                    <h2>168</h2>
                </div>
            </div>
        </div>
    </div>
    
        <div class="my-card">
        <div class="imgBx">
            <img src="/test.jpg">
        </div>
        <div class="my-content">
            <div class="my-product-name">
                <h3>Test Name</h3>
            </div>
            <div class="my-rating">
                <div class="rating">
                    <i class="fas fa-fire"></i>
                    <h2>168</h2>
                </div>
                <div class="rating">
                    <i class="fas fa-eye"></i>
                    <h2>168</h2>
                </div>
                <div class="rating">
                    <i class="fas fa-heart"></i>
                    <h2>168</h2>
                </div>
            </div>
        </div>
    </div>
    

</div>
</div>
        <script src="js/jquery-1.12.1.min.js"></script>
        <script src="js/pCard_script.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>

    </body>
    
</html>

I am stuck, pls advice =(

Train Time Table

  1. The display should show a clock, so people know what time it is.
  2. The display should show the next two buses due to leave the station
  3. The display should show a minute-by-minute update on when the buses
    are due to depart
  4. The display should indicate when no buses are due to depart in the
    next 15 minutes
  5. Every minute on the timetable should be represented in real-time
    seconds (i.e. 1 hour = 60 seconds)

In React / JavaScript

Looking to identify if a member has Timeout on

So with Discord releasing member timeout, mute roles are no longer a necessity, however with my whois command I check to see if the user is muted with a mute role but I want to move that over to see if the user has a timeout on them

    const { MessageEmbed } = require('discord.js')

module.exports = {
  name: 'whois',
  description: 'Displays Information about a user',
  async execute(client, message, cmd, args, Discord){
    const { guild, channel } = message;
    const user = message.mentions.users.first() || message.author;
    const member = message.guild.members.cache.get(user.id);
    let muteRole = message.member.roles.cache.some(role => role.name === 'muted')
    if(!muteRole) muteRole = message.member.roles.cache.some(role => role.name === 'Muted');

    const userInfoEmbed = new MessageEmbed()
    .setColor("BLACK")
    .setTitle(`User Info for ${user.username}`)
    .setThumbnail(`${user.displayAvatarURL()}`)
    .addFields(
      { name: 'User Tag:', value: `${user.tag}` },
      { name: 'Online Status:', value: `${member.clientStatus}` },
    { name: 'Nickname:', value: member.nickname || 'N/A' },
   { name: 'Bot:', value: `${user.bot}` , inline: true },
   { name: 'Joined on:', value: new Date(member.joinedTimestamp).toLocaleDateString() , inline: true },
   { name: 'Created on:', value: new Date(user.createdTimestamp).toLocaleDateString() , inline: true },
   { name: 'Bannable:', value: `${member.bannable}` , inline: true },
   { name: 'Highest Role:', value: `${member.roles.highest}`, inline: true },
  // { name: 'Muted:', value: `${muteRole}`, inline: true},
 )
 .setFooter(`Requested by ${message.author.username}`)
 .setTimestamp()


message.channel.send({ embeds: [userInfoEmbed] })

  }
}

Mongodb Or query with two arrays

I am trying to perform an or query in MongoDB.

I have two array

firstNames = ['John', 'Tim','Joey']
lastNames = ['Alex', 'Smith', 'Mac']

I want to perform a query like

{$or: [{firstName: 'John', lastName: 'Alex'}, {firstName: 'John', lastName: 'Smith'}, {firstName: 'John', lastName: 'Mac'}, {firstName: 'Tim', lastName: 'Alex'} ... ]}

I tried

1.

Users.find({firstName: {$in: firstNames}, lastName: {$in: lastNames} })
Users.find({$or:[{firstName: {$in: firstNames}}, {lastName: {$in: lastNames} }]})

but this is wrong I guess. Can someone provide a better solution to this?

How can you get more than one $or condition into a single mongodb find() operation?

I’ve got an operation where I’m trying to limit results on a collection using the $or operator, however I have more than one field that needs to utilize this functionality.

See query below:

db.items.find({//"isDeleted":false,
    "$or":[
        {"$and":[{"passages.fleschKincaid.readingEase":{"$gte":90}}]},
        {"$and":[{"passages.fleschKincaid.readingEase":{"$gte":60}},{"passages.fleschKincaid.readingEase":{"$lte":70}}]},
        {"$and":[{"passages.fleschKincaid.readingEase":{"$gte":50}},{"passages.fleschKincaid.readingEase":{"$lte":60}}]}
    ],
    "$or":[{"$and": [{"contentBanks":{$in: element.statusIds}}]}]})

The first condition loops through and adds on gte/lte operators based on certain conditions, and the second or condition I’ve used here is within a for loop that pushes on an additional $and for each new contentBank. Each one only needs to satisfy one of the conditions to show as a result, but contentBank and passages.fleschKincaid.readingEase are mutually exclusive so they can’t be grouped together in the same $or group.

i.e. – if I have an item, for it to meet my conditions in the above example, it needs both a readingEase score of let’s say 55, AND have a contentBank in statusIds. It needs to meet both conditions, but check the $or‘s separately.

What I end up with is a query that overwrites the written conditions and treats it as one big $or, returning results that might match one contentBank but not be within the readingEase range.

Any help would be greatly appreciated. I’m writing this with javascript, mongoose, and mongodb. If you know of a way to get the query to treat them separately that would be great.

p.s. – I’m trying to avoid it getting to chock-full of $and operators, but if that’s the only way to do this, I can find a way to create a whole new object and add it in. The only issue with that is the complexity increases quite a bit because the pipeline operators are all built dynamically – so the additional $and operator wrapping everything would require a solid amount of changes/overhead to get working.

Regex testing a string with uppercase letters, lowercase letters, numbers, special symbols, with no whitespace

I’m trying to evaluate a js string with a regex function that will detect the above mentioned criterias except for the symbols part, as I only need to evaluate if dots or underscores are in the string. An example is this:

mfv.3djtSewe5jCrg19A_fkdrOe8LG2zL7cY1oK4lEN5m3z6jh9bvpUlnxfP4qdbAwhuUruN_uKRv6trcROqXm4P

and the regex I’m using is this:

/^(?!.*s+$)(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_.]).+$/

I’m new to javascript let alone regex matching and I’m not entirely sure how to do this.

Trouble splitting a string in JavaScript using regular expressions

I am VERY new to regex in js and having a very hard time manipulating them to do what I am looking for.

I have a series of strings that I am trying to strip of unusual characters, spaces, newlines, etc. and put them into arrays where each entry is a word consisting of only alphanumeric characters.

For example:

let testString = "this*is " + "an" +" test string "
test = testString.split(/W/)  
console.log(test)

Yields [ 'this', 'is', 'a', '', 'test', 'string', '' ]

But ideally I would like it to yield [ 'this', 'is', 'a', 'test', 'string']

I can achieve the desired result by adding .filter(word => word !== '') to the end, but I am wondering if there is a way to do this using only regular expressions? Also would it be necessary to add a global flag to the regex?

Thanks in advance for any input!