Search the Community
Showing results for tags 'python'.
-
so i made a bot following this tutorial right now it's a very simple bot just reads message and posts a reaction image or meme, but the method to keep the bot online on replit is now paid, and I don't have any dineros, so is there a way to keep my bot online for atleast 24 hours without any interaction and how do i import my file to that while keeping the env secrets and stuff, i tried pythonanywhere.com but it just won't connect to discord, please help me out
-
So im trying to make a discord bot so I started following this freecodecamp.org tutorial and made some changes to it because somethings don't work any more my bot is up online but it won't repond to me import os import discord token = os.environ['token'] intents = discord.Intents.default() intents.messages = True # Enable message intents client = discord.Client(intents=intents) @client.event async def on_ready(): print('we have logged in as {0.user}'.format(client)) @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith("!hello"): await message.channel.send("hello") client.run(token) here's the tutorial im following https://www.youtube.com/watch?v=SPTfmiYiuok&t=622s I googled for solutions but could'nt find any working ones, pls help
-
So, Im going to be attending college within a few months doing a bachelors in computer science engineering, I have nothing good to do in these months so i thought why not level up my skills a little, which I don't really have any except the python I learnt in school, now it's not much but I know basic stuff (if/elses, loops ,lists/tupples/dictionaries,functions, handling text files/binary files/csv files) and using mysql library to handle some dbms stuff, i wanna learn some more but ii don't know what to learn where to learn from, I want to get into making atleast 1 small project, I am really interested in ML and would also like to try some Iot stuff with a raspberry pi, but i have no idea how to go on about those things, what libraries to learn, and where and how should I learn them, I've been using IDLE to do python until now, so I have no idea what code editor should I even use, please help me out.
-
Budget: Under $2000 United States My dad made the mistake of buying a dell computer that has horrid cooling and I can hear the fans ramping up full; he has only had this desktop for 3-4 years; it has a Xeon chip and Quadro graphics card with 64 gigs of ram and 2 m.2 nvme drives. He uses the computer for emails, thunderbird, web browsing, watching Netflix, communication through Microsoft teams, chrome and Microsoft edge open with lots of tabs, one note, etc. He uses visual studio, eclipse, powershell, copilot, esri ArcGIS pro; (spatial data, advanced mapping analytics, 2d 3d and 4d visualizations) IntelliJ idea; JavaScript, typescript, kotlin, react, vue, angular, node.js) He also programs in bash and C sharp He has all of these things open at once on a 4k monitor@60hz He was thinking of an i9-13900 with a score of 48,088 on cpubenchmark.net (passmark) and wants the next pc to be around 50,000 (but it can be lower as long as it can run everything he uses) I was hoping he would build his next computer but he is thinking of buying a dell alienware laptop :(. I told him it wouldn’t have as good cooling as building a desktop. So what parts (cpu) amd or intel would be good for his workload, also what gpu (he doesn’t game) but I was thinking like a cheap Radeon card; an all amd build with smart access memory (or intel build) would be good for his workload? Basically intel or amd with 64 gigs of ram a decent motherboard and would fit in a mAtx/mini itx like this one https://a.co/d/i01WITR And if he did buy a laptop what brand/model would be good for his work? (Please link a couple options)
-
I'm having an issue with a Python project script on my Ubuntu system, involving Bluetooth communication with an Android/Linux system. The script, titled project-script.py, is engineered to configure a Bluetooth adapter and execute a range of Bluetooth commands. However, I am running into an issue where the script is unable to recognize my Bluetooth adapter 'hci1 The error message that appears is: Unable to find adapter 'hci1', aborting. The output when I attempt to execute the script is as follows: vboxuser@ubuntu:~/Downloads/hi_my_name_is_keyboard-main$ ./project-script.py -i hci1 -t 5C:F3:70:AA:07:BD [2024-01-15 15:37:39.259] executing 'sudo service bluetooth restart' [sudo] password for vboxuser: [2024-01-15 15:37:45.538] configuring Bluetooth adapter [2024-01-15 15:37:45.550] calling RegisterProfile [2024-01-15 15:37:45.558] running dbus loop [2024-01-15 15:37:45.560] Unable to find adapter 'hci1', aborting. I have made sure that the Bluetooth adapter is correctly plugged in and is recognized by the system. Additionally, I have restarted the Bluetooth service and checked that all necessary permissions and dependencies are in place. Despite these measures, the 'hci1' adapter remains undetected by the script.
-
# Importing libraries I deemed necessary import tensorflow as tf from tensorflow.keras import layers import matplotlib.pyplot as plt import os import mediapipe as mp import cv2 import numpy as np # The training data set contains 78,000 images which are 200x200 pixels. There are 26 classes for the letters A-Z. # The test data set contains a mere 26 images, to encourage the use of real-world test images. # for dirname, _, filenames in os.walk(r'D:\ASL Recognition using CNN\Input_Images'): # print("Data Loading....") # for filename in filenames: # print(os.path.join(dirname, filename)) # print("Data Successfully Loaded") train_dataset = tf.keras.utils.image_dataset_from_directory( directory=r'D:\ASL Recognition using CNN\Input_Images\asl_alphabets\asl_alphabet_train', labels='inferred', label_mode='int', image_size=(200, 200), color_mode='rgb', batch_size=32, shuffle=True, seed=42, validation_split=0.2, subset='training' ) # for image, label in train_dataset.take(1): # print("Before preprocessing", image.dtype, label.dtype) # print(image) validation_dataset = tf.keras.utils.image_dataset_from_directory( directory=r'D:\ASL Recognition using CNN\Input_Images\asl_alphabets\asl_alphabet_train', labels='inferred', label_mode='int', image_size=(200, 200), color_mode='rgb', batch_size=32, shuffle=False, seed=42, validation_split=0.2, subset='validation' ) # test_dataset = tf.keras.utils.image_dataset_from_directory( # directory=r'D:\ASL Recognition using CNN\Input_Images\asl_alphabets\asl_alphabet_test', # labels=None, # image_size=(200, 200), # color_mode='rgb', # batch_size=32, # shuffle=False, # ) # Since the test_data didn't have subdirectories that reflected their class_names, # I couldn't use tf.keras.utils.image_dataset_from_directory() # So I had to create a function that extracts labels from file name and creates a dataset def test_dataset_generator(): test_image_directory = r'D:\ASL Recognition using CNN\Input_Images\asl_alphabets\asl_alphabet_test' batch_size = 26 img_height, img_width = 200, 200 # Get the list of test image file paths test_filepaths = tf.data.Dataset.list_files(os.path.join(test_image_directory, '*.jpg')) # Extract labels from file names def extract_label(file_path): # Assuming file names are like 'A_test.jpg' .... # and filepaths are like "D:\ASL Recognition using CNN\Input_Images\asl_alphabets\asl_alphabet_test\A_test.jpg" parts = tf.strings.split(tf.strings.split(file_path, '\\')[-1], '_') return parts[0] # Map file paths to images and labels def process_path(file_path): label = extract_label(file_path) img = tf.io.read_file(file_path) img = tf.image.decode_jpeg(img, channels=3) img = tf.image.resize(img, [img_height, img_width]) return img, label # Create the test dataset test_datasets = test_filepaths.map(process_path) test_datasets = test_datasets.batch(batch_size) return test_datasets test_dataset = test_dataset_generator() # Creating Preprocessing Layers data_augmentation = tf.keras.Sequential([ layers.RandomFlip("horizontal"), layers.RandomRotation(0.2), layers.Rescaling(1. / 255) ]) # data_rescaling = tf.keras.Sequential([ # layers.Rescaling(1. / 255) # ]) # Applying Preprocessing Layers to the dataset # We only augment the training data! # Configuring the datasets for performance, using parallel reads and buffered prefetching .... # ... to yield batches from disk without I/O become blocking. AUTOTUNE = tf.data.AUTOTUNE def preprocess(ds, augment=False): if augment: ds = ds.map(lambda image, label: (data_augmentation(image, training=True), label), num_parallel_calls=AUTOTUNE) return ds.prefetch(buffer_size=AUTOTUNE) train_preprocessed_dataset = preprocess(train_dataset, augment=True) validation_preprocessed_dataset = preprocess(validation_dataset, augment=True) test_preprocessed_dataset = preprocess(test_dataset) # for image, label in train_preprocessed_dataset.take(1): # print(image.dtype, label.dtype) # for image, label in train_dataset.take(1): # print(image.dtype, label.dtype) # Creating Mediapipe Hands Landmark Layers mp_hands = mp.solutions.hands hands = mp_hands.Hands( max_num_hands=2, min_detection_confidence=0.3, min_tracking_confidence=0.3, model_complexity=1, static_image_mode=True ) # Vectorized landmark extraction function using TensorFlow ops def feature_extraction(image): img = (image.numpy() * 255).astype(np.uint8) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) print(img.dtype, img.shape) # Apply MediaPipe Hands processing results = hands.process(img) # print("The resulting array is:", results.multi_hand_landmarks) # Handle cases where no hands are detected if results.multi_hand_landmarks is None: return tf.zeros((21, 3), dtype=tf.float32) # Placeholder for no hands # Extract landmarks with error handling try: # landmarks = tf.gather_nd(results.multi_hand_landmarks, [[0, 0, 0], [0, 1, 0], [0, 2, 0], ...]) landmarks = np.array( [landmark.x, landmark.y, landmark.z] for hand_landmarks in results.multi_hand_landmarks for landmark in hand_landmarks.landmark) except ValueError as e: print(f"Error extracting landmarks: {e}") return tf.zeros((21, 3), dtype=tf.float32) # Fallback placeholder return landmarks train_landmark_dataset = train_dataset.map(lambda x, y: (tf.py_function(feature_extraction, [x], tf.float32), y)) validation_landmark_dataset = validation_dataset.map(lambda x, y: (tf.py_function(feature_extraction, [x], tf.float32), y)) # train_combined_dataset = tf.data.Dataset.zip((train_preprocessed_dataset, train_landmark_dataset)) # validation_combined_dataset = tf.data.Dataset.zip((validation_preprocessed_dataset, validation_landmark_dataset)) for landmarks in train_landmark_dataset.take(1): print("\n\n\nThe landmarks of a batch are:", landmarks)
-
- python
- tensorflow
-
(and 1 more)
Tagged with:
-
Hello! I don't know how to list download links from an archive.org directory, and would like to know.
- 10 replies
-
- networking
- wget
-
(and 1 more)
Tagged with:
-
I am working on a project in ubuntu with wsl2. I want to digitize a book. I am planning on making 200 jpg images of the even pages of the book and 200 jpg images of the odd pages. These images wil be saved in google foto's from where I can download them as 2 zip files to ubuntu. I want to give these images to a program that wil make them in to a pdf. This program (img2pdf) wants a .txt file with the names of the img files. To do this I have written a python script that has 2 list of the files, one for even and one for odd and wil merge these list together. the problem is that when I run the code I use the os.listdir method to get the list of files, but this does not give me the files in the order that I have taken the foto's. Bing ai gave me this method to sort them: even_files.sort(key=lambda x: os.path.getctime(os.path.join(pathInputEven, x))) But that does not seam to work. This is the whole python code: import os import shutil pathInputEven = "digitizeBoekTemplateProject/InputEven" pathInputOdd = "digitizeBoekTemplateProject/InputOdd" outputPath = "digitizeBoekTemplateProject/OrderdInput" if not os.path.exists(outputPath): os.makedirs(outputPath) # Get the list of files in the input folders even_files = os.listdir(pathInputEven) odd_files = os.listdir(pathInputOdd) # Sort the photos by creation time even_files.sort(key=lambda x: os.path.getctime(os.path.join(pathInputEven, x))) odd_files.sort(key=lambda x: os.path.getctime(os.path.join(pathInputOdd, x))) print(even_files) print(odd_files) # Copy the files to the output folder and rename them counter = 0 for photo in even_files: shutil.copy(pathInputEven + "/" + photo, outputPath + "/" + str(counter) + ".jpg") counter += 2 counter = 1 for photo in odd_files: shutil.copy(pathInputOdd + "/" + photo, outputPath + "/" + str(counter) + ".jpg") counter += 2 print("Orderd the photos in OrderInput now creating the txt file") orderdPhotos = os.listdir(outputPath) txtFile = open(outputPath + "/OrderInputList.txt", "w") i = len(orderdPhotos) number = 0 while i > 0: txtFile.write(str(number) + ".jpg\n") number += 1 i -= 1 print("Klaar") TLDR: How do I keep the order of the foto's that I have taken and store this order in a .txt file? I am already working 3 days on this project (not this specific problem) and this is the last problem so if I you can help that would be predicated.
-
I know this isn't the correct forum, but I've looked everywhere. How can I have Python recognize handwriting with a custom dataset? I want to use it for script hebrew, and I can't find any datasets, of instructions on how to make your own dataset and use it.
-
List download links from archive.org directory
euro234 posted a topic in Programs, Apps and Websites
JDownloader doesn't work.- 10 replies
-
- networking
- wget
-
(and 1 more)
Tagged with:
-
Im making a simple game where you can shoot stars in pygame zero, but after a bit of time coding i ran the code, but i didnt see the stars. Is there any way to fix this? (please note that some of these things are temporarily and i will remove them later on in the project) import pgzrun import random import pygame WIDTH=800 HEIGHT=600 amount_of_stars=10 clicked=False def draw(): screen.blit("bg1",(0,0)) star1=Actor("star") star1.pos=random.randint(0,750),random.randint(0,550) def update(): global clicked mouse_x, mouse_y = pygame.mouse.get_pos() if clicked==True and star1.collidepoint(mouse_x, mouse_y): star1.pos=random.randint(0,750),random.randint(0,550) clicked=False #star.pos=random.randint(0,750),random.randint(0,550) pgzrun.go()
-
Budget (USD): $400 Country: United States, California Games, programs or workloads that it will be used for: PyTorch, Python, and Java Other details (existing parts:Storage and Ram): I am Building this pc for my mom who is getting into programing and coding and I am curious as to what parts to invest more into. I am looking at used and new parts This is more for planning than an actual hard set plan.
-
I'm wondering if someone can help me out by modifying this code so it automatically starts at say "1" and ends at say "1000000" and outputs the time it took to do the work to get there? Thank you. import time def nextInt(input1): cont = True try: input1 = int(input1) except: return 'ERROR' while cont: steps = 0 input2 = input1 while input2 != 1: steps += 1 if input2 % 2 == 0: input2 = input2 // 2 else: input2 = 3 * input2 + 1 value = [input1,steps, input2] print(value) time.sleep(0.0) if value[2] != 1: cont = False else: input1 += 1 nextInt(input('Input a integer: '))
-
Whenever i try pasting a .png file in vs code i get this error: Error loading webview: "Error: Could not register service worker: InvalidStateError: Failed to register a ServiceWorker: The document is in an invalid state.." I do not know what its trying to say. If its maybe a problem with my code heres my code: import pgzrun from random import randint WIDTH,HEIGHT = 600,500 bee=Actor(bee) def draw(): bee.draw()
-
So basically I have a main 2d array called grid filled with cell objects and I create a clone of this array called gridN for later use but when I set all of gridN's density to 0 the main grid's density is set to 0 aswell. class cell: x = 0 y = 0 den = 0 velX = 0 velY = 0 width = 10 height = 10 grid = [] for i in range(width): grid.append([]) for j in range(height): grid[i].append(cell()) grid[i][j].x = i grid[i][j].y = j def diffuse(k,grid): gridC = list(grid) gridN = list(grid) for i in range(width): gridN.append([]) for j in range(height): gridN[i].append(cell()) gridN[i][j].den = 0 print(gridN[0][0].den) grid[0][0].den = 100 diffuse(0.5,grid)
-
I work in a small factory in a lab - we got a smaller department that takes raw mats and makes a mat for use in line. the new mat "sheet" - the sheet can have different specs. it has a standard - each different "sheet" got different specs but all got a weighted color and other stuff in spec so it's the same pattren just diffrent standart. just started python but i want to create a digital way to keep data , check that the "sheet" is according to spec and have a way for techs to see problems and statistics and change spec as needed. 1.make gui useing pyqt\pyside to add\edit\delete sample and add\edit\delete standart plus statistics . 2. need some ind of file for standarts . 3. some db for all the tests ? maybe excel files for each ? (sheet a ,sheet b etc), any good db for? maybe sql? 4.the option for after adding a sample to db print a report for it - now each sample got a paper report that going in a binder. in the end i want both digital sofeware and and paper but maybe paper wont be needed? still a long road but is it possible to do? using pyqt openpyxl and others? i need guidance on what to learn and if possible not looking for anyone to write for me.
- 5 replies
-
- python
- graphical user interface
-
(and 1 more)
Tagged with:
-
Budget : £1000 Country: United Kingdom Games, programs or workloads that it will be used for: Valorant with some screen recording and light ML training and coding for personal projects( planning to dual boot with Ubuntu). Specs chosen: AMD Ryzen 5 7600x, Nvidia 4070 12GB ( MSI Ventus), MSI B650P pro WiFi motherboard, Corsair vengeance 32GB RAM (6000 Mhz CL36), Corsair RM 850, Corsair 4000D airflow Other details : I've a 240 Hz 1080p monitor, G pro Superlight and a decent mechanical keyboard. Doubts : is the 4070 an overkill? But downgrading my GPU makes sense if I downgrade my CPU too right? Also not sure about the PSU as well. I also need a cooler for the CPU, which would be best in a budget sense?
-
pswdic = { "A" : { "Username" : "AB1", "Password" : "12345" } "B" : { "Username" : "Cool1", "Password" : "qwerty!" } "C" : { "Username" : "No_scope", "Password" : "nO-ScOpE" } "D" : { "Username" : "Elite007", "Password" : "IAmSuperCool1" } Its giving me an error at line 2 at the first {. I dont know how to fix it, can someone please help?
-
Hi, I am looking into creating a mixture model based on the Generalised Extreme Value distribution (GEV). As opposed to a Gaussian Mixture Model, which is very popular and a Google search can help with most issues, creating a GEV mixture model is proving to be very difficult for me. I am not overly experienced in using Python, any analysis I've done to date was carried out using MATLAB, but for a number of reasons using Python makes more sense for this project. If anyone has any experience creating mixture models or clustering in general (It doesn't have to be GEV) I would really appreciate any advice you may have. The dataset I will be using is time-series data.
-
I am learning Python, but my only keyboard compatible device is my Chromebook. I have been using an online IDE to code, but I find the UI laid out odd. I know I could download the official Python IDE on my iPad, but my iPad doesn't support my USB keyboard and I can't afford a Bluetooth Keyboard/Keyboard Case.
- 3 replies
-
- chromeos
- chromebooks
-
(and 3 more)
Tagged with:
-
while True: ag=input("\nENTER E TO REROLL\n") if ag=="E" or ag=="e": for i in range(_q): r1=random.choice(list2) list1.append(r1) list2.remove(r1) print("LOADING...") time.sleep(2) os.system("clear") for i in list1: print(i, end="") elif ag=="!exit": break If i run this code, it gives me an error. How do i fix it and what am i doing wrong? Edit: There is more code. This is only a fracture of it. File "main.py", line 37 elif ag=="!exit": ^^^^ SyntaxError: invalid syntax
-
I have a concerning thing with a truenas scale server that is shutting down kinda randomly, and as a band aid fix I was hoping to use a pi zero w to short the pwr switch pins to turn it back on. BingGPT has been helpful and this is the code I have so far (I do not know how to code lol): import os import RPi.GPIO as GPIO import time import datetime GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) last_time = datetime.datetime.now() was_offline = False while True: response = os.system("ping -c 1 192.168.0.127") if response == 0: if was_offline: with open('log.txt', 'a') as f: f.write(f'{datetime.datetime.now()} - Device is back online\n') was_offline = False time.sleep(30) else: print('Device is offline') current_time = datetime.datetime.now() if (current_time - last_time).seconds >= 30: GPIO.output(18, GPIO.HIGH) with open('log.txt', 'a') as f: f.write(f'{datetime.datetime.now()} - Device is offline\n') time.sleep(2) GPIO.output(18, GPIO.LOW) last_time = current_time was_offline = True It works great, logs correctly, and does indeed hold the gpio pins turning on an led for testing. But I realized this is applying a voltage, and I intended to replace the LED with leads to the power switch, is that an issue applying a voltage there? And if so, how would I go about it, I saw something in a forum post about using a transistor, I currently have 2 2N3904 NPN transistors from a soldering starter project I did when I was younger, if those would work. If that is horrid I would very much appreciate a correction and guidance lol. Also not sure about the length of time needed, if 2 seconds is fine or 1 second, it works for testing but I dont want to fry anything. Thanks so much for any replies
-
I am programming a script in python that huddles words and prints them. I added a few lines of code to see this error. What did i do wrong? Edit: Line 27 is this code: r1=random.choice(list2)
-
this shouls be simple imho but after 5 days of breaking my head against it , i think i need some help. tbh i dont do OOP, but since python is as OOP as OOP goes under the hood. sometimes you have to... the end goal is to have a metaclass that inherits from type(makes classes) a baseclass for the metaclass that can serve as a blueprint for spinoffs of that class. every instance that gets created in the end should have this layout: a regular class instance , with 1 default attribute set, that is an instance attribute, not a class attribute (<= as a class attibute i can get it to work but thats not what i need) this attribute 'Data' should be a dict when an instance gets create trough one of the subclasses , they all add one attribute to the instance. . eg if an instance earth is created with the class 'planet' , it calls the constructor in the solarsystem class , that one in the galaxy class eg they would respectively set the attributes planet = earth , solarsystem=ours, galaxy=milkyway on the instance now on the instance the following methods should be overridden : __getattr__ __setattr__ __getitem__ __setitem__ __iter__ __contains__ __delitem__ __delattr__ __hash__ __len__ ... and they should work such that they no longer work on the attributes of the instance but on the one attribute that is the dict=> foo.something=1 should actually set foo.Data['something']=1 the problem i run into each time is that when i try to set the dict before the instance is created the dict becomes a class variable, and is shared by all instances , wich should not be the case. if i try to set it in the __init__ method. the rest of the methods is already overridden , and trying to create instance.Data . actually tries to create instance.Data.Data={} since it calls the setattr methond , and since there is no instance.Data yet it fails... here are some (in the mean time exfiltrated code im trying to get work , if for starters the get, set of both addr and item work as it should im a happy man. : breakpoint() class QBase(type): def __new__(cls, name, bases, attrs): print(f'QBase.__new__ called with {cls}:{name}:{bases}:{attrs}') return super().__new__(cls, name, bases, attrs) def __init__(s,*a,**k): super().__init__(*a,**k) class QBaseDict(metaclass=QBase): def __new__(cls, *args, **kwargs): return super().__new__(cls) def __init__(s,n,*a,**k): print(f'QBaseDict.__init__ called with {s},{n} ') s.Data=dict() super().__init__(*a,**k) def __setattr__(s, k, v): super().__setattr__(k,v) class QDict(QBaseDict): def __new__(cls, *args, **kwargs): return super().__new__(cls) def __init__(s,n,*a,**k): super().__init__(n,*a,**k) def __setattr__(s, k, v): s.Data[k]=v def test(n): t=QDict(n) return t a=test('foo') b=test('bar') b.Data['test']='ikkel' breakpoint() https://replit.com/@hoefkensj/customtypeproblems#main.py
-
Hello! You probably clicked on this forum post for a reason. So, If you need any ideas / examples / help with simple python stuff feel free to paste/look up solutions from my github! You cant learn anything from these, you still need a basic knowledge of what you're doing to paste/ understand my code! {This is not any kind of advertisement, i just want to help python beginners (just like me)} You can also find windows bsod code, (which i also commented on in the code) so beware! Please note that im not a python expert either, and i also dont really make comments in my code, becuase this was my first time making these kind of apps/script and It just popped into my head that maybe someone could get help from them.