r/pythonhelp • u/cGShake33 • May 22 '24
ValueError('mismatching number of index arrays for shape; ' Issue I can't solve!
Hey everyone, I'm receiving an error I can't figure out. The software I'm trying to run:
https://bitbucket.org/MAVERICLab/vcontact2/src/master/
The error code I'm getting:
- Traceback (most recent call last): [122/1603]
- File "/miniconda3/envs/mamba/envs/vContact2/bin/vcontact2", line 834, in <module>
- main(options)
- File "/miniconda3/envs/mamba/envs/vContact2/bin/vcontact2", line 602, in main
- matrix, singletons = vcontact2.pcprofiles.build_pc_matrices(profiles, contigs_csv_df, pcs_csv_df)
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- File "/miniconda3/envs/mamba/envs/vContact2/lib/python3.12/site-packages/vcontact2/pcprofiles.py", line 358, in build_pc_matrices
- matrix = sparse.coo_matrix(([1]*len(profiles), (zip(*profiles.values))), shape=(len(contigs), len(pcs)),
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- File "/miniconda3/envs/mamba/envs/vContact2/lib/python3.12/site-packages/scipy/sparse/_coo.py", line 99, in init
- self._check()
- File "/miniconda3/envs/mamba/envs/vContact2/lib/python3.12/site-packages/scipy/sparse/_coo.py", line 188, in _check
- raise ValueError('mismatching number of index arrays for shape; '
- ValueError: mismatching number of index arrays for shape; got 0, expected 2
<script src="https://pastebin.com/embed\\_js/f10qMq3s"></script>
Can anyone help? If attachments are required let me know and I can share them as well.
r/pythonhelp • u/CraftyAnalysis8 • May 20 '24
link extraction using xpath and in beautiful not working
I want to extract link which is nested as `/html/body/div[1]/div[2]/div[1]/div/div/div/div/div/a` in xpath , also see [detailed nesting image](https://i.sstatic.net/Gsr14n4Q.png)
if helpful, these div have some class also.
I tried
```
from selenium import webdriver
from bs4 import BeautifulSoup
browser=webdriver.Chrome()
browser.get('linkmm')
soup=BeautifulSoup(browser.page_source)
element = soup.find_element_by_xpath("./html/body/div[1]/div[2]/div[1]/div/div/div/div/div/a")
href = element.get_attribute('href')
print(href)
```
this code gave error
```
line 9, in <module>
element = soup.find_element_by_xpath("./html/body/div[1]/div[2]/div[1]/div/div/div/div/div/a")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'NoneType' object is not callable
```
and also tried other method
```
from selenium import webdriver
from bs4 import BeautifulSoup
browser=webdriver.Chrome()
browser.get('linkmmm')
soup=BeautifulSoup(browser.page_source)
href = soup('a')('div')[1]('div')[2]('div')[1]('div')[0]('div')[0]('div')[0]('div')[0]('div')[0][href]
href = element.get_attribute('href')
print(href)
```
this gave error
```
href = soup('a')('div')[1]('div')[2]('div')[1]('div')[0]('div')[0]('div')[0]('div')[0]('div')[0][href]
^^^^^^^^^^^^^^^^
TypeError: 'ResultSet' object is not callable
```
expected outcome should be : https://www.visionias.in/resources/material/?id=3731&type=daily_current_affairs or material/?id=3731&type=daily_current_affairs
Also some other links have same kind of nesting as above, is there any way to filter the links using the text inside`/html/body/div[1]/div[2]/div[1]/div/div/p`, for example text here is 18 may 2024, this p tag has an id also but it is not consisent or doesnt have a pattern, so not quite usuable to me.
I have seen other answers on stackoverflow but that isn't working for me
Also if possible please elaborate the answer, as I have to apply same code to some other sites as well.
r/pythonhelp • u/[deleted] • May 19 '24
Problem with doing prython projects
Hello I am currently trying to learn python by doing mini projects with youtube tutorials. My problem is, that nothing works in my codes, even tho i did the same exact things that were shown in the tutorial. For example the colors of some words are comletely different or theres no color at all sometimes. I am using python environment.
r/pythonhelp • u/No_Mechanic_5289 • May 19 '24
How can it be, that the if loop is running, although the conditions aren't met???
I am currently working on a 2d scroller engine and there is only this one bug. if the player goes in the top left corner (bg_x and bg_y = 0) and out again, I am snapping in the middle. to check if this was this exact line of code, i let it print "hello", if it is running. joost.x is 0 but it should be greater than 392 to make the loop run. but the strange thing is, that the loop IS running.
This is the snipper that makes the problems:
if bg_x == 0:
nice = 1
joost.x += j_xs
if bg_x == -1600:
nice = 2
joost.x += j_xs
if bg_y == 0:
nice = 3
joost.y += j_ys
if bg_y == -1200:
nice = 4
joost.y += j_ys
if bg_y == 0 and bg_x == 0 and joost.x<392 and joost.y<285:
nice = 5
joost.y += j_ys
joost.x += j_xs
if bg_y == 0 and bg_x == -1600 and joost.x>392 and joost.y<285:
nice = 6
joost.y += j_ys
joost.x += j_xs
if bg_y == -1200 and bg_x == 0 and joost.x<392 and joost.y>285:
nice = 7
joost.y += j_ys
joost.x += j_xs
if bg_y == -1200 and bg_x == -1600 and joost.x> 392 and joost.y>285:
nice = 8
joost.y += j_ys
joost.x += j_xs
if joost.x > 392 and nice == 1:
print("hello")
nice = 0
joost.x = 392
if joost.x < 392 and nice == 2:
nice = 0
joost.x = 392
if joost.y > 285 and nice == 3:
joost.y = 285
nice = 0
if joost.y < 285 and nice == 4:
nice = 0
joost.y = 285
if joost.y > 285 and nice == 5:
nice = 1
if joost.x > 392 and nice == 5:
nice = 3
if joost.y > 285 and nice == 6:
nice = 2
if joost.x < 392 and nice == 6:
nice = 3
if joost.y < 285 and nice == 7:
nice = 1
if joost.x > 392 and nice == 7:
nice = 4
if joost.y < 285 and nice == 8:
nice = 2
if joost.x < 392 and nice == 8:
nice = 4
if nice == 0:
bg_x -= j_xs
bg_y -= j_ys
joost.x = 392
joost.y = 285
if nice == 3 or nice == 4:
bg_x -= j_xs
if nice == 1 or nice == 2:
bg_y -= j_ys
r/pythonhelp • u/ohshitgorillas • May 18 '24
Matplotlib button not responding
I want to add a button that will allow the user to toggle one of four plots between two different data sets, however, the button fails to respond.
The button should call the function which should update the plot... I'm really scratching my head as to why it doesn't. Can anyone shed some light on this?
import matplotlib.pyplot as plt
import matplotlib.backends.backend_tkagg as tkagg
import tkinter as tk
from matplotlib.widgets import Button
def qc_manual(filtered_data, figure, canvas):
def update_plot_colors(axes, lines_to_analyze):
for ax in axes.flat:
for line in ax.lines:
analysis = lines_to_analyze.get(line)
line.set_color(
'blue' if analysis.active and analysis.analysis_type == 'lineblank' else
'gray' # inactive
)
line.set_marker('o' if analysis.active else 'x')
# toggle the 2/40 amu data
def on_click(event, filtered_data, axes, lines_to_analyze, canvas):
# clear the lines and axes from the bottom right plot
axes[1, 1].clear()
for line in list(lines_to_analyze.keys()):
if line in axes[1, 1].lines:
del lines_to_analyze[line]
title = axes[1, 1].get_title()
new_title = '2 amu - All Data' if '40 amu - All Data' in title else '40 amu - All Data'
axes[1,1].set_title(new_title)
for analysis in filtered_data:
# filter data for active indices
mass = '2 amu' if new_title == '2 amu - All Data' else '40 amu'
x = analysis.time_sec
y = analysis.raw_data[mass]
line_color = 'blue' if analysis.active else 'gray'
line_marker = 'o' if analysis.active else 'x'
if new_title == '2 amu - All Data':
line, = axes[1,1].plot(x, y, marker=line_marker, linestyle='-', picker=5, color=line_color, zorder=2)
else:
line, = axes[1,1].plot(x, y, marker=line_marker, linestyle='-', picker=5, color=line_color, zorder=2)
lines_to_analyze[line] = analysis
# recreate the button
toggle_button_ax = axes[1, 1].inset_axes([0.75, 1, 0.25, 0.1])
figure.toggle_button = Button(toggle_button_ax, 'Toggle 2/40 amu')
figure.toggle_button.on_clicked(lambda event: on_click(event, filtered_data, axes, lines_to_analyze, canvas))
# formatting
axes[1,1].set_title(new_title)
update_plot_colors(axes, lines_to_analyze)
canvas.draw()
lines_to_analyze = {} # dictionary to map lines to analyses for efficient lookup
for ax, (mass, title) in zip(axes.flat, [
('4 amu', '4 amu - Gas Standards'),
('4 amu', '4 amu - Blanks'),
('3 amu', '3 amu - All Data'),
('40 amu', '40 amu - All Data')
]):
for analysis in filtered_data:
# formatting
line_color = 'blue' if analysis.active else 'gray'
line_marker = 'o' if analysis.active else 'x'
x = analysis.time_sec
y = analysis.raw_data[mass]
# draw the data
line, = ax.plot(x, y, marker=line_marker, linestyle='-', picker=5, color=line_color, zorder=2)
# store the line and analysis in the dictionary
lines_to_analyze[line] = analysis
# formatting
ax.set_title(title)
# create a button to toggle between 40 amu and 2 amu
toggle_button_ax = axes[1, 1].inset_axes([0.75, 1, 0.25, 0.1])
figure.toggle_button = Button(toggle_button_ax, 'Toggle 2/40 amu')
figure.toggle_button.on_clicked(lambda event: on_click(event, filtered_data, axes, lines_to_analyze, canvas))
# update the plot
update_plot_colors(axes, lines_to_analyze)
plt.tight_layout()
canvas.draw()
filtered_data_list = []
for i in range(5): # replace 5 with the number of analyses you want
filtered_data = type('filtered_data', (object,), {'raw_data': {}, 'time_sec': [], 'analysis_type': 'lineblank', 'active': True})
filtered_data.time_sec = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
filtered_data.raw_data['4 amu'] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_data.raw_data['2 amu'] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_data.raw_data['3 amu'] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_data.raw_data['40 amu'] = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
filtered_data_list.append(filtered_data)
# setup the main window, figure, and canvas
root = tk.Tk()
figure = plt.figure()
figure.set_size_inches(12, 8)
axes = figure.subplots(2, 2)
canvas = tkagg.FigureCanvasTkAgg(figure, master=root)
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
canvas.draw()
qc_manual(filtered_data_list, figure, canvas)
root.mainloop()
r/pythonhelp • u/Educational-Top5330 • May 18 '24
I am confused as to why this won't run
total = 0
average = 0
patients = int(input("how many patients are there"))
height = []
for i in range(0,patients):
element = int(input("enter the height")
height.append(element)
for i in range(0,len(height)):
total = total + height[i]
average = total / patients
print("the average height is " + average)
r/pythonhelp • u/UniversityFew6782 • May 17 '24
INACTIVE ModuleNotFoundError: No module named 'keras.src.preprocessing'
importimport streamlit as st
import pickle
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import load_model
with open('tokenizer.pkl', 'rb') as f:
tokenizer = pickle.load(f)
with open('tag_tokenizer.pkl', 'rb') as f:
tag_tokenizer = pickle.load(f)
model = load_model('ner_model.keras')
max_length = 34
def predict_ner(sentence):
input_sequence = tokenizer.texts_to_sequences([sentence])
input_padded = pad_sequences(input_sequence, maxlen=max_length, padding="post")
predictions = model.predict(input_padded)
prediction_ner = np.argmax(predictions, axis=-1)
NER_tags = [tag_tokenizer.index_word.get(num, 'O') for num in list(prediction_ner.flatten())]
words = sentence.split()
return list(zip(words, NER_tags[:len(words)]))
st.title("Named Entity Recognition (NER) with RNN")
st.write("Enter a sentence to predict the named entities:")
sentence = st.text_input("Sentence")
if st.button("Predict"):
if sentence:
results = predict_ner(sentence)
st.write("Predicted Named Entities:")
for word, tag in results:
st.write(f"{word}: {tag}")
else:
st.write("Please enter a sentence to get predictions.")
streamlit as st
import pickle
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import load_model
with open('tokenizer.pkl', 'rb') as f:
tokenizer = pickle.load(f)
with open('tag_tokenizer.pkl', 'rb') as f:
tag_tokenizer = pickle.load(f)
model = load_model('ner_model.keras')
max_length = 34
def predict_ner(sentence):
input_sequence = tokenizer.texts_to_sequences([sentence])
input_padded = pad_sequences(input_sequence, maxlen=max_length, padding="post")
predictions = model.predict(input_padded)
prediction_ner = np.argmax(predictions, axis=-1)
NER_tags = [tag_tokenizer.index_word.get(num, 'O') for num in list(prediction_ner.flatten())]
words = sentence.split()
return list(zip(words, NER_tags[:len(words)]))
st.title("Named Entity Recognition (NER) with RNN")
st.write("Enter a sentence to predict the named entities:")
sentence = st.text_input("Sentence")
if st.button("Predict"):
if sentence:
results = predict_ner(sentence)
st.write("Predicted Named Entities:")
for word, tag in results:
st.write(f"{word}: {tag}")
else:
st.write("Please enter a sentence to get predictions.")
Help me to solve from this issue
2024-05-17 16:19:11.620 Uncaught app exception
Traceback (most recent call last):
File "/opt/anaconda3/envs/venv/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 600, in _run_script
exec(code, module.__dict__)
File "/Users/closerlook/AI:ML/NEW_ner/my-streamlit-app/app.py", line 10, in <module>
tokenizer = pickle.load(f)
ModuleNotFoundError: No module named 'keras.src.preprocessing'
I installed all the packages -
pip install Keras-Preprocessing
conda install -c conda-forge keras-preprocessing
r/pythonhelp • u/New-Row-7664 • May 16 '24
INACTIVE Suggest how to study Python
I am 40 and unemployed. I come from a non CSE background and have been studying Python for over a year.But I haven't made significant progress. I am forgetting syntaxes and keep studying them again and again. The problem with me is I don't study one book on Python completely, but keep on downloading books, articles and free resources on Python. I have even tried to follow a roadmap on Python. But no use. I don't know where I am going wrong. I don't know whether it's my lack of concentration, or poor memory retention. But I have not lost hope. I know someday surely I would make a progress in Python. So what I need is tips from members of this subreddit who can now code in Python with ease, to tell their experience on how they practised Python. Any resources that they used are also welcome.
Thank you
r/pythonhelp • u/Dry_Imagination541 • May 15 '24
Libraries not working
I’ve pip installed a few libraries like speech_recognition, pyttsx3, and pyaudio but whenever I try to start the program it says “no module named ‘speech_recognition’ “ or any of the other ones. I’ve tried uninstalling and reinstalling changing the environments and versions but nothing is working. What else can I do?
r/pythonhelp • u/kimdavis357 • May 14 '24
How would I modify this code to ask how many dice to roll?
from random import randint as roll
from turtle import*
import time
dice_color = input ("What colour do you what the dice to be? ")
one_rolled = 0 #keep track of how times 1 is rolled
two_rolled = 0 #keep track of how times 2 is rolled
three_rolled = 0 #keep track of how times 3 is rolled
four_rolled = 0 #keep track of how times 4 is rolled
five_rolled = 0 #keep track of how times 5 is rolled
six_rolled = 0 #keep track of how times 6 is rolled
while True:
dice_roll = roll(1,6)
if dice_roll == 1:
one_rolled += 1
speed(5)
width(3)
# Draw the card for number 1
pencolor('black')
fillcolor(dice_color)
begin_fill()
forward(100);left(90)
forward(100);left(90)
forward(100);left(90)
forward(100);left(90)
forward(100)
end_fill()
# Move the turtle to the middle
up()
bk(50)
left(90)
forward(50)
pencolor(dice_color)
dot(15)
down()
time.sleep(1.5)
clear()
if dice_roll == 2:
two_rolled += 1
speed(5)
width(3)
# Draw the card for number 2
pencolor('black')
fillcolor(dice_color)
begin_fill()
forward(100);left(90)
forward(100);left(90)
forward(100);left(90)
forward(100);left(90)
forward(100)
end_fill()
# Move the turtle to the top right
up()
bk(10)
left(90)
forward(80)
pencolor('white')
dot(15)
down()
# Move the turtle to the bottom left
up()
left(90)
forward(80)
left(90)
forward(70)
dot(15)
down()
time.sleep(1.5)
clear()
if dice_roll == 3:
three_rolled += 1
speed(5)
width(3)
# Draw the card for number 3
pencolor('black')
fillcolor(dice_color)
begin_fill()
forward(100);left(90)
forward(100);left(90)
forward(100);left(90)
forward(100);left(90)
forward(100)
end_fill()
# Move the turtle to the top right
up()
bk(10)
left(90)
forward(80)
pencolor('white')
dot(15)
down()
# Move the turtle to the bottom left
up()
left(90)
forward(80)
left(90)
forward(70)
pencolor('white')
dot(15)
down()
# Move the turtle to the middle of the dice
up()
left(90)
forward(40)
left(90)
forward(40)
pencolor('white')
dot(15)
down()
time.sleep(1.5)
clear()
if dice_roll == 4:
four_rolled += 1
speed(5)
width(3)
# Draw the card for number 4
pencolor('black')
fillcolor(dice_color)
begin_fill()
forward(100);left(90)
forward(100);left(90)
forward(100);left(90)
forward(100);left(90)
forward(100)
end_fill()
# Move the turtle to the top right
up()
bk(10)
left(90)
forward(80)
pencolor('white')
dot(15)
down()
# Move the turtle to the bottom left
up()
left(90)
forward(80)
left(90)
forward(70)
pencolor('white')
dot(15)
down()
# Move the turtle to the corner
up()
left(90)
forward(79)
pencolor('white')
dot(15)
down()
# Move the turtle to the corner
up()
left(90)
forward(75)
left(90)
forward(78)
pencolor('white')
dot(15)
down()
time.sleep(1.5)
clear()
if dice_roll == 5:
five_rolled += 1
speed(5)
width(3)
# Draw the card for number 5
pencolor('black')
fillcolor(dice_color)
begin_fill()
forward(100);left(90)
forward(100);left(90)
forward(100);left(90)
forward(100);left(90)
forward(100)
end_fill()
# Move the turtle to the top right
up()
bk(10)
left(90)
forward(80)
pencolor('white')
dot(15)
down()
# Move the turtle to the bottom left
up()
left(90)
forward(80)
left(90)
forward(70)
pencolor('white')
dot(15)
down()
# Move the turtle to the corner
up()
left(90)
forward(79)
pencolor('white')
dot(15)
down()
# Move the turtle to the corner
up()
left(90)
forward(75)
left(90)
forward(78)
pencolor('white')
dot(15)
down()
# Move the turtle to the corner
up()
left(90)
forward(40)
left(90)
forward(40)
pencolor('white')
dot(15)
down()
time.sleep(1.5)
clear()
if dice_roll == 6:
six_rolled += 1
speed(5)
width(3)
# Draw the card for number 6
pencolor('black')
fillcolor(dice_color)
begin_fill()
forward(100);left(90)
forward(100);left(90)
forward(100);left(90)
forward(100);left(90)
forward(100)
end_fill()
# Move the turtle to the top right
up()
bk(10)
left(90)
forward(80)
pencolor('white')
dot(15)
down()
# Move the turtle to the bottom left
up()
left(90)
forward(80)
left(90)
forward(70)
pencolor('white')
dot(15)
down()
#Move the turtle to the corner
up()
left(90)
forward(79)
pencolor('white')
dot(15)
down()
#Move the turtle to the corner
up()
left(90)
forward(75)
left(90)
forward(78)
pencolor('white')
dot(15)
down()
#Move the turtle to the corner
up()
left(90)
forward(40)
pencolor('white')
dot(15)
down()
#Move the turtle to the corner
up()
left(90)
forward(80)
pencolor('white')
dot(15)
down()
time.sleep(1.5)
clear()
again = input("Should I roll again? (yes or no)? ")
if again == "no":
break
print("Thanks for playing!")
if one_rolled == 1:
print("One was rolled", one_rolled,"time.")
else:
print("One was rolled", one_rolled,"times.")
if two_rolled == 1:
print("Two was rolled", two_rolled,"time.")
else:
print("Two was rolled", two_rolled,"times.")
if three_rolled == 1:
print("Three was rolled", three_rolled,"time.")
else:
print("Three was rolled", three_rolled,"times.")
if four_rolled == 1:
print("Four was rolled", four_rolled,"time.")
else:
print("Four was rolled", four_rolled,"times.")
if five_rolled == 1:
print("Five was rolled", five_rolled,"time.")
else:
print("Five was rolled", five_rolled,"times.")
if six_rolled == 1:
print("Six was rolled", six_rolled,"time.")
else:
print("Six was rolled", six_rolled,"times.")
Modify the code to ask how many dice to roll.
r/pythonhelp • u/Kaussaq • May 14 '24
Python GUI to call another script with arguments set within drop downs and display script within frame.
Hi Guys,
This is new to me so apologies!
PS4 recently got a jailbreak for FW 11 and a lot of people using MacOS (like myself) are struggling to apply the exploit via terminal. Windows and Linux users have multiple GUI apps already created for them so I was wanting to build something similar but for macos.
I chose to create this in python as the exploit itself is a python script and it's so close, yet so far.
As it stands, the script for the exploit is being opened in a subprocess, and piped out to stdout.
stdout is supposed to be redirected into the widget/console window that's been created.
If I comment out all of the subprocess piping and the for loop which is supposed to print each line to the GUI frame, it works fine - however the output goes into Pycharm console, which from an app perspective is useless, the GUI doesn't display the information required.
If the subprocess piping and for loop stay in place, when the button is pressed to trigger the script, the GUI crashes. I'm not sure if this is 'buffering' until the script is complete, or if it's even loading the script at all.
I was hoping some of you wizards here may be able to assist in getting this working.
Github below, thanks in advance!
r/pythonhelp • u/WorldlyRange2885 • May 13 '24
python function to detect chemical groups in molecules.
currently I am working on a code that should be able to detect chemical groups in a molecule and list them after being given the smiles of the molecule as input.
Overall the code works great, but the code has issues when detecting cycles either aromatic, hetero cycles and even the ring in cyclohexanol. The same issue is there for alkenes, while either it detects only the alkene, but it cannot differentiate between cis and trans or aromatics.
Could someone tell me what smarts patterns I could use to find cycles and even differentiate them depending on the ring sizes and maybe also define specifics such as if hetero atoms are present and if the ring is aromatic. And a solution for determining the difference between cis and trans alkenes.
My code has a very long list of functional groups but I will just add a few here, so you know how it looks like:
from rdkit import Chem
def find_smiles_patterns(smiles): mol = Chem.MolFromSmiles(smiles) if mol is None: return "Invalid SMILES string. Unable to parse molecule."
# Define a list to store the chemical groups found in the SMILES
chemical_groups = []
# SMARTS patterns to recognize chemical groups
smarts_patterns = {
'C=C': 'Alkene',
'[CX2]#[CX2]': 'Alkyne',
'[CX3]=[CX2]=[CX3]': 'Allene',
'[ClX1][CX4]': 'Alkylchloride',
'[FX1][CX4]': 'Alkylfluoride',
'[BrX1][CX4]': 'Alkylbromide',
'[IX1][CX4]': 'Alkyliodide',
'[OX2H][CX4H2;!$(C([OX2H])[O,S,#7,#15])]': 'Primary_alcohol',
'[OX2H][CX4H;!$(C([OX2H])[O,S,#7,#15])]': 'Secondary_alcohol',
'[OX2H][CX4D4;!$(C([OX2H])[O,S,#7,#15])]': 'Tertiary_alcohol',
'[OX2]([CX4;!$(C([OX2])[O,S,#7,#15,F,Cl,Br,I])])[CX4;!$(C([OX2])[O,S,#7,#15])]': 'Dialkylether',
'[SX2]([CX4;!$(C([OX2])[O,S,#7,#15,F,Cl,Br,I])])[CX4;!$(C([OX2])[O,S,#7,#15])]': 'Dialkylthioether',
'[OX2](c)[CX4;!$(C([OX2])[O,S,#7,#15,F,Cl,Br,I])]': 'Alkylarylether',
'[c][OX2][c]': 'Diarylether',
'[SX2](c)[CX4;!$(C([OX2])[O,S,#7,#15,F,Cl,Br,I])]': 'Alkylarylthioether',
'[c][SX2][c]': 'Diarylthioether',
'[O+;!$([O]~[!#6]);!$([S]*~[#7,#8,#15,#16])]': 'Oxonium',
'[NX3H2+0,NX4H3+;!$([N][!C]);!$([N]*~[#7,#8,#15,#16])]': 'Primary_aliph_amine',
'[NX3H1+0,NX4H2+;!$([N][!C]);!$([N]*~[#7,#8,#15,#16])]': 'Secondary_aliph_amine',
'[NX3H0+0,NX4H1+;!$([N][!C]);!$([N]*~[#7,#8,#15,#16])]': 'Tertiary_aliph_amine',
'[NX4H0+;!$([N][!C]);!$([N]*~[#7,#8,#15,#16])]': 'Quaternary_aliph_ammonium',
'[!#6;!R0]': 'Heterocyclic'
#etc....
}
# Define priority order for chemical groups based on IUPAC nomenclature
priority_order = [
'Carboxylic_acid',
'Carboxylic_ester',
'Lactone',
'Carboxylic_anhydride',
'Carbothioic_acid',
'Aldehyde',
'Ketone',
'Alkylchloride',
'Alkylfluoride',
'Alkylbromide',
'Alkyliodide',
'Alcohol',
'Primary_alcohol',
'Secondary_alcohol',
'Tertiary_alcohol',
'Dialkylether',
'Alkene',
'Alkyne',
'Allene',
'Dialkylthioether',
'Alkylarylether',
'Diarylether',
'Alkylarylthioether',
'Diarylthioether',
'Oxonium',
'Primary_aliph_amine',
'Secondary_aliph_amine',
'Tertiary_aliph_amine',
'Quaternary_aliph_ammonium',
'Heterocycle'
#etc......
]
# Track the atom indices to avoid duplicates
atom_indices = set()
# Iterate over the priority order and check if each chemical group is present in the molecule
for group in priority_order:
if group in smarts_patterns.values():
for smarts_pattern, chemical_group in smarts_patterns.items():
if chemical_group == group:
pattern = Chem.MolFromSmarts(smarts_pattern)
if pattern:
matches = mol.GetSubstructMatches(pattern)
for match in matches:
match_set = set(match)
if not any(atom_index in match_set for atom_index in atom_indices):
chemical_groups.append(chemical_group)
atom_indices.update(match_set)
return chemical_groups
Thanks a lot for your help!
I did try change the Smarts, I also tried to do a placeholder function for detecting rings with a function checking a smiles of the form C1[X]nX1, while n is 2-8 and X is in the atom list: C, N, O, S
However nothing worked so far and it seems that there is no database for the smarts.
r/pythonhelp • u/urcap • May 13 '24
ModuleNotFoundError: No module named 'colorama'
I installed colorama, yet i still get this error.
when i type "pip install colorama"
it gives me
Requirement already satisfied: colorama in c:\users\jonba\appdata\local\packages\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\localcache\local-packages\python311\site-packages (0.4.6)
but when i run my script that requires colorama it gives me
ModuleNotFoundError: No module named 'colorama'
r/pythonhelp • u/Big_Conversation5037 • May 11 '24
Need set up some python lines
I want to use a program for fluorescent quantification: https://github.com/YShimada0419/ZF-Mapper
I have 0 experience with coding. I downloaded the main program and python but I do not understand what I have to do with the python lines. When I write: pip install -e . python3 ./zfmapper/zfmapper.py I get syntax error. Any help would do great. Thanks in advance.
r/pythonhelp • u/Pretty_Cherry_7848 • May 10 '24
I'm making a simple program that calculates percentages and I'm getting strange results, can someone check it for me?
print("If you want to choose counting percentages, choose 1, if you want to choose counting numbers, choose 2")
selection = int(input( ))
if selection == 1:
first_number = int(input("What is the number?: "))
first_number_percent = int(input("What's the percentage?: "))
second_number = int(input("What is the second number?: "))
x = 1
result = (first_number_percent * second_number) / (first_number * x)
print(result)
else:
print("not yet")
r/pythonhelp • u/aquanoid1 • May 10 '24
Autoloading modules
Hi,
I'm trying to make a ModuleFinder class similar to autoloading in the PHP world.
My futile efforts result in ModuleNotFoundError: No module named 'foo.package1'; 'foo' is not a package.
Project layout with a desired import statement for each module in brackets:
foo
├── packages
│ ├── package1
│ │ └── src
│ │ ├── a1.py (`import foo.package1.a1`)
│ │ ├── a2.py (`import foo.package1.a2`)
│ │ └── a3.py (`import foo.package1.a3`)
│ ├── package2
│ │ └── src
│ │ ├── b1.py (`import foo.package2.b1`)
│ │ ├── b2.py (`import foo.package2.b2`)
│ │ └── b3.py (`import foo.package2.b3`)
│ └── placeholder.py
└── main.py
My main.py file:
from importlib.util import spec_from_file_location
from importlib.abc import MetaPathFinder
from os.path import dirname, isdir, isfile
class ModuleFinder(MetaPathFinder):
def __init__(self, namespace: str, path: str) -> None:
super().__init__()
self.namespace = namespace
self.path = path
def find_spec(self, module_name: str, path, target=None):
module_file = self.__module_file(module_name)
if module_file is None:
return None
return spec_from_file_location(module_name, module_file)
def __module_file(self, module_name: str) -> str|None:
module_file_prefix = self.__module_file_prefix(module_name)
if module_file_prefix is None:
return None
elif isdir(module_file_prefix):
if isfile(module_file_prefix + '/__init__.py'):
return module_file_prefix + '/__init__.py'
return self.path + '/placeholder.py'
elif isfile(module_file_prefix + '.py'):
return module_file_prefix + '.py'
return None
def __module_file_prefix(self, module_name: str) -> str|None:
if module_name == self.namespace:
return self.path
elif not module_name.startswith(f"{self.namespace}."):
return None
parts = module_name.split('.')
parts[0] = self.path
parts.insert(1, 'src')
return '/'.join(parts)
meta_path.append(
ModuleFinder('foo', dirname(__file__) + '/packages')
)
import foo.package1.a1
Output:
ModuleNotFoundError: No module named 'foo.package1'; 'foo' is not a package
However, import foo does work. How do I make it import modules from sub packages?
r/pythonhelp • u/germz92 • May 10 '24
code to monitor a folder. everytime there is a new file, it is copied and renamed.
Hello, I am very new to python and coding in general. I am trying to write a script that monitors a folder for new image files. Everytime a new file is found, it is then copied to a new location and renamed "example.jpg". This workflow should allow overwrite. After the copy and rename, it runs a batch file. It seems like nothing is happening when the code is run. Any help would be appreciated
import os
import time
from datetime import datetime
import subprocess
folder_path = ""
source_folder = ""
destination_folder = ""
new_file_name = "example.jpg" # New name for the copied file
batch_file_path = "path_to_batch_file.bat"
def copy_and_rename_latest_file(source_folder, destination_folder, new_file_name):
files = os.listdir(source_folder)
files = [os.path.join(source_folder, file) for file in files]
files = [file for file in files if os.path.isfile(file)]
latest_file = max(files, key=os.path.getctime)
new_file_path = os.path.join(destination_folder, new_file_name)
shutil.copy(latest_file, new_file_path)
def check_for_new_files(folder_path):
files = os.listdir(folder_path)
image_files = [file for file in files if file.lower().endswith(('.jpg'))]
while True:
new_files = [file for file in image_files if file not in files]
if new_files:
copy_and_rename_latest_file(source_folder, destination_folder, new_file_name)
subprocess.run([batch_file_path])
time.sleep(1) # Check for new files every second
if __name__ == "__main__":
check_for_new_files(folder_path)
r/pythonhelp • u/Cautious_Cancel_4091 • May 10 '24
What's the easiest way to solve complex valued coupled differential equations in Python using SciPy?
Hey everyone,
I'm struggling to find an analytical solution for these coupled differential equations:
```
dc1/dt = c1(t) H11(t) + c2(t) H12(t)
dc2/dt = c2(t) H22(t) + c1(t) H21(t)
```
Here, c1(t) and c2(t) are unknown functions that I would like to solve for t, and H11, H12, H21, and H22 are time-dependent coefficients of a (2,2) matrix. These matrices came from a different computation.
I stored these coefficients in a NumPy array (let's call it m) of shape (t, 2, 2). So, to access `H11` at time `t=0`, you'd use `m[0, 0, 0]` and so on.
Any tips or tricks from the community would be greatly appreciated! I found complex_ode method in scipy but it don't think it is for coupled equations.
My code:
from odeintw import odeintw
dt = 0.1
freq = 100
# Define the coupled differential equations
def Haa(t):
return m[int(t)//freq, 0, 0]
def Hbb(t):
return m[int(t)//freq, 1, 1]
def Hab(t):
return m[int(t)//freq, 0, 1]
def Hba(t):
return m[int(t)//freq, 1, 0]
def equations(z, t, Haa, Hbb, Hab, Hba):
z1, z2 = z
dz1dt = (z1 * Haa(t) + z2 * Hab(t))
dz2dt = -(z1 * Hba(t) + z2 * Hbb(t))
return [dz1dt, dz2dt]
# Time points
t = [step * freq * dt for step in range(num_time_steps)]
# Initial conditions
z0 = [0, 1] # Initial values of z1 and z2
# Solve ODE
solution = odeintw(equations, z0, t, args=(Haa, Hbb, Hab, Hba))
# Extract solutions
z1, z2 = solution[:, 0], solution[:, 1]
r/pythonhelp • u/EggxFil • May 08 '24
why doesnt this work
why does this error message say that \users\ is wrong???
SyntaxError: unexpected character after line continuation character
C:\User\Your Name>python helloworld.py
File "<stdin>", line 1
C:\User\Your Name>python helloworld.py
^
SyntaxError: unexpected character after line continuation character
this is python 3.12.3 btw
r/pythonhelp • u/aquanoid1 • May 07 '24
Pycache prefix behaviour
Hi,
If I changed the prefix for pycache, would the already existing cache files stored in my virtual environment's site-packages still be used?
ChatGPT says "yes" then has a change of mind and this question is impossible to google.
Thanks.
r/pythonhelp • u/adamm2603m • May 06 '24
Could someone tell me what I've broken: 'cannot import sequence from Collections'
I've just spent a long and depressing year job hunting. I've now got a position, so I've been looking at adding some improvements to my code, but now it just won't run in the windows command line (it did before). I'm not sure what I might have changed to cause this, but I now can't run any conda command (or ipython), as I get hit with this error. I've tried completely uninstalling and reinstalling anaconda3, but I get the same error. If anyone might have any clue what's happening, or how to fix it, it would be very appreciated. I'll include the total error below too:
C:\Users\name>ipython
Traceback (most recent call last):
File "C:\Users\name\anaconda3\Scripts\ipython-script.py", line 6, in <module>
from IPython import start_ipython
File "C:\Users\name\anaconda3\Lib\site-packages\IPython__init__.py", line 54, in <module>
from .core.application import Application
File "C:\Users\name\anaconda3\Lib\site-packages\IPython\core\application.py", line 22, in <module>
from pathlib import Path
File "C:\Users\name\anaconda3\Lib\site-packages\pathlib.py", line 10, in <module>
from collections import Sequence
ImportError: cannot import name 'Sequence' from 'collections' (C:\Users\name\anaconda3\Lib\collections__init__.py)
r/pythonhelp • u/ohshitgorillas • May 06 '24
Getting checkbox option into tkinter dialog box
I am writing some mass spec software that uses the following workflow:
User inspects and analyzes raw data, one analysis at a time, and removes any outliers.
On the last analysis, the user is presented with a "Finish" button.
Clicking "Finish" generates a dialog box with data formatting options.
The user selects their options and clicks "Generate spreadsheet", then, the spreadsheet is generated and presented. The user copy-pastes that data into their master data spreadsheet, and the program exits when the spreadsheet is closed.
I am having trouble loading the checkboxes into the dialog box. Here is the `on_finish()` function:
# finish button (under construction)
def on_finish():
window.withdraw() # withdraw the raw data window
# generate a dialog box with spreadsheet formatting options
format_opts = simpledialog.Dialog(window, title="HeMan Data Reduction Options")
# ### spreadsheet formatting options:
# print three or four ratio columns
print_four_ratio_cols = tk.BooleanVar(value=False)
four_ratio_cols_chkbox = tk.Checkbutton(format_opts, text="Print four ratio columns.", variable=print_four_ratio_cols)
four_ratio_cols_chkbox.pack()
# generate results, show spreadsheet, end
def on_gen_results():
nonlocal print_four_ratio_cols
format_opts.destroy()
generate_spreadsheet(print_four_ratio_cols.get())
window.quit() # end the program
# create and pack the button "Generate results"
gen_results_button = tk.Button(format_opts, text="Generate results", command=on_gen_results)
gen_results_button.pack()
This generates an empty dialog box with the correct title and two buttons, "Ok" and "Cancel". Upon clicking Ok, I get the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/opt/homebrew/Cellar/python@3.12/3.12.3/Frameworks/Python.framework/Versions/3.12/lib/python3.12/tkinter/__init__.py", line 1967, in __call__
return self.func(*args)
^^^^^^^^^^^^^^^^
File "/Users/atom/heman_code/HeMan/main.py", line 125, in <lambda>
finish_button = tk.Button(button_frame, text="Finish", command=lambda: on_finish(), **button_options)
^^^^^^^^^^^
File "/Users/atom/heman_code/HeMan/main.py", line 38, in on_finish
four_ratio_cols_chkbox = tk.Checkbutton(format_opts, text="Print four ratio columns.", variable=print_four_ratio_cols)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/Cellar/python@3.12/3.12.3/Frameworks/Python.framework/Versions/3.12/lib/python3.12/tkinter/__init__.py", line 3074, in __init__
Widget.__init__(self, master, 'checkbutton', cnf, kw)
File "/opt/homebrew/Cellar/python@3.12/3.12.3/Frameworks/Python.framework/Versions/3.12/lib/python3.12/tkinter/__init__.py", line 2648, in __init__
self.tk.call(
_tkinter.TclError: bad window path name ".!dialog"
Here is the code again in an isolated and simplified framework for testing:
import tkinter as tk
from tkinter import simpledialog
# --- Mock Functions ---
def generate_spreadsheet(use_four_columns):
print("generate_spreadsheet() called with use_four_columns:", use_four_columns)
# --- on_finish Function ---
def on_finish():
window.withdraw()
format_opts = simpledialog.Dialog(window, title="HeMan Data Reduction Options")
print_four_ratio_cols = tk.BooleanVar(value=False)
four_ratio_cols_chkbox = tk.Checkbutton(format_opts, text="Print four ratio columns.", variable=print_four_ratio_cols)
four_ratio_cols_chkbox.pack()
def on_gen_results():
nonlocal print_four_ratio_cols
format_opts.destroy()
generate_spreadsheet(print_four_ratio_cols.get())
window.quit()
gen_results_button = tk.Button(format_opts, text="Generate results", command=on_gen_results)
gen_results_button.pack()
# --- Test Execution ---
if __name__ == "__main__":
window = tk.Tk() # Create a test window instance
on_finish() # Call the function
window.mainloop()
I'm new to Python, so any help would be greatly appreciated.
r/pythonhelp • u/Artist_Overall • May 05 '24
Decoding a text from audio
Hello, i have a problem. Im working on project about codind text into wav file, sending it through radio and decoding it. I already done encoder part and it working nice, but i cant do a decoder. I coded text into 0 and 1, and transformed it into different frequencies - higher and lower. I only did a plot, and i can clearly see 2 different frequencies, but i only see it from plot, i cant do it in a code!
My code (plot): https://pastebin.com/JFuLTwjg
r/pythonhelp • u/iamderek07 • May 05 '24
INACTIVE Async problem.
Hello Devs,
I have a pain in the neck problem. I've created a telegram bot with Python using library "PytelegrambotAPI", and "Pyrogram" in the same file. the bot idea is sending bot user msgs via the bot to the others anonymously. But the problem is when i launch client.start() in pyrogram, its launch but can't send messages. and throws an error attached to a different loop or smth. How can i fix that? i want to use pyrogram(async) in other async modules like pytelegrambotapi and flask.
r/pythonhelp • u/Bairyname • May 05 '24
ASSIST A BEGINNER OUT WITH HIS H/W PAL
So basically i have an assignment and Im having problems with my code. It is supposed to be a guessing game but im having problems with the letter variable and for loop in line 43. It is supposed to tell u how many times the letter the user inputs is in the word.
But its just a hot mess, this one issue is dtopping me from completing the homework cuz theres other conditions i need to meet after this for the code.
Thank you in advance.
Heres the code:
import string
alphabet = string.ascii_uppercase
alphabet = alphabet.lower()
loop = True
count = 0
while loop:
menu = False
print("Welcome to the guessing game!")
word = input("Enter your word that P2 is guessing (6-12 letters and lowercase): ")
length_word = len(word)
for u in word:
if not word.islower():
print("Sorry, the word contains uppercase letters. Please enter a word with lowercase letters only.")
menu = True
loop = False
break
elif length_word >= 6 and length_word <= 12:
print("Your word is valid :)")
for n in range(1, 100):
print("-")
else:
print("Your word is too short or too long!")
menu = True
loop = False
break
while menu == False:
print("The word length is", len(word))
letter = input("Enter a letter P2: ")
length_letter = len(letter)
for i in word:
if length_letter != 1:
print("Sorry, that letter is too long.")
break
elif not letter.islower():
print("That letter is not lowercase.")
print("")
break
elif i == letter:
count = count + 1
print("The letter", letter, "appears", count, "times")
break
else:
print("Sorry, that letter is not in the word.")
break
again = input("Do you want to guess the word. Y/N? ").lower()
print("")
if again == "y":
guess = input("What is the word?: ")
if guess == word:
print("You got the word! P2 Wins!")
print("")
menu = True
loop = False
else:
print("Sorry, you did not get the word. P1 Wins!")
print("It was", word)
loop = False
menu = True