Skip to main content

Posts

Showing posts from June, 2023

How can I detect when the line has crossed both sides of my curve?

Is there a way of detecting when the line (drawn by the mouse) has interseted both sides of the curve? The aim of my game is for the user to successfully cut the object using the mouse.[ ] let level4; window.onload = function() { let gameConfig = { transparent: true, type: Phaser.AUTO, scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH, parent: "thegame", width: 600, height: 700 }, scene: scene4, physics: { default: "matter", matter: { gravity: { y: 0 }, debug: true, } } } level4 = new Phaser.Game(gameConfig); window.focus(); } let levelText; class scene4 extends Phaser.Scene{ constructor(){ super(); } create(){ const graphics = this.add.graphics(); const path = new Phaser.Cur...

Fastest way to find the size of the union of two lists/sets? Coding Efficiency

I am conducting research on the relationships between different communities on Reddit. As part of my data research I have about 49,000 CSV's for sub I scraped and of all the posts I could get I got each commentator and thier total karma and number of comments (see pic for format) Each CSV contains all the commentors I have collected for that individual sub. I want to take each sub and then compare it to another sub and identify how many users they have in common. I dont need a list of what users they are just the amount the two have in common. I also want to set a karma threshold for the code I currently have it is set to more than 30 karma. For the code I have I prepare two lists of users who are over the threshold then I convert both those lists to sets and then "&" them together. Here is my code:    Since I am re-reading the same CSVs over and over again to compare to each other can I prepare them to make this more efficient, sort user names alphabetically? I p...

sequelise with postgreSQL: column doesnt exist

i am trying to make a small webservice with nodejs, express, pogreSQL database using sequelise. Created the database using this in psql CREATE TABLE Contacts ( id SERIAL PRIMARY KEY, phoneNumber bigint, email VARCHAR(255), linkedId INTEGER, linkPrecedence VARCHAR(20), createdAt TIMESTAMPTZ DEFAULT NOW(), updatedAt TIMESTAMPTZ DEFAULT NOW(), deletedAt TIMESTAMPTZ, FOREIGN KEY (linkedId) REFERENCES Contacts (id) ); Defined the contact model in contacts.js as const { DataTypes } = require("sequelize"); const sequelize = require("./database"); // Define the Contact model const contacts = sequelize.define( "contacts", { id: { type: DataTypes.INTEGER, autoIncrement: true, allowNull: false, primaryKey: true, }, phoneNumber: { type: DataTypes.BIGINT, allowNull: true, }, email: { type: DataTypes.STRING, allowNull: true, }, linkedId: { type...

I wrote swiper but when the screen is zoomed behaves terribly how can I fix it?

I zoom in on the whole page 50% 60% ... 100% 110% 120% .. 200%, and the image on each slide is twitching. https://codesandbox.io/s/great-monad-m44qcm?file=/index.html - code https://m44qcm.csb.app/ - demo How can i resolve this problem? I would be grateful if you send me the code of a working sweeper without a bug. Via Active questions tagged javascript - Stack Overflow https://ift.tt/ICeyAG7

How to check if a firebase timestamp is greater than current date

I need to compare a timestamp field with the current date in javascript. I tryed like this: let myDocs = []; await getDocs( collection( database, 'myCollection' ) ).then( ( documents ) => { documents.docs.forEach( ( document ) => { if(document.data().createdAt < new Date() ){ myDocs.push({ id:document.id, ...document.data() }); } }); }); Via Active questions tagged javascript - Stack Overflow https://ift.tt/ZfglBbw

Executing Javascript in Python [closed]

I have created a javascript function which I would like to execute in Python using the 'Javascript' import. The javascript function currently takes data from a HTML form and posts it within SQL Server. For further background information please visit this website . I have devised the following code already, but this doesn't as yet work as I intend. I would like to insert data into the Javascript function by calling the function within Python. The end result is to be executing and inserting data using Python with links to Javascript. from javascript import require data.executeQuery = require("test.js") data.executeQuery(This is a test, another test, another another test) Via Active questions tagged javascript - Stack Overflow https://ift.tt/ZfglBbw

Getting data via Tradingview chart

I'm trying to import data with selenium through trading view, but the table that appears in black does not appear in the HTML source code. I have searched with the texts in the table and cannot be found. It's probably like it's printed on the chart in image format, but when I look at it with a bookmark, it shows the whole chart. I couldn't find the Tag of this table. Any ideas on how I can get this table? enter image description here I couldn't find an answer to my question and I decided to write it here. I think the answers will come. Via Active questions tagged javascript - Stack Overflow https://ift.tt/ZfglBbw

how to remove a ul li by id after a ajax call to delete a MySQL row? not sure where in the i put (#liid).remove with jquery

I have a app that shows list of income items where each item is inside a li with a id= "number,item description and little trash icon inside the li. so far i have a code that calls a ajax when the user clicks the trash icon that removes the mysql row using a php script called by ajax, however i am not able to remove the li with a unique id without refreshing the page when i click on trash icon this is a piece of the code that i have so far <ul> <?php $sqlinc = "SELECT * FROM transactions WHERE username = '$username' AND transaction = 'income'"; $resultinc = mysqli_query($conn, $sqlinc); if (mysqli_num_rows($resultinc) > 0) { // output data of each row while($rowinc = mysqli_fetch_assoc($resultinc)) { echo '<li class="delli" id="'.$rowinc['id'].'"> <button id="" class="fl delbutton" onclick="">'. $rowinc['memo'].'</button...

Form submits instead of displaying error when button is clicked

I have made a form as index.html. I have a from validation using JavaScript. When the submit button is clicked it must open another html page(detail.html). When I supply wrong data, it must prevent the opening of detail.html page and display the error messages but neither of them happens . here is the code <form action="/detail" method="POST" role="form" name="index" onsubmit="return validateForm()" enctype="application/x-www-form-urlencoded"> <label for="name">Name</label> <input type="text" name="name" placeholder="Enter your name" required/> <span class="formerror"></span> <br /> <label for="phone_number">Mobile:</label> <input type="number" name="phone_number" placeholder="enter your mobile number" required > <span class="formerror"...

The code block below execute before my async await finishes

const getGroup = async (req, res) => { const { id } = req.params try { const group = await Group.findOne({ _id: id }); const groupNotesPromise = await group.group_notes.map( async (fileId) => { const file = await File.findById(fileId) return file; }) const groupNotes = await groupNotesPromise.map( async (notePromise) => { await notePromise.then(res => console.log(res)) }) console.log(groupNotes) } catch (error) { console.log(err.message); res.status(400).json({ err: err.message }); } } Hello guys, I have a function above, this is retrieving data from MongoDB. However, I would like to know why would my console.log(groupNotes) be printed before the execution of the groupNotesPromise.map above, as it has an await in the function. Below is the console.log(groupNotes) and console.log(res) from the code above [ Promise { <pending> }, Promise { <pending> } ] { _id: new ObjectId("6496c645bf2bb...

Loading nodes CSV to AGE with provided IDs returns "label_id must be 1 ... 65535"

I have a csv file that is not formatted in the correct way for AGE to load. I was on the task to transform it into a new one so that AGE could read it and create nodes, like it is specified in the documentation . For that, I created a python script that creates a new file, connects to postgres, and performs the queries. I though this could be useful since if someone had csv files and wanted to create nodes and edges and send it to AGE, but it was not in the specified format, this could be used to quickly solve the problem. Here is the old csv file (ProductsData.csv), it contains the data of products that have been purchased by other users (identified by their user_id ), the store where the product was purchased from (identified by their store_id ), and also the product_id , which is the id of the node: product_name,price,description,store_id,user_id,product_id iPhone 12,999,"Apple iPhone 12 - 64GB, Space Gray",1234,1001,123 Samsung Galaxy S21,899,"Samsung Galaxy S21 -...

How to add and multiply arguments? [closed]

I'm trying to make it so it will add or multiply based on if the result is over or under 1000. Sorry if my coding is atrocious. I'm still very new to this. def multi_sol(*num): product1 = 1 for i in num: if product1 <= 1000: product1 *= i return product1 else: for i in num: if product >= 1000: product1 += i return product1 result = multi_sol(20, 50) print("The result is", result) source https://stackoverflow.com/questions/76551947/how-to-add-and-multiply-arguments

How to use YAML to create a common node between two functions in Apache Age?

have two Python functions that each create a Person node in an Apache Age graph. I want to create a common Person node between these two functions that has the same properties. I've been told that YAML can be used to define a common configuration file that can be included in both functions to create or update the common Person node. My question is: How can I use YAML to define a common configuration file that can be used to create or update a common Person node between my two functions in Apache Age? Specifically, how do I load the YAML file into a Python dictionary, and how do I use the dictionary to set the properties of the Person node in my Apache Age graph? Here's an example YAML configuration file that defines a common Person node with a name property: Copy common_person: name: John Doe And here's an example function that creates or updates the Person node in Apache Age using the common_config dictionary: from age import Graph def update_person_node(common_config...

Is there any way to make an API within the same URL of React.js application just like Next.js?

In Next.js, I can access my application on localhost:3000 , and access to my API from localhost:3000/api/hello . Is there any way to do this by using React.js and some other framework like Express.js? What is the solution if I don't want to use Next.js? Both on development and production. EDIT: In production: I just deployed my express.js app to my shared hosting using app.listen() and it works fine because in production we don't or we shouldn't specify the port as I know. So there's no need to worry about ports being different just because they are in development. In develoment: I haven't tried anything yet but as jcubic mentioned maybe we need a proxy. Via Active questions tagged javascript - Stack Overflow https://ift.tt/qGvtTKg

Multiline named match with JavaScript regex not matching regex101

I'm trying to create a named match regex expression in JavaScript which captures build information from a multiline string. It tests fine in regex101 but fails to match correctly in JavaScript in a single pass of exec. When I try the the following regex in JavaScript all that is matched is the first match, i.e. . Everything else shows up as undefined . When I test the following in regex101.com /(BuildTimestamp:)(?<timestamp>.*)|(VersionCode:)(?<major>.*)|(VersionName:)(?<minor>.*)/gm BuildTimestamp:30-May-2023 14:25\r\n VersionCode:6\r\n VersionName:.0.5\r\n I get the following matches: timestamp: 30-May-2023 14:25 major: 6 minor: .0.5 In JavaScript I'm doing the following: const regex = /(BuildTimestamp:)(?<timestamp>.*)|(VersionCode:)(?<major>.*)|(VersionName:)(?<minor>.*)/gm; const match = regex.exec(contents); If I put the exec in a loop I'm able to capture each named match in turn when exec is called. I'm hoping that ...

Can't get preview image from video after uploading file

I'm used React TS but i don't know how i can get preview images after i uploaded video in input type file I know for uploaded images we can use filereader api but how we can implement this for video I have input type file and when i uploaded video file i need to get some images(frames) from this video ( for example on first second, 5sec and 25 sec) I did not found decisions for this. Can some get example or send link for this case please? I know for uploaded images we can use filereader api but how we can implement this for video I know for uploaded images we can use filereader api but how we can implement this for video Via Active questions tagged javascript - Stack Overflow https://ift.tt/thJNZAr

Update the youtube video's title in a popup window of my chrome extension

Every time I switch videos on youtube, the title doesn't change in my popup window. I have to manually refresh the page for the title to change. Which script should take care of doing this ? Any help is really appreciated. I'm using javascript for the first time. <!-- popup.html --> <!DOCTYPE html> <html> <head> <title>YouTube Song Matcher Popup</title> <link rel="stylesheet" type="text/css" href="styles.css"> <script src="popup.js"></script> </head> <body> <h1>YouTube Song Matcher</h1> <div id="songInfo"> <h2>Currently Playing:</h2> <p id="videoTitle"></p> </div> <div id="matchingSongs"> <h2>Matching Songs:</h2> <ul id="songList"></ul> </div> </body> </html> // Popup script (popup.js) // Retrieve the stored video titl...

My AJAX request is not retrieving the value from my select element in my form

I tried to retrieve my select html element like this because i need the owner_id from people : // Call Store Method $("body").on("submit", "form", function (e) { e.preventDefault(); if ($(this).hasClass("update")) { return update($(this)); } return store($(this)); }); // Store Method function store($form) { let data = { name: $form.find('input[name="name"]').val(), chip_number: $form.find('input[name="chip_number"]').val(), sexe: $form.find('input[name="sexe"]').val(), is_sterilize: $form.find('input[name="is_sterilize"]').val(), birthday: $form.find('input[name="birthday"]').val(), owner_id: $form.find('select[name="owner_id"]').val(), }; $.post("/animals", { data: data }) .done(function (result) { ...

React native testing library how to test async function?

Im trying to test when a user clicks a button and see if the function assign to that button is called. Im having problems because the function is an async function. Is there something wrong with the way Im testing it? Function I want to test const handlerFunction = useCallback(async () => { await Storage.deleteKyes()l A.reset(); navigate("Screen"); }, [navigate]); return ( <Button testID="btnChangeUser1" data-testid="btnChangeUser1" onPress={handlerFunction} title={ChangeUser} titleStyle={[t.fontSansSemiBold]} /> ) Testing method describe("method should be called", () => { it("Should activate when user press button ", async () => { const handlerFunction = jest.fn(); const { getByText } = render(<ReactComponent />); const element = getByText("ChangeUser"); fireEvent.press(element); await waitFor(asyn...

Strip function not working in a list in python

I'd like to remove white spaces before & after each word in a list with open(r"C:\filelocation") as f: lines = f.readlines() for i in lines: i = i.strip() i= i.split(",") When I print my list, I get the following ['46', 'Celsius '] ['42', ' Celsius '] ['93', ' Fahrenheit '] I tried i = i.strip() & it doesn't work for my list. source https://stackoverflow.com/questions/76503747/strip-function-not-working-in-a-list-in-python

Expression in Entity Framework?

The Entity Framework does not support the Expression.Invoke operator. You receive the following exception when trying to use it: "The LINQ expression node type 'Invoke' is not supported in LINQ to Entities. Has anyone got a workaround for this missing functionality? I would like to use the PredicateBuilder detailed here in an Entity Framework context. Via Active questions tagged javascript - Stack Overflow https://ift.tt/qSaXZ6D

how to convert two/there column images to text with ( tesseract.js ocr)?

I am working on a react.js project, I have almost done but my problem is if I want to convert two/three column images to text by Tesseract (OCR) does not convert as I want. because two columns' text is mixed. no separately convert by column. can possibel to solve this problem anyway? enter image description here import React, { useState, useEffect } from "react"; import Tesseract from "tesseract.js"; import ClipboardJS from "clipboard"; import Select from "react-select"; const languageOptions = [ { value: "afr", label: "Afrikaans" }, { value: "amh", label: "Amharic" }, { value: "ara", label: "Arabic" }, { value: "asm", label: "Assamese" }, { value: "aze", label: "Azerbaijani" }, { value: "aze_cyrl", label: "Azerbaijani - Cyrillic" }, { value: "bel", label: "Belarusian" }, { value: ...

autopytoexe doesn't stop compiling

I made an application on Windows. I had previously created the interface using PyQt5, and it worked fine with autopytoexe. However, when I rebuilt the application with Kivy and clicked the "convert .py to .exe" button, I encountered a continuous stream of trace in the Output section for minutes. I also tried building it with PyInstaller, but it didn't work at all. If anyone has any suggestions or knows the solution, I would greatly appreciate it. Here is a recurring snippet from the log: [TRACE ] [determine_parent Package('kivy', 'C]\\Users\\mrakd\\Desktop\\Depository\ \python_projects\\text_snap\\venv\\lib\\site-packages\\kivy\\__init__.py', ['C:\\Us ers\\mrakd\\Desktop\\Depository\\python_projects\\text_snap\\venv\\lib\\site-packag es\\kivy']) [TRACE ] [determine_parent -> Package('kivy', 'C]\\Users\\mrakd\\Desktop\\Deposito ry\\python_projects\\text_snap\\venv\\lib\\site-packages\\kivy\\__init__.py', ['C:\ \Users\\mrakd\\D...

Open square bracket on line 4 is apparently unclosed even though there is a closed square bracket on line 24. Python [closed]

import random def ask_riddle(): riddles = [ { "question": "I speak without a mouth and hear without ears. I have no body, but I come alive with wind. What am I?", "answer": "echo" }, { "question": "I am taken from a mine, and shut up in a wooden case, from which I am never released, and yet I am used by almost every person. What am I?", "answer": "pencil lead" }, { "question": "The more you take, the more you leave behind. What am I?", "answer": "footsteps" } { "question": "What has a neck but no head?", "answer": "a bottle" } { "question": "Tread on the living, they make not a mumble, tread on the dead, they mutter and grumble" ...

Pyinstaller and qpageview

I have a PyQt5 project where I am using qpageview . I am working on Ubuntu Linux and I am trying to run PyInstaller to make a single executable file, for convenience for me. The application works fine if I run it from a virtual environment, or with all of the Python modules installed locally to my machine (no virtual environment). It has a problem, however, if I run the executable produced by the command pyinstaller -F src/main.py , the executable dist/main , it runs without any errors, but the actual Page View is just blank, as though there is no PDF. I have made an simple example application that experiences this phenomenon here (my actual app is much larger than this and has multiple files): from PyQt5.QtWidgets import QApplication import qpageview app = QApplication([]) v = qpageview.View() v.resize(900, 500) v.show() v.loadPdf("pyqt.pdf") app.exec() This assumes there is a PDF at the current working directory called "pyqt5.pdf". Does anyone know how to f...

Calculating a shadow length and angle based on the X/Y offsets

I am working on parsing data from file generated by a program, it can apply a shadow to text. In the UI you simply set an angle, length, and radius With those values shown in the screenshot, that data is saved like this inside of an XML node 10|{1.41421356237309, -1.4142135623731} The format is: radius|{offsetX, offsetY} I'd like to calculate these values back into the angle and length so I can return them in my parser. Looking around online I have only found the opposite: a way to calculate those offsets from the angle and length. let length = 2; let angle = 135; let shadowX = Math.sin(angle * (Math.PI / 180)) * length; let shadowY = Math.cos(angle * (Math.PI / 180)) * length; console.log(shadowX, shadowY); //1.4142135623730951 -1.414213562373095 This is where I wish I'd paid more attention in my algebra classes. I have no idea how to proceed here to calculate the values I want. I need to be able to input those X/Y offset values and get the angle and length returned. ...

Is there a way in Py-Script to run the input() function?

When I run the input function inside the pyscript tags like this: <py-script> user_input = input("what is your name") print(user_input) </py-script> it will ask the question before the loading screen closes, and the loading screen won't even close until the prompt is answered. I have tried to use promises in javascript, a text input, and a button to replace the input function in python. However, Py-Script doesn't wait until the promise is resolved and just immediately prints out None. it is almost like py-script is ignoring the wait even though it seems like the promise is still running in the background (i used console.log() to test for that). And yes, i have already tried to use skulpt and flask and ajax requests. Either they don't work, or they ask the question too early. I just want a way to run python code (with input() functions) in the browser, so if anyone knows any alternatives to py-script, it would be greatly appreciated. Here i...

Behavior of this in global and function scope - Also inside IIFE [duplicate]

I saw this code example online and when I run it it logs nothing on the console. I was expecting it to log "User Name" but its logs nothing. why is that so? Why "this" is not pointing to a newly created object? how JS determines the reference of this. What will be the behavior if I change normal function to arrow function and also if I put comple function createUser() { // create an object and return from function return { name: "User Name", userRef: this, }; } // newly create object assigned to user variable var user = createUser(); console.info(user.userRef.name); Via Active questions tagged javascript - Stack Overflow https://ift.tt/REGDlQj

how can i cancel the drag if the element is not over a specific element (placeholder) vuedraggable

Inside each item I created a placeholder where I want the element to only be dropped if the mouse is over the placeholder Tried to check on 'move' but once found the element the check stops working Tried to check on 'move' but once found the element the check stops working move(evt) { let component = evt.relatedContext.component; if (evt) { let placeholder = evt.originalEvent.target.getAttribute("data-placeholder"); console.log(placeholder); if (placeholder === null) { console.log("Não dropar"); return false; } let groups = component.componentData.groups; let draggedGroup = evt.draggedContext.element.group; if (!groups.includes(draggedGroup)) { console.log("Não Pode"); return false; } } else { return false; } }, This approach didn't work Via Active questions tagged javas...

Instagram post analysis with machine learning

For user preferences analysis in urban green spaces, i want to Instagram post analysis with machine learning, explain about phases, process and how do it completely! I tried to find Instagram scrapers and related Python libraries, but I don't know how start and continue! source https://stackoverflow.com/questions/76468005/instagram-post-analysis-with-machine-learning

How to make a single chrome extension or a javascript file run at every page of a website?

For context, I am trying to build a chrome extension for Codeforces.com which automatically enters my login credentials and logs me in and then drops me of at whatever subsection I have selected (like contests, home, profile, etc.). I have currently hacked up a solution with a seperate js file which sends me to the contests page if go to the Profile page( where I land by default after login). Once I get redirected once I dont want to get redirected again if I try to visit some other site. I want to find a way to make a js file run for every codeforces.com subpage and conditionally exectue tasks based on what subpage I am on. Any other solutions to my above problem will also help. Thank you. Json file { "name": "CodeforcesAutologger", "description": "Automatically logs into Codeforces account", "author": "A", "version": "1.0", "manifest_version": 2, "browser_action...

Attaching an event listener to all possible text fields

I am developing a chrome extension. How can I efficiently attach an event listener to all text fields, including input type text, textarea, content editable, even for dynamically added fields and fields within iframes? Is it possible to limit the attachment only to visible or active elements instead of searching all fields at once? Currently, I am using the following code, but I'm looking for a more optimised solution: function getNodes(selectors, callback) { const nodeList = document.querySelectorAll(selectors); const nodes = Array.from(nodeList); nodes.forEach(node => callback && callback(node)); const mutationObserver = new MutationObserver(() => { const newNodes = Array.from(document.querySelectorAll(selectors)); const addedNodes = newNodes.filter(node => !nodes.includes(node)); addedNodes.forEach(node => nodes.push(node) && callback && callback(node)); }); mutationObserver.observe(document.bo...

when open dropdown, other drop down does not close React JS

I have created a dropdown container of my own. the dropdown works well - when I click it it opens, if I click again it closes, and if I click outside of a dropdown container it also closes the drop down . yet, I have an issue - when I open a dropdown, it does not close the other drop downs I opened. if I click outside of the drop downs - all the drop downs are closes. I am not sure what to do. this is my logic code: const [showState, setShowState] = useState<boolean>(false); const dropdownRef = useRef<HTMLDivElement>(null); useEffect(() => { const $dropdown = dropdownRef.current; if (showState && $dropdown) { const handleClickOutside = (event: MouseEvent) => { if ($dropdown !== event.target && !$dropdown.contains(event.target as HTMLElement)) { setShowState(() => false); props.onToggle?.(false); } }; document.addEventListener('click', handleClickOutside); return...