Logical OR operators throws a syntax error here in JS – where am I going wrong?

Logical OR operators throws a syntax error here in JS – where am I going wrong?

function playRound(playerSelection, computerSelection) {
  if (playerSelection == 'rock' && computerSelection == 'paper') ||
  (playerSelection == 'paper' && computerSelection == 'shotgun') ||
  (playerSelection == 'shotgun' && computerSelection == 'rock') {
  console.log(`Sorry! ${computerSelection} beats ${playerSelection}`);}
}

Remove a URL search parameter when there is duplicate names?

I am trying to manipulate my URL using URLSearchParams. However URLSearchParams.delete() expects the name of the param. If I have params with the same name, (from what I’ve tested) the function only removes the last matching param. Is there a way to delete by both name and value?

My query looks something like this:

?color[]=Black&color[]=Green&material[]=Steel

So when I call .delete("color[]") it will remove the color[]=Green param, but what if I want to remove color[]=Black?

The reason for the duplicate names is the backend (PHP) is leveraging this functionallity to auto parse the parameters into arrays…which requires the syntax above.

Big picture is- I’m trying to add/remove “filters” from this array-to-be. Also, some filter categories could have matching values so I don’t want remove by value either. I am open to considering an entirely new approach…just trying to do it in the least hacky way.

How to create an application that has some functionality and share it so someone else can put it on their website?

If I create a small web application on my desktop (html and js files) and want to share the functionality of it so my friend could use it on his website, how can I do that?

For example, if I want to use the benefits of bootstrap to quickly make changes, they instruct me to download this file

<!-- JavaScript Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

  1. What is this file? I’m assuming all the js code and logic to their
    platform lives in this file, yes?

  2. If I want to build my own
    application and share it so others can use it, how would I do it?

Sample application: a user copies the CDN file link, they add it to their index.html file at the top of the page, when they reload their website a modal pops up in 5 seconds. That’s it.

How can I filter to an array and choose a random Id from it?

Good night folks.

I’m new to programming, less than 2 months, so I don’t quite understand how to make this work. Here’s exactly what I want to do:
I have this game I’m trying to make which needs to do a raffle between existing units that fit the condition “is alive” and have “is able to use the prize”. To do that, I was told I needed to include an array with the unit Id for the units that can receive it, then filter them by “is alive” to choose from by a random generator. Thing is, I have no idea how to make this work. I’ve tried this code, but it does not work. Anyone has any idea why or how I should do it instead?

var rafflearray = []; // the array containing the units
if (root.getExternalData().isUnitRegistered() = true) {var character = root.getCurrentSession().getPlayerList().getData()}; // establish the character as a variable

if (var character.getAliveStatus = true ) {rafflearray.push(character)}; // checks his alive status and send him to the array

var chosen = rafflearray [Math.random()*chosenarray.lenght]; // to choose amongst them
chosen.addItem()

Thanks in advance for the attention!

Some functions appear as undefined firebase/auth v9

I was rewriting my code from firebase v8 to v9, i was watching this tutorial

i try to use the signInWithRedirect() function followed by the getRedirectResult() function

i import them like i import my others functions but when i console.log() thoses i get undefined in my console

here is my code :

import { View } from "react-native";

import firebase, { initializeApp } from 'firebase/app';

import { GoogleAuthProvider, useDeviceLanguage, signInWithCredential, onAuthStateChanged, getAuth, signInWithRedirect, getRedirectResult } from "firebase/auth";

const LoginSceen = (props) => {

  console.log(signInWithRedirect) //return undefined
  console.log(getRedirectResult ) //return undefined
 
  console.log(getAuth) //return [Function getAuth]
  console.log(GoogleAuthProvider) //return [Function GoogleAuthProvider]
  

  return (
    <View style={{ flex: 1, backgroundColor: "#9297C4" }}>

    </View>[enter image description here][1]
  );
}

export default LoginSceen;

PS : the error i get is TypeError: _auth.signInWithRedirect is not a function
firebase version in my package.json "firebase": "^9.6.0",

