Skip to main content

Posts

Showing posts from July, 2022

How would I turn this for loop output into a Pandas dataframe?

I have this code and I am having trouble figuring out how to put the for loop output into a dataframe. How could I take the for loop data and put it into a Pandas DataFrame? Rows look like ('tag', 34) select_stmt = select(Tag.tag, func.count('Tag.tag').label('CCount')).group_by(Tag.tag) with Session(config.connect()) as session: exec = session.execute(select_stmt) for row in exec: print(row) source https://stackoverflow.com/questions/73186044/how-would-i-turn-this-for-loop-output-into-a-pandas-dataframe

Math returning NaN to page [closed]

Hey guys I'm having trouble understanding where I've gone wrong, I'm assuming its within my maths but I can't see what it is that resulting in it not giving the correct answer let input = Number(document.querySelector('.rep').value); let btn = document.getElementById('submit'); let display = document.getElementById('1rm'); btn.addEventListener('click', function(ev) { let twentyPercent = Math.floor(input * 0.2); let max = Number(twentyPercent.value) * 100; display.textContent = Number(max.value); ev.preventDefault(); return }); <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>1 Rep Mac Calculator</title> <link href="1rm.css" rel=...

Find a set of points with the same distance in a euclidean matrix Python

I have a list with coordinates and this Euclidean matrix which represents the distance between each point: [0, 0], [0, 1], [0, 2], [0, 3], [0, 4] [0. 1. 2. 3. 4.] [1. 0. 1. 2. 3.] [2. 1. 0. 1. 2.] [3. 2. 1. 0. 1.] [4. 3. 2. 1. 0.] And what I want to do is check how many sets of two distinct but equal-length line segments which have one shared endpoint exists, for example: As we can see in the following image from the coordinate (0,0) to the coordinate (0,1) there is a distance equal to 1 and from the coordinate (0,2) to the coordinate (0,1) there is a distance equal to 1 (we already have two line segments with the same distance) and both share a point at the coordinate ( 0, 1). As shown in the following image: S1 represents the segment from the point (0, 0) to the point (0, 1) and S2 the segment from the point (0, 2) to the point (0, 1). And what I want as my output is the number of cases that match the requirements that I mentioned above, in the images below we can see t...

Conditional Render react-card-flip children based on a button or else 1 frontside 2 backsides

is the following im trying to do possible with the react-flip-package? Basically my front side is a card with 2 buttons. When i click the one button id like to flip into one backside and if i click to the other button i want to flip on another different backside. https://codesandbox.io/s/cool-sunset-pfjjln?file=/src/App.js Heres my code. import CardContent from '@mui/material/CardContent' import { IconButton, Box } from '@mui/material' import TrainIcon from '@mui/icons-material/Train' import ExpandMoreIcon from '@mui/icons-material/ExpandMore' import ReactCardFlip from 'react-card-flip' import CardDestination from './CardDestination' import CardBrowsePlan from './CardBrowsePlan' import React from 'react' function CardTrial() { const [isFlipped, setIsFlipped] = React.useState(false) const handleClick2 = () => { setIsFlipped(!isFlipped) } return ( <ReactCardFlip isFlipped={isFlipp...

Vue app compiles successfully but does not load in browser

I have a Vue app that outputs the following in the console after npm run serve . DONE Compiled successfully in 17450ms 2:15:55 PM App running at: - Local: http://localhost:8080/ - Network: http://10.0.0.72:8080/ Note that the development build is not optimized. To create a production build, run npm run build. No issues found. However, the app will not load on http://localhost:8080/ . The page displays the "This site cannot be reached.The connection was reset." message. Other pages load fine, including the Node server I am using for the backend, running on localhost:3002 . I have tried removing the node_modules and running npm install again, but that hasn't fixed it. With the app compiling ok there is little help troubleshoot. There are also no errors in the browser dev tools console. Does anyone know what might be going wrong or how to debug this? Thanks! ...

How to map a dynamic value to a range with a min and max

Within my IntersectionObserver I am storing the Y position of each target element: const targetPosition = entry.target.getBoundingClientRect().y; And when the target is in view, I am applying a translateX() synced with that changing Y position. It essentially works, but I am trying to take that dynamic Y position of the target and map it to a range defined by me so I can more easily control the translateX() (and in both left and right directions). I thought it might be as simple as const transformRange = Math.max(Math.min(targetPosition,90),0); but I understand why that doesn't do what I want (see edit below). I also have the following working... function scale (number, inMin, inMax, outMin, outMax) { return (number - inMin) * (outMax - outMin) / (inMax - inMin) + outMin; } const num = targetPosition; const transformRange = scale(num, -100, 1000, 0, 90); but I don't want to be required to set a range for the source value as well ( inMin and inMax ) as that is chan...

