My Frontend wont connect to my node.js websocket

My Frontend wont connnect to my node.js websocket server, when i want to run it on another port than port 80. I cant run it on port 80 because my apache is already on port 80. Im currently trying it on port 39100 it shouldnt be a problem with the firewall.

My node.js websocket file runs on port 39100:
it runs on port 39100

In my node.js websocket server:

    const wss = new WebSocketServer.Server({ port: 39100})

My Frontend file which trys to connect to this port

In my Frontend File:

    const ws = new WebSocket("ws://flagduel.com:39100"); 

I tried it with apache stopped and port 80 in my server.js and “ws://flagduel.com” in my Frontend file which worked perfectly fine

Detect changes to class instance (using proxies)

I want to detect changes to arbitrary objects, such that I can react to them. I have the ability to intercept their creation process, so essentially the boilerplate I have is something like this:

function withChangeDetector(factory) {
    const obj = factory();
    return attachChangeListener(obj, () => console.log("Change occurred");
}

const myObject = withChangeDetector(() => new MyObject());
doSomethingThatMayChangeMyObject(myObject);
// if ^ changes myObject at any point in the future, then we should see the "Change occurred" log line

The constraints that I have are:

  1. I do not control the factory method, i.e. it can create any arbitrary object.
  2. I do not control the doSomethingThatMayChangeMyObject – i.e. anything may happen here.
  3. I DO control the wihChangeDetector/attachChangeListener functions.
  4. I can’t use polling.

Now my first instinct is to use a proxy. Simplified, it would be something like this:

function attachChangeListener(obj, onChange) {
    // I'm ignoring nesting here, that's solvable and out of scope for this question. 
    return new Proxy(obj, {
        set: (target, key, val) => {
            const res = Reflect.set(target, key, val);
            onChange();
            return res;
        }
    });
}

Now this works great for external changes to an object, but unfortunately it doesn’t quite work for internal changes in class instances. The problem is that if the caller defines their class like this:

class MyObject {
    prop;
    setProp(val) => this.prop = val;
}

then this will be bound to the unproxied instance, and therefore the proxy will not be called, and it won’t detect the change.

Hooking into get and doing some magic there is also not going to work, as this won’t detect async internal changes to MyObject (e.g. imagine setProp using a timeout).

Is there any way that I can detect changes to MyObject – using a proxy or otherwise – given the constraints I outlined above?

deletion of repeated STRING words

I have an output of words, but they are repeated, I need to exclude repetitions, so that the output would be the same format (STRING) that I entered.

For example:

i use, sequelize database and map:

const myreqdb = await Model.findall();
myreqdb.map((v) => {
console.log(v.status.split('_')[0]) 
console.log(v.status) 
//ok
//ok
//ok_false
//ok_true
//no
//no_false
//no_true
//db_true
//ff_false
console.log(v.status.split('_')[0]) 
//ok
//ok
//ok
//ok
//no
//no
//no
//db
//ff
})

I need an exit like this:

ok
false
db
ff

this is a quick example, the titles are quite different and there are more of them.

Updating the URLField of model with JavaScript

I have a page that displays some information about website admins such as username, skills, Instagram profile and bio. The admins are able to edit their profile information and the update is being saved using JavaScript fetch. When I click on the save button everything except the Instagram profile which is a URLField gets updated. For Instagram element to be updated I need to reload the page. How can I make it get updated without reloading the page? Everything is correct in the console log.

about.js:

document.addEventListener("DOMContentLoaded", function(){

    const button = document.querySelectorAll("#edit_profile")
    button.forEach(function(button){
        button.onclick = function(){
            const username = document.getElementById(`username_${memberID}`);
            const skills = document.getElementById(`skills_${memberID}`);
            const bio = document.getElementById(`bio_${memberID}`);
            var instagram = document.getElementById(`instagram_${memberID}`).href;

            let edit_username = document.createElement("textarea");
            edit_username.setAttribute("rows", "1");
            edit_username.innerHTML = username.innerHTML
            edit_username.id = `edit_username_${memberID}`;
            edit_username.className = `form-control username ${usernameID}`;
            
            let edit_skills = document.createElement("textarea");
            ...
            
            let edit_instagram = document.createElement("textarea");
            edit_instagram.setAttribute("rows","1");
            edit_instagram.innerHTML = instagram;
            edit_instagram.id = `edit_instagram_${memberID}`;
            edit_instagram.className = "form-control social-media";

            const saveButton = document.createElement("button");
            saveButton.innerHTML = "Save";
            saveButton.id = `saveButton_${memberID}`;
            saveButton.className = "btn btn-success col-3";
            saveButton.style.margin = "10px";
            
            document.getElementById(`edit_${memberID}`).append(edit_username);
            ...
            document.getElementById(`edit_${memberID}`).append(edit_instagram);
            document.getElementById(`edit_${memberID}`).append(saveButton);

            // When the save button is clicked
            saveButton.addEventListener("click", function(){
                edit_username = document.getElementById(`edit_username_${memberID}`);
                ...
                edit_instagram = document.getElementById(`edit_instagram_${memberID}`);
            
                fetch(`/edit_profile/${memberID}`,{
                    method: "POST",
                    body: JSON.stringify({
                        username: edit_username.value,
                        skills: edit_skills.value,
                        instagram: edit_instagram.value,
                        bio: edit_bio.value,
                    })
                })
                .then(response => response.json())
                .then(result => {
                    console.log(result);
                    if(result[`error`]){
                    cancel(memberID)
                    } 
                    else {
                        username.innerHTML = result.username;
                        secusername.innerHTML = result.username;
                        skills.innerHTML = result.skills;
                        instagram = result.instagram;
                        bio.innerHTML = result.bio;
                    }
                })
            })
        }
    });
})
  

about.html:

{% for member in team_members %}
      <div class="col" id="border">
<!--If user is admin, show edit button-->
        {% if user.is_superuser %}
        <div class="position-relative" id="edit_button_{{member.id}}" style="display: block;">
          <button class="btn btn-lg position-absolute top-0 end-0" id="edit_profile" data-id="{{member.id}}" data-username="{{member.username}}">
          <i class="fa fa-edit fa-solid" style="color: white; margin-right: 5px;"></i></button>
        </div>
        {% endif %}
        
        <!--Edit form-->
            <div class="form-group" id="edit_{{member.id}}">
            </div>
     
          <!--Display username,skills,socials and bio-->
            <div id="remove_{{member.id}}" style="display: block;">
              <h3 class="username" id="username_{{member.id}}">{{member.username}}</h3>
              <p class ="skills" id="skills_{{member.id}}">{{member.skills}}</p>
              <p><a class="social-media" href="{{member.instagram}}" id="instagram_{{member.id}}"><i class="fa-brands fa-instagram fa-solid" style="color: #e3c142; margin-right: 5px;"></i></a>
              <a class="social-media" href="{{member.itch_profile}}" id="itch_{{member.id}}"><i class="fa-brands fa-itch-io" style="color: #e3c142;"></i></a>
              <div class="bio">
                  <strong class="username" id="secusername_{{member.id}}"  style="font-size: large;">{{member.username}}, </strong><p id="bio_{{member.id}}">{{member.bio}}</p>
              </div>
            </div>
        </div>
      </div>
      {% endfor %}

views.py:

@csrf_exempt
def edit_profile(request, member_id):
    if request.method != "POST":
        return JsonResponse({"error": "POST request required."}, status=400)
    team_members = Team.objects.get(id = member_id)

    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)
    username = body['username']
    skills = body['skills']
    instagram = body['instagram']
    itch_profile = body['itch_profile']
    bio = body['bio']
    Team.objects.filter(id=member_id).update(username=f'{username}',skills=f'{skills}',instagram=f'{instagram}',itch_profile=f'{itch_profile}',bio=f'{bio}')
    return JsonResponse({"message": "Successful", "username": username, "skills": skills, "instagram":instagram, "itch_profile":itch_profile, "bio": bio}, status=200)