here the getAuth function detected by vscode IntelliSense
here the signInWithRedirect function who appear as undefined in my console but detected too by IntelliSense

In mongoDB using mongoose, get count of array elements

In mongoDB, get number of array items in a document — and why didn’t I just use sql to begin with!?

I have a document that looks like this …

{
    "age": 18,
    "role": "client",
    "email": "[email protected]",
    "name": "down",
    "answers": [{
        "_id": {
            "$oid": "61aa9a5e467fa9109b745d21"
        },
        "position": 2,
        "scale": 9,
        "slider": 0
    }, {
        "_id": {
            "$oid": "61aa9d3cd3912610d1196e40"
        },
        "position": 2,
        "scale": 9,
        "slider": 0
    }],
    "createdAt": {
        "$date": "2021-11-01T20:26:05.225Z"
    },
    "updatedAt": {
        "$date": "2021-12-03T22:42:04.861Z"
    },
    "__v": 0
}

Using mongoose, how do I get the number of array elements in the answers array?

Elegant, Vue-only solution for getting browser width in multiple components in Vue.js?

I’m relatively new to Vue 3, working on an application in which many components need access to the value of screen width, with the necessity of updating it dynamically as the window resizes.

Is there any elegant, no-third-party-plugin solution for implementing such a variable once, and using it in multiple components, without having to add event listeners seperately inside each one of them?

I’ve tried to define windowWidth in main.js as a globalProperty, and add a window event listener:

import { createApp, ref } from "vue";
import App from "./App.vue";
import router from "./router";

const app = createApp(App).use(router);

app.config.globalProperties.breakpoints = {
  sm: 768,
  md: 1024,
  lg: 1200,
};

app.config.globalProperties.winWidth = ref(window.innerWidth);

window.addEventListener(
  "resize",
  () => (app.config.globalProperties.winWidth = window.innerWidth)
);

app.use(router);
app.mount("#app");

But the value does not change when I resize the window (calling winWidth inside a <p> tag in a component to test).

I would love to learn how to implement this successfully!

Window 1⇏877⇏947⇏7788 ㍐ Get “Help” With File Explorer In Windows 11

Get Help with File Explorer in Windows 11 +1-877-947-7788 rebuilds the data utility but doesn’t fix the Get Help with File Explorer in Windows 11. This is often a complicated issue and has required fixing as soon as possible. When this Get Help with File Explorer in Windows 11 occurs users generally get the message, ‘Recover data file’ or ‘Your Get Help with File Explorer in Windows 11 isn’t working. For this Get Help with File Explorer in Windows 11, the Get Help with File Explorer in Windows 11 file must fix and recovered. To stop this Get Help with File Explorer in Windows 11 from doing any damage, restore a backup copy, and then condense the company file. It’s a really support software issue that needs immediate Get Help with File Explorer in Windows 11 mention and will be fixed as soon as possible. How does Get Help with File Explorer in Windows 11 +1-877-947-7788 talk to a person affect? As mentioned earlier they skipped 111 Get Help with File Explorer in Windows 11 is one of the most accounting. Get Help With File Explorer In Windows 11 s in MS OFFICE. So it means the business or user is at constant risk of Contact of Get Help With File Explorer In Windows 11 This Get Help With File Explorer In Windows 11 mostly occurs within the application system because of file damage. The file must be repaired by either restoration or by replacing it with an earlier saved backup copy of the stored data. Get Help with File Explorer in Windows 11- However, this is often Get Help With File Explorer In Windows 11 software within the end and that’s why Get Help With File Explorer In Windows 11 sometimes it does face issues affecting the business operations of its users. An issue that’s quite common has the Get Help with File Explorer in Windows 11 +1-877-947-7788. This Get Help with File Explorer in Windows 11 code recovers the data that has been founded and again rebuilds the data section. Losing their financial and operational data. Then they need storing in MS OFFICE. It’s imperative to make a backup of the data to stop problems in the future. Steps to resolve Get Help with File Explorer in Windows 11 Wherever there’s a problem there’s always a resolution. A similar is that the case with Get Help with File Explorer in Windows 11 +1-877-947-7788. Below mentioned are some steps that may help to repair can pass few tests and if your file passes these tests, then the backup of the file has automatically been created in the ADR folder. After this, the logging program of ADR transactions will invoice all the transactions quickly also as automatically. It’ll invoice all the transactions that have integrated with the file from a specific instance on Get Help with File Explorer in Windows 11 +1-877-947-7788 Software. Once the recovering process is complete, Get Help with File Explorer in Windows 11 accounting software will create a duplicate of that file. But if your application is open, you’d not find any backup created. This may produce two backup duplicates and also the latest one would be 12 hours old while another would be 24 hours old. This way the oldest file would get deleted.