Cloud Firestore API issue with listeners, Python/Kivy jnius/jnius_proxy.pxi error on android

I have a problem that I've been stuck for 2 weeks trying to understand and solve. In the application I have a RecycleView , so I also have a system that reads and adds a listener(stream) to a Cloud Firestore document, when data changes in the database it is automatically placed in a DictProperty . But the real problem is in RecycleView , when database data is changed, RecycleView is affected for some reason and an error is returned: Traceback (most recent call last): File "jnius/jnius_proxy.pxi", line 156, in jnius.jnius.invoke0 File "jnius/jnius_proxy.pxi", line 124, in jnius.jnius.py_invoke0 AttributeError: 'list' object has no attribute 'invoke' List refers to RecycleView's data attribute E às vezes retornava esse outro error: Traceback (most recent call last): File "jnius/jnius_proxy.pxi", line 156, in jnius.jnius.invoke0 File "jnius/jnius_proxy.pxi", line 124, in jnius.jnius.py_invoke0 AttributeError: ...

Detect if Matter.js Body is Circle

I often find myself needing to test if a particular Matter body is a circle or not, as in: const compounds = Matter.Composite.allBodies(engine.world) compounds.forEach(compound => compound.parts.forEach(part => { const isCircle = ??? if (isCircle) console.log(part.id, 'is a circle') else console.log(part.id, 'is not a circle') }) I can't find an official way to test if a Matter body was created as a circle. How can I test if a body was created with new Matter.Body.Circle versus another Body constructor? Via Active questions tagged javascript - Stack Overflow https://ift.tt/fjsQkOt

is this is the right way to use prefetch_related?

i have these models class Theme(models.Model): name = models.charfield() class Category(models.Model): name = models.charfield() class Product(models.Model): name = models.charfield() ......... class MstProduct(Product): category = models.ForeignField(Category, related_name = 'category_products') themes = models.ManyToManyField(Theme, related_name='theme_products') ......... i want to fetch categories and there related products by Category.objects.prefetch_related('category_products').select_related('category_products__themes') is this is the right way to do this? source https://stackoverflow.com/questions/73178385/is-this-is-the-right-way-to-use-prefetch-related

How to create a list out of a json array

What i need to do is console.log all ip adresses and objects inside services and i have no idea what to do my current code is fetch('https://search.censys.io/api/v2/hosts/search?q=' + option1 + '&per_page=' + option2 + '&virtual_hosts=' + option3, fetchauth) .then(response => response.json()) .then(response => console.log(response.result.hits[0].ip)) .catch(err => console.error(err)); sample API response https://pastebin.com/s7k2YLG5 Im planing to display these informations inside a discord embed Via Active questions tagged javascript - Stack Overflow https://ift.tt/fjsQkOt

Trouble downloading pandarallel

I'm trying to download pandarallel but it's not working, this is the code I'm using in terminal: pip install pandarallel [--upgrade] [--user]` I'm getting the error: Parse error at "'[--upgra'": Expected string_end How can I fix this? source https://stackoverflow.com/questions/73171067/trouble-downloading-pandarallel

Difficulty With Register Route, not able to register without image

In the User model I have set avatar to be not required avatar: { public_id: { type: String, }, url: { type: String, }, }, but still if I register without image it shows error POST http://localhost:3000/api/v1/register 500 (Internal Server Error) and REGISTER_USER_FAIL constant state is returned Here is my UserController.jsx, Register Route exports.registerUser = catchAsyncErrors(async (req, res, next) => { const myCloud = await cloudinary.v2.uploader.upload(req.body.avatar, { folder: "avatars", width: 150, crop: "scale", }); const { name, email, password } = req.body; if(req.body.avatar){ const user = await User.create({ name, email, password, avatar: { public_id: myCloud.public_id, url: myCloud.secure_url, }, }); sendToken(user, 201, res); } else { const user = await User.create({ name, email, password }); sendToken(u...

Python code blocks not rendering with readthedocs and sphinx

I'm building docs for a python project using Sphinx and readthedocs. For some reason, the code blocks aren't rendering after building the docs, and inline code (marked with backticks) appears italic. I've checked the raw build, there was a warning that the exomagpy module couldn't be found which I resolved by changing ".." to "../" in the os.path.abspath() part of conf.py, this didn't appear to change anything in the docs. There was a similar question here on stackoverflow, I tried the solution but it didn't change. The raw build can be found here: https://readthedocs.org/api/v2/build/17574729.txt Here is the link to the github page: https://github.com/quasoph/exomagpy/tree/Develop The repo is structured like so: >.vscode >build/lib/exomagpy >docs >conf.py >rst files (.rst) >makefile >make.bat >exomagpy.egg-info >exomagpy >__init__.py >module files (.py) >.readthedocs.yml >requ...

Difference between converting date into string with toISOString() and JSON.stringify()

I researched about converting date into string in ISO format, and I found two methods to do that giving me the same result '2022-07-29T06:46:54.085Z' : (new Date()).toISOString() JSON.parse(JSON.stringify(new Date())) Question: Does JS make two approaches/algorithms of converting date or just one function code just call on different object JSON or Date , If So Which one is the best to use? Via Active questions tagged javascript - Stack Overflow https://ift.tt/sJ8nYFL

usage of all cores in numpy einsum

I have code which heavily uses np.einsum calls. I have installed numpy-intel in a python virtual environment using: $ pip install mkl $ pip install intel-numpy np.show_config() prints: blas_mkl_info: libraries = ['mkl_rt', 'pthread'] library_dirs = ['/home/sat_bot/base/conda-bld/numpy_and_dev_1643279478844/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/lib'] define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)] include_dirs = ['/home/sat_bot/base/conda-bld/numpy_and_dev_1643279478844/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/include'] blas_opt_info: libraries = ['mkl_rt', 'pthread'] ...

