Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
QuarkJets
Sep 8, 2008

Emacs Headroom posted:

A few more advantages of notebooks (a non-exhaustive list):

1. Very quick iteration time -- instead of "edit script, save script, run script, look at plots, repeat", it's "edit cell, hit shift-enter, repeat"

Oh come on, really? "Save script, run script, look at plots" is one keystroke in any competent IDE

I feel like I'm watching one of those goofy infomercials where they try to sell you a product by showing people getting flummoxed by basic tasks, with the promise that everything will be so much easier if you just buy this special bread knife or some sort of human grazing muzzle or whatever



(I'm not trying to poke fun, the superfluous steps in your example just really gave me that infomercial vibe and I loving love infomercial GIFs)

Adbot
ADBOT LOVES YOU

Cingulate
Oct 23, 2012

by Fluffdaddy
Maybe if you look at it like this ...

A paper certainly has some value in communicating the results of an analysis. Now imagine a format which has all of the information in the paper, but instead of there only being a description of the code, there is the actual code, right at your fingertips. And you can not only look at the code and read it along with the output it gave, you can also, depending on a few circumstances, re-run specific analysis stages under manipulation of certain parameters, or do follow-up analyses building on the total output.

An IDE is for developing. The notebook is for developing, visualising, communicating/presenting, all at once. I don't think anybody will argue IDEs are not better at the single thing they do, but I'd be surprised if you would really claim notebooks are not really good at the other things they do, and that there are scenarios where the combination of these has some nice synergies.

QuarkJets
Sep 8, 2008

Cingulate posted:

Maybe if you look at it like this ...

A paper certainly has some value in communicating the results of an analysis. Now imagine a format which has all of the information in the paper, but instead of there only being a description of the code, there is the actual code, right at your fingertips. And you can not only look at the code and read it along with the output it gave, you can also, depending on a few circumstances, re-run specific analysis stages under manipulation of certain parameters, or do follow-up analyses building on the total output.

An IDE is for developing. The notebook is for developing, visualising, communicating/presenting, all at once. I don't think anybody will argue IDEs are not better at the single thing they do, but I'd be surprised if you would really claim notebooks are not really good at the other things they do, and that there are scenarios where the combination of these has some nice synergies.

Yeah, I agree with everything in your post. Notebooks are the "jack of all trades" utility for a scientific analysis, basically.

Cingulate
Oct 23, 2012

by Fluffdaddy
I accept it was dumb to say all science in Python should be done in the notebook. The statement reflects my specific circumstances.

FoiledAgain
May 6, 2007

I have another Qt question. I have enabled Drag and Drop so that a user can re-arrange rows and columns in a TableView. How do I commit these changes to the TableModel? Everything that I can find on google about editing a table has to do with editing individual cells, which requires a Delegate. I don't need that. I just want to change the order of the rows/columns. The fact that no one else has asked this question to StackExchange makes me think it's something very basic that I'm missing.

Melian Dialogue
Jan 9, 2015

NOT A RACIST
Im currently learning Python through a coursera course for data analysis, but one of my reasons for learning Python over my last attempt at learning R was because of Python's seemingly bigger use for automating tasks and other stuff (while R seemed to be much more on hardcore stats and data analysis only).

One task I have that I want to tackle automating is where, I'll get a dump of .docx files in a networked folder. They are all formatted in a specific style with usually the title written in all caps with an underscore, and then a couple paragraphs, and then a signature block at the bottom. I have to take these word documents, go into an Excel spreadsheet thats formatted like a documents log, and manually copy and paste the title into a column labelled titles, copy the body of the work into a column for body, dates, times etc. and do these for each file. Basically I am creating a mini-database of all these reports by hand.

Yes I realize that this is an incredibly stupid process that ought to be fixed at a level above mine, but at the same time Im interested in learning more Python automation to teach myself to work within these environments that are very computer-averse.

Now I know that .docx files are essentially zipped files of XML based formatted text, so that there should be a library or function I can use to read and automate the extraction of the Headers, body, etc., but then also I need a way for it to populate a .CSV or Excel file.

QuarkJets
Sep 8, 2008

Sounds pretty straightforward to me. Check out docx2txt for dumping the raw text to an ascii format. From there it's all a matter of intelligently extracting the pieces that you want, but it sounds like you have some good ideas of how to do this. Once you've identified what everything is, dumping it to a CSV is extremely easy

Proteus Jones
Feb 28, 2013



QuarkJets posted:

Sounds pretty straightforward to me. Check out docx2txt for dumping the raw text to an ascii format. From there it's all a matter of intelligently extracting the pieces that you want, but it sounds like you have some good ideas of how to do this. Once you've identified what everything is, dumping it to a CSV is extremely easy

re: CSV. There the builtin 'csv'. I use it all the time and it's very easy to use. Or there's always the option to write it out as a standard file just separating the elements with a ',' and manually adding a '\r\n' at the end of each row. But that seems like a lot of work compared to just using csv.

Superdawg
Jan 28, 2009
I'm not sure if this has been asked before, but I'm not sure exactly what I would be searching for.

When I have a list of things and I iterate through it and remove things, I notice that my for loops don't iterate over the whole list. Is it specifically because I'm performing a remove on the same list I'm iterating over?

Example:
code:
>>> testList = []
>>> for count in [1,2,3,4,5,6,7,8,9,10,11,12]:
...   testList.append("Count: %s" % count)
...
>>> while (len(testList)):
...   i = 0
...   print "Length: %s" % len(testList)
...   for item in testList:
...     print "%s item %s" % (i, item)
...     testList.remove(item)
...     i += 1
...
Output:
code:
Length: 12
0 item Count: 1
1 item Count: 3
2 item Count: 5
3 item Count: 7
4 item Count: 9
5 item Count: 11
Length: 6
0 item Count: 2
1 item Count: 6
2 item Count: 10
Length: 3
0 item Count: 4
1 item Count: 12
Length: 1
0 item Count: 8
My guess is that yes, it is because I am removing things. When I don't remove things, the for loop seems to work fine.
code:
>>> testList = []
>>> for count in [1,2,3,4,5,6,7,8,9,10,11,12]:
...   testList.append("Count: %s" % count)
...
>>> i = 0
>>> print "%s items remaining" % len(testList)
12 items remaining
>>> for item in testList:
...   print "%s: Use %s to check something, and if it passes then remove it" % (i, item)
...   i += 1
...
Output:
code:
0: Use Count: 1 to check something, and if it passes then remove it
1: Use Count: 2 to check something, and if it passes then remove it
2: Use Count: 3 to check something, and if it passes then remove it
3: Use Count: 4 to check something, and if it passes then remove it
4: Use Count: 5 to check something, and if it passes then remove it
5: Use Count: 6 to check something, and if it passes then remove it
6: Use Count: 7 to check something, and if it passes then remove it
7: Use Count: 8 to check something, and if it passes then remove it
8: Use Count: 9 to check something, and if it passes then remove it
9: Use Count: 10 to check something, and if it passes then remove it
10: Use Count: 11 to check something, and if it passes then remove it
11: Use Count: 12 to check something, and if it passes then remove it
So two questions.

1. Am I right in my understanding?
2. I don't see any problems in the results I get when I do this (except weird logs), but is there a better way to iterate over the list and remove items midway through?

Superdawg fucked around with this message at 19:18 on Oct 4, 2015

overeager overeater
Oct 16, 2011

"The cosmonauts were transfixed with wonderment as the sun set - over the Earth - there lucklessly, untethered Comrade Todd on fire."



Superdawg posted:

Is it specifically because I'm performing a remove on the same list I'm iterating over?

So two questions.

1. Am I right in my understanding?
2. I don't see any problems in the results I get when I do this (except weird logs), but is there a better way to iterate over the list and remove items midway through?

Yeah, don't modify lists while iterating over them. The docs explain what's happening:

quote:

Note: There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.:

code:
for x in a[:]:
    if x < 0: a.remove(x)

Superdawg
Jan 28, 2009
Makes sense. Thanks for the help.

I have made the adjustment and confirmed that the issue does not show anymore.

code:
>>> testList = []
>>> for count in [1,2,3,4,5,6,7,8,9,10,11,12]:
...   testList.append("Count: %s" % count)
...
>>> while (len(testList)):
...   i = 0
...   print "%s items remaining" % len(testList)
...   for item in testList[:]:
...     print "%s: Use %s to check something, and if it passes then remove it" % (i, item)
...     testList.remove(item)
...     i += 1
...
Output:
code:
12 items remaining
0: Use Count: 1 to check something, and if it passes then remove it
1: Use Count: 2 to check something, and if it passes then remove it
2: Use Count: 3 to check something, and if it passes then remove it
3: Use Count: 4 to check something, and if it passes then remove it
4: Use Count: 5 to check something, and if it passes then remove it
5: Use Count: 6 to check something, and if it passes then remove it
6: Use Count: 7 to check something, and if it passes then remove it
7: Use Count: 8 to check something, and if it passes then remove it
8: Use Count: 9 to check something, and if it passes then remove it
9: Use Count: 10 to check something, and if it passes then remove it
10: Use Count: 11 to check something, and if it passes then remove it
11: Use Count: 12 to check something, and if it passes then remove it

Nippashish
Nov 2, 2005

Let me see you dance!
It's more idiomatic to make a new list with all the things you want to keep, instead of removing the things you don't want from the old list.

Fergus Mac Roich
Nov 5, 2008

Soiled Meat
Look into filter.

Proteus Jones
Feb 28, 2013



Superdawg posted:

Makes sense. Thanks for the help.

I have made the adjustment and confirmed that the issue does not show anymore.


I've always used this to prune items from my list:

Python code:
>>> some_list = [1,2,5,3,4,5,6,5,7,8,5,9,10]
>>> print(some_list)
[1, 2, 5, 3, 4, 5, 6, 5, 7, 8, 5, 9, 10]
>>> some_list = [x for x in some_list if x != 5]
>>> print(some_list)
[1, 2, 3, 4, 6, 7, 8, 9, 10]
I've fallen into using that to get rid of duplicate values. If there's a better way to do this, I'd appreciate someone letting me know. Always looking to improve.

BannedNewbie
Apr 22, 2003

HOW ARE YOU? -> YOSHI?
FINE, THANK YOU. -> YOSHI.
In the specific case of getting rid of duplicates you can do list(set(some_list))

Superdawg
Jan 28, 2009
My use case is to eventually eliminate everything in the list, but I have to wait until each of the items returns the right state. Until then, I need to keep looping.

Cingulate
Oct 23, 2012

by Fluffdaddy

Superdawg posted:

My use case is to eventually eliminate everything in the list, but I have to wait until each of the items returns the right state. Until then, I need to keep looping.
You'd still probably rather want to do something like

code:
while len(your_list):
    do_a_thing()
    your_list = [x for x in your_list if not has_attribute(x)]

Melian Dialogue
Jan 9, 2015

NOT A RACIST

QuarkJets posted:

Sounds pretty straightforward to me. Check out docx2txt for dumping the raw text to an ascii format. From there it's all a matter of intelligently extracting the pieces that you want, but it sounds like you have some good ideas of how to do this. Once you've identified what everything is, dumping it to a CSV is extremely easy

Yeah I have an idea of how I want to do it, but Im still pretty new to Python. Any tips or resources about how I should go about extracting those pieces, and then dumping them into an excel?

PoizenJam
Dec 2, 2006

Damn!!!
It's PoizenJam!!!
Quick question. I have a piece of code in a psychology experiment that goes like this:

code:
for i in range(len(study_trials)):
    fixationStim.draw()
    win.flip()
    core.wait(1)
    word1Stim.setPos([0,0])
    if study_trials[i] == 'cong':
        word1 = old_congruent_list[old_cong_order[cong_num]]
        cong_num+=1
    else:
        word1 = old_incongruent_list_1[old_incong_order_1[incong_num]]
        incong_num+=1
    word1Stim.setText(word1)
    word1Stim.draw()
    win.flip() 
    
    rt = 0
    my_clock.reset()
    second_clock.reset()  
    stream = p.open(rate = 44100, channels = 1, format = pyaudio.paInt16, input = True)
    for y in range(500):
        sound_data = stream.read(882)
        if my_clock.getTime() > .5:
            stream.close()
            break
        elif audioop.rms(sound_data, 2)>Threshold*2:
            rt = my_clock.getTime()
            stream.close()
            remaining_time = .5-rt #calculating time left for stim to be presented
            break
    if rt != 0: #if rt is 0, then already displayed for full second
        word1Stim.draw()
        win.flip()
        core.wait(remaining_time)
    #displaying blank screen
    win.flip()
    if rt == 0: #second chance to respond
        second_clock.reset() #resetting for timing purposes; do not want to reset  my_clock for RT 
        stream = p.open(rate = 44100, channels = 1, format = pyaudio.paInt16, input = True)
        for y in range(500):
            sound_data = stream.read(882)
            if second_clock.getTime() > 2: #use second clock' my_clock not reset for RT
                stream.close()
                break
            elif audioop.rms(sound_data, 2)>Threshold*2:
                rt = my_clock.getTime()
                stream.close()
                remaining_time = 2-rt #calculating time left for blank screen to be presented
                break
        if rt != 0: #if rt is 0, then already displayed for full second
            win.flip()
            core.wait(remaining_time)
    else: #rt already recorded
        core.wait(2)

    win.flip()

    acc_resp_raw = event.waitKeys(10000,'num_1,num_2,num_3') 
    if acc_resp_raw[0] == 'num_1':
        acc_resp = '1'
    elif acc_resp_raw[0] == 'num_2':
        acc_resp = '2'
    elif acc_resp_raw[0] == 'num_3':
        acc_resp = '3' #change for benq
        
    trial_num+=1
          
    rt = rt*1000
     
    phase2_output.write('{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n'.format(group, subject, '2', str(condition), str(trial_num), study_trials[i], word1, acc_resp, str(rt)))
 
phase2_output.close()
It displays a series of words the participants must read aloud. A basic trial goes like:

Fixation cross (1s) -> WORD (500ms) -> Response window (2s)

During the response window, both while the word is still on screen and for 2s afterward, the participant's response time is recorded via verbal input using a microphone.

The piece of the code I am interested in, however, is this:

code:
    acc_resp_raw = event.waitKeys(10000,'num_1,num_2,num_3') 
    if acc_resp_raw[0] == 'num_1':
        acc_resp = '1'
    elif acc_resp_raw[0] == 'num_2':
        acc_resp = '2'
    elif acc_resp_raw[0] == 'num_3':
        acc_resp = '3' #change for benq
Basically, after each trial, the program pauses until the experimenter inputs a code on the numpad- 1 for 'correct', 2 for 'incorrect', 3 for 'spoils'. Given the fact 90%+ of trials are answered correctly, this is an unnecessary, attention demanding task. Ideally, what I'd like to occur is something like this:

If keypress in time window, then code 'acc_resp' as 1
If no keypress in time window, code 'acc_resp' as 0

That way, the trials will advance normally, without pausing for input, but I'm still able to 'tag' bad trials if need be. I'd like for the program to 'listen' for this key input for the same window it's 'listening' for mix input. How might I go about doing this, or would it require a serious re-write of the code?

QuarkJets
Sep 8, 2008

Poizen Jam posted:

Basically, after each trial, the program pauses until the experimenter inputs a code on the numpad- 1 for 'correct', 2 for 'incorrect', 3 for 'spoils'. Given the fact 90%+ of trials are answered correctly, this is an unnecessary, attention demanding task. Ideally, what I'd like to occur is something like this:

If keypress in time window, then code 'acc_resp' as 1
If no keypress in time window, code 'acc_resp' as 0

That way, the trials will advance normally, without pausing for input, but I'm still able to 'tag' bad trials if need be. I'd like for the program to 'listen' for this key input for the same window it's 'listening' for mix input. How might I go about doing this, or would it require a serious re-write of the code?

Right, so you already have the block that listens for a key press. Just grab the time before the keypress prompt and after the key has been pressed, then compare those

Python code:
# "from time import time" is somewhere at the top of the file, ideally
    time_before = time()

    acc_resp_raw = event.waitKeys(10000,'num_1,num_2,num_3') 
    if acc_resp_raw[0] == 'num_1':
        acc_resp = '1'
    elif acc_resp_raw[0] == 'num_2':
        acc_resp = '2'
    elif acc_resp_raw[0] == 'num_3':
        acc_resp = '3' #change for benq

    time_after = time()
    time_elapsed = time_after - time_before  # Seconds it took for the user to respond
    if time_elapsed > 10: 
        # User took over 10 seconds to respond, do something
        acc_resp = 0
Note that time() from the time module is using the system time (in seconds), so if the system clock gets changed then your measurement is hosed, but you probably don't need to worry about that.

QuarkJets
Sep 8, 2008

Melian Dialogue posted:

Yeah I have an idea of how I want to do it, but Im still pretty new to Python. Any tips or resources about how I should go about extracting those pieces, and then dumping them into an excel?

This is mostly an implementation question, there are any number of good answer and they're all going to depend on you having a good understanding of your inputs. Let's say that your inputs all look something like this:

Python code:
THIS_IS_A_SICK_NASTY_TITLE

I LIKE, BIG BUTTS AND I CAN NOT LIE

YOU OTHER BOTHERS CAN'T DENY

Sincerely,
Your momma
9-14-2015
First step is to dump this to ascii file with docx2txt. I've never used that module, so you'll have to read the help page. It sounds pretty straightforward though, there's probably just a function that you need to call with an input file name and an output file name.

After that, you can immediately read the text file with open().

Python code:
# Create an empty dictionary to hold the data
# I chose a dictionary because I like them, there could be a better way
data = {}
with open(ascii_file.txt, 'r') as fi:
    all_lines = fi.readlines()  # Read all lines in the file
This will read every line of the file and store it in a list, which makes the text easy to handle.

First, let's remove any lines that are empty
Python code:
all_lines = [line in all_lines if len(line) > 0]
Presumably the body can include any number of paragraphs, so it's probably easiest to pull from the top and the bottom first and then assume that everything leftover is the body.

Python code:
# The title is always the first line
data['title'] = all_lines[0]
del all_lines[0]

# The date is always the last line
data['date'] = all_lines[-1]
del all_lines[-1]

# And then the name is the line right before that
data['name'] = all_lines[-1]
del all_lines[-1]

# Don't care about the "sincerely"
del all_lines[-1]

# Assume the rest is body
data['body'] = all_lines
By this point you have a dictionary that holds the keys 'name', 'date', 'title', and 'body'. The csv module makes it really easy to dump this dictionary to a CSV file, but

All together:
Python code:
###
# Dump the docx to an ASCII file using docx2txt
###
output_file_name = 'ascii_output_file.txt'
# Something gets called here that does the dumping
##
##


### 
# Fetch data from the ASCII file
###
# Create an empty dictionary to hold the data
# I chose a dictionary because I like them, there could be a better way
data = {}
with open(output_file_name, 'r') as fi:
    all_lines = fi.readlines()  # Read all lines in the file

# Remove empty lines
all_lines = [line in all_lines if len(line) > 0]

# The title is always the first line
data['title'] = all_lines[0]
del all_lines[0]

# The date is always the last line
data['date'] = all_lines[-1]
del all_lines[-1]

# And then the name is the line right before that
data['name'] = all_lines[-1]
del all_lines[-1]

# Don't care about the "sincerely"
del all_lines[-1]

# Assume the rest is body
data['body'] = all_lines

# Use the csv module to write the contents of our dictionary
import csv
# I'm assuming that you want to create a new CSV file
# If you want to append to an existing CSV file, just use 'a' instead of 'w'
with open('my_file.csv', 'w') as csvfile:
    # Note that the column names in the output file are defined here.
    # You can reorder the columns however you want by just changing
    # the order of the column names on this line:
    csv_writer = csv.DictWriter(csvfile, fieldnames = ('title', 'date', 'name', 'body'))
    csv_writer.writerow(data)
DISCLAIMER: your actual messages are probably more complex than the example that I made up above, so you'll need to think carefully about how to extract the information that you want. But I think that this is a good overall approach. The body of a message tends to be variable length, so it makes sense to pull out the message headers (title, name, date, etc) and then to assume that the rest of the thing is the body. So you can just grab the whole message and then start removing the items and storing them in a different, more organized data structure like a dictionary.

QuarkJets fucked around with this message at 03:41 on Oct 5, 2015

Gothmog1065
May 14, 2009

Gothmog1065 posted:

Okay, more of a theoretical question than a straight code question, but I'm still working on the Skynet game I started (Here is my ultimate revised code and Here is the game itself).

Now if you just play the "triple star" scenario, you'll see there's 3 gateways the "enemy" can go to. One of the achievements is to complete the game (trap the enemy so it can't get to any node) with 50 links available. I've gotten it close, but my current code leaves 41 links left, which means you have to trap the enemy on one of the stars and not let it out. My question is how do you predict where the enemy is going well enough to accomplish that? Playing out with my current code, it leaves three "wasted" link breakages, the rest stop them directly at the gateway.

I guess I'm trying to problem solve it now.

One way I could think of is to break certain links (the links on the rings that are only between two nodes) at the ends of the "stars", and when the virus goes around a star and has to come back, break the other side so it's trapped on the outer ring of a star, but I'm not sure how I'd go about determining where to break.

Okay, update on this, here's what I've gotten so far (Without all my notes):

code:
loops = []
for gateway in gateways:
    temp_loop = []
    for links in link_list:
        x, y = links[0], links[1]
        if x == gateway:
            temp_loop.append(y)
        elif y == gateway:
            temp_loop.append(x)
    loops.append(temp_loop)
So basically I'm creating a list of all the "loops" around gateways, I'm going to find the beginning and end of each loop, then use those as my "spare" breaks (I have three of them), and when the enemy is on the loop, break the other end. Is this basically how you guys would go about this? Am I somewhat on the correct path?

e: I haven't tested the code yet, so there might be some minor errors in there.

Gothmog1065 fucked around with this message at 20:02 on Oct 5, 2015

PoizenJam
Dec 2, 2006

Damn!!!
It's PoizenJam!!!

QuarkJets posted:

Right, so you already have the block that listens for a key press. Just grab the time before the keypress prompt and after the key has been pressed, then compare those

Python code:

# "from time import time" is somewhere at the top of the file, ideally
    time_before = time()

    acc_resp_raw = event.waitKeys(10000,'num_1,num_2,num_3') 
    if acc_resp_raw[0] == 'num_1':
        acc_resp = '1'
    elif acc_resp_raw[0] == 'num_2':
        acc_resp = '2'
    elif acc_resp_raw[0] == 'num_3':
        acc_resp = '3' #change for benq

    time_after = time()
    time_elapsed = time_after - time_before  # Seconds it took for the user to respond
    if time_elapsed > 10: 
        # User took over 10 seconds to respond, do something
        acc_resp = 0

Note that time() from the time module is using the system time (in seconds), so if the system clock gets changed then your measurement is hosed, but you probably don't need to worry about that.

I'm not terribly worried about system time changing. You'll notice other code depends on elapsed time as well. But will this allow Python to 'listen' for a key press during the same window it's listening for a vocal response, or is this still executed afterward?

Referring back to the design

Fixation cross (1s) -> Stimulus (500ms) -> Response Window/blank screen (2s)

The vocal response window is 2.5 s (the bolded part- from the onset of the stimulus to the end of the response window), and I want the key press accepted at any point during this same window, else it simply moves onto the next trial (at the end of the 2s 'response window'- new trial, back to fixation cross) and codes a 0. Correct me if I'm wrong, but the way you have it coded- doesn't it still append itself to the end of the trial like-

Fixation cross (1s) -> Stimulus (500ms) -> Vocal Response Window/blank screen (2s) -> Key Press window (arbitrary time, code 0 if no response)

Cingulate
Oct 23, 2012

by Fluffdaddy
I think you want to use getKeys() instead, which doesn't block (and has a timeStamped flag).

If you use core.wait with getKeys, make sure to constantly poll.

Also psychopy has the worst docs.

PoizenJam
Dec 2, 2006

Damn!!!
It's PoizenJam!!!

Cingulate posted:

I think you want to use getKeys() instead, which doesn't block (and has a timeStamped flag).

If you use core.wait with getKeys, make sure to constantly poll.

Also psychopy has the worst docs.

The 'get keys' function is likely simple enough to look up, but what do you mean by 'constantly poll', and how does core wait interrupt it?

Edit: Also, is there a simple way to 'pause' a Python script? As in, when I press space, it halts script execution wherever it may be and resumes when I hit space again?

PoizenJam fucked around with this message at 16:38 on Oct 6, 2015

Cingulate
Oct 23, 2012

by Fluffdaddy

Poizen Jam posted:

The 'get keys' function is likely simple enough to look up, but what do you mean by 'constantly poll', and how does core wait interrupt it?
When you use getKeys (in the docs it's right after waitKey), you probably also use core.wait(). For this, note:

quote:

If you want to obtain key-presses during the wait, be sure to use pyglet and to hogCPU for the entire time, and then call psychopy.event.getKeys() after calling wait()

So you'd do core.wait(secs, hogCPUperiod=some_time_here)
You only get accurate time within the period where you hog the CPU.

BigRedDot
Mar 6, 2008

ahmeni posted:

Luckily I had my Jupyter notebook handy to calculate the results of this plague:



Seeing Bokeh plots in the wild always makes my day.

Gothmog1065
May 14, 2009
Is there an easy way (without doing a whole lot of major importiong beyond sys and math) to iterate over a 2 dimensional list (think a list of coordinates in tuples)?

Example:

[(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (0, 10), (0, 11), (0, 12), (0, 13), (0, 14), (0, 15), (0, 16), (0, 17), (1, 2), (2, 3), (3, 4), (3, 34), (4, 5), (4, 33), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), (10, 11), (11, 12), (12, 13), (13, 14), (14, 15), (15, 16), (16, 17), (17, 1), (18, 19), (18, 20), (18, 21), (18, 22), (18, 23), (18, 24), (18, 25), (18, 26), (18, 27), (19, 20), (20, 21), (21, 22), (22, 23), (23, 24), (24, 25), (25, 26), (26, 27), (27, 19), (28, 29), (28, 30), (28, 31), (28, 32), (28, 33), (28, 34), (28, 35), (28, 36), (29, 21), (29, 30), (30, 31), (31, 32), (32, 33), (33, 34), (34, 35), (35, 2), (35, 23), (35, 36), (36, 22), (36, 29), (37, 1), (37, 2), (37, 23), (37, 24), (37, 35)]

Iterating over that list and seeing how many times say "0" exists at all within those tuple pairs (17 I think).

KICK BAMA KICK
Mar 2, 2009

Gothmog1065 posted:

Iterating over that list and seeing how many times say "0" exists at all within those tuple pairs (17 I think).
Python code:
>>> sum(point.count(0) for point in points)
17

Gothmog1065
May 14, 2009

KICK BAMA KICK posted:

Python code:
>>> sum(point.count(0) for point in points)
17

Thanks. I really need to get into writing quick for loops like that.

No Safe Word
Feb 26, 2005

Gothmog1065 posted:

Thanks. I really need to get into writing quick for loops like that.

comprehensions, not for loops :eng101:

Prince John
Jun 20, 2006

Oh, poppycock! Female bandits?

Hi folks. I'm interested in coding a productivity app for personal use and as a learning project. I'm not a professional programmer, but I have some very basic python experience, so I'd like to use python as the starting point.

As an end goal, I'd like my program to track a list of tasks and catalogue them in lots of different ways, with the ability to look at my workload through different 'lenses' and group them differently according to which lens I'm using.

I'd be grateful for some broad advice about what software/frameworks I should be using to code an app like this, so I can direct my learning in the right direction. I really have no experience, but I'm thinking I'll need some sort of database to track the tasks and assign attributes to them as well as some software to provide the GUI. My only real criteria for the GUI is something that doesn't look like crap and it would be a bonus if it were able to be cross-platform (Windows and Linux).

Sorry for the unavoidably vague questions!

OnceIWasAnOstrich
Jul 22, 2006

Prince John posted:

I'd be grateful for some broad advice about what software/frameworks I should be using to code an app like this, so I can direct my learning in the right direction. I really have no experience, but I'm thinking I'll need some sort of database to track the tasks and assign attributes to them as well as some software to provide the GUI. My only real criteria for the GUI is something that doesn't look like crap and it would be a bonus if it were able to be cross-platform (Windows and Linux).


If you have any inclination towards or experience with websites, a webapp might be the way to go, more relevant to almost anything else than some Python-specific GUI kit, completely cross-platform, fits very well with Python, and lets you learn Python, web frameworks, and basic web stuff all in one go. As a downside, you have to learn all of those things in one go.

Proteus Jones
Feb 28, 2013



Microsoft OneDrive dev team just released this today:

https://github.com/OneDrive/onedrive-sdk-python

Prince John
Jun 20, 2006

Oh, poppycock! Female bandits?

OnceIWasAnOstrich posted:

If you have any inclination towards or experience with websites, a webapp might be the way to go, more relevant to almost anything else than some Python-specific GUI kit, completely cross-platform, fits very well with Python, and lets you learn Python, web frameworks, and basic web stuff all in one go. As a downside, you have to learn all of those things in one go.

I was idly wondering this. My only reluctance to go the web app route was that I might want to use it at work eventually, and probably wouldn't be permitted to run a local webserver on my machine.

Would you go for django + sqlite as a starting point?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Prince John posted:

I was idly wondering this. My only reluctance to go the web app route was that I might want to use it at work eventually, and probably wouldn't be permitted to run a local webserver on my machine.

Would you go for django + sqlite as a starting point?

I'm not sure what you mean by "a local webserver", but in case you weren't aware, an app like this can be served straight from python, basic python has an HTTP server built-in, and the different frameworks like Django, have their own built-in webserver. In other words, you don't have to actually install a "real" webserver like Apache, which you might be thinking you have to do...

Django + sqlite is a fine choice.

OnceIWasAnOstrich
Jul 22, 2006

Prince John posted:

I was idly wondering this. My only reluctance to go the web app route was that I might want to use it at work eventually, and probably wouldn't be permitted to run a local webserver on my machine.

Would you go for django + sqlite as a starting point?

Like Themopyle aludes to, you won't need any more permissions to run a Python webapp than you would any other Python script on a local machine, so if they are fine with you running/programming arbitrary programs on your local machine you should be good to go.

Django is probably a good route to go since you will likely have a bunch of data that should fit the normal relational database usecases. If you find it to be difficult to match up to how you want to store data or for some reason want to more directly implement your data management stuff you can use simpler frameworks like Flask or CherryPy. Sqlite is also ideal, for the most part in Python you should be using a database library that will abstract out all of your database interactions so you could trivially switch from Sqlite to any other SQL implementation with no effort, not that you would need to for personal use.

SurgicalOntologist
Jun 17, 2004

This my first foray into scraping Javascript pages, and I'm trying to use dryscrape which is based on QT webkit. If everything is working correctly I should be triggering a "download file" popup. How do I catch the file the site is trying to send me, ideally into a string but I would be happy reading it again off the local file system.

Prince John
Jun 20, 2006

Oh, poppycock! Female bandits?

Thermopyle posted:

I'm not sure what you mean by "a local webserver", but in case you weren't aware, an app like this can be served straight from python, basic python has an HTTP server built-in, and the different frameworks like Django, have their own built-in webserver. In other words, you don't have to actually install a "real" webserver like Apache, which you might be thinking you have to do...

Django + sqlite is a fine choice.

Thanks all for the advice everyone. I wasn't aware of the distinctions between running something like Apache and what was proposed, so that's very helpful. I have permission to run arbitrary programs on the computer so that shouldn't be a problem.

Adbot
ADBOT LOVES YOU

boner confessor
Apr 25, 2013

by R. Guyovich
i'm trying to make a palindrome tester, what am i doing wrong here?

code:
def palindromeCheck(rawString):
	#convert input to lowercase
	lowerString = rawString.lower()
	#clean out any punctuation
	cleanString = lowerString.translate(None, '! .,')
	#find half the length of the result
	searchLength = len(cleanString) / 2
	#compare char to char, starting from the middle and working outwards, ignoring the middle char of odd numbered strings
	while searchLength > 0:
		if cleanString[searchLength] == cleanString[-searchLength]:
			searchLength -= 1
		else:
			return False
		return True	
rawString = raw_input("Give me a Palindrome: ")
isPalindrome = palindromeCheck(rawString)
if isPalindrome == True:
	print "This is a Palindrome!"
else:
	print "Sorry, this is not a Palindrome."
the problem is i can't get it to iterate through the if, i had assumed "while searchLength is still greater than 0 keep doing the if"

i managed to get it to work much more cleanly with a for

code:
isPalindrome = True
	#compare char to char, starting from the outside and working in, ignoring the middle char of odd numbered strings
	for n in range (0, int(len(cleanString) / 2)):
		if cleanString[n] != cleanString[-n-1]:
			isPalindrome = False
			break
	return isPalindrome
but where did i go wrong with the first attempt?

  • Locked thread