How to update the values of all custom element instances in Javascript?

I began to use Web Components in Javascript. I have a class called VariantSelects and I want each instance to have the same value. So whenever something changes in instance A, instance B should receive the same value. How do I do that?

I minimized my code for presentation purpose. The actual amount of functions is more complex.

<!-- instance A -->
<variant-selects></variant-selects>
<!-- instance B -->
<variant-selects></variant-selects>
class VariantSelects extends HTMLElement {
    constructor() {
        super();
        this.currentVariant = null;
        this.addEventListener('change', this.onVariantChange);
        this.init();
    }

    init() {
        // do stuff
    }

    onVariantChange() {
        // should be updated in all instances
        this.currentVariant = 123;
    }
}

customElements.define('variant-selects', VariantSelects);

Thanks in advance!

how to create openable accordion

I got problem with my accordion script. I,m trying to create accordion lokking like this in screen enter image description here

<div class="accordion-item">
            <div class="accordion-item_header">
                <h3>Experience</h3>
                <button class="accordion-btn">+</button>
            </div>
            <div class="accordion-item_content container">
               
            </div>
        </div>
var accordionItem = document.querySelectorAll('.accordion-item');
var accordionContent = document.querySelectorAll('.accordion-item_content');
var accordionButton = document.querySelectorAll('.accordion-btn');

