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!

Recursive function to return overall overall results

I need a recursive method to roll up all results from a series of paginated calls and returns the complete list of results. Something feels off in the way I am doing it and feel there is a better way to do this, possibly with Array.reduce

Any recommendations appreciated.

interface Result {
  users: Widget[];
  start: number;
}

interface Widget {
  id: number;
}

// create 3 widgets for test
const widgets = Array(3).fill(null).map((i, index: number) => {
  return {
    id: index + 1,
  } as Widget;
});

const getFromAPI = (start: number = 0): Result => {
  // return 1 at a time from a specified position
  const current = widgets.slice(start, start + 1);
  let nextStart: number;
  if (start < widgets.length - 1) {
    nextStart = start + 1;
  }

  return {
    users: current,
    start: nextStart,
  }
}

// I don't like that em is outside the scope here
let em: Widget[] = [];
const getWidgets = (start?: number): Widget[] => {
  const result = getFromAPI(start);
  em = [...em, ...result.users];
  if (result.start) {
    getWidgets(result.start);
  }

  return em;
}

const all = getWidgets();

Handling of optional properties of objects to be used as mapped or indexed properties

I am working on a scenario of handling an array type property with indexed access. Tried to encapsulate the problem in simplest form here.

type User = {
    readonly name: string; 
    readonly roles: ReadonlyArray<string>;
}

const buildActions = <T extends User>(u: T) => {
    // Implementation
    return {login: (role: T['roles'][number]) => {
        console.log(u, role);
    }}
}

const actions = buildActions({name: 'user', roles: ['admin', 'client']} as const);
actions.login('client');

So above code works fine. But in my scenario the property roles is optional.

type User = {
    readonly name: string; 
    readonly roles?: ReadonlyArray<string>;
}

In above case we get error

Type ‘number’ cannot be used to index type ‘T[“roles”]’

I tried to use conditional type to handle the scenario but didn’t worked out.

const buildActions = <T extends User>(u: T) => {
    // Implementation
    return {login: (role: T['roles'] extends never ? never : T['roles'][number]) => {
        console.log(u, role);
    }}
}

Definitely it’s not the right way to handle such scenario, but covers the use case very well.

Any idea how to get through this typing scenario?

Thanks

How can I toggle between 2 classes on click on the same element on JS

Need your help on something,

Trying to toggle between classes when I click on an element on an HTML page but unfortunately once toggled I cannot change it back.

Even tried returning the querySelector but no luck.

Here is the code I wrote;

let fetchNumbers = document.querySelectorAll(`.cardnumber`);

    for (let index = 0; index < fetchNumbers.length; index++) {
    
    if (fetchNumbers[index].classList.contains('unselected') === true) {
        fetchNumbers[index].addEventListener(`click`, function () {
            fetchNumbers[index].classList.add(`selected`);
            fetchNumbers[index].classList.remove(`unselected`);
            fetchNumbers = document.querySelectorAll(`.cardnumber`);
            return fetchNumbers;
        }); 
    } else {
        fetchNumbers[index].addEventListener(`click`, function () {
            fetchNumbers[index].classList.add(`unselected`);
            fetchNumbers[index].classList.remove(`selected`);
            fetchNumbers = document.querySelectorAll(`.cardnumber`)
            return fetchNumbers;
        }); 
    }
}

Thank you in advance

populating a table in SQL database(id:string, value: array of strings)

SELECT * FROM tableT WHERE

Please write code to populate tableT with id as a string, and array of strings as values, so the table would look like:

"Animals"   ["dogs","cats","rats"]
"Liquids"   ["water","tea","milk"]

The purpose of this is to see a certain id, get that Id from the database and display the corresponding array. So, f.e if the client types in “Animals”. The code would connect to database and retrivie the value ["dogs","cat","rats].

Retrieval code is also appreciated (in Javascript)

React State producing strange result on first state change

I am trying to create a basic square foot calculator using React State and am running into something I’ve not seen before. I’m sure it is something I’m not pervy to yet but would like to know if this is expected or not.

My goal here is when a user enters in a price I’d like to calculate that in real-time. So far, it is able to do this. HOWEVER, when I first load the page and enter in a set of numbers, for example, 5 in the width and 5 in the length – I get NaN printed to the console. Only after I enter a second number like 55 and 55, will it do the calculation and print it to the console.

I had suspected it has something to do with the initial state so instead of useState() I switched it to useState(0). Instead of producing NaN I get 0 printed to the console after each number I enter. Again, If I enter 55 and 55 it does the calculation. Why is this and how can I avoid this?

const PPSQ = 12;

const [width, setWidth] = useState()
const [length, setLength] = useState()

function calculate() {
    console.log((width * length) * PPSQ);
}

function getWidth(val) {
    setWidth(val.target.value)
    calculate()
}

function getLength(val) {
    setLength(val.target.value)
    calculate()
}

<input
className="form-control"
id="length"
name="length"
placeholder="Length"
type="number"
onChange={getLength}
autoComplete="off"
required
/>

<input
className="form-control"
id="width"
name="width"
placeholder="Width"
type="number"
onChange={getWidth}
autoComplete="off"
required
/>

“WebSocket connection to ‘wss://mydomain.com:8080/’ failed:” with no extra details

I am trying to host a websocket using node.js and it seems to host fine, but I cannot connect to it externally because I just get the error in the title. The : after failed suggests there should be extra details and similar questions here prove that, but I’m not getting anything after the colon making this very difficult to debug. I have tried in multiple browsers and I get the same error so it’s not my browser causing this. My best guess would be that my cerificates aren’t working, but they’re the same certificates I use for the rest of my websites and they work fine for them so not too sure.

This is my server-side (node.js) code:

const server = require('https').createServer({
    cert: fs.readFileSync('/etc/letsencrypt/live/mydomain.com/fullchain.pem'),
    key: fs.readFileSync('/etc/letsencrypt/live/mydomain.com/privkey.pem')
});

const websocket = new (require('ws').Server)({server});
websocket.on('connection', (client, request) => {
    console.log("New connection from "+request.socket.remoteAddress);
});

And my client-side (Javascript) code is just

new WebSocket("wss://mydomain.com:8080").onmessage = (event) => {
    console.log(event.data);
};

I have tried making my node.js server listen to port 8080 but that made no difference. I have also tried different URLs on the client side (such as without the protocol, without the port, using my ip) but as I would expect, those don’t work either.