Firestore/Python - get() function to access a document fails in GCP Cloud Function

I'm trying to access a document in Firestore like this: from google.cloud import firestore def check_stuff(document_id, update_time): firestore_client = firestore.Client() doc_ref = firestore_client.collection(u'TestCollection').document(document_id) print(f"Ref OK") document = doc_ref.get() print(f"Doc OK") if document.exists: return True else: return False It prints the first print ("Ref OK") but not the following one. Instead I get this error, which I don't really understand. I seems to comes from the get() function itself: Exception on / [POST] Traceback (most recent call last): File "/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py", line 2073, in wsgi_app response = self.full_dispatch_request() File "/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py", line 1518, in full_dispatch_request rv = self.handle_user_exception(e) Fi...

RangeError [BITFIELD_INVALID]: Invalid bitfield flag or number: Guilds

throw new RangeError('BITFIELD_INVALID', bit); ^ RangeError [BITFIELD_INVALID]: Invalid bitfield flag or number: Guilds. at Function.resolve (C:\Users\Chase\Desktop\CureCraftBot\node_modules\discord.js\src\util\BitField.js:152:11) at C:\Users\Chase\Desktop\CureCraftBot\node_modules\discord.js\src\util\BitField.js:147:54 at Array.map () at Function.resolve (C:\Users\Chase\Desktop\CureCraftBot\node_modules\discord.js\src\util\BitField.js:147:40) at Client._validateOptions (C:\Users\Chase\Desktop\CureCraftBot\node_modules\discord.js\src\client\Client.js:550:33) at new Client (C:\Users\Chase\Desktop\CureCraftBot\node_modules\discord.js\src\client\Client.js:76:10) at Object. (C:\Users\Chase\Desktop\CureCraftBot\loadslash.js:6:16) at Module._compile (node:internal/modules/cjs/loader:1105:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10) at Module.load (node:internal/modules/cjs/loader:981:32) { [Symbol(code)]: 'BITFIELD_INVALID' here's my m...

I'd like my Discord.py bot to display a random embedded message from a single channel

I have a discord channel that is full of embedded messages. I would like have the bot display a random embedded message from this channel in to any other channel where the command is called, similar to the functionality shown below. When I call this code while pointed at the embed channel it returns an error: "discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message" I believe this is caused by the channel being totally embeds, but I am very stupid and open to being corrected. I have confirmed that the bot has full admin privileges and thus can see/write into any channel. I've also confirmed that the below code works on non-embeds in other channels. Thank you in advance for any assistance you can provide. @client.command() async def bestpost(ctx): channel = client.get_channel(channelID) best_posts = [] async for message in channel.history(limit=500): best_posts.append(message) ran...

To create a custom table by getting values from a dynamicaly created table

what I want is on save click to show another table like below where the second column(Questions) has sub-columns depending maximum L value a row has: unit Question unit1 23(L1) unit2 23(L3) unit3 24(L3) unit4 6(L2) unit4 10(L4) unit5 7(L1) unit5 10(L6) unit6 10(L2) unit 7(L4) var x = []; function getval() { var trs = $('#DyanmicTable3 tr:not(:first-child):not(:nth-last-child(2)):not(:last-child)'); var trs1 = $('#DyanmicTable3 tr:last-child'); var lastTotalElement = $('#DyanmicTable3 tr:nth-last-child(2)'); console.log(trs1); for (let i = 2; i <= 7; i++) { const total = Array.from(trs) .reduce((acc, tr) => x.push(Number(tr.children[i].textContent)), 0); ; } console.log(JSON.stringify(x)); } this is wt i got so far getting values in an array Via Active questions tagged javascript - Stack Overflow https://ift.tt/4T1qrtd

How do you concatenate several arrays into one?

const sumAll = function (min, max) { const allSums = []; const initialValue = 0; for (let i = min; i <= max; i++) { allSums.push([i]); } console.log(allSums); // let sumTotal = allSums.reduce(function (acc, curr) { acc += curr; return acc; }, initialValue); console.log(sumTotal); }; sumAll(1, 4) returns 01234 instead of 10. I can see that allSums is 4 arrays inside of an array. How would I go about concatenating them? Thank you for the help! Via Active questions tagged javascript - Stack Overflow https://ift.tt/4T1qrtd

How to Add variables to os.system() command

I am programming a software that does manipulation of my screens (3 monitors). I would like to add a variable in my line os.system(R'"command line here"') import os os.getcwd() os.system(R'"tools\MultiMonitorTool.exe /MoveWindow "\\.\DISPLAY5" Process "msedge.exe""') os.system(R'"tools\MultiMonitorTool.exe /MoveWindow "\\.\DISPLAY1" Process "Pos.exe""') os.system(R'"tools\MultiMonitorTool.exe /MoveWindow "\\.\DISPLAY2" Process "chrome.exe""') I would like to replace the words \\.\DISPLAY# with a variable in my configurations.ini file. I succeeded in displaying the information in my configurations.ini file but I can't insert it in my os.system() code, it always gives an error. Each computer has a different screen configuration. So I need to have a config file with the info for each installation. My configuratoins.ini [Configuration] frontview = ...

NoJMSMessageIdException: MISSING_JMS_MESSAGE_ID

I try to send message by Python package stomp to a queue on ActiveMQ Artemis, but the server answered me: NoJMSMessageIdException: MISSING_JMS_MESSAGE_ID. I tried to set like a header or property different values like JMSMessageID , msgID , MESSAGE_ID , etc. I found out that it validates by this method . I tried to send it with prefix id , but it didn't help. What does it expect? How to send it by stomp in Python? Documentation of stomp has such example but it doesn't explain how to send this JMS id: Protocol12.send(destination, body, content_type=None, headers=None, **keyword_headers) Send a message to a destination in the messaging system (as per https://stomp.github.io/stomp-specification-1.2.html#SEND ) Parameters: destination (str) – the destination (such as a message queue - for example ‘/queue/test’ - or a message topic) :param body: the content of the message :param str content_type: the MIME type of message :param dict headers: additional headers to send in the m...

Get search results for terms that are not part of the table

I have an HTML table with a search function that works well. However, my search function only finds the results based on the existing table data. I am trying to show results for terms that aren't in the table. I am able to do this but with limited success. As an example, if I search for "Apple Banana" (text that is not part of my table), the results are the same as if I searched for "ABC" (text that is part of my table). See my table below for example. The problem is, I only get results after searching the entire term "Apple Banana". Is there a way to search for "App" or "Ban" (not exact match but contains) and still get the results? If using an object is not the best approach, I am open to any other suggestions. Note that the HTML table is generated automatically by the Content Management System and I am not able to manipulate it. I can update JavaScript or CSS file. const obj = { 'Apple Banana':'ABC', }; fu...

Concatenate variable name with variable value Javascript [duplicate]

I have a flexible amount of titles, aka title1, title2, title3 etc. How can i create a dynamic variable that gives me the value of that field? function getTitle(i){ var myScope={} myScope["title"+i]="title"+i // should i use this in any way, and how? var output = props.attributes.title1 // This works, but it is static. Instead the 1, add the value of i here like: var output = props.attributes.title+i return output } I would like to concatenate the value of i to the word 'title'. So it becomes title1 or title2 etc. Via Active questions tagged javascript - Stack Overflow https://ift.tt/K6OlQDJ

Should not import the named export in React

i have a config.json file where i stocked all my BaseUrls and API_KEYS but, when i'm trying to import these from other component i get this error : **Should not import the named export 'API_URL_Geo' (imported as 'config') from default-exporting module (only default export is available soon) **, i tried 2 methods of importing import * as config from "../config.json"; config.API_URL_GEO and import {API_URL_Geo} from "../config.json"; but i still get same errors, any help ? Via Active questions tagged javascript - Stack Overflow https://ift.tt/K6OlQDJ

Edit->Find for WebView2 UI Component (WPF/C#/javascript)

I need to implement "Edit->Find" function for a WebView2 UI Component using WPF/C#/javascript... Below you will find two examples: One that is made for a TextBox UI Control called MainWindow1, and the other that is implemented for a WebView2 UI Control that is called MainWindows2. I'm giving both examples because I need to work the same way for each one. The TextBox example is working, but the WebView2 example is missing some javascript code to finish it and maybe requires some tweeting of the C# calls to WebView2. First, I implemented a "Find Forward" button for a TextBox that I can click multiple times to find the next string matching the search pattern in the textbox. And Here's my XML and C# for it: MainWindow1 GUI: MainWindow1 XML: <Window x:Class="WpfApp1.MainWindow1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x...

puppeteer Error Unknown key: " " when trying to press space key

I was trying to make a fun project by automating a typing test using puppeteer, but when I want to press space this error pops up D:\scraping\puppeteer tut\node_modules\puppeteer\lib\cjs\puppeteer\common\assert.js:28 throw new Error(message); ^ Error: Unknown key: " " at assert (D:\scraping\puppeteer tut\node_modules\puppeteer\lib\cjs\puppeteer\common\assert.js:28:15) at Keyboard._Keyboard_keyDescriptionForString (D:\scraping\puppeteer tut\node_modules\puppeteer\lib\cjs\puppeteer\common\Input.js:265:28) at Keyboard.down (D:\scraping\puppeteer tut\node_modules\puppeteer\lib\cjs\puppeteer\common\Input.js:112:119) at Keyboard.press (D:\scraping\puppeteer tut\node_modules\puppeteer\lib\cjs\puppeteer\common\Input.js:231:20) at D:\scraping\puppeteer tut\typingTest.js:37:34 at processTicksAndRejections (node:internal/process/task_queues:96:5) The code for the project is const puppeteer = require("puppeteer"); (async () =...

How do I make an HTTP 1.0 POST request in JavaScript?

This is the documentation of the API I'm trying to receive a response from. XL SQL over HTTP POST Request Format Description SQL access to the XL device is exposed via a web services API accessed using a key=value pair POST request to the path /sql-request.do. The body of the request must specify the following two parameters, in this order, separated by an ‘&’ character: •response_type: Either application/json, or text/xml; detailed descriptions of the response formats are included below. •sql_statement: A single LESQL statement to be evaluated. The length of the unencoded text cannot exceed 2048 bytes. The request may be URL encoded, but does not need to be; if it is, the following HTTP header must be attached to the request: Content-Type: application/x-www-form-urlencoded The only other necessary HTTP header is an accurate Content-Length. ExampleThe entire POST request for a statement selecting the most recent 5 sequence numbers and start times from the Timeline Stream m...

Convert list to string in python such that it separates the each integer as an element

I have a list f=['20.0', '21.0', '22.0', '23.0', '24.0', '25.0', '26.0', '27.0', '28.0', '29.0', '30.0', '31.0', '32.0', '33.0'] I want to change the list to string such that each element is recognized as an integer 20 21... That is f[0]=20 , f[1]=21 . If I just use f=str(f) , then it will count [' as an element too. source https://stackoverflow.com/questions/73129143/convert-list-to-string-in-python-such-that-it-separates-the-each-integer-as-an-e

Filter pandas dataframe by multiple columns, using tuple from list of tuples

So I have been referencing this previous question posted here Filter pandas dataframe from tuples . But the problem I am trying to solve is slightly different. I have a list of tuples. Each tuple represents a different set of filters I would like to apply to a dataframe accross multiple columns, so I can isolate the records to perform additional tasks. Whenever I try and filter by a single tuple within the list of tuples, the dataframe I get back has no records.. If I break the tuple values out in a very long form way it works fine. Not sure what I am missing or not thinking about here.. Using the same example from the post I have been referencing.... AB_col = [(0,230), (10,215), (15, 200), (20, 185), (40, 177), (0,237), (10,222), (15, 207), (20, 192), (40, 184)] sales = [{'account': 'Jones LLC', 'A': 0, 'B': 230, 'C': 140}, {'account': 'Alpha Co', 'A': 20, 'B': 192, 'C': 21...

material-table in react does not display data in onRowAdd but but the state is changed

This is my onRowAdd function, before adding the value in the table I'm testing if the values provided are true or not. The Issue is that when input values are true, new data newData is added into the state, but the material table does not display them. It's added but not visible Then when I clicked on the edit icon it shows me the values that were entered before but after saving it still, the values vanish. As shown in the image new row was added and action are also shown in it but material table is not displaying the values of the column. 'onRowAdd: newData =>' new Promise((resolve, reject) => { setTimeout(() => { handleTestConnection(newData) .then(isValid => { if (isValid) { setData([...data, newData]) resolve(); } else reject(); }) }, 1000) }) Via Active questions tagged javascript - Stack Overfl...

How to connect Prisma and migrate AWS ebs

After deploying successfully my nodejs app to AWS elastic beanstalk, I could open it on postman and check my routes, although it was all working correctly, from ebs logs, I could see a javascript error: Environment variable not found: DATABASE_URL. so it seems that my app on AWS doesn't have a DATABASE_URL environment to load on my Prisma/schema.prisma file. on the other hand, I discovered that AWS does provide database connection details through proccess.env as follows here: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-nodejs.rds.html#nodejs-rds-create but I have no clue how can I connect to my database on AWS when it's in production but with my .env DATABASE_URL when it's in development. Via Active questions tagged javascript - Stack Overflow https://ift.tt/cVEMHn7

What can I do in JavaScript to make each drop down menu only appear after selecting the one before it?

<div class="row"> <div class="col-md-4"> <label for="selectCustomers">Customer Select</label> <select class="form-control pointer" name="tableCustomers" id="tableCustomers" style="font-size:100%" > <option id="nothing" value="">---Select---</option> <option id="1" value="1" >1</option> <option id="2" value="2">2</option> <option id="3" value="3">3</option> <option id="4" value="4">4</option> </select> </div> <div class="col-md-4...

How to properly build my NPM ui package that uses other packages?

I've created a UI library and I created it using some packages like styled-component and react hook form, I can build and publish the library without any problem but when I install it in my main application it says that modules (like styled or react hook form) doesn't exists. How can I build and publish my npm package with the modules as well? so when installing it in the main app it doesn't look for those modules? Scripts to build the lib: rm -rf dist/ && prettier --write src/ && npm run build:esm && npm run build:cjs Via Active questions tagged javascript - Stack Overflow https://ift.tt/z3NtFJc

Want to get email using pandas

import pandas as pd df=pd.read_html('http://www.advpalata28.ru/reestr/reestr-advokatov/') df[0].to_excel("link14.xlsx",encoding='utf-8') I want to get email only from these text these is page link http://www.advpalata28.ru/reestr/reestr-advokatov/ : 676740, Амурская обл, Архара пгт, Ленина ул, 76 E-mail: advokat527@mail.ru source https://stackoverflow.com/questions/73114151/want-to-get-email-using-pandas

CRISPY_TEMPLATE_PACK doesn't work with pyinstaller

Hi I have a djnago app which is using websockets and django channels . I have converted it in an exe file with pyinstaller . Everything is working fine just my signup page is not working. I have used crispy_forms in it. When I run my exe file and open signup url, it gives me this error below is my spec file I know that I have to add CRISPY_TEMPLATE_PACK = "bootstrap4" somewhere but I dont know where should I add it source https://stackoverflow.com/questions/73114358/crispy-template-pack-doesnt-work-with-pyinstaller

No module named 'docker'

I'v tried to run some docker modules in ansible and get exact same error - name: Get infos on container docker_container_info: name: gitlab - name: Create gitlab container community.docker.docker_container: name: gitlab image: gitlab/gitlab-ce An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ModuleNotFoundError: No module named 'docker' fatal: [172.16.86.38]: FAILED! => {"changed": false, "msg": "Failed to import the required Python library (Docker SDK for Python: docker above 5.0.0 (Python >= 3.6) or docker before 5.0.0 (Python 2.7) or docker-py (Python 2.6)) on localhost.localdomain's Python /usr/bin/python3. Please read the module documentation and install it in the appropriate location. If the required library is installed, but Ansible is using the wrong Python interpreter, please consult the documentation on ansible_python_interpreter, for example via `pip...

os.chdir returns No such file or directory: 'None'

How come that these lines of code creates a folder, but returns an error output? key_ = "Test" new_folder = os.makedirs(str(key_)+str(datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M'))) os.chdir(str(new_folder)) The error I'm getting is line 457, in download_url os.chdir(str(new_folder)) FileNotFoundError: [Errno 2] No such file or directory: 'None' source https://stackoverflow.com/questions/73114307/os-chdir-returns-no-such-file-or-directory-none

I am building a python experiment and am trying to get my code to run every time I hit space but I cant figure out how to do that

I am making this kind of a game but it isn't really a game so basically I want this to run every time I hit space but it doesn't work no matter what I try so I would be really thankful if somebody could have helped me out on this. import random import keyboard food = 5 x = 0 y = 0 if keyboard.is_pressed('space'): bobsDecision = random.randint(0,1) if bobsDecision == 1: print ('bob ate') food = 5 else: xoy = random.randint(1,4) if xoy == 1: x = x + 1 elif xoy == 2: x = x - 1 elif xoy == 3: y = y + 1 elif xoy == 4: y = y - 1 food = food - 1 print ('the cords are ', x, " ", y) print ('The food supply is ', food) source https://stackoverflow.com/questions/73113852/i-am-building-a-python-experiment-and-am-trying-to-get-my-code-to-run-every-time

chartjs-plugin-datalabels not showing values on chartjs

I am using the following versions: Angular: 14.0.6 TypeScript: 4.7.4 chart.js: ^3.8.2 chartjs-plugin-annotation: ^1.4.0 chartjs-plugin-datalabels: ^2.0.0 ng2-charts: ^4.0.0 And I am trying to create a simple demo Doughnat Chart with dummy data. The problem is that the values are not shown on the chart, no matter what I tryied. I helped myself using that as an example but I figured out that with the newer version this approach is not working.. Here is what I tried so far.. My app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { HeaderComponent } from './header/header.component'; import { FoodManagementModule } from './food-management/food-management.module'; import { NgChartsModule } from ...

Is it possible to access the event object in a function without having to pass it in?

So i have this equalizer function here, which gives all elements the same minHeight. The function uses lodash's throttle function and executes everytime the window resizes and on load . export const equalizer = throttle((elems, e, stopAt = 0) => { const elements = [...document.querySelectorAll(elems)]; const setMinHeight = (el) => el.style.minHeight = '0px'; if (e.type === 'resize') elements.forEach(setMinHeight); const minHeight = elements.reduce((acc, cur) => { if (cur.clientHeight >= acc) return cur.clientHeight; if (acc >= cur.clientHeight) return acc; }, 0); elements.forEach((el) => (el.style.minHeight = `${minHeight}px`)); }, 500); So the "problem" now is that everytime I call this function I have to pass in the event object (because of e.type === "resize" ) and I want to know if there is a way to avoid that. ['load', 'resize'].forEach((event) => { window.addEventListene...

Enforcing numerical stability in numpy.log()

I have something like this: import numpy as np x = np.random.rand(10) # I risk a zero entry log_x = np.log(x) # Risk of a divide by 0 What is the best way to enforce numerical stability here in the np.log call? Current Solution import numpy as np def safe_log(x: np.ndarray) -> np.ndarray: while not x.all(): x = np.nextafter(x, 1) return np.log(x) source https://stackoverflow.com/questions/73101705/enforcing-numerical-stability-in-numpy-log

Uncaught TypeError: Cannot read properties of undefined (reading 'fromURL') while upload gif to canvas

Good evening, dear colleagues! My task is to upload a gif file to fabric. for this I use the code provided in the official documentation . The code of uploading file is below. (function() { var canvas = this.__canvas = new fabric.Canvas('myCanvas'); fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center'; fabric.Object.prototype.transparentCorners = false; for (var i = 0, len = 5; i < len; i++) { for (var j = 0, jlen = 5; j < jlen; j++) { fabric.Sprite.fromURL('https://i.ibb.co/3TkHBVg/sprite.png', createSprite(i, j)); } } function createSprite(i, j) { return function(sprite) { sprite.set({ left: i * 100 + 50, top: j * 100 + 50, angle: fabric.util.getRandomInt(-30, 30) }); canvas.add(sprite); setTimeout(function() { sprite.set('dirty', true); sprite.play(); }, fabric.util.getRandomInt(1, 10) * 100); }; } (function r...

How to catch event: re-initialise search in Algolia Instantsearch?

I am using Algolia and the Instantsearch library in a Vue project, to search for items. The user has the option to check each item (with a simple checkbox). Checking at least one item makes a toolbar visible, with a selection of actions to be applied on the selected batch of items in the search results. When an search result item is checked, it fires a Vue method that pushes the item to a Vuex array called "selectedItems". In order not to lose this selection with pagination, I have gone for the infinite hits widget. Thus all results remain on the same page. Until here things work fine. My problem is that when the user clicks on the cross in the searchbox to reinitialise the search, then the items are not checked anymore, but obviously they remain within the "selectedItems" array in Vuex. How can I capture the event of the search re-initialising? If I can catch this event, I can then empty the "selectedItems" array so that it remains in sync with the search...

React Tailwind - not able to start my app

I was trying to use Tailwind css with react project, i followed the exact instructions on Tailwind website on how to use Tailwind in React but when trying to run npm run start it displays : Failed to compile. EIO: i/o error, read did anyone ever faced this, ad please how to solve this ? Via Active questions tagged javascript - Stack Overflow https://ift.tt/xcE6ZuR

Add Checkbox/DropDownList in WORD using Addin JS API

I'm new to WORD ADDIN and I want to add Checkbox/DropDownList in MS WORD using Word Addin and I tried to add using Word.ContentControlType but its not helping. Can anybody tell me or provide any reference regarding it? I'm sharing my code along with the link to the official documentation of WORD ADDIN JAVASCRIPT API. Thanks. document.getElementById("btn-1").addEventListener("click", ()=>{ Word.run(function (context) { var range = context.document.getSelection(); // var myContentControl = range.insertContentControl(); var myContentControl = range.insertContentControl(Word.ContentControlType.checkBox); myContentControl.tag = 'FirstName'; myContentControl.title = 'FirstName'; myContentControl.cannotEdit = false; // myContentControl.style = 'Heading 2'; myContentControl.insertText(''); myContentControl.appearance = Word.ContentControlAppearance.boundingBox; ...

fetch() explain principle and what happing behind [closed]

can someone explain this line of code to me when we want to use fetch() some data to firebase? we are trying to get some data from users in the form and then sending them to the firebase servers instead of the browser database directly actually is part of the youtube practice course, not my project I am very new to whole web developer things Blockquote irect to data fetch( "https://training-for-react-default-rtdb.firebaseio.com/meetups.json", { method: "POST", body: JSON.stringify(meetupData), headers: { "content-type": "appLication/json", }, } Via Active questions tagged javascript - Stack Overflow https://ift.tt/ecTySWl

How to pass a style from one component to another if condition is true in Vue 3

I have two sibling components where one relies on the other for an event to happen. In this case, I want to apply this styling - marginTop = "-20px"; to the div of one component when the length of an input inside another component is more than 0 characters. Whether it be props, slots, refs or events, I'm still not sure what fits this use case (I'm very new to Vue). I'm also not sure if I can even pass data between these two sibling components directly or if I have to pass from one child to the parent and then to the other child. What I'm currently attempting to do is to simply grab the element I want to apply the style to (in the vanilla JS way) and have the method invoked when the aforementioned condition becomes true (all in the same component). // Component trying to style the element <ais-state-results v-if="input.length > 0"> // Component trying to style the element mounted() { this.positionSecondaryContent(); }, methods: { ...

Searching for strings in one txt file in another txt file

Here I just want to search for the keyword in the domain file without doing anything on the files. There is one key and one domain in each line. Please consider performance as there is a lot of data. My code: def search_keyword_domain(): # here I just want to search for the keyword in the domain file without doing anything on the files. # There is one key and one domain in each line. # Please consider performance as there is a lot of data with open("result.txt", "a") as result: result.writelines(line) def search_keyword(): with open('domains.txt', 'r') as d: for line in d: line.strip() d.close() with open('keywords.txt', 'r') as f: for line in f: line = line.strip() search_keyword_domain(line) f.close() if __name__ == '__main__': search_keyword() EXAMPLE: strings.txt : Note: There are 180 keywords. google mess...

How to avoid trading holidays during historical data

from datetime import timedelta, date from nsepy import get_history def importdata(stock): stock_fut = get_history(symbol=stock, start=date.today() - timedelta(days = 15), end=date.today(), futures=True, expiry_date=date(2022,7,28)) print(stock_fut[["Underlying","Change in OI","Open Interest"]]) a = ["MARUTI","HEROMOTOCO","BAJAJ-AUTO","M&M","EICHERMOT"] for i in range(0,len(a)): print(a[i]) importdata(a[i]) Now I want only last 10 days historical data. So I need to change the timedelta value regularly.What will be the code for start date and end date so that it always give me only 10 days data without need of changing timedelta value. In other words it takes input of 10 days always excluding Saturday, Sunday and other trading holidays. source https://stackoverflow.com/questions/73093571/how-to-avoid-trading-h...

how can i remove dates from a url with amp-link-rewriter

I am a blogger user and I have my website at www.kangutingo.com and I want the dates to be deleted from the url and only the text remains. is this possible to do? I leave here the link of the amp plugin https://amp.dev/documentation/components/amp-link-rewriter/ Via Active questions tagged javascript - Stack Overflow https://ift.tt/ecTySWl

Similar time submissions for tests

I have a dataframe for each of my online students shaped like this: df=pd.DataFrame(columns=["Class","Student","Challenge","Time"]) I create a temporary df for each of the challenges like this: for ch in challenges: df=main_df.loc[(df['Challenge'] == ch)] I want to group the records that are 5 minutes apart from each other. The idea is that I will create a df that shows a group of students working together and answering the questions relatively the same time. I have different aspects of catching cheaters but I need to be able to show that two or more students have been answering the questions relatively the same time. I was thinking of using resampling or using a grouper method but I'm a bit confused on how to implement it. Could someone guide me to the right direction for solving for this? Sample df: df = pd.DataFrame( data={ "Class": ["A"] * 4 + ["B"] * 2, "Student...