for (i = 0; i < accordionButton.length; i++) {
    accordionButton[i].addEventListener('click', () => {
        accordionContent[i].classList.add('opnen')
    })
}

I want to open my content box after clicking only button in accordion header div. How to do it?

part of my div is out of mobile view in tailwindcss

I am using tailwindcss for responsive design with grid layout and set my child div to col-span-12 to use all of viewport in mobile display. But I face with issue that part of my div is outside the viewport and when I apply some padding I can see just right side padding.
my body overflow was set in hidden and every thing was set to mobile display.
x-overflow is hidden and
x-overflow is hidden and col-span-12

when I resize it

<div className="lg:col-span-4 bg-stone-200 flex flex-col py-5 rounded-md col-span-12 md:px-5 mx-5 ">
      <div className="info  border-b-2 border-black pb-6 mb-6 px-5 w-screen max-w-[100%] ">
        <h3>Order Summary</h3>
        <div className="flex justify-between">
          <h6 className=""> Total price</h6>
          <p className="">${totalPrice}</p>
        </div>
      </div>
      <div className="checkout lg:text-center">
        <button
          className="md:ml-7 uppercase font-semibold text-xs
           text-slate-900 bg-white rounded-full px-10 py-3 border
           border-slate-400 hover:border-black transition ease-linear duration-150 cursor-pointer"
        >
          Check out
        </button>
      </div>
    </div>

Plotting nodes in force-directed graph with the help of co=ordinates

“pos”: [
72.69264221191406,
101.9963302612305,
117.7442626953125
]

The above is the co-ordinates of a node. How can I create a node in d3 according to the given co-ordinates?
I’ve tried with co-ordinates which has pixel as unit of the co-ordinates but the above sample set does not contain any units as such.

The full code is below…

<!DOCTYPE html>
<meta charset="utf-8">
<style>
 .node {
   fill: blue;
   stroke: black;
   stroke-width: 2px;
  }

 .node.visited {
   fill: red;
 }

 .link {
   stroke-width: 2px;
 }
</style>

