Python taking a bit long and weird? - python-2.7

I'm new to python.
Again, uh..I apologize for the noobnes.
so, I have the following script
Basically I'm trying to learn by making projects, for example a .py that changes your wallpaper, plays a creepy sound and shows a 'message box'. and it repeats for 3 times.
import ctypes
from ctypes import wintypes as w
from playsound import playsound
count = 0
while (count < 3):
count = count + 1
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, "horror.jpg" , 0)
user32 = ctypes.WinDLL('user32')
MessageBox = user32.MessageBoxW
MessageBox.argtypes = w.HWND,w.LPCWSTR,w.LPCWSTR,w.UINT
MessageBox.restype = ctypes.c_int
MessageBox(None, u'works 3 times', u'test:', 0)
playsound('cursed.mp3')
my question would be : why is it working so slow or what am I doing wrong ?
For example, it firsts changes the wallpaper and shows the notification...after I click ok it plays the sound :/
Then it repeats...but it takes like 2 seconds in-between-commands...if that makes sense...I apologise for the extreme stupid question, but I would like some clarification...Have I skipped the 'syntax' class ?

Related

NLTK regex parser's output has changed. Unable to parse phrases like verb followed by a noun

I have written a piece of code to parse the action items from a troubleshooting doc.
I want to extract phrases that start with a verb and end with a noun.
It was working as expected earlier (a month ago). But on running against the same input as earlier, its missing some action items that it was catching previously.
I haven't changed the code. Has something changed from nltk or punkt side that may be affecting my results?
Please help me figure what needs to be changed to make it run as earlier.
import re
import nltk
from nltk.tokenize import PunktSentenceTokenizer
from nltk.tokenize import word_tokenize
#One time downloads
#nltk.download('punkt')
#nltk.download('averaged_perceptron_tagger')
#nltk.download('wordnet')
custom_sent_tokenizer = PunktSentenceTokenizer()
def process_content(x):
try:
#sent_tag = []
act_item = []
for i in x:
print('tokenized = ',i)
words = nltk.word_tokenize(i)
print(words)
tagged = nltk.pos_tag(words)
print('tagged = ',tagged)
#sent_tag.append(tagged)
#print('sent= ',sent_tag)
#chunking
chunkGram = r"""ActionItems: {<VB.>+<JJ.|CD|VB.|,|CC|NN.|IN|DT>*<NN|NN.>+}"""
chunkParser = nltk.RegexpParser(chunkGram)
chunked = chunkParser.parse(tagged)
print(chunked)
for subtree in chunked.subtrees(filter=lambda t: t.label() == 'ActionItems'):
print('Filtered chunks= ',subtree)
ActionItems = ' '.join([w for w, t in subtree.leaves()])
act_item.append(ActionItems)
chunked.draw()
return act_item
except Exception as e:
#print(str(e))
return str(e)
res = 'replaced rev 6 aeb with a rev 7 aeb. configured new board and regained activity. tuned, flooded and calibrated camera. scanned fi rst patient with no issues. made new backups. replaced aeb board and completed setup. however, det 2 st ill not showing any counts. performed all necessary tests and the y passed . worked with tech support to try and resolve the issue. we decided to order another board due to lower rev received. camera is st ill down.'
tokenized = custom_sent_tokenizer.tokenize(res)
tag = process_content(tokenized)
With the input as shared in the code, earlier, the following action items were being parsed:
['replaced rev 6 aeb', 'configured new board', 'regained activity', 'tuned , flooded and calibrated camera', 'scanned fi rst patient', 'made new backups', 'replaced aeb board', 'completed setup', 'det 2 st ill', 'showing any counts', 'performed all necessary tests and the y', 'worked with tech support']
But now, only these are coming up:
['regained activity', 'tuned , flooded and calibrated camera', 'completed setup', 'det 2 st ill', 'showing any counts']
I finally resolved this by replacing JJ. with JJ|JJR|JJS
So my chunk is defined as :
chunkGram = r"""ActionItems: {<VB.>+<JJ|JJR|JJS|CD|NN.|CC|IN|VB.|,|DT>*<NN|NN.>+}"""
I dont understand this change in behavior.
Dot (.) was a really good way of using all modifiers on a POS

