Skip to main content

Posts

Showing posts from March, 2023

How to interact with a website's nested shadow DOM in python Selenium?

I'm writing a script to test an input box embedded into multiple nested shadow DOMs with the structure below. Red boxes are the shadow DOMs (I had to cut off the first one out because it won't fit onto the screenshot) and green box is the element I want to interact with (a text box): I wrote the script below following the nested shadow DOM guidance here thinking that I need to send the type command to the final shadowRoot variable. When running it, I get a javascript error: By is not defined error. I'm weak in JS but I'm pretty sure I have the correct selenium syntax so I can't understand why it's failing to locate the shadow DOM tags. host = driver.find_element(By.TAG_NAME, "macroponent-f51912f4c700201072b211d4d8c26010") shadowRoot = driver.execute_script(f"return arguments[0].shadowRoot.findElements(By.tagName('sn-polaris-layout'))[0].shadowRoot.findElements(By.tagName,('sn-polaris-header'))[0].shadowRoot.findElements(By.t...

React Js child map function returns only first parent map function value but not others on using input type radio

I am using 2 arrays and rendering it as parent and child map function Array : const array1 = [{id: 1,message: "apple",},{id: 2,message: "banana",},{id: 3,message: "cherry",},]; const array2 = [{id: 4,reply: "mango",},{id: 5,reply: "grape",},{id: 6,reply: "kiwi",},]; Now when I render these arrays as parent and child and in onChange function in radio button i get each time "1" as id and I want parent's id 2 and 3 also on onChange function. export const app = () => { const array1 = [{id: 1,message: "apple",},{id: 2,message: "banana",},{id: 3,message: "cherry",},]; const array2 = [{id: 4,reply: "mango",},{id: 5,reply: "grape",},{id: 6,reply: "kiwi",},]; const handleChange = (parentId) => { console.log(parentId) // Each time returns 1 and not 2 and 3 } return ( <div> {array1.map((parentItem) => { ...

Why Promise.then not firing?

I bound the below method to a click event getValue() { this.ready = Promise.resolve('test'); } and on ngOnInit I am expecting the Promise.then to fire as, ngOnInit() { this.ready.then((res) => alert(res)); } Whenever I click the button, I call the getValue method, and expect the Promise.then to fire Why is it not working? Link to my code Via Active questions tagged javascript - Stack Overflow https://ift.tt/gRsVZjA

Cannot lock down 82287136 byte memory area (Cannot allocate memory) / An error ocurred : module 'speech_recognition' has no attribute 'recognize'

I found the python script below that should be able to give a realistic humanoid voice to chat gpt,converting the text produced by it into a humanoid voice and using my voice with a mic to talk with it. In short terms I want to do the same thing that the “amazon echo / Alexa” voice assistant does,without buying it,but using only what I already have…the Jetson nano (where I have installed ubuntu 20.04). Why the Jetson nano ? Because I can move it from a place to another one within my home,like a voice assistant and because I’ve already spent some money to buy it and I want to use it. This is the video tutorial where I found it : https://www.youtube.com/watch?v=8z8Cobsvc9k This is the code connected to the video tutorial : code.py : https://pastebin.ubuntu.com/p/G4wHRBNr7D/ I have configured my kinect 2 on the jetson nano and I’m using it correctly as a mic to send voice messages to my whatsapp and telegram friends. They can hear my voice very well,so I’m sure that it works. Did that...

How to fix returning multiple same users in response in Nodejs?

How to fix returning multiple same users in response in Nodejs? When I currently use the API it's giving me multiple same users in response for example "there is only one user in the database MongoDB and that username is User1 so if I type U it gives User1 User1 User1 User1 User1 multiple times" How can I fix that? And only give one user instead of looping the same user multiple times? router.post('/searchuser', (req, res) => { const { keyword } = req.body; if (!keyword) { return res.status(422).json({ error: 'Please Search A Username' }); } User.find({ username: { $regex: keyword, $options: 'i' } }) .then(user => { console.log(user); let data = []; user.map(item => { data.push({ _id: item.id, username: item.username, email: item.email, profileImg: item.profileImg, ...

Python Introduction class, 10.8 Lab; Toll Calculation [closed]

10.8 LAB: Toll calculation Toll roads often have different fees based on the time of day and whether it's during the week or on the weekend. Write a function calc_toll() that takes three parameters: The current hour of the day (int) Whether the time is morning (boolean) where AM = True and PM = False Whether the day is during the weekend (boolean) The function returns the correct toll fee (float), based on the chart below. Weekday Tolls Before 7:00 am ($1.15) 7:00 am to 9:59 am ($2.95) 10:00 am to 2:59 pm ($1.90) 3:00 pm to 7:59 pm ($3.95) Starting 8:00 pm ($1.40) Weekend Tolls Before 7:00 am ($1.05) 7:00 am to 7:59 pm ($2.15) Starting 8:00 pm ($1.10) Example: The function calls below, with the given arguments, will return the following toll fees: calc_toll(8, True, False) returns 2.95 calc_toll(1, False, False) returns 1.90 calc_toll(3, False, True) returns 2.15 calc_toll(5, True, True) returns 1.05 * Currenlty at 2/10, if anyone has or is able to reach solution would be hel...

Javascript: Global array loose content between events [duplicate]

I am trying to have an array be available for all my events. I have defined it at the top of my code right after $(document).ready When I use it in my first event I fill it up with values and that works well. When I try to use it in another events, the array exist but it is now empty. Note, the second event cannot be executed before the first one. In the code below, my first event is $('#fileInput').on('change' and my second event is $("#btnSubmit").on('click' . The array is named fileListProperty and I have tried the following to make it global: var fileListProperty =[]; window.fileListPropery = []; In both case it gets created, filled up by the first event but gets emptied when second event gets called on. Here's the code: $(document).ready(() => { var fileListProperty = []; $("#loaderContainer").hide(); /******************************************************************** * Click on browse button trigger the c...

How to put a string of json string representation into a json string: AWS eventbridge

I hope the title makes sense. What I am trying to do is create the AWS cdk code to have an AWS eventbridge rule trigger a lambda function with static input. What the input needs to look like is this """{ "resource": "/{proxy+}", "path": "/jobs/sendRepoJob", "httpMethod": "POST", "requestContext": "{}", "queryStringParameters": null, "multiValueQueryStringParameters": null, "pathParameters": null, "stageVariables": null, "body": "{\"Configs\":{\"_url\":\"<some_url>",\"name\":\"<some_name>\"},\"Configs2\":{\"_url\":\"<some_url>",\"name\":\"<some_name>\"}}" "isBase64Encoded": null }""" Basically, I need the json string as the body in the static input for the eventbridg...

Why is my websocket coroutine not being called in the following code?

I am using alpaca-py, Alpaca's new python package, to create a basic tradebot. My goal is to have the bot make a trade (buy), get data back from Alpaca's webhook regarding whether the order was filled (and some other information), and then make another trade with the same shares (sell). Before attempting to intergrate the webhook, the bot was buying and selling fine. I cannot seem to get a coroutine up and running, however. I have tried the following: Move await statements to different areas in the coroutines. Change the placement of the method and removed async from various methods. Check Alpaca's documentation. (Unfortunately, alpaca-py launched in 2023 and a lot of their documentation is outdated) Read the TradingStream code to ensure I am doing everything correctly. All looks good. Change the asyncio.gather call and run them both as routines. I get the same result. Add logger statements to the code. This clued me in that my method 'trade_update_handler' ...

Trigger event depending on local state on component unmount in React

I have a component with some internal state that is not being propagated throughout the application just on certain events. const FunComponent = (initialDescription, onSave) => { const [description, setDescription] = useState('initialDescription'); const handleDescriptionSave = () => { onSave(description); } return ( ... ); } My issue is that the component can get unmounted by something higher up in the component tree, and at that point I would want to force-trigger onSave . Great - i thought - I can just write a useEffect with an empty dependency array, and it will be run on unmount. The issue is that both the onSave prop and the description state is something my useEffect cleanup depends on. If I add them to the dependency array, it will save with the previous description value on every description change. I don't want that. If I don't add them to the dependency array, it will just use the initial onSave and description value on unmount. c...

Google Cloud Functions - Count documents by id and timestamp

I am a frontend developer working on some backend stuff in a private side project aka. I am signed up for trouble. So this is my first cloud function. I am using typescript. I want it to: Be called when a document is created in the collection [WORKS] Calculate the start of the day in GMT the document was uploaded on according to the time (type is timestamp) I add to the document when uploading it using the FieldValue.serverTimestamp() [WORKS] Count the number of documents which were created today and have the same id as the document we are calling the cloud function for [DOESN'T WORK] Here's my code: import * as functions from "firebase-functions"; import * as admin from "firebase-admin"; admin.initializeApp(); exports.countPrevious = functions.firestore .document("entries/{documentId}") .onCreate(async (snap, context) => { try { //Get current id const id = snap.data().id; //Calculate start and end of day the entry was uploaded...

I am making a 3 layer navigation and the mobile menu won't work. Sub Menu disappears every time I try to hover or click on a link

link to code When I hover on top of the appliance link the sub menu will appear but when I try to hover on top of the appliances listed within that submenu, the sub menu will disappear. Please someone help. <ul id="navMenu"> <!-- OUTDOOR KITCHENS MENU --> <li class="nav-item"> <a href="#" class="nav-link">Outdoor Kitchens</a> <ul class="kitchen-sub-items second-layer"> <li> <a href="#">Appliances</a> <ul class="third-layer"> <li><a href="#" class="nav-link">LYNX</a></li> <li><a href="#" class="nav-link">COYOTE</a></li> <li><a href="#" class="nav-link">CROWN VERITY</a></li> <li><a href="#" class="nav-link...

Python - Need help renaming all pdf in a folder based on 2 criteria

I am very new to programing, and I am trying to strengthen my Python skills via unique problems I find at my job. Currently, I have a program that is exporting PDFs from a remote desktop and it is automatically lowercasing all of the letters in the filename. We use two different item code formats, so I need to come up with a way to rename them all at once so that I can run a script periodically to fix this issue and gain my sanity back. I will provide examples of what I have, and what I want to convert the names to below: Materials 4000a example material test 4000A Example Material Test Finished Products test-2000a-tp-a example finished product TEST-2000A-TP-A Example Finished Product I am not sure how to best do this, but you can see exactly which positions I want to capitalize based on these formats. The materials one should be easier, the finished product one will take a little more creativity probably. I have looked around on here, Github, and a few other places...and I like t...

Analytical expressions for ODE integration methods using Sympy

I am trying to use Sympy to calculate analytical expressions for the error of numerical solutions of ordinary differential equations (ODEs), such as the Euler and Runge-Kutta methods. We have the ODE: $\dot x = f(x)$ with initial value $x(t_0) = x_0$, and we want to find the error of the approximate solution $x(t+\Delta t) \approx x_0 + \Delta t f(x_0) + \Delta t^2 f'(x_0)f(x_0)/2 +...$. The procedure is to expand the solution $x(t)$ in a Taylor series up to two orders higher than the numerical method under analysis and then compare this expansion to the expanded evaluation of the numerical solution. For the Euler method this is very straightforward (easy), because both expansions don't require much algebra: Euler method: x1 = x0 + \Delta t f(x_0) Taylor series, up to $O(\Delta t^2)$: $x(t+\Delta t) = x_0 + \Delta t f(x_0) + \Delta t^2 f'(x_0)f(x_0)/2 + O(\Delta t^3) $ Error: $|E| = | \Delta t^2 f'(x_0)f(x_0)/2 | $. The trick above is to use $dx/dt = f(x)$ and $d^...

Misalignment of Preloader on iPhones

I have the following preloader: /*-------------------------------------------------------------- # Preloader --------------------------------------------------------------*/ * { padding: 0; margin: 0; box-sizing: border-box; } @import url('https://fonts.googleapis.com/css2?family=Montserrat+Alternates:wght@500;700&family=Montserrat:wght@400;600&family=Oswald:wght@500&family=Pacifico&family=Roboto:ital,wght@0,400;0,900;1,500&display=swap'); .svg-file { width: 40vw; max-width: 133px; } .svg-file path { fill: transparent; stroke-width: 3; stroke: rgb(1, 36, 133); } .svg-file.z-logo path { stroke-dasharray: 550; stroke-dashoffset: 0; } .svg-file.z-logo path { animation: animate-zlogo 2s linear infinite; } .svg-file.z-logo svg { filter: drop-shadow(2px 2px 3px rgba(0, 0, 0, 1)); transform: scale(2); } .svg-file h2 { font-family: "Roboto", cursive; transform: translate(0, 50px) skewX(-210deg) rotate(-6deg); font-...

How can I use startswith without specifying a certain string? Is there any alternative?

I would like to apply vocal_start to so many different variables and i can't handle them all and i wouldn't always repeat startswith . So I don't want to write variable1.startswith(("a", "e", "i", "o", "u")) , but i would like to apply startswith(("a", "e", "i", " o", "u")) directly to all variables without specifying variable1.startswith (something similar to my code). I wouldn't always repeat startswith I guess using startswith is only like this (variable1.startswith), so is there anything else I can use? I need something like my code, but not with startswith (or I'd like to use startswith differently if possible) vocal_start = startswith(("a", "e", "i", "o", "u")) variable1 = "open" #Only for Test if variable1 == vocal_start: print("correct") In the code, of course, I get the NameErro...

remove stripes / vertical streaks in remote sensing images

I have a remote sensing photo that has bright non continuous vertical streaks or stripes as in the pic below, my question is there a way to remove them using python and opencv or any other ip library? , source https://stackoverflow.com/questions/75869481/remove-stripes-vertical-streaks-in-remote-sensing-images

Is there a way to resize iframe content dynamically based on iframe height and width?

Right now I have a plotly graph up on Heroku that I am trying to embed in a site via iframe. Based on what the user selects, the content can change size (height and width). I want the content to always fit inside the iframe without scrolling. The best way I can think of doing it is to zoom the inner webpage out until it's width and height are equal to or smaller than the iframe's width and height, but I'm not sure if this can be done or if it's even a good way of doing it. I have tried using css (zoom: 0.8; etc.) but it doesn't seem to do anything. I have also tried transform: scale() and a bunch of other things, but 1) these solutions only work on the iframe itself (e.g. using scale() the iframe gets smaller, not it's content), and 2) these solutions aren't dynamic because I can't use them to change the size of the page inside. Does anyone know how I can accomplish this? Thanks in advance! Via Active questions tagged javascript - Stack Overflow https:...

What's the most efficient way to get a key from a huge json?

I'm making a dictionary browser extension that for various reasons can't use an online API. Instead, I have two huge .json files, one for English to the target language and the other for vice versa, the larger of which is about 26MB. I'm aware that I can use fetch() to import a json file as an object, but I'm afraid that something that large will heavily impact performance. Is there a way to retreive just one key from a huge .json file in js? Would it be best if I hosted the .json online somehow? Or is 26MB actually not such a big deal, and I should just import the whole thing as an object? Via Active questions tagged javascript - Stack Overflow https://ift.tt/azCTM7e

Reseting values in st.number_input

Currently, I'm trying to program a website using Streamlit,Python. In it, I'm using st.number_input to then calculate a value with a button. Since it's too cumbersome to change each value back to 0.0 (the default value), I now want to add a button that resets all values to 0.0 and also displays them as such on the website. While I can change the values, the website still displays the previous value I entered. Therefore, I want to ask if it's possible to change the values and have them reflected on the website as well. Here is the code-snippit im using right now: st.subheader('Pigments') pigm_bayfer_yellow_420 = st.number_input('Bayferrox gelb 420:', min_value=0.0, max_value=1.0, step=0.00001, format='%.7f', value=0.0) pigm_bayfer_red_110 = st.number_input('Bayferrox rot 110:', min_value=0.0, max_value=1.0, step=0.00001, format='%.7f...

Calling JS function from C#

I have this JS function: function callUpdateGaugeValue(newValue) { updateGaugeValue(newValue, event); } Which works when I call it directly from HTML. Is it somehow possible to call it from C# code? Something like this: protected void Button_Click(object sender, EventArgs e) { value = 5; // callUpdateGaugeValue(value) } I need to put input value to function which I get from the C# function. I tried ScriptClient and Manager (I don't know if I tried it properly), but doesn't work. Via Active questions tagged javascript - Stack Overflow https://ift.tt/wbkqJ68

Is there a way to remove the user input and create a road background for the car to move on? [closed]

When I try creating a car game in python, there is a user input which keeps popping up when I try to change it, but I don't know how to remove it and keep a background. I tried to fix this problem, but it didn't work. source https://stackoverflow.com/questions/75859927/is-there-a-way-to-remove-the-user-input-and-create-a-road-background-for-the-car

Problem configuring Realm (mongodb) in react native with typescript

What I'm trying to do is configure a Realm in React Native. I have a class defining the schema of the object I want to persist in realm/mongodb. import {Realm, createRealmContext} from '@realm/react'; import { Configuration, ConfigurationWithSync } from 'realm'; import {appId} from "../atlasConfig.json"; const app = Realm.App.getApp(appId); const { currentUser } = app; export class Task extends Realm.Object { _id!: Realm.BSON.ObjectId; description!: string; isComplete!: boolean; createdAt!: Date; count!: number; static generate(description: string) { return { _id: new Realm.BSON.ObjectId(), description, isComplete: false, createdAt: new Date(), count: 0 }; } static schema = { name: 'Task', primaryKey: '_id', properties: { _id: 'objectId', description: 'string', isComplete: {type: 'bool...

Dataform - getting os username

How would I get the name of the user currently logged into the system using Dataform? I tried this: const os = require("os"); console.log(os.userInfo().username); but after typing "dataform compile" in the terminal I get this Do you have any ideas? Thank you in advance Via Active questions tagged javascript - Stack Overflow https://ift.tt/wbkqJ68

Split audio of stereo microphone cuts out in Web Audio API

I am trying to split the audio channels of my stereo microphone (SingStar Microphone). They are 2 microphones connected to one USB input actually and they send audio on either the left or the right channel. The issue is that when I sing into one of the microphones, the other channel get completely muted and does not pick up any audio. It doesn't matter which microphone. The first one to pick up audio works and the other cuts out until you stop the audio on the first microphone. (Weird is that if you input roughly the same audio into both at the same time they do pick up the audio on both channels, that makes me think it is some pre processing or something like that to remove background noise on stereo microphones but I am not sure about that). The issue is in chrome, I am not sure if Safari or Firefox have that problem but I am limited to chrome because I am using Electron. I already disabled all the preprocessing options here. Without echoCancellation, both channels send the same...

how can I filter array in object?

I would like to filter only people who have the color red as favColor... how can I do that? this is what i tried: but not worked const filteredpersonen = personen.filter(personen => personen.favColor= 'red'); console.log(filteredpersonen); This is my code: let personen = [ { naam : 'jan', age : 41, favColor:[ 'blue', 'green', 'yellow', 'orange' ] }, { naam : 'james', age : 31, favColor:[ 'red', 'black', 'yellow', 'purple' ] }, { naam : 'linda', age : 21, favColor:[ 'blue', 'white', 'red', 'grey' ] }, { naam : 'marya', age : 31, favColor:[ 'creme', 'green', 'orange', 'red' ...

how to loop through json object to get key and value, and display them in angular html?

I need to build an email sender by using nodemailer . I am sending the json object below and want to display the previous and current value changes with a pair of key and value in angular html. <json input> async function showChanges(formdata){ let htmlFile = await fs.promises.readFile(templatePath, { encoding: "utf-8", }); let template = handlebars.compile(htmlFile); let templateInput = { Message_Body: { Previous: formData.Message_Body.formChanges.Previous, Current: formData.Message_Body.formChanges.Current, } }; return template(templateInput); } For example, imagine the formData input looks like: "Message_Body": { "formChanges": { "Previous": { "Events": "TEST", "AdditionalInfo": "" }, "Current": { "Events": "TEST111...

prediction with tensorflow model being much slower than on tensorflow.js with a default configuration on a macbook M1

I'm likely doing something very wrong. Since the prediction was much slower on python I've written two, seemingly equivalent, snippets to test the two libraries. In Python (Python 3.9.12): from tensorflow.python.keras.layers import Dense, Flatten from tensorflow.python.keras.models import Sequential import time from tensorflow.python.client import device_lib def create_model(): input_shape = (1, 300) model = Sequential() model.add(Dense(200, activation="elu", input_shape=input_shape)) model.add(Flatten()) model.add(Dense(50, activation="elu")) model.add(Dense(20, activation="linear")) model.compile() return model if __name__ == '__main__': print(device_lib.list_local_devices()) model = create_model() inp = [[[0.5] * 300]] # warmup for i in range(0, 100): model.predict(inp) start_time = time.time() for i in range(0, 100): model.predict(inp) end_time = ti...

ValueError: cannot insert Date, already exists

I try to import a excel file get all dates from a column with dates and count how many events i have every year on all days of year from 2012 till now. And i have this error: ValueError(f"cannot insert {column}, already exists") ValueError: cannot insert Date, already exists import pandas as pd file_path = r'C:\Users\xxx\Desktop\yyy.xlsx' data = pd.read_excel(file_path) data['Date'] = pd.to_datetime(data['AVVIATO']) data['Year'] = data['Date'].dt.year data['DayOfYear'] = data['Date'].dt.dayofyear df = data.groupby([pd.Grouper(key='Date', freq='D'), pd.Grouper(key='Date', freq='Y')]).size().reset_index(name='counts') df['CumulativeSum'] = df.groupby('Date')['counts'].cumsum() df['YearCount'] = df.groupby('Year').cumcount() + 1 export_path = r'C:\Users\adrcl\Desktop\output.xlsx' df.to_excel(export_path, index=False) source https://...

Updating MongoDB after Stripe API purchase

I've been working on a E-Store built on Express.js, MongoDB and Stripe. This is my first ever project handling transactions and database stuff. I have a weird project structure where the product info is stored on MongoDB, payment stuff on Stripe and server handling with express.js. I've gotten to the point where im able to make successful purchase, but I can't update the data on mongoDB. When Stripe send a response that items are purchased, it only shows their Stripe ID, but I want to somehow save the MongoDB ID. Here is the app.js snippet for Stripe. app.post("/buy", async (req, res) => { const id = req.body.id; const p = await Product.find(({_id: id})); try { let items = []; for(const i in p) { const item = p[i]; items.push({ price_data: { currency: "eur", product_data: { name: item.title, }, ...

Mongo Aggregate: failed to query

`const {pageIndex, pageSize, sortField, sortOrder, filters} = data; return Voter.aggregate([ { $match: { isVoterVerified: false }, $facet: { metadata: [{$count: "total"}, {$addFields {page:pageIndex}}], data: [ { $sort: { [sortField || "createdAt"]: sortOrder || -1, }, }, {$skip: (pageSize * (pageIndex - 1)) || 0}, {$limit: pageSize}, ], }, } ]).exec();` Postmen I want to get all of the entries based on "isVoterVerified = false" and add pagination. when I run on postmen or in web client, I get a error saying "bad request". However, if I remove one of the stages and run it works perfectly fine. I want to match the entries "isVoterVerified = false" and add pagination. Thank You. Any solutions for this problem will be ap...

Unable to add a slider in Plotly.js

I tried to add a slider to change the value of scaleFactor which has been added in the code. But even after writing down the steps and arguments I'm unable to add the slider in the existing 'var layout' and thus getting no results. Here is the code that I've written to implement the slider var scaleFactor = 120; // adjust this to change the scale of the cones var velocity_trace_cones = []; // code for creating velocity cones goes here var data = [pressure_trace_edges, velocity_trace_nodes, velocity_trace_edges, ...velocity_trace_cones]; var steps = []; for (var i = 0; i <= 10; i++) { var newScaleFactor = i * 10; var newData = []; for (var j = 0; j < velocity_trace_cones.length; j++) { var cone = velocity_trace_cones[j]; var newCone = Object.assign({}, cone); // create a deep copy of the cone object newCone.u = [cone.u[0] * newScaleFactor]; newCone.v = [cone.v[0] * newScaleFactor]; newCone.w = [cone.w[0] * ne...

Extracting Device Name from Model using Python Scraping

I am attempting to scrape device information from a specific website (gsmarena) based on its model number. I would like to extract the model name (and eventually price). I'm using a headless browser and rotating proxies to do so, but have had little success in extracting the info. required for ~2000 devices (am able to extract roughly 10 before all IPs blocked). The (~200) proxies are obtained from https://free-proxy-list.net/ , which seem to contain a few that work. I've explored a number of different options but have had little success. Below is the code I'm currently running- any help would be appreciated. def get_device_name(device_model, proxies_list): # Check if the device model is provided, return None if not if device_model is None: return None # Create a list for storing working proxies working_proxies = list(proxies_list) # Start a web driver instance attempts = 0 while attempts < len(working_proxies): proxy = working_proxies[attempts] print(p...

How to use window_create method in customtkinter

I'm trying to build a chat system like a normal messenger interface using customtkinter, but I'm having attribute error. self.chat_frame = ct.CTkFrame(self) self.textbox = ct.CTkTextbox(self.chat_frame, width=400, height=400) self.textbox.grid(row=0, column=0, padx=(10, 0), pady=(10, 0), sticky="nsew") self.entry = ct.CTkEntry(self.chat_frame, placeholder_text="Hi there! I'm Bella, let's chat") self.entry.grid(row=3, column=0, padx=(10, 5), pady=(20, 20), sticky="nsew") self.chat_button = ct.CTkButton(self.chat_frame, width=10, text="Send", command=self.on_submit) self.chat_button.grid(row=3, column=2, padx=(0, 10), pady=(20, 20)) self.entry.bind("<Return>", self.on_submit) def on_submit(self, event=None): wrap = self.entry.get().strip() user_input = textwrap.fill(wrap, 30) self.entry.delete(0, 'end') if user_input != '': ...

Python - convert hex byte array to pure hex byte array

I am reading SML protocol based data from my power meter. From /dev/ttyUSB0 I receive the following data (excerpt): b"\x1b\x1b\x1b\x1b\x01\x01\x01\x01v\x07\x00\x17\x06\xf7\x84\x08b\x00b\x00rc\x01\x01v\x01\x01\x07\x00\x17\x11\x9d\x81x\x0b\t\x01emh\x00\x00c_\xdd\x01\x01cl\x18\x00v\x07\x00\x17\x06\xf7\... How can I convert this bytearray of hex values to a pure hex bytearray like 1b 1b 1b 1b source https://stackoverflow.com/questions/75844467/python-convert-hex-byte-array-to-pure-hex-byte-array

Desperate need for help python created folder with \ insted of /

(Code is below) Using jupyter notebook, I created a python code that would copy files with a keyword from one directory to a new one created in the script (i.e. files were kept in: D:/Main_Folder/SubFolder1/SubFolder2, and the new directory would be D:/Main_Folder/SubFolder1/SubFolder2/NewFolder). I used the filedialog.askdirectory() to get the directory of the original files, and the new directory would be created within that one. Python did it all wrong and created the new directory as follows: D:/Main_Folder/SubFolder1/SubFolder2\NewFolder Basically created the new folder but used a backslash instead. Is there any way at all to recover the files? I used the shutil.copyfile so I'm not entirely sure why they got deleted form the original folder. Please please please someone be my hero and help me! import os import shutil from tkinter import Tk from tkinter import filedialog root = Tk() root.withdraw() folder_path = filedialog.askdirectory() new_directory = os.path.join...

Python Twisted rpy module called multiple times - why?

I am programming Python the first day today. I am running Twisted webserver like this /usr/bin/python3 -m twisted web --http=80 --path=/website I wanted to add a scripted page using an .rpy file at /test.rpy This is the code in the test.rpy file from twisted.web.resource import Resource from twisted.python import log import subprocess class MyResource(Resource): def render_GET(self, request): log.startLogging(open('/root/test.log', 'a')) log.msg('test') request.setHeader(b"content-type", b"text/html") return b'abc' resource = MyResource() when i navigate to the location on the web browser, it shows "abc" as I would expect. But what I did not expect was in the test.log file (ip replaced with x.x.x.x)... as you can see, everytime i press Refresh on web browser it looks like the module is called multiple times -- first one time, next 2 times, next 3 times... can someone explain it to ...

How to store images from dall E 2 API into mongoDB

I'm creating a web application that accepts a user's prompt and then uses the dall E 2 api to generate an image. The issue that I'm running into is that once the image is generated. I want to store it in MongoDB so that I can retrieve it later to be displayed on a web gallery. My problem is that I cant use the URL of the image because it expires after an hour. So is there a way to store it without the URL into mongodb So im using node.js and javascript. I have a couple of ideas to try but dont know if they work. I want to see if anyone else has had this issue and how did they get through it. Via Active questions tagged javascript - Stack Overflow https://ift.tt/Q1fIK3O

Stream large XML file directly from GridFS to xmltodict parsing

I am using Motor for async MongoDB operations. I have a gridfs storage where I store large XML files (typically 30+ MB in size) in chunks of 8 MBs. I want to incrementally parse the XML file using xmltodict . Here is how my code looks. async def read_file(file_id): gfs_out: AsyncIOMotorGridOut = await gfs_bucket.open_download_stream(file_id) tmpfile = tempfile.SpooledTemporaryFile(mode="w+b") while data := await gfs_out.readchunk(): tmpfile.write(data) xmltodict.parse(tmpfile) I am pulling all the chunks out one by one and storing them in a temporary file in memory and then parsing the entire file through xmltodict. Ideally I would want toparse it incrementally as I don't need the entire xml object from the get go. The documentation for xmltodict suggests that we can add custom handlers to parse a stream, like this example: >>> def handle_artist(_, artist): ... print(artist['name']) ... return True >>> ...

How to re-trigger Airflow pipeline within a DAG

Our company's internal airflow2 platform has some issue, it can show "success" even if we didn't get any output from the pipeline, sometimes. To avoid this happen, we hope to have automated code to check whether there's output after Airflow pipeline finished, if not, then re-run the pipeline automatically. Do you know how can we do that? source https://stackoverflow.com/questions/75838115/how-to-re-trigger-airflow-pipeline-within-a-dag