<body>
 <script src="https://d3js.org/d3.v3.min.js"></script>
 <script>
   var width = 640,
       height = 480;

   var links = [{
       source: 'Rohit',
       target: 'Deep'
     },
     {
       source: 'Deep',
       target: 'Deepa'
     },
     {
       source: 'Deepa',
       target: 'Rohit'
     },
   ];
   var nodes = {};

   //adding to nodes
   links.forEach(function(link) {
     link.source = nodes[link.source] ||
       (nodes[link.source] = {
         name: link.source
       });

     link.target = nodes[link.target] ||
       (nodes[link.target] = {
         name: link.target
       });
   });

   //adding svg to body

   var svg = d3.select('body').append('svg')
     .attr('width', width)
     .attr('height', height);

   var defs = svg.append('defs');

   var gradient = defs
     .append('linearGradient')
     .attr('id', 'svgGradient')
     .attr('x1', '0%')
     .attr('x2', '10%')
     .attr('y1', '0%')
     .attr('y2', '10%');

   gradient
     .append('stop')
     .attr('class', 'start')
     .attr('offset', '0%')
     .attr('start-color', 'red')
     .attr('start-opacity', 1);

   gradient
     .append('stop')
     .attr('class', 'end')
     .attr('offset', '100%')
     .attr('stop-color', 'blue')
     .attr('stop-opacity', 1);

   var force = d3.layout.force()
     .size([width, height])
     .nodes(d3.values(nodes))
     .links(links)
     .on("tick", tick)
     .linkDistance(300)
     .start();

   var link = svg.selectAll('.link')
     .data(links)
     .enter().append('line')
     .attr('class', 'link')
     .attr('stroke', 'url(#svgGradient)');

   var node = svg.selectAll('.node')
     .data(force.nodes())
     .enter().append('circle')
     .attr('class', 'node')
     .on("click", clicked)
     .attr('r', width * 0.03);

   function clicked(event, d) {
     if (event.defaultPrevented) return; // dragged

     d3.select(this).transition()
       .style("fill", "black")
       .attr("r", width * 0.2)
       .transition()
       .attr("r", width * 0.03)
       .transition()
       .style("fill", "blue")
       //.attr("fill", d3.schemeCategory10[d.index % 10]);
   }


   //define the tick func.
   function tick(e) {
     node
       .attr('cx', function(d) {
         return d.x;
       })
       .attr('cy', function(d) {
         return d.y;
       })
       .call(force.drag);

     link
       .attr('x1', function(d) {
         return d.source.x;
       })
       .attr('y1', function(d) {
         return d.source.y;
       })
       .attr('x2', function(d) {
         return d.target.x;
       })
       .attr('y2', function(d) {
         return d.target.y;
       })

   }
    </script>
  </body>
</html>

Any changes to the above code snippet is acceptable. Please help me in finding the proper solution

Simple replacing of text in a website requires refresh to work

I have the following code and I want to replace some text/behavior of the page:

$(“a[href=’/my_tasks/incomplete’]”).attr(“href”, “/my_tasks/completed”);
$(‘input[name=commit].btn.btn-primary’).val(‘Save’);
$(‘input[name=save_and_next].btn.btn-primary’).val(‘New Task’);
$(‘label[for=”task_judgments_attributes_0_answer_id”]’).text(‘Relevence’);
$(‘label[for=”task_comment”]’).text(‘Feedback’);

Very simply the above replaces some fields and text on the code to redirect to different pages and change some text boxes. However because all the clicks are driven by type=”button” buttons, only the first page load works properly.

After the first load, everything is back to normal and I have to force re-fresh the page.

Any ideas to make it work all the time?

What is the point of Dependency Injection in Typescript? [closed]

Point of clarification: I am NOT asking, “Why use the Interface Segregation Principle”, or “Why use interfaces to inject services to classes”.


I AM asking, “Specifically in Typescript, what are the benefits to using a Dependency Injection framework, OTHER THAN code cleanliness?”


Whether its manual constructor injection, manual parameter injection or manual setter injection, other than making it less work to instantiate a class (new keyword), what benefits exist to a Typescript codebase? It seems to me I could just use constructor injection and be ok with the messy instantiation of new classes, rather than taking on a DI framework.