How do I give __init__ the arguments it wants?

I am trying to draw a sine wave as a beginner python project. So far everything was going as smoothly as possible for me, but when I started working on drawing lines between points, I started to get the Error mentioned below, which hasnt happened before. As I am fairly new to programming in general, I don't understand a) what __init__() is and does and b) what it means by "arguments" and where I am giving it too many/of the wrong kind (also I dont really know what a class is so try to keep your answer simple)
As stated before, the program used to work fine under python 2.7 on windows 10 64bit until I added the
l = Line(prex, prey, x, truey)
l.draw(win)
bit.
I have tried putting everything in a seperate class as I have seen it work in a similar example, this has however only led to more problems and confusion and since it didnt sem to help I have abandoned this approach.
I have tried googling and looking on the internet but I havent found anything that has satisfied me.
from math import sin
from graphics import *
def main():
global x #sets up variables and defines start values
global y
global truey #used for drawing points
global prex #used for drawing lines between points
global prey #used for drawing lines between points
truey = 1
x = 1
y = 1
prex = 0
prey = 0
win = GraphWin("Sin wave", 1000, 500) #creates the window
for i in range(1, 1000): #repeats the "logic"
x = x + 2.3 #goes along the x-axis to repeat calculations
y = sin(x) #calculates y-value which will be used later
truey = (y * 100) + 100 #calculates actual y value used to draw
c = Circle(Point(x, truey),2) #draws a point to represent wave
l = Line(prex, prey, x, truey) #connects points with lines, WIP
l.draw(win) #draws the line, WIP
c.setFill("black") #fills "points"
c.draw(win) #draws circles
print truey
win.getMouse() #keeps window open
win.close() #keeps window open
main()
And the error I get is:
Traceback (most recent call last):
File "C:/Users/Lion/.PyCharmCE2018.2/config/scratches/Sin wave.py", line 31, in <module>
main()
File "C:/Users/Lion/.PyCharmCE2018.2/config/scratches/Sin wave.py", line 23, in main
l = Line(prex, prey, x, truey)
TypeError: __init__() takes exactly 3 arguments (5 given)
Process finished with exit code 1

How to fix 'NoneType' object is not subscriptable' error in while loop

Windows 10
Python 3.7
Anaconda 1.9.7
Spyder 3.3.3
PsychoPy for Python 2.7
I am coding an experiment that needs to present images in a random order for the participant to respond to. I am able to get the images in an array, but to present them one at a time I am using a while loop with a variable that increases by 1 every time it goes through the loop. It is not recognizing the variable as a number and therefore the array cannot call anything.
I've tried not randomizing the variable to see if that is the issue, but it just seems to be that my variable i is not being read as a number
#import packages
import random, os
from psychopy import core, visual, event
from PIL import Image
#setup screen with specs and draw
win = visual.Window([400, 300], monitor="testMonitor")
message = visual.TextStim(win, text="")
message.draw()
win.flip()
core.wait(3.0)
#set image size and populate array with images
stim_size = (0.8, 0.8)
image = [i for i in os.listdir('C:/Users/*/psychopy-tests')
if i.endswith('.bmp')]
#randomize image order
images = random.shuffle(image)
this is where my issue seems to be
i = 0
while i != 29: #there are only 28 images
new = images[i] #this is where the issue is
image_stim = Image.open(new)
stim = visual.ImageStim(win, image_stim, size = (stim_size))
stim.draw()
win.update()
output = []
if event.getKeys(keyList=['space']):
output[i] = 1
if event.getKeys(['escape']):
win.close()
core.quit()
if event.getKeys(keyList=None):
output[i] = 0
core.wait(5.0)
i = i + 1
The random.shuffle shuffles in place and doesn’t return anything i.e., It returns None.
Therefor images is None and not subscriptable.
source

Feedback requested: Global variables or classes in python2.7 countdown timer for Raspberry Pi

