Skip to main content

Posts

Showing posts from November, 2023

Apify Flipkart scraper Not scrape data properly

I use apify (Flipkart scraper) website to scrape data from flipkart but scrape data only for mobile categories, i want to get all categories products details. If there is a solution let me know... Thanks I tried some meathod but it's not work Via Active questions tagged javascript - Stack Overflow https://ift.tt/gTKvAbZ

Sending an array from the javascript to the laravel controller

Im trying to send an array from my javascript to my laravel controller but when I dd() I get null. Javascript : $('#submmit').click(function() { $.ajax({ method: 'POST', url: '/Calendar/store', contentType: 'json', data: JSON.stringify(partconValues), success: function(response) { console.log(response); }, error: function(error) { console.error('Error sending partconValues to the controller:', error); } }); }) Controller : public function store(Request $request) { Log::info('Request data:', $request->all()); $partconValues = json_decode($request->getContent()); $process = \App\Models\Process::find($request->input('partcon_id')); $part = \App\Models\ProductPart::find($request->input('part_id')); ...

Does Javascript have a way to parse numeric strings accounting for different global character sets?

Is there a way to validate/parse strings into integers when the characters used may use numeral character sets other than the standard Western 0-9? Background: My Javascript application prompts users for integer input (their age), but some users answer using non-Western numerals due to their keyboard settings. Currently, those don't pass validation, but I'd like to accept and parse all valid integer responses, regardless of what numeral character set is used. Desired behavior: "12" => 12 // English/Western "১৬" => 16 // Assamese "२४" => 24 // Hindi Is there a way to do this consistently without hardcoding all possible numeral sets explicitly? Via Active questions tagged javascript - Stack Overflow https://ift.tt/euaPzdn

ExtJs - grid.column.Column - how to take it out and use it somewhere else

I need to extract these column lists from Ext.grid.column.Column together with the checkboxes and the entire mechanism for the button above the table. I would not like to create the entire mechanism from scratch, but just use the available option. Is it possible? This: Via Active questions tagged javascript - Stack Overflow https://ift.tt/MV1o0qt

Fiori Controller.js Changes not Reflecting without Modifying Component-Preload.js

I have a Fiori app that I need to customize in VS Code. The change is to be made in the Detail.controller.js file. I noticed that the changes I made in the Detail.controller.js file did not reflect until I made those exact changes in the Component-preload.js file. Interestingly, I haven't encountered a similar situation with View files. Can someone shed light on why this behavior seems specific to Controller files? Does this imply that for code changes in Controller files, updating only the Component-preload.js file is necessary? TIA, Ruzna Via Active questions tagged javascript - Stack Overflow https://ift.tt/MV1o0qt

fetch graphql query from external server

i'm trying to fetch some leetcode stats using leetcode's graphql schema. when i enter the query in the browser, it gives me a response, but it's not responding to me when i use axios. here's the query i enter in the browser: https://leetcode.com/graphql?query=query { questionSubmissionList( offset: 0, limit: 20, questionSlug: "two-sum" ) { lastKey hasNext submissions { id title titleSlug status statusDisplay lang langName runtime timestamp url isPending memory } } } and here's what i have in my code: let url = `https://leetcode.com/graphql`; const fetchSubmissionList = async (questionSlug) => { let query = ` query questionSubmissionList( offset: 0, limit: 20, questionSlug: $questionSlug ) { lastKey hasNext submissi...

415 (Unsupported Media Type) error in dot net core web API

I am using dot net core Web API. I have a controller HomeController.cs using Microsoft.AspNetCore.Mvc; using WebAPI.Models; namespace WebAPI.Controllers { [ApiController] [Route("[controller]")] public class HomeController : Controller { [HttpPost] public IActionResult Index(User user) { return Ok(user); } } } The model user is as follows namespace WebAPI.Models { public class User { public string username { get; set; } public string password { get; set; } } } When I run the following jquery code from the front end I get an error 415 (Unsupported Media Type) $.ajax({ type: "POST", url: "https://localhost:7137/Home", data: { username: "username" , password: "password"}, success: function(data){console.log(data)}, dataType: "application/json" }); I am not getting what mistake I am doing. Via Active questions ...

Form validation error message alert does not appear (JavaScript)

I have a form that, with JS, has an error message that is meant to appear when one or more of the fields in the form are left empty. However, when I click the submit button, nothing appears. HTML: <body> <script type=text/javascript src="script.js"></script> <h1>Organisation Score Calculator</h1> <!-- <h4>Input the name of the charity.</h4> <input type="text" id="nameOfOrganisation"> <h4>Which state/territory does this organisation service?</h4> <input type="text" id="state"> <h4>What is the ACNC listed size for this organisation?</h4> <input type="text" id="size"> <h4>What percentage of the organisation's total income is from government grants?</h4> <input type="text" id="governmentGrants"> <h4>How much net profit does the organisatio...

How to show a loading spinner while fetching and compiling a component framework (Astro Island) Vue and AstroJS

I have the following astro page: --- import BaseLayout from '../../layouts/BaseLayout.astro'; import ListadoProfesionales from "../../components/pages/ListadoProfesionales/ListadoProfesionales.vue"; --- <BaseLayout title="Listado de profesionales"> <main class="container py-6"> <ListadoProfesionales client:only="vue" /> </main> </BaseLayout> The framework component "ListadoProfesionales" is rendering only in the browser with VueJS. How can I show a Spinner (or a loading UI element) while AstroJS is fetching and rendering that component? Via Active questions tagged javascript - Stack Overflow https://ift.tt/FTd7cAS

How to divide column in dataframe by values in a dict according to some key?

I have a dataframe df with the columns delta and integer_id . I have a dict d that maps integer_id to some floating point value. I want to divide each row's delta in df by the corresponding value from d for the integer_id , and if the row's integer_id doesn't exist in the dict, leave delta unchanged. Here's an example: df = pd.DataFrame({ "integer_id": [1, 2, 3], "delta": [10, 20, 30] }) d = {1: 0.5, 3: 0.25} The result should be df = pd.DataFrame({ "integer_id": [1, 2, 3], "delta": [20, 20, 120] # note the middle element is unchanged }) I tried df["delta"] /= df.integer_id.map(d) , but this will return NaN for the second row because d doesn't have the corresponding key. But something like df["delta"] /= df.integer_id.map(lambda x: d.get(x, 1)) will get what I need, but I'm wondering what other approaches there are for this case? source https://stackoverflow.com/questions/7...

I'm having problems when sending User's Id's on a django model

I'm tryng to do a post method on projetos on my Vue Front-end but i keep getting the error message of "null value in column "professor_id" of relation "fabrica_projeto" violates not-null constraint" even though the request body is the same when i try to post on django-admin and it works there I'm kinda new to this whole coding world so sorry if my vocabulary is lacking On Vue/ my front-end enter image description here On Django-Admin(works) enter image description here enter image description here This is the model for Projeto enter image description here from django.db import models from usuario.models import Usuario from uploader.models import Image class Projeto(models.Model): nome = models.CharField(max_length=200) descricao = models.CharField(max_length=2500) data = models.DateTimeField(auto_now_add=True) professor = models.ForeignKey(Usuario, related_name='professor', on_delete=models.PROTECT) alunos = m...

How to make Input Checkbox checked by default [closed]

<div \*ngFor="let serviceName of selectedServices_user" class="left-align-label"\> <label style="text-align: left;"\> <input class="left-align-label" type="checkbox" checked="true"\[(ngModel)\]="selectedServices_user\[serviceName\]" \[style.margin-top.px\]="i === 0 ? 10 : 0" style="text-align: left;"\> </label\> This is my html, please help me select all the checkboxes by default? Tried everything from checked to checked="true" doesn't seem to work Via Active questions tagged javascript - Stack Overflow https://ift.tt/OTmRClD

Open url directly after scan with html5-qrcode (javascript)

I used the html5qrscan code from geeksforgeeks ( url ) After successfully scanning the QR code a message including the url of the QR code is shown, I would prefer to automatically get redirected to the url. I have a project with a due date in a couple of days, but I no idea how to solve this. Help is very much appreciated! I've tried to fix it, but I'm clueless and I give up. Org. codes from geeksforgeeks: <!-- Index.html file --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>QR Code Scanner / Reader </title> </head> <body> <div class="container"> <h1>Scan QR Codes</h1> <div class="section"> ...

Unable to get id value in vanilla JavaScript [closed]

I am trying to fetch data from Pixabay api using JavaScript. Currently, I am able to display the api data but I am trying to create a separate page for each image id dynamically. For example, if someone click on one image, it should redirect to a different page called photos.html/id/photoname. JavaScript Code let editorChoice = document.querySelector('.editorchoice') async function getImg(){ let imgData = await fetch('https://pixabay.com/api/?key=12345&editors_choice') let imgRaw = await imgData.json() console.log(imgRaw) let itemData = imgRaw.hits //To create <div class="row"> in each row dynamically for(let i = 0; i < itemData.length; i++) { //Declare item variable and store itemData since itemData has stored api details let item = itemData[i] //i stands for those id starts from 0 in the api. //It won't possible to display image if we don't add i let imgId = item.id let imgType = item.type l...

How to import a library only if it exists in Vite?

Let's say in my library I want to import an animation library only if the developer has installed it. Pseudo code as follows: let utility = null // If the library returns the library location as a string if (Boolean(require.resolve('animation-library'))) { import('animation-library').then(library => utility = library.helper) } Currently, on Vite (Rollup.js) you get a warning, as the import is analyzed on compilation. The above dynamic import cannot be analyzed by Vite. See https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations for supported dynamic import formats. If this is intended to be left as-is, you can use the /* @vite-ignore */ comment inside the import() call to suppress this warning. Via Active questions tagged javascript - Stack Overflow https://ift.tt/FfPtnER

How to remove an image with PyGame? [duplicate]

I want to remove an image but i don't know really how to do it. I think we have to create a function ? import pygame pygame.init() pygame.display.set_caption("Képomon") screen = pygame.display.set_mode((284*2,472*2)) BattleStartImage = pygame.image.load('assets/BattleStart.png') buttonRondAImage = pygame.image.load('assets/buttonRondA.png') class Button(): def __init__(self, x, y, image, scale): width = image.get_width() height = image.get_height() self.image = pygame.transform.scale(image, (int(width * scale), int(height * scale))) self.rect = self.image.get_rect() self.rect.topleft = (x,y) self.clicked = False def draw(self): action = False #get mouse position pos = pygame.mouse.get_pos() #check mouseover and clicked conditions if self.rect.collidepoint(pos): if pygame.mouse.get_pressed()[0]==1 and self.clicked == False: self.cl...

Tkinter layout doesn’t place buttons in the right place

I am trying to make an image viewer using Python Tkinter as a part of the course I am participating in and I am having some trouble with my code. My problem is in the positioning of the forward and the exit button in the first image, The picture explains this Look at the exit and forward(>>) button under the screen By the way, this problem is only appears in the first image but in the others, the positioning is perfect as shown in the picture the back(<<) and the forward and the exit buttons are in the correct position I have tried to read and debug the code multiple times, and I have even looked at the source code from the course, but I still can't seem to find the issue. Do you have any suggestions or recognize any bugs that I may have missed? Any help would be greatly appreciated. Thank you! Here is all code: #importing files from tkinter import * from PIL import ImageTk,Image #the start of the program root = Tk() root.title("Image Viewer") root....

How to properly declare optional dependencies both as extras and in dedicated groups in Poetry?

From Poetry documentation about the difference between groups and extras: Dependency groups, other than the implicit main group, must only contain dependencies you need in your development process. Installing them is only possible by using Poetry. To declare a set of dependencies, which add additional functionality to the project during runtime, use extras instead. Extras can be installed by the end user using pip. This perfectly makes sense and works fine most of the time. However, during development one usually wants to install all the extras dependencies in order to test all the functionalities of the package. However, extras are not installed by default contrary to groups. Moreover, the Poetry documentation states that: The dependencies specified for each extra must already be defined as project dependencies. Dependencies listed in dependency groups cannot be specified as extras. Thus, because it is not possible to define extras in a Poetry project that are defined in dep...

Where to find the code for ESRK1 and RSwM1 in the Julia library source code?

I'm trying to implement the SDE solver called ESRK1 and the adaptive stepsize algorithm called RSwM1 from Rackauckas & Nie (2017). I'm writing a python implementation, mainly to confirm to myself that I've understood the algorithm correctly. However, I'm running into a problem already at the implementation of ESRK1: When I test my implementation with shorter and shorter timesteps on a simple SDE describing geometric Brownian motion, the solution does not converge as dt becomes smaller, indicating that I have a mistake in my code. I believe this algorithm is implemented as part of the library DifferentialEquations.jl in Julia, so I thought perhaps I could find some help by looking at the Julia code. However, I have had some trouble locating the relevant code. If someone could point me to the implementation of ESRK1 and RSwM1 in the relevant Julia librar(y/ies) (or indeed any other readable and correct implementation) of these algorithms, I would be most grateful. ...

How to input Multiple Image for one output and fit ImageDataGenerator data Tensorflow

I am using ImageDataGenerator to load data. My code is below, When I try to fit, I'm getting error this error: ValueError: Failed to find data adapter that can handle input: (<class 'list'> containing values of types {"<class 'keras.src.preprocessing.image.DirectoryIterator'>"}), <class 'NoneType'> from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense # Loading Data train_a = ImageDataGenerator(rescale=1/255) train_a_gen = train_a.flow_from_directory(path+'/a/', target_size=(500, 500), batch_size=32, class_mode='binary') train_b = ImageDataGenerator(rescale=1/255) train_b_gen = train_b.flow_from_directory(path+'/b/', target_size=(500, 500), batch_size=32, class_mode='binary') # Layers conv1 = Conv2D(32, (3, 3), activation='relu') pool1 = MaxPool2D(pool_size=(2, 2)) conv2 = Conv2D(64, (3, 3), ac...

How to increase timeout limit on Vercel Serverless functions

I have an API endpoint on a NextJS project that needs longer than 60s to run. I'm on a pro Vercel plan but for some reason cannot get the timeout limit to increase. At the endpoint itself I've tried export const maxDuration = 300 export const dynamic = 'force-dynamic' which doesn't seem to do anything, I also tried adding a vercel.json file at the top level (above /src ) like so: { "functions": { "pages/api/**": { "memory": 3008, "maxDuration": 300 }, } } Which again isn't working. I've combed through the documentation (mostly here ) and also a handful of threads ( one example ), none of which have helped. I'm running NextJs version 13.5.6 , am definitely on a pro plan, and Node v18, what am I doing wrong? Am really unsure of what else to try. Via Active questions tagged javascript - Stack Overflow https://ift.tt/Agu1h8b

Naming New Tab with Image

I am trying to rename a new tab I am opening up. This new tab contains an iframe with an image as the source. This is how I am opening the tab, but can't seem to get document.title to work. var customTab = window.open(); customTab && customTab.document.title = 'My new tab';//this doesn't work customTab && customTab.document.write( '<iframe src="' + myImage + '" style="border: none;"></iframe>' ); Any ideas would be much appreciated. Via Active questions tagged javascript - Stack Overflow https://ift.tt/Agu1h8b

Shopify Checkout Ui Extension Unable To Get address From ShippingAddress (API) Method Using Javascript

Need a function built that block checkout if it's an International Order with a PO Box. For international orders Shopify populates DHL Express as a shipping name. IF DHL Express and Address = PO Box in this condition we need to Block Progress of checkout. How to get the ShippingAddress using API in JavaScript code? First I need to get the address after that am going to validate if address have PO Box. Am not using react, am using the JavaScript. It seems there is no proper example for using the Ui Extension API with JavaScript. Here is my code. I am new to using the app with extension and I am not sure my code is correct. import { extension, } from "@shopify/ui-extensions/checkout"; // Set the entry point for the extension export default extension("purchase.checkout.delivery-address.render-before", renderApp); function renderApp(root, api, { extension, buyerJourney }) { const address = api.shippingAddress(); // Use the `buyerJourney` intercept to condi...

How to solve this Error: read ECONNRESET or after second try then error occur is connection connect ECONNREFUSED 127.0.0.1:8000

The server is running fine and the registration API is also running fine and the registration is getting done. But when calling login API in postman this error is showing in console And error in server after call login API I want to call login API successfully. Via Active questions tagged javascript - Stack Overflow https://ift.tt/LXRVqZm

Gif not loading in react

I tried to fetch gif from giphy using API, bu[enter image description here][1]t the gif does not load useFetch.jsx import { useEffect, useState } from 'react'; const API_KEY = import.meta.env.VITE_GIPHY_API; const useFetch = ({ keyword }) => { const [gifUrl, setGifUrl] = useState(""); const fetchGifs = async () => { try { const response = await fetch(`https://api.giphy.com/v1/gifs/search?api_key=${API_KEY}&q=${keyword.split(" ").join("")}&limit=1`); const { data } = await response.json(); ; setGifUrl(data[0]?.images?.downsized_medium.url); } catch(error) { setGifUrl("https://metro.co.uk/wp-content/uploads/2015/05/pokemon_crying.gif?quality=90&strip=all&zoom=1&resize=500%2C284"); } }; useEffect(() => { if(keyword) fetchGifs(); }, [keyword]); return gifUrl; }; export default useFetch; How I've imported and implemented import useFetch from '../hooks/...

Not allowed to use async/await while using serverActions in Client component in next.js

Building an infinite scroll in next.js, I am trying to call my serverAction to loadMoreData and using async/await with it to wait for the API call and get result. Getting an error: "async/await is not yet supported in Client Components, only Server Components." page.tsx is a server component and calls the same server action one time for initial images. // page.tsx const Home = async ({ searchParams }) => { const searchKeyword = typeof searchParams.keyword === "string" ? searchParams.keyword : ""; let apiResponse = await getPhotos({ query: searchKeyword }); return ( <main className='p-6 flex justify-center w-full min-h-screen bg-black'> <InfiniteScrollData search={searchKeyword} initialData={apiResponse?.results || []} /> </main> ); }; export default Home; Here is the server action: // actions.ts "use server"; export const getData = async ({ query, }) =...

I am having MongoDB Cast Error anyone know what this means?

I am having this unknown error but in my interface and Schema I am not defining any field with the property of ObjectId and this is probably the first ever error of it's kind to appear here so I really hope this gets fixed GET /auth/discord/redirect?code=MsYzdlnjVC6upRhp37LmK5HbFP9IPW 302 7085.898 ms - 64 /Discord Authentication/node_modules/mongoose/lib/schema/objectId.js:250 throw new CastError('ObjectId', value, this.path, error, this); ^ CastError: Cast to ObjectId failed for value "{ id: { discordId: '713145789463134269', globalName: 'URIZEN', _id: new ObjectId("65536ab9bec76a177731bb99"), __v: 0 } }" (type Object) at path "_id" for model "User" at SchemaObjectId.cast (/Discord Authentication/node_modules/mongoose/lib/schema/objectId.js:250:11) at SchemaObjectId.SchemaType.applySetters (/Discord Authentication/node_modules/mong...

Can't import this github repo as a package: @openartmarket/pdfkit

Here's my code: https://github.com/ErnestoBorio/pdfkit-example I'm just trying to import the package https://github.com/openartmarket/pdfkit/ which is a fork of another package. The errors I get are: main.ts:1:25 - error TS2307: Cannot find module '@openartmarket/pdfkit' or its corresponding type declarations. Error [ERR_MODULE_NOT_FOUND]: Cannot find package './node_modules/@openartmarket/pdfkit/' imported from ./main.js Via Active questions tagged javascript - Stack Overflow https://ift.tt/ZwBOhfG

Stop execution of a recusive function that reads a JSON object with two nested object types

I have a JSON object built from two nested objects, both of which have a label property. My function checks that, for a given rank n, the array of QuestionModel[] or ResponseModel[] does not have equal labels. type ResponseModel = { label: string; questions?: QuestionModel[]; }; export type QuestionModel = { label: string; responses?: ResponseModel[]; }; const duplicatedLabel = async (data: QuestionModel[] | ResponseModel[]): Promise<boolean> => { const labelSet = new Set<string>(); for (let obj of data) { if (labelSet.has(obj.label)) { return true; } else { labelSet.add(obj.label); } if ("questions" in obj) return await duplicatedLabel(obj.questions!); if ("responses" in obj) return await duplicatedLabel(obj.responses!); } return false; }; For example, this JSON document is poorly constructed, with two equal labels at the same level yes . The funct...

Playwright Locator Issue

I am using Playwright trying to automate a button clicking action. I have tried to locate the HTML content through several methods, but will not click and proceed to the next screen. Here is the HTML content: [<button class="c-button checkoutConfirmButton--OXR5TyUP f-primary f-flex" data-bi-dnt="true" data-tv-strategy-up="projection" data-focus-rank="0">Checkout</button>] My Methods: page.get_by_role("button", name="Checkout").click() page.get_by_text("Checkout", exact=True).click() I expect the page to move to the next screen but the code refuses to interact. I've also added many print statements for errors and found out the button is not being located. Am I messing up my "locators" or should I use something else? Note: This is the only content with "Checkout" on the page. source https://stackoverflow.com/questions/77470118/playwright-locator-issue

Push the dates to another list if dates in the first list are matching with the inserted dates

I have rooms list, and it's like this: const insertedDates = [2023-11-13, 2023-11-14, 2023-11-15]; const roomList = [ { name: "Room 1", price: 250, roomNumbers: [ { number: 104, unavailableDates: [2023-11-13, 2023-11-14, 2023-11-15] } { number: 102, unavailableDates: [] } ] } ] Firstly, I want to compare the inserted dates to rooms' unavailable dates. If the first room number's dates matches with them, pass to the next one. Then the room number's dates doesn't match with the inserted dates, it should be pushed in it. Expected: const roomList = [ { name: "Room 1", price: 250, roomNumbers: [ { number: 104, unavailableDates: [2023-11-13, 2023-11-14, 2023-11-15] } { number: 102, unavailableDates: [2023-11-13, 2023-11-14, 2023-11-15] } ] } ] Is it possible to do it in JavaScript? Via Active questions tagged javascript - Stack Overflow https://ift.tt/Ne1lc8...

The TextInput clear and keyboard close every time i type(React Native)

Every time i type at Input in my app the text disappear and keyboard close, i searched forms to solve this but there is not many things, actually nothing that help me. Then this is my code, the useState: const [nameRoom, setNameRoom] = useState(''); The textInput: <TextInput style={styles.modalTextInput} onChangeText={(txt) => setNameRoom(txt)} value={nameRoom} /> I think that my code is ok, but i think that there is another thing on my full code that is cause of the problem Via Active questions tagged javascript - Stack Overflow https://ift.tt/Ne1lc8z

Appending a stream of repeated bytes to IO in Python

I am writing a program that allows recording audio packets continuously from an event loop. Each iteration I would either get an actual packet of data, or no packet at all. I have to track the time since the last packet and append the silence packets to IO upon the next received packet. The problem with that though is that the silence could be very long, and I don't want to create a large buffer of repeated data in order to write it to file, but it would also be extremely slow to write each silence frame individually in a loop, so my current solution is to combine the two and write in a loop with bigger to smaller segments of pre-generated silence. I'm looking for a better optimal method. I have been looking at BufferedWriter 's write method and noticed that it takes a bytes-like object. If that is possible, the optimal method would be being able to create a "bytes-like" object that simulates a stream of repeated data, that can be written x amount of times by th...

Adding Output Layer with Python

I'm having issues troubleshooting how to get my python code to automatically add my output layer to my current map in ArcPRO. I've included the code snippet below along with my error. Snippet: aprx = arcpy.mp.ArcGISProject("CURRENT") aprxMap = aprx.listMaps("Map")[0] newLayer = (("FinalSurveyPts" + "_" +str(projName +".shp"))) aprxMap.addLayer(newLayer) aprx.save() arcpy.RefreshActiveView() arcpy.RefreshTOC() del aprx Error: Traceback (most recent call last): File "D:\Grid Tool\Goshawk Survey Grid Tool.py", line 144, in <module> aprxMap.addLayer(newLayer) File "C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\utils.py", line 191, in fn_ return fn(*args, **kw) File "C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\_mp.py", line 2560, in addLayer return convertArcObjectToPythonObject(self._arc_object.addLayer(*gp_fixargs((add_layer_or_layerfile, add_position), True))) Valu...

closeOnClick not working in materialize css dropdown

I have a website and i am using materialize css and i have a profile icon and when you click on that icon i show a dropdown having multiple sub-items but whenever i click on any sub-item, the dropdown disappears and i dont want. I tries these solution but not working Solutions that i have tried Solution - 1 $(".dropdown-trigger2").dropdown({ closeOnClick : false }); Solution - 2 $(document).ready(function(){ var elems = document.querySelectorAll('.dropdown-trigger2'); var instances = M.Dropdown.init(elems, {closeOnClick:false}); $(".dropdown-trigger2").dropdown('destroy'); $(".dropdown-trigger2").dropdown(); console.log(instances); }); Solution - 3 by using e.stopPropagation() But not of them is working/ here is my html code <a class="dropdown-trigger2 btn-user waves-effect waves-light guided-tour-notification-disabled drop-btn" href="#!" data-target="dropdown1"> ...

Seeking Proven Workarounds for Twitter Data Scraping Challenges Post API V2 Update

I'm currently grappling with Twitter's API v2 updates, which have significantly impacted the effectiveness of data scraping libraries like Tweepy and Scrapy.  The new rate limits and access restrictions have introduced a set of challenges that I'm trying to navigate. Specifically, I'm encountering problems with: Adhering to the new rate limits without compromising the continuity of data collection. Gaining access to certain data types that seem to have new restrictions. Ensuring that my data scraping remains compliant with Twitter's updated terms of service. Here are the steps I've already taken: I've updated the libraries to the latest versions, hoping to align with the new API requirements. I've scoured the Twitter API documentation to understand the updated restrictions and modify my code accordingly. I've researched alternative scraping methods and tools designed for Twitter API v2, but with limited success. With these changes, I...

Adding a cap to a logarithmic regression

I'm running a log regression to model out reach curves. A typical reach curve looks like: So using a log regression seems the obvious choice. The reach curves are based on historical activity, but I have some additional knowledge of the total user count, so I know for certain that the reach can never exceed a certain number. I am having a hard time blending a modelled log curve with a known hard cap. Ideally I think I should add some modifier that increases the diminishing effect as the output approaches the known cap, to help preserve the curve on the lower values (where most the activity happens) while adding in the known cap to prevent the model from returning values where the reach is 125% of all users. Currently i'm using scipy optimize, i've added a ton of synthetic data at the known max to try and force this model to respect the max, but I think i'm going down the wrong road here: I feel like I need another function that takes the output of this one, and add...

My reset button not resetting the game mode in Tic Tac Toe (Noughts and Crosses)

I have created a Tic Tac Toe game (Noughts and Crosses in the UK!) and have finished almost everything except perhaps improving the computer AI (its just random at the moment). However, there is one bug that I can't seem to fix. When you first play the game you get the choice of playing against another human (player 2) or computer. Once this "human" or "computer" button is pressed it will save the information in a variable "let choiceComp" as either "human" or "comp". This will then call their respective functions, computerGame() or humanGame(), once the player enters their details and the subsequent start button is pressed. This works fine the first time around but when the reset button is pressed and the alternative game mode is selected (e.g. human first, then computer second - or vice versa), the same game mode will continue as the first time. I've reset the choiceComp variable as an empty string, along with everything els...

Will window.close work only work if the window shares a domain with the window trying to close it?

I'm trying to understand when window.close() will / won't work. I know there are some requirements around the window being script closeable etc., but it seems like there are some additional requirements that I can't find formally laid out (at least, not laid out in terms I can't understand with my current javascript knowledge.) At a high level, my use case is as follows: a user clicks a button I do some stuff and then do something like windowRef = window.open("http://example.com/somedocument.pdf","popup") . Once the user takes clicks a different button, I want to be able to call windowRef.close() and have it close the pdf I opened in a popup. My current implementation works as long as the url I'm opening shares a domain with the window that's trying to close it, and not otherwise. That's fine (I can guarantee the PDF will come from the same domain as the window trying to close it) but I'd like to understand why this doesn...

Buttons of Edit and Delete in DataTables Vue 3

I'm trying to include Edit and Delete buttons in the actions column in DataTables, the buttons are rendered on the screen, but the @click event doesn't work, and doesn't return an error message, can you check where I'm going wrong? Thank you all. The MontaTable component was created in another file. <template> <div id="divClientes"> <div style="padding-bottom: 20px; color: navy; font-weight: bold;"> <h3>Clientes cadastrados</h3> <button type="button" @click="novoCliente" class="btn btn-secondary">Novo Cliente</button> </div> <MontaTabela :rows="rows" :columns="columns" /> </div> </template> <script> /* eslint-disable */ import MontaTabela from '@/components/MontaTabela/MontaTabela.vue'; import http from '@/services/http.js'; import { FuncoesAuxiliares } from '@/helpers/FuncoesAuxiliares.vue'...

How to redirect to index.php after checking the email if already exist in database?

Im trying to use Google OAuth 2.0 using the GSI library. Im using localhost to try to log in (authenticate) using google account. So I need to get the email address to check if already exist in the database. If yes, proceed to assigning the email address to session and redirect to index.php. If not, user will redirect to a form to complete the sign-up process. The problem is, after I select Google account, it redirects to login.php. I tried to surf for answers but it's no use as the tutorials are using (gapi) oauth 2.0 The files are: login.php google_signin.php (where the checking of email takes place) Here is the code for reference. Suggestions are highly appreciated <script> function onSignIn(response) { const { id_token, access_token } = response.credential; fetch('google_signin.php', { method: 'POST', headers: { 'Content-Type': 'application/j...

Cannot access member arrays in Prisma model with a relational table. Using next.js, prisma, typescript

I have two tables defined with a relationship. Categories and Articles. Prisma build the relationship and all that looks good. Here is the definition of the Category table. model Category { id Int @id @default(autoincrement()) parentId Int? name String @unique articles Article[] } model Article { id Int @id @default(autoincrement()) date DateTime @default(now()) title String @unique summary String @db.Text text String @db.MediumText userId String user User @relation(fields: [userId], references: [id], onDelete: Cascade) categoryId Int category Category @relation(fields: [categoryId], references: [id]) image String? tags String? commentsEnabled Boolean @default(true) comments Comment[] likes Like[] } When I query the categories from Prisma, I do it like this: const categories = await ...