I started to use Inversify and unless I am wrong about the pattern of how to use it, then I am making a new container for every set of classes in the same scope as the functionality being run. Right?

The only way I can see that this would be beneficial is if you create 1 container for the whole app and it manages the lifecycle of them all at once… but Javascript already does this naturally for me based on closures and lexical scope. Also, getting access to this single container would be hard (or easy as a default export of another file).

Also, it doesn’t help me when making new services to replace class-level service variables because I can just swap the import out for one with a new service and the code will work just fine (as long as the interface contracts are met).

So…

Why do it? There has to be SOME benefit other than “Well… strongly types languages use it!”

TypeError: contract.methods.balanceOf is not a function

I am trying to get the balance of a specific NFT of a wallet but i am getting the error “TypeError: contract.methods.balanceOf is not a function”

This is the code i am using to do it

        const main = async () => {
            await connect()
            contract = new web3.eth.Contract(ABI, ADDRESS)

            const balance = Number(await contract.methods.balanceOf(account).call())
        }

What am i doing wrong?

I have looked into the documentation but i can’t find why it’s an issue

How can I display a random word from array, and display it letter by letter in the site element?

I’m trying to write a code that, when I type a word in the search field, it display the word from the array, but the word that have been displayed must be random word from array. When word displayed, I want to display it letter by letter in the screen. So I’m confusing, so I appreciate someone can help me do it. Thanks.
Here’s the code I’ve write, P.S. The input field is the variable->text that is element from the html.

let words = ['Përshëndetje', 'Tung', 'Tungjatjeta'
            ,'Përshëndetje', 'Tung', 'Tungjatjeta']; 
let str = "";
i = 0;
    
function genetic() { 
    text.addEventListener("change", (value)=> { 
        this.value = text.value;  
        // console.log('hello' + ' ' + this.val); //TESTING
        let generate = Math.floor(Math.random() * words.length);
        words.forEach((element) => { 
            if(this.value === element) { 
                word.textContent += words[generate].charAt(i);
                console.log(word.textContent);
                i++; 
           }
        });
        window.setTimeout(genetic, 100);
    });
}   genetic();
    

I’ve tried many alternatives, but there’s no result.

react js count value is lost

I am new to react js. I have a form with a checkbox.
In the checkbox value, I have a dynamic user id and product quantity. I have also store(useState) and qty properties to track the count values. I have a count handler as well and it works nicely. It can increment the qty of product and I can see it in my UI.
However, when I submit the form, the value from the checkbox is not as expected. The value I have returned is userid:product quantity. However once the form is submitted after incrementing the qty count by clicking the anchor tag, the response shows quantity always 1 even if the qty is greater than 1.

Lets say I have incremented index 0 product qty to 3, so I expect my response as
120343:3, the first part is {user.id} and second part is {user.qty}, however respone should shows 120343:1, which means qty is again rested back to 1. I am not sure why this is happening.

my state is like this

const[userData, setuserData] = useState([
{
id:120343,
name:’tofu’,
qty:1
},
id:340343,
name:’jam’,
qty:1
},
])

Here is the form and checkbox with dynamic value which is looped

<form onSubmit={handleForm}>

{userData.map(user,index)
<div>
<label>
<input
    type="checkbox"
    id="userIdentity"
    value={`${user.id}:${user.qty}`}
/>
{extra.name}
<a href="#" onClick={()=>handleIncrement(index)}>Increment Qty</a>

<button >Submit Form</button>
</label>
</div>
}
</form>

I have increment logic like this and it works

const handleIncrement = (index) => {
    setuserData(userData => {
        const item = userData[index]
        if (item) {
            item.qty += 1;
        }

        return [...userData];
    });
}

and finally, handleForm with console.log the submitted data, which shows qty always event even if it is greater than 1.
Any help would be highly appreciated.