Setting Wallpaper Engine’s Window Listener to Typescript

I’m working on a wallpaper engine application in angular and the documentation says to grab a property off the window object and set it to a function to get the current user properties. I’m trying to convert this logic into angular but haven’t been able to get it to work correctly.

Here’s what I’m trying to match:

window.wallpaperPropertyListener = {
    applyUserProperties: function(properties) {
        if (properties.yourproperty) { // Don't forget to check if the property is included in the event
            // Checkbox / boolean example, change this as needed for your property type
            if (properties.yourproperty.value == true) {
                // Do something if your property is true
            } else {
                // Do something if your property is false
            }
        }
    },
};

Here’s what I have:

app.module.ts

declare global {
  interface Window {
    wallpaperPropertyListener : any;
  }
}
@NgModule({
  declarations: [
    AppComponent,
    FuzzyTimeComponent
  ],
  imports: [
    BrowserModule,
    NgbModule,
    BrowserAnimationsModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

export class AppComponent implements AfterViewInit {
  title = 'wordclock2';

  constructor(private el: ElementRef, private renderer: Renderer2, private settingsService: SettingsService) {
    window.wallpaperPropertyListener = {
      applyUserProperties(properties) {
        this.settingsService.setTimePeriodEnabled(false);
      }
    };
  }

I’m not checking for any properties right now, since I just want to see if the function is ever called and it doesn’t seem like it is.

How to fill message box on Whatsapp Web?

I’m trying to send a message on Whatsapp Web (https://web.whatsapp.com/) only using Javascript, for study purposes.

Here is the DIV that has the message box :

enter image description here

<div class="fd365im1 to2l77zo bbv8nyr4 mwp4sxku gfz4du6o ag5g9lrv" contenteditable="true" role="textbox" spellcheck="true" title="Type a message" data-tab="10" data-lexical-editor="true" style="user-select: text; white-space: pre-wrap; word-break: break-word;"><p class="selectable-text copyable-text"><br></p></div>

And here is my code :

document.getElementsByClassName('fd365im1 to2l77zo bbv8nyr4 mwp4sxku gfz4du6o ag5g9lrv')[0].innerText = 'My message content';

The code runs without errors, but the message field is not filled, nothing happens on the interface. This code used to run before, but not anymore.

What am i missing ? You can try your self accessing the whatsapp web and using Chrome devtools.

Mongoose Remove key(s) from child schema (nested subdocuments)

I have two schemas defined, imageSchema and userSchema. imageSchema has key postedBy: userSchema. Question is shall I remove unused attributes of userSchema (like password) when nested into imageSchema, if so how to do it?

var userSchema = new mongoose.Schema({
  email: String,
  password: String,
  name: String,
}, {versionKey: false})

var imageSchema = new mongoose.Schema({
  filePath: String,
  user: userSchema,
  createdAt: Date,
  comments: [{body: "String", by: mongoose.Schema.Types.ObjectId}]
})
...
app.post("/upload-image", async function(req, res){
  if(req.session.user_id) {
    ...
      fileSystem.rename(oldPath, newPath, function(err2){
        getUser(req.session.user_id, function(user){
          delete user.password
          var currentTime = new Date().getTime()
          Image.create({
            "filePath": newPath,
            "user": user,
            "createdAt": currentTime,
            "comments": []
          }, function(err2, data){
            res.redirect("/?message=image_uploaded")
          })
...

So after I created a new document of Image, I checked the database, the user field of the new Image has the attribute of password, which is not desired. “delete user.password” seems not working. How should I delete this attribute? Shall I do it when defining the imageSchema, or remove it when posting the data (the app.post part)?

DiscordAPIError: Invalid Form Body user_id: Value is not a snowflake

I am trying to get my leaderboard script to work, but I keep encountering this error. This only started after I started using a command handler.

module.exports = {
    name: "leaderboard",
    aliases: ['lb'],
    description: "leaderboard",

    async run (Discord, client, message, member, args, Levels) {

        const rawLeaderboard = await Levels.fetchLeaderboard(message.guild.id, 10);

        if (rawLeaderboard.length < 1) return message.reply("Nobody's in leaderboard yet.");

        const leaderboard = await Levels.computeLeaderboard(client, rawLeaderboard, true);

        const lb = leaderboard.map(e => `${e.position}. ${e.username}#${e.discriminator}nLevel: ${e.level}nXP: ${e.xp.toLocaleString()}`);


        const embed = new Discord.MessageEmbed()
        .setColor("WHITE")
        .setTitle("LEADERBOARD")
        .setDescription(lb.join("nn"))


        message.channel.send({embeds: });

    }
}

ERROR:

node_modulesdiscord.jssrcrestRequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^

DiscordAPIError: Invalid Form Body user_id: Value
“<@My ID>” is not snowflake.
at RequestHandler.execute (C:UsersMEOneDriveDesktopDiscord BotsTest
Botnode_modulesdiscord.jssrcrestRequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:UsersMEOneDriveDesktopDiscord BotsTest
Botnode_modulesdiscord.jssrcrestRequestHandler.js:51:14)
at async UserManager.fetch (C:UsersMEOneDriveDesktopDiscord BotsTest
Botnode_modulesdiscord.jssrcmanagersUserManager.js:93:18)
at async Function.computeLeaderboard (C:UsersMEOneDriveDesktopDiscord BotsTest
Botnode_modulesdiscord-xpindex.js:271:22)
at async Object.run (C:UsersMeOneDriveDesktopDiscord BotsTest Botcommandsleaderboard.js:15:29) { method: ‘get’,
path: ‘/users/<@my id>’, code: 50035, httpStatus:
400, requestData: { json: undefined, files: [] } }

Is there a way to link a file in js to another js file ? Code snippets below

So basically a button in Res after Sign in should put a real time chat on screen. Res contains two buttons Sign Out and Chat. Why isn’t the Press button in Res to call Chat not calling Chat?
If Anyone can help that would be great!

App.js file here

import Res from './components/Res';
import Chat from './components/Chat';
import Signin from './components/Signin';
import './App.css';
import {auth} from './firebase.js'
import {useAuthState} from 'react-firebase-hooks/auth'
import Router from './Router'


function App() {
  const [user] = useAuthState(auth)
  return (
    <>
      {user ? <Res/> : <Signin/>} //After you sign in it goes to Res
    </>
  );
}

export default App;

Res.js file here

import React from 'react'
import {Routes, Route, useNavigate} from 'react-router-dom';
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import {Button} from '@material-ui/core'
import { auth } from '../firebase.js'
import Signin from './Signin';
import Signout from './Signout';
import {useAuthState} from 'react-firebase-hooks/auth'
import ReactDOM from 'react-dom';
import Chat from './Chat'


function Res() {

    
    return (
        
    <div>
        
        <button onClick={()=><Chat/>} >Press</button> //I want it to call the javascript file Chat

        <Signout/>
        
        
    </div>
  )
}

export default Res

Chat.js file here

import React, {useState, useEffect,useRef} from 'react'
import { db, auth } from '../firebase'
import Sendmessage from './Sendmessage'
import Signout from './Signout'

function Chat() {
  

  const scroll = useRef()
  const [messages, setMessages] = useState([])
  useEffect(
    ()=>{
      db.collection('message').orderBy('createdAt').limit(50).onSnapshot(snapshot => {
      setMessages(snapshot.docs.map(doc => doc.data()))
  })
}, [])
  return (
    
    <div id = "chat">
      
      <Signout/>
      
      <div className="msgs">
      {messages.map(({id,text,photoURL,uid})=>(
        <div>

        <div key={id} className={`msg ${uid == auth.currentUser.uid ?'sent':'received'}`}>
          <img src = {photoURL} alt = ""/>
          <p>{text}</p>
      </div>
      </div>
      ))}
      </div>
      <Sendmessage scroll />
      <div ref = {scroll}></div>
      </div>
  )
}

export default Chat

Not sure why the press button does nothing

JavaScript generate an empty dynamic sized 2D array

I am trying to create a dynamically sized, empty 2D grid using arrays that can have a percentage of one value at specific co-ordinates, and the remainder another value, all assigned post-generation. I have found a suitable solution, but wanted to gain some clarification on why the original implementation didn’t work as intended.

The code that works:

const height = 5;
const width = 5;
const percentage = 0.2;    // control percentage of certain value

// grid construction
const grid = new Array(height).fill().map(element => new Array(width));

// grid population
for (let y = 0; y < height; y++) {
  for (let x = 0; x < width; x++) {
    const probability = Math.random();
    grid[y][x] = probability > percentage ? 'x' : 'o';
  }
}

console.log(grid);

/* Example Output:
[
  ['x', 'x', 'x', 'o', 'x'],
  ['o', 'o', 'x', 'x', 'x'],
  ['x', 'x', 'x', 'x', 'x'],
  ['x', 'x', 'x', 'x', 'x'],
  ['x', 'x', 'o', 'x', 'o']
]
*/

The issue arises when I change the ‘grid construction’ block:

const height = 5;
const width = 5;
const percentage = 0.2;    // control percentage of certain value

// grid construction (doesn't work as intended)
const row = new Array(width).fill();
const grid = new Array(height).fill(row);

// grid population
for (let y = 0; y < height; y++) {
  for (let x = 0; x < width; x++) {
    const probability = Math.random();
    grid[y][x] = probability > percentage ? 'x' : 'o';
  }
}

console.log(grid);

/* Example Output:
[
  ['x', 'x', 'x', 'o', 'x'],
  ['x', 'x', 'x', 'o', 'x'],
  ['x', 'x', 'x', 'o', 'x'],
  ['x', 'x', 'x', 'o', 'x'],
  ['x', 'x', 'x', 'o', 'x']
]
*/

I think I understand why the first code block gives the desired result, but I can’t for the life of me work out what is going wrong in the second example.

I would really appreciate some clarification on what is going on here.

Cheers 🙂

Photoshop Javascript – Resize multiple layers

I have a script on Photoshop that allows me to resize a layer to the image bounds while maintaining the proportions.
The code is the seguent:

    var Document = app.activeDocument;
    var BND = app.activeDocument.activeLayer.bounds;
    var IHeight = (BND[3] - BND[1]);
    var IWidth = (BND[2] - BND[0]);
    if (IWidth >= IHeight) {
        Document.activeLayer.resize ((Document.width / IWidth * 100), (Document.width / IWidth * 100), AnchorPosition.MIDDLECENTER);
        }
    else {
        Document.activeLayer.resize ((Document.height / IHeight * 100), (Document.height / IHeight * 100), AnchorPosition.MIDDLECENTER);
        }

The problem is that it only resizes the active layer.
I’m trying to integrate the seguent piece of code that selects all the layers:

    var NAD = new ActionDescriptor ();
    var NAR = new ActionReference ();
    NAR.putEnumerated (charIDToTypeID ("Lyr "), charIDToTypeID ("Ordn"), charIDToTypeID ("Trgt"));
    NAD.putReference (charIDToTypeID ("null"), NAR);
    executeAction (stringIDToTypeID ("selectAllLayers"), NAD, DialogModes.NO);

What I want to do is resize all the layers together so that they can keep the same aspect ratio between each other, so i can’t resize with a loop or the proportions would be lost by transforming all layers to the same size as the canvas.
Do you have any ideas how this could be done?
I have already tried to replace activeLayer with layers or artLayers, but I get “Error 1302: No such element” and I don’t know how to address the problem.

Only display current y-value on ToolTip in chart.js

I am working on a developing a chart using Chart.js and I want to only display te y-axis value in the tool-tip. Currently it displays:

date
name_of_line: measurement

ex.
Jan 1, 2020, 8:00:00 AM
5th Percentile: 100 oz.

And this is what I want it to look like:
5th Percentile: 100 oz

Here is the code I have so far to format the y-axis tooltip:

callbacks: {
                    label: function(context) {
                        let label = context.dataset.label || '';

                        if (label) {
                            label += ': ';
                        }

                        if (context.parsed.y !== null) {
                            label += new Intl.NumberFormat('en-US').format(context.parsed.y);
                            label += ' oz';
                        }

                        return label;
                    }
}

Create Id with sequalize

i have a proyect with sequalize in my back, i have a model Dogs, that has id with dataTypes.UUID. I want to create my own ID autoincremet width concat string. example: 12345db, 12346db.

this is my code in the model

id:{
  type: DataTypes.UUID,
  defaultValue: DataTypes.UUIDV4,
  allowNull:false,
  primaryKey: true,
},

this is result in db
enter image description here

Change dropdown selected value in loop

I am looping through available appointments and trying to change the color of the selected value in the dropdown(more than 1 dropdown in the list). I can see the color is different for each value but when I select it changes it back to black.

    .appt-status select option[value="0"] {
        color: #3EA47B;
    }

    .appt-status option[value="1"] {
        color: #3EA47B
    }

    .appt-status option[value="2"] {
        color: #FF0000;
    }

    .appt-status option[value="3"] {
        color: #FFA927;
    }
<!-- begin snippet: js hide: false console: true babel: false -->

 <div class="appointmentList" data-bind="foreach: visibleAppointments">
      <select class="form-control appt-status" data-bind="value: confirmationStatus, event:{ change: $parent.statusChanged}" >
                    <option data-icon="" class="status-list" value="1" > Confirmed</option>
                    <option class="status-list" value="2" >Reschedule</option>
                    <option class="status-list" value="3" >Pending</option>
                    <option class="status-list" value="0" >Not opted-in</option>
                </select>
 </div>

How to fix net::ERR_ABORTED 404 (Not Found) when callink api route using next/link in NextJS

I have created an api route to download a CSV file and I am getting this error when using Next Link. I cannot just switch to because then my application will not build, so my hands are tied. The component is simple

const DownloadCsvPage = () => {
  return (
    <section className="w-full h-screen grid place-content-center">
      <Link href="/api/db-to-csv">
        <a className="px-20 py-9 border text-black no-underline">
          Download CSV
        </a>
      </Link>
    </section>
  );
};

I tried to follow this article https://www.loudnoises.us/solving-next-static-pages-js-404-not-found/ but setting href to current page path and as to the path of api route only appended the api routes url to the localhost but that did not trigger the download. Like

   <Link href="/download" as="/api/db-to-csv">
        <a className="px-20 py-9 border text-black no-underline">
          Download CSV
        </a>
      </Link>

After reading this solution https://exerror.com/js-file-gets-a-neterr_aborted-404-not-found/ i thought that moving the file I want to download to the public folder would do the job but it did not.
Thanks

JQuery select name array with unknown id

I have multiple inputs as an array like this:

<input name="data[extras][1][id]" value="1">
<input name="data[extras][1][netto]">
<input name="data[extras][1][tax]">
<input name="data[extras][1][brutto]">

<input name="data[extras][2][id]" value="2">
<input name="data[extras][2][netto]">
<input name="data[extras][2][tax]">
<input name="data[extras][2][brutto]">

i got all extras with:

let extras = $('input[name^=data\[extras\]]');

now i would like to iterate through all to create an array out of it but i need for the id for further actions (the 1 or the 2).

i would like to achive something like this:

let id = $('input[name^=data\[extras\]\[UNKNOWN ID\]\[id\]]').val();

i hope anybody can help me.

Greetings

H27 error thrown when sending response back to client

I think this is probably a fairly simple fix, even though it’s a lot of code…when the user starts loading into the app, it essentially sends a request to the server that calls a bunch of different APIs and sub functions, then returns some data queried from a Postgres table to the user. For some reason, About 40% of the time, I’m getting an H27 error thrown when the response is sent back to the user. The logs look like this:

2022-07-18T01:46:36.443368+00:00 app[web.1]: User is attempting to sign in
2022-07-18T01:46:36.443386+00:00 app[web.1]: Started processing
2022-07-18T01:46:36.883171+00:00 app[web.1]: Signing in from X,Y
2022-07-18T01:46:38.662059+00:00 app[web.1]: API Call 1,2,and 3
2022-07-18T01:46:40.416057+00:00 app[web.1]: API Call 4
2022-07-18T01:46:40.932732+00:00 app[web.1]: API Call 5
2022-07-18T01:46:40.949921+00:00 app[web.1]: API Call 6
2022-07-18T01:46:44.683997+00:00 app[web.1]: finished processing
2022-07-18T01:46:44.684014+00:00 app[web.1]: Sending 110 results back to the client
2022-07-18T01:46:44.694904+00:00 heroku[router]: sock=client at=warning code=H27 desc="Client Request Interrupted" method=POST path="/userLoadingInToApp" host=app-name.herokuapp.com request_id=11caaa97-4b27-431e-84bd-e8b82162877f fwd="xxx.xxx.xxx.xx" dyno=web.1 connect=0ms service=8343ms status=499 bytes= protocol=https

I print out ‘Sending x results back to the client’ RIGHT before sending the results back to the client, so because the H27 error is thrown after that, it only makes sense there is an error being thrown when trying to send response back to the client:

app.post('/userLoadingInToApp', async function (request, response) {
  let results = await start(request) // All the calculations, database queries, api calls, console.logging etc are done inside this container function.
  console.log(`Sending ${results.length} back to the client`)
  response.send(results)
})

Often, the response is returned fine to the client, so not sure what’s going on here…

Export an array containing mysql results to another javascript file

I making use of node.js + mysql in my app. I would like to export an array containing results/rows of an SQL select statement to another javascript file and display the values stored in the array.

stats.js

var phonenum='0718900000'
var sql='SELECT name,surname,age from Tbluser WHERE number=?;'
conn.query(sql,[phonenum],function(err,results){
                      if (err){
                        throw err;
                      };
                      /*if (results==0)
                      {
                        let dealersMessage="❌ User not found"
                      }*/
                      
              console.log(results)      
             var datastatagentStore=[];
             results.forEach(item =>{
                 module.exports=datastatagentStore.push({
                        name:item.name,
                        surname:item.surname,
                        age:item.age,
                      })
                    }) 

app.js

 var{datastatagentStore}=require('../functions/stats.js')

 console.log('User details '+datastatagentStore);