How to get user information from Shiny server inside Azure web apps using EasyAuth?

I’ve got a shiny app inside azure app service using Azure’s EasyAuth. I can successfully authenticate to open a page. However, I’d like to get the user information which isn’t automatic since Shiny strips headers without buying the full pro edition.

I can think of a few high level potential work arounds but I’m not sure how well, if at all, any of these would work without trying to fully implement each.

  1. Put an nginx or apache reverse proxy in front of Shiny that would rewrite headers to query parameters which could then be accessed as session[['clientData']]$url_search Pro: I’m pretty sure this would work. Con: I think people could spoof who they are by just changing the query in their address and also they’d see their name appended to the url which would make copy-paste a pain. This isn’t a deal breaker because it’s just for convenience, not security, everyone has access to everything anyway (at least for now)

  2. Access the secure&HTTPonly AppServiceAuthSession cookie from the server and then httr::GET myurl.com/.auth/me using that cookie to get a concise json of who the user is. Pro: If it’s possible then I don’t have to reconfigure my Docker image like in #1 Cons: It doesn’t seem I can readily get the cookie into the shiny so this may not really be a potential

  3. Have the client brower access myurl.com/.auth/me through a js script and return those results to shiny server. Pro: Like 2, wouldn’t require reconfiguring my app service. Con: Don’t know if possible but it’s the same domain so I think it is.

It’d be most helpful if 2 and 3 could either be quickly implemented or 100% ruled out. If there’s a 4th option that I hadn’t thought of then that would be welcome too.

How do I render objects from a client-side JSON file?

I’ve been trying to render some objects from a test JSON file, but it doesn’t seem to be working. I’ve copied similar code from this website: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON, but adjusted to my own JSON file. I’ve tried to troubleshoot it, but I can’t see what the problem is.

Here is the code I have:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
      <header>
      </header>
      <section>
      </section>

    <script>
    const header = document.querySelector('header');
    const section = document.querySelector('section');

    let requestURL = 'http://www.piwebinars.co.uk/test.json';
    let request = new XMLHttpRequest();
    request.open('GET', requestURL);
    request.responseType = 'text';
    request.send();

    request.onload = function() {
      const superHeroesText = request.response;
      const superHeroes = JSON.parse(superHeroesText);
      renderComments(superHeroes);
    }


function renderComments(jsonObj) {
  const currentComments = jsonObj['post'];
  
  for (let i = 0; i < currentComments.length; i++) {
  const myArticle = document.createElement('article');
  const renderMessage = document.createElement('p3');
  const renderCommentLikes = document.createElement('h6');
  const renderLikeButton = document.createElement('button');
  const renderReplyButton = document.createElement('button');

  renderMessage.textContent = currentComments[i].text;
  renderCommentLikes.textContent = currentComments[i].name;
  renderLikeButton.textContent = "Like Comment";
  renderReplyButton.textContent = "Reply Comment";
  
    myArticle.appendChild(renderMessage);
    myArticle.appendChild(renderCommentLikes);
    myArticle.appendChild(renderLikeButton);
    myArticle.appendChild(renderReplyButton);
    
    section.appendChild(myArticle);
};
};
    </script>
  </body>
</html>

Help would be appreciated, thanks.

get neighboring pixels from linear array (as in context.getImageData)