This is my first post to Stack Overflow. I started working with python 2.7 roughly 3 weeks ago and this is my first attempt at creating something in code (I have some basic experience with the Arduino IDE). Although the countdown timer now works for my purposes, I think I can make the code a lot better, especially where I keep declaring my global variable for color so that my digits appear to be flashing (red to black to red every second). I think I might need to use a class for color, but I don't know how. Would you have any tips for me?
This code is just bits and pieces collected and sewn together from code I found in online guides, mainly from this one: https://www.element14.com/community/community/code_exchange/blog/2012/12/17/raspberry-pi-workout-timer
Any feedback would be greatly appreciated, especially on any beginner mistakes I might be making.
All the best,
Katrien
digit_colour = pygame.Color(0, 255, 0)
# Colon between minutes and seconds
pygame.draw.rect(screen, digit_colour, pygame.Rect(left_offset + 2*(2*offset + digit_width), top_offset + offset + led_width / 2 - led_height, led_height, led_height))
pygame.draw.rect(screen, digit_colour, pygame.Rect(left_offset + 2*(2*offset + digit_width), top_offset + 3*offset + 3 * led_width / 2 - led_height, led_height, led_height))
print "Time is up!"
for j in range(0, timeIsUp):
# Draw time on screen
def colourChange():
global digit_colour
digit_colour = pygame.Color(255, 0, 0)
colourChange()
draw_time(screen, 0)
pygame.display.flip()
time.sleep(1)
def colourChange():
global digit_colour
digit_colour = pygame.Color(0, 0, 0)
colourChange()
draw_time(screen, 0)
pygame.display.flip()
time.sleep(1)
if __name__ == '__main__': main()
Hi I am new to and have experience with arduino IDE. You could've done a raw input asking you how long the countdown timer should last. And then you could have a loop with a minus -1 and a time.sleep(1) and a print of the time left example
import time
minutes = raw_input("Minutes? ")
seconds = raw_input("Seconds? ")
time = minutes*60 + seconds
while(remaintime = True)
time-1
time.sleep(1)
print(time," seconds left")
if time<0
remaintime = False
print("time out")
This is a much simpler countdown clock but it works!

Bokeh figure doesn't show

I am new to python. I tried the example given in here http://docs.bokeh.org/en/latest/docs/gallery/color_scatter.html with my own dataset, which looks like this
Unnamed: 0 fans id stars
0 0 69 18kPq7GPye-YQ3LyKyAZPw 4.14
1 1 1345 rpOyqD_893cqmDAtJLbdog 3.67
2 2 105 4U9kSBLuBDU391x6bxU-YA 3.68
3 3 2 fHtTaujcyKvXglE33Z5yIw 4.64
4 4 5 SIBCL7HBkrP4llolm4SC2A 3.80
here's my code:
import pandas as pd
from bokeh.plotting import figure, show, output_file
op = pd.read_csv('FansStars.csv')
x = op.stars
y = op.fans
radii = 1.5
colors = ["#%02x%02x%02x" % (int(r), int(g), 150) for r, g in zip(50+2*x, 30+2*y)]
TOOLS="hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,tap,save,box_select,poly_select,lasso_select,"
p = figure(tools=TOOLS)
p.scatter(x, y, radius=radii,
fill_color=colors, fill_alpha=0.6,
line_color=None)
output_file("color_scatter.html", title="color_scatter.py example")
show(p)
However, when I run this code, I get no error and a webpage is opened, but BLANK. On reloading several times, I can finally see the tools, but that's all.
Can anyone tell me where am I going wrong?
Thanks!
I cant replicate this on Python 3.4 with Bokeh 0.12.3. So in that way, your code seems fine. I tried it both in the notebook (output_notebook) and to a file like you do and both seem to work fine.
The radius of 1.5 which you specify is taken in data units (x apparently), this makes the circles extremely big, covering the entire screen at first render. But using the wheelzoom to zoom out a bit reveals all circles as expected. Here is what your code looks like in Firefox for me (after zooming out):