I have an image with a red filled-in circle in the middle. I want to read that image, analyze the pixels, and write it back to the canvas with just the outline of the circle. So I am checking to see if the pixel is surrounded by pixels with red channel value of 255. If yes, I make transparent. If no, I color the pixel cyan.

I used this post, as reference for writing the script.

I’m doing something wrong. Instead of outlining the circle in cyan, and making the center transparent, it is coloring all the white pixels cyan.

I’d really appreciate some help!

Image used: enter image description here

Code:

<img alt="input" height="170" id="input" src="img/input.png" width="170">
<canvas height="170" id="myCanvas" style="border:1px solid #d3d3d3;" width="170"></canvas>
let neighbors = []

  function isSurrounded(index, imageData, data) {
    neighbors = [] // clear array
    neighbors[0] = data[index - imageData.width * 4 - 4] // Upper left
    neighbors[1] = data[index - imageData.width * 4]     // Upper middle
    neighbors[2] = data[index - imageData.width * 4 + 4] // Upper right
    neighbors[3] = data[index - 4] // left
    neighbors[4] = data[index + 4] // right
    neighbors[5] = data[index + imageData.width * 4 - 4] // Lower left
    neighbors[6] = data[index + imageData.width * 4]     // lower middle
    neighbors[7] = data[index + imageData.width * 4 + 4] // Lower right

    // check red channel
    for (let i = 0; i < neighbors.length; i++) {
      let redPixel = neighbors[i]
      if (redPixel !== 255) {
        return false
      }
    }
    return true
  }

  let img = document.getElementById("input")
  img.onload = function () {
    let c = document.getElementById("myCanvas")
    let ctx = c.getContext("2d")
    ctx.drawImage(img, 0, 0)
    let imgData = ctx.getImageData(0, 0, c.width, c.height)
    let pxl = imgData.data
    for (let i = 0; i < pxl.length; i += 4) {
      if (isSurrounded(i, imgData, pxl)) {
        pxl[i] = 0
        pxl[i + 1] = 255
        pxl[i + 2] = 255
        pxl[i + 3] = 255
      } else {
        pxl[i + 3] = 0
      }
    }
    ctx.putImageData(imgData, 0, 0)
  }

How to target & replace the name of a property from a different document in JavaScript?

Im wanting to replace/translate text on a webpage. This is for some online software where I only have access to a custom code section.

Ive managed to translate some words, but my script doesn’t have an affect on some others which are populated from a different file called storeSettings.js.

How can I edit my current translation script to translate the words I need in storeSettings.js ?

This is my current translation code to replace the word ‘State’ with ‘County’:

window.onload = function() {const replaceOnDocument = (pattern, string, {target = document.body} = {}) => {
  [
    target,
    ...target.querySelectorAll("*:not(script):not(noscript):not(style)")
  ].forEach(({childNodes: [...nodes]}) => nodes
    .filter(({nodeType}) => nodeType === document.TEXT_NODE)
    .forEach((textNode) => textNode.textContent = textNode.textContent.replace(pattern, string)));
};

replaceOnDocument(/State/g, "County");
                        };

And this is the contents of storeSettings.js



 var fillGeneralSettings = function () {
      mergeUnique(settings.general, {
        state: '',
      }, true);

{
          property: 'state',
          field: self.container.find('[name="state"]')
        }

Say I want to replace ‘State’ with ‘County’ (cosmetically). Instead of target = document.body in my translation script what should I replace it with to access the content of storeSettings.js?

Thank you! 🙂

How to convert base 2 integer with leading zeros to a string javascript

I’m given an array of integers such as:

const vals=[
  00100,
  11110,
  00100101,
  ...
]

and I need to simply make each value iterable maintaining the position of the leading zeros. My first thought was to turn them into strings, but JavaScript want’s to use base 10 and nothing that I have tried will change this. And when I try parsing it back to base 2, the leading zeros are all swapped around:

let testNum = 00100; // saves as 64
testNum = parseInt(testNum, 10); // using radix 2 returns NaN
testNum = testNum.toString(2); // 1000000

Any help would be greatly appreciated!