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.
 
  • Post
  • Reply
bob dobbs is dead
Oct 8, 2017

I love peeps
Nap Ghost

edmund745 posted:

I had a problem but I already edited the files so I can't show the code...

Does it make any difference if you declare the Toplevel widgets inside a class? I was declaring them in the root level of the files.

It worked in the first attempt, but when I coped the two .py files into another folder and tried to make something useful out of them, it no longer worked right.

Specifically what went wrong was that when the first window opened, it would also open a small phantom window with no attributes set.
As long as I left the phantom window alone, the second window would open and close repeatedly.
If I closed the phantom window, the second window would also close, and after closing the phantom window (if window-2 was either open or closed at the time) then the second window wouldn't open anymore.

,,,,,,,

Also while searching Google for "python try except", I got the Google code challenge! :D ,,,,,,,,,Or does everybody get these now?
I declined to take it.
They'd probably just hire me as a contractor, and gently caress that.
I aint takin no lousy 100K job where I gotta live in a 300K neighborhood, or face a 4-hour commute.

its a 350k total comp (150k cash 200k rsu) job in a 2-5 million neighborhood

Adbot
ADBOT LOVES YOU

cinci zoo sniper
Mar 15, 2013




Isn’t 150k formally poverty in some parts of SF?

Hadlock
Nov 9, 2004

120K is the poverty line for a single male in Palo Alto, I think in SF the poverty line is 98K for a family of 4.

You can live pretty comfortably in SF in a one bedroom in a desirable neighborhood for $100K, for $150 you can afford a really nice 1 bedroom and a hobby like race cars or sail boats, so long as you aren't trying to save money to buy a house or invest more than 5% in your 401k. Gets a lot cheaper if you get a roommate.

QuarkJets
Sep 8, 2008

edmund745 posted:

I had a problem but I already edited the files so I can't show the code...

Does it make any difference if you declare the Toplevel widgets inside a class? I was declaring them in the root level of the files.

It worked in the first attempt, but when I coped the two .py files into another folder and tried to make something useful out of them, it no longer worked right.

Specifically what went wrong was that when the first window opened, it would also open a small phantom window with no attributes set.
As long as I left the phantom window alone, the second window would open and close repeatedly.
If I closed the phantom window, the second window would also close, and after closing the phantom window (if window-2 was either open or closed at the time) then the second window wouldn't open anymore.

,,,,,,,

Also while searching Google for "python try except", I got the Google code challenge! :D ,,,,,,,,,Or does everybody get these now?
I declined to take it.
They'd probably just hire me as a contractor, and gently caress that.
I aint takin no lousy 100K job where I gotta live in a 300K neighborhood, or face a 4-hour commute.

If you just dump everything into the root of your file then it's going to be really difficult to implement the design that I mentioned. Use a class, this kind of problem is exactly what a class is good for. Define a main window class and a child window class. Have the main window class own an instance of the child window class. This will be easy to implement and relatively foolproof so long as you know basic python syntax

A try/except block is a way of catching exceptions and then reacting to them instead of j letting the code crash. I recommend looking up some tutorials on how to use this

edmund745
Jun 5, 2010

bob dobbs is dead posted:

its a 350k total comp (150k cash 200k rsu) job in a 2-5 million neighborhood
Yes but I'm kinda white-trashy so I figured I'd be in the slummy part of Palo Alto. So maybe that's a 1-mil neighborhood?

QuarkJets posted:

If you just dump everything into the root of your file then it's going to be really difficult to implement the design that I mentioned. ...
Learn python, they said. It's simple, they said.

quote:

A try/except block is a way of catching exceptions and then reacting to them instead of j letting the code crash. I recommend looking up some tutorials on how to use this
That bit also wasn't working.
As I was searching for answers to the phantom window, I don't think I ran across any examples of using the Toplevel widget that said it was better to only use them inside classes.

cinci zoo sniper
Mar 15, 2013




If you want to do GUI programming then “learn Python” is not a good thing to say or something that is commonly said, sorry.

Mister Fister
May 17, 2008

D&D: HASBARA SQUAD
KILL-GORE


I love the smell of dead Palestinians in the morning.
You know, one time we had Gaza bombed for 26 days
(and counting!)
I'm taking a Udemy course on Python for data science and so far it's excellent. However, one thing that is lacking is lack of exercises. There's only one homework problem per section.

Can anyone suggest a good resource for data science centric python exercises (with solutions), whether free or paid so i can practice some more?

I'm taking Python A-Z: Python for data science with Kirill Eremenko on Udemy. If anyone could recommend any other Python courses (or any other data science related courses) on Udemy, i'd greatly appreciate it as well! Thanks!

Proteus Jones
Feb 28, 2013



I was impressed with Tree House classes when I went to brush up a couple years ago.

However, it's anywhere from $25 to $200/mo depending on which plan you want. So it might not be economically feasible if you can't get work to pay for it.

https://teamtreehouse.com/account/enrollment

Mister Fister
May 17, 2008

D&D: HASBARA SQUAD
KILL-GORE


I love the smell of dead Palestinians in the morning.
You know, one time we had Gaza bombed for 26 days
(and counting!)

Proteus Jones posted:

I was impressed with Tree House classes when I went to brush up a couple years ago.

However, it's anywhere from $25 to $200/mo depending on which plan you want. So it might not be economically feasible if you can't get work to pay for it.

https://teamtreehouse.com/account/enrollment

Thanks for the suggestion! Looks like it focuses on python for web development rather than data science/analytics though.

Proteus Jones
Feb 28, 2013



Mister Fister posted:

Thanks for the suggestion! Looks like it focuses on python for web development rather than data science/analytics though.

My bad. I didn't look at the current courses. For some reason I thought they had some data courses.

Maybe that was Coursera, I remember looking at that around the same time.

CarForumPoster
Jun 26, 2013

⚡POWER⚡

edmund745 posted:

Yes but I'm kinda white-trashy so I figured I'd be in the slummy part of Palo Alto. So maybe that's a 1-mil neighborhood?

You joke but there is a slummy part of Palo Alto called East Palo Alto. Its separated by 101 and its unmetaphorically the other side of the tracks highway. Probably gentrified by now though.

jerry seinfel
Jun 25, 2007


Mister Fister posted:

I'm taking a Udemy course on Python for data science and so far it's excellent. However, one thing that is lacking is lack of exercises. There's only one homework problem per section.

Can anyone suggest a good resource for data science centric python exercises (with solutions), whether free or paid so i can practice some more?

I'm taking Python A-Z: Python for data science with Kirill Eremenko on Udemy. If anyone could recommend any other Python courses (or any other data science related courses) on Udemy, i'd greatly appreciate it as well! Thanks!

imo datacamp is pretty good if you can get it on a deal. Mostly smaller projects but there's a pretty wide range of subjects

QuarkJets
Sep 8, 2008

edmund745 posted:

Yes but I'm kinda white-trashy so I figured I'd be in the slummy part of Palo Alto. So maybe that's a 1-mil neighborhood?

Learn python, they said. It's simple, they said.
That bit also wasn't working.
As I was searching for answers to the phantom window, I don't think I ran across any examples of using the Toplevel widget that said it was better to only use them inside classes.

What I said is that if you want parent windows to keep track of children windows then you should use a class to do that. Because then the children window literally belongs to the class

You can use Toplevel wherever you want, the choice to use classes or not use classes is a question of design.

edmund745 posted:

That bit also wasn't working.

What do you mean? Did you find some tutorials showing how try/except works? Did you try setting up a try/except block for yourself? What didn't work?

bob dobbs is dead
Oct 8, 2017

I love peeps
Nap Ghost

CarForumPoster posted:

You joke but there is a slummy part of Palo Alto called East Palo Alto. Its separated by 101 and its unmetaphorically the other side of the tracks highway. Probably gentrified by now though.

and it is pretty much actually at the $1 mil range
https://www.redfin.com/city/5401/CA/East-Palo-Alto

palo alto <-> mountain view commute is much more annoying than the distance lets on, tho, because zoning in the bay area is turbofucked and they can't build intermediate size roads worth poo poo and the transit sucks

Hadlock
Nov 9, 2004

Yeah it is 30 minutes from SF to PA, about 36 miles, and then 30 minutes from PA to MV, about 9 miles. Doesn't help that the bridge (Dunbarton?) dumps out right in Palo Alto and their idea of on ramps and offramps are rooted in 1940s methodology.

shrike82
Jun 11, 2005

Any suggestions on scraping frameworks? I've always defaulted to requests + BS4 & falling back to Selenium + Chrome if I need funky stuff.
But Scrapy looks quite appealing with its baked-in concurrency and plug-in support for stuff like proxies.

Slimchandi
May 13, 2005
That finger on your temple is the barrel of my raygun

cinci zoo sniper posted:

If you want to do GUI programming then “learn Python” is not a good thing to say or something that is commonly said, sorry.

Are there any decent tutorials on GUI programming, python or otherwise? I have done some basic interfaces but I feel like there should be some basic OO guidelines and good practice I am missing.

NtotheTC
Dec 31, 2007


It's all under the header of UX (user experience) now

Or wait when you say gui programming are you talking about the interface or the code behind it?

Slimchandi
May 13, 2005
That finger on your temple is the barrel of my raygun

NtotheTC posted:

It's all under the header of UX (user experience) now

Or wait when you say gui programming are you talking about the interface or the code behind it?

I mean how to implement an interface in code, like discussion above regarding child and parent windows, but for higher complexity. I don't even know if there common patterns for building multiscreen applications that work with an MVC approach.

unpacked robinhood
Feb 18, 2013

by Fluffdaddy
I'd like to use panda's sample function to skew the results according to the values in a column.
For example, repeated executions of the following snipped usually return the row with the highest 'hugeness':

Python code:
df = pd.DataFrame({"width":['large','a lot','passable','not'], 'hugeness':[113, 8, 12, 0],'number of dads':[0,1,2,3]})
df = df.sample(n=1, weights='hugeness', axis=0)
print(df)
I'm doing a silly web thing where users input a word and get a bunch of other words in return.
I use the sample function to get a few items from groupby objects, but I'd like to keep track of the number of times a word is returned, and skew the result towards words that were never returned.
For example if my algo returns 'FunnyString' to the web ui a number of times, a field somewhere is updated and I'd want it to be less likely to come up later. ( I'm not even sure it makes sense from a math perspective. )

My two main questions are:
  • Can you use it so it favors rows with a lower count ? (Entering negative numbers doesn't work)
  • How do you actually put weights to several columns ? Here I use a single string as parameter but it should accept a bunch of numbers I assume.

I find very few examples online, trial and error doesn't get me very far, and I can't really parse the docs.

Loel
Jun 4, 2012

"For the Emperor."

There was a terrible noise.
There was a terrible silence.



So I'm following along with 'Automate the Boring Stuff', and I'm trying to apply some things.

Lesson 1 posted:

print('How many cats do you have?')
numCats = input()
try:
if int(numCats) >= 4:
print ('That is a lot of cats!')
elif int(numCats) <= 0:
print ('Get more cats')
else:
print ('Not that many cats')
except ValueError:
print ('You did not enter a number.')

Lesson 2 posted:

if guess > secretNumber:
print('Your guess is too high.')
elif guess < secretNumber:
print('Your guess is too low.')
else:
break #This condition is for the correct guess

So I'm trying to merge them as follows:

quote:

try:
if guess > secretNumber:
print('Your guess is too high.')
elif guess < secretNumber:
print('Your guess is too low.')
else:
break #This condition is for the correct guess
except ValueError:
print ('You did not enter a number.')

But its telling me the break is outside the loop.

Mark Larson
Dec 27, 2003

Interesting...

Loel posted:

But its telling me the break is outside the loop.

Try posting with [code] tags so that we can see your indentation.

Hadlock
Nov 9, 2004

At one point the main flask website has a great link near the bottom of the main page, or maybe it was the GitHub readme.md, that linked to the best example about how to structure a flask app. Does this still exist, or is there a good resource that replaces it? There's a lot of examples out there when you Google this question, but hard to find a quality example. There's a whole thread (two actually) on hacker news about how the example by digital ocean is the worst pattern to follow but is frequently referenced.

cinci zoo sniper
Mar 15, 2013




unpacked robinhood posted:

I'd like to use panda's sample function to skew the results according to the values in a column.
For example, repeated executions of the following snipped usually return the row with the highest 'hugeness':

Python code:
df = pd.DataFrame({"width":['large','a lot','passable','not'], 'hugeness':[113, 8, 12, 0],'number of dads':[0,1,2,3]})
df = df.sample(n=1, weights='hugeness', axis=0)
print(df)
I'm doing a silly web thing where users input a word and get a bunch of other words in return.
I use the sample function to get a few items from groupby objects, but I'd like to keep track of the number of times a word is returned, and skew the result towards words that were never returned.
For example if my algo returns 'FunnyString' to the web ui a number of times, a field somewhere is updated and I'd want it to be less likely to come up later. ( I'm not even sure it makes sense from a math perspective. )

My two main questions are:
  • Can you use it so it favors rows with a lower count ? (Entering negative numbers doesn't work)
  • How do you actually put weights to several columns ? Here I use a single string as parameter but it should accept a bunch of numbers I assume.

I find very few examples online, trial and error doesn't get me very far, and I can't really parse the docs.

Lower count weights would be, quick and dirty:
code:
df['weights'] = 1 - (df.hugeness/df.hugeness.sum())
as for using multiple columns as weights, if I understand the second question correctly - just calculate your weights based on multiple columns and pass them, e.g.:
code:
df['multiweights'] = (df['number of dads']/df['number of dads'].sum())*df.weights
Alternatively you could do something like:
code:
df['dadweights'] = df['number of dads']/df['number of dads'].sum()
df.sample(n=10, weights='weights').sample(weights='dadweights')

cinci zoo sniper fucked around with this message at 17:02 on Aug 30, 2018

Average Lettuce
Oct 22, 2012


Loel posted:

But its telling me the break is outside the loop.

Well, it is :) as in, there isn't any loop at all (unless you didn't post that part of the code). To work as you intend, you can put pass instead of break, or better yet, don't put anything at all, since it isn't doing anything, just remove the else.

Loel
Jun 4, 2012

"For the Emperor."

There was a terrible noise.
There was a terrible silence.



Mark Larson posted:

Try posting with tags so that we can see your indentation.

code:
#This is a Guess the Number game
import random

print('Hello, what is your name?')
name = input()

print('Well ' + name + ' I am thinking of a number between 1 and 20.')
secretNumber = random.randint(1, 20)

for guessesTaken in range (1, 7):
    print('Take a guess.')
    guess = int(input())

try:
    if guess > secretNumber:
        print('Your guess is too high.')
    elif guess < secretNumber:
        print('Your guess is too low.')
    else:
        break #This condition is for the correct guess
    except ValueError:
        print ('You did not enter a number.')

if guess == secretNumber:
    print('Good job ' + name + '!') 
else:
    print('Nope. The correct guess was ' + str(secretNumber))

print('You took ' + str(guessesTaken) + ' guesses')

Dr Subterfuge
Aug 31, 2005

TIME TO ROC N' ROLL
Should be this:

code:
#This is a Guess the Number game
import random

print('Hello, what is your name?')
name = input()

print('Well ' + name + ' I am thinking of a number between 1 and 20.')
secretNumber = random.randint(1, 20)

for guessesTaken in range (1, 7):
    print('Take a guess.')
    guess = int(input())

    try:
        if guess > secretNumber:
            print('Your guess is too high.')
        elif guess < secretNumber:
            print('Your guess is too low.')
        else:
            break #This condition is for the correct guess
    except ValueError:
        print ('You did not enter a number.')

if guess == secretNumber:
    print('Good job ' + name + '!') 
else:
    print('Nope. The correct guess was ' + str(secretNumber))

print('You took ' + str(guessesTaken) + ' guesses')
Each time the program gets a number, it needs to process it to see if it is correct. That's what is happening in the try block, so it needs to start at the same indentation as everything else in the for loop. Also, except is part of the try, so it needs to be at the same indentation. (Like how else needs to have the same indentation as the if it is a part of.) The break statement needs to be in a for loop because all it does is stop a for loop from iterating further. (In this case you want this to happen so the program stops asking for guesses when the right one has been reached.)

Da Mott Man
Aug 3, 2012


Hadlock posted:

At one point the main flask website has a great link near the bottom of the main page, or maybe it was the GitHub readme.md, that linked to the best example about how to structure a flask app. Does this still exist, or is there a good resource that replaces it? There's a lot of examples out there when you Google this question, but hard to find a quality example. There's a whole thread (two actually) on hacker news about how the example by digital ocean is the worst pattern to follow but is frequently referenced.

Maybe talking about this? http://flask.pocoo.org/docs/1.0/patterns/packages/

Sad Panda
Sep 22, 2004

I'm a Sad Panda.

Dr Subterfuge posted:

Should be this:

code:
#This is a Guess the Number game
import random

print('Hello, what is your name?')
name = input()

print('Well ' + name + ' I am thinking of a number between 1 and 20.')
secretNumber = random.randint(1, 20)

for guessesTaken in range (1, 7):
    print('Take a guess.')
    guess = int(input())

    try:
        if guess > secretNumber:
            print('Your guess is too high.')
        elif guess < secretNumber:
            print('Your guess is too low.')
        else:
            break #This condition is for the correct guess
    except ValueError:
        print ('You did not enter a number.')

if guess == secretNumber:
    print('Good job ' + name + '!') 
else:
    print('Nope. The correct guess was ' + str(secretNumber))

print('You took ' + str(guessesTaken) + ' guesses')
Each time the program gets a number, it needs to process it to see if it is correct. That's what is happening in the try block, so it needs to start at the same indentation as everything else in the for loop. Also, except is part of the try, so it needs to be at the same indentation. (Like how else needs to have the same indentation as the if it is a part of.) The break statement needs to be in a for loop because all it does is stop a for loop from iterating further. (In this case you want this to happen so the program stops asking for guesses when the right one has been reached.)

Yes. Indentation is king in Python.

M. Night Skymall
Mar 22, 2012

The other problem with that code is that the exception you're using the try/except block to catch happens when you convert the input from a string into an integer, you need to move that part inside the try.


code:
#This is a Guess the Number game
import random

print('Hello, what is your name?')
name = input()

print('Well ' + name + ' I am thinking of a number between 1 and 20.')
secretNumber = random.randint(1, 20)

for guessesTaken in range (1, 7):
    print('Take a guess.')

    try:
        guess = int(input())
        if guess > secretNumber:
            print('Your guess is too high.')
        elif guess < secretNumber:
            print('Your guess is too low.')
        else:
            break #This condition is for the correct guess
    except ValueError:
        print ('You did not enter a number.')

if guess == secretNumber:
    print('Good job ' + name + '!') 
else:
    print('Nope. The correct guess was ' + str(secretNumber))

print('You took ' + str(guessesTaken) + ' guesses')

Dr Subterfuge
Aug 31, 2005

TIME TO ROC N' ROLL
Whoops. Yeah. Guess I was too busy looking at the indents to notice the guess.

huhu
Feb 24, 2006
Could someone help me out with what I'm missing here? Just switched over two VSCode from Pycharm which used to handle all this kind of stuff for me. My issue is that I have a course I'm taking that has weekly assignments. I'd like to have a directory per week, and then a collection of utilities, such as timing functions to measure various solutions I come up with. Here is my directory structure.

code:
c1_algorithmic_toolbox/
__init__.py
    week1_programming_challenges/
        __init__.py
        maximum_pairwise_product.py
    utilities/
        timing.py
        __init__.py
timing.py consists of some code, which I don't think is relevant to my current problem

code:
def timing(method):
    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()
        if 'log_time' in kw:
            name = kw.get('log_name', method.__name__.upper())
            kw['log_time'][name] = int((te - ts) * 1000)
        else:
            print '%r  %2.2f ms' % \
                  (method.__name__, (te - ts) * 1000)
        return result
    return timed
Inside of maximum_pairwise_product.py, when I try to run the file from the command line, I get:

code:
(3336) >> python week1_programming_challenges/maximum_pairwise_product.py
Traceback (most recent call last):
  File "week1_programming_challenges/maximum_pairwise_product.py", line 6, in <module>
    from utilities.timing import timing
ModuleNotFoundError: No module named 'utilities'


It seems to be getting tripped up on the line

code:
from utilities.timing import timing

Dr Subterfuge
Aug 31, 2005

TIME TO ROC N' ROLL
pretty sure this would work

Python code:
from c1_algorithmic_toolbox.utilities.timing import timing

huhu
Feb 24, 2006

Dr Subterfuge posted:

pretty sure this would work

Python code:
from c1_algorithmic_toolbox.utilities.timing import timing

That results in:
code:
(3337) >> python week1_programming_challenges/maximum_pairwise_product.py
Traceback (most recent call last):
  File "week1_programming_challenges/maximum_pairwise_product.py", line 6, in <module>
    from c1_algorithmic_toolbox.utilities.timing import timing
ModuleNotFoundError: No module named 'c1_algorithmic_toolbox'
Edit: If I open this in Pycharm and do
code:
from utilities.timing import timing
It works. What magic is happening!?

huhu fucked around with this message at 02:02 on Sep 1, 2018

SurgicalOntologist
Jun 17, 2004

Personally, I always make a setup.py file, and pip install -e it. Otherwise whether it works depends on what's on the path and what your current directory is. From PyCharm, your current directory is the parent folder, whereas from the command line you were already one folder deep. I believe that's the difference, rather than any PyCharm shenanigans.

It might also work if you put
code:
from c1_algorithmic_toolbox import utilities
in c1_algorithmic_toolbox/__init__.py
and
code:
from c1_algorithmic_toolbox.utilities import timing
in c1_algorithmic_toolbox/utilities/__init__.py.

Or something like that. Although that will help the import chain along, exactly where to start importing from will depend on what directory you're in. Unless c1_algorithmic_toolbox is on the path, which is most reliably accomplished by packaging and installing it.

Dr Subterfuge
Aug 31, 2005

TIME TO ROC N' ROLL
And I just realized the print statement isn't a function, so this is python 2. I know some import behavior changed between 2 and 3, but I don't know if that's relevant here.

huhu
Feb 24, 2006

Dr Subterfuge posted:

And I just realized the print statement isn't a function, so this is python 2. I know some import behavior changed between 2 and 3, but I don't know if that's relevant here.

That's why I tried to highlight that " some code, which I don't think is relevant to my current problem " because I couldn't even get anything to yell about it being Python 2 code.

SurgicalOntologist
Jun 17, 2004

Good point, I haven't used Python 2 in a long time so that might throw off my suggestion.

Is your class really having you use Python 2? It will be deprecated in 15 months. It's been the wrong choice (especially for an educational environment) for years, but at this point there's no excuse and it's probably worth complaining about. Granted, the differences aren't huge, but still.

Edit: Oh, you're using Python 3 but have some old Python 2 code you want to run? Well, fix the import problem first, and then yes, you'll have to update timing.py.

huhu
Feb 24, 2006

SurgicalOntologist posted:

Edit: Oh, you're using Python 3 but have some old Python 2 code you want to run? Well, fix the import problem first, and then yes, you'll have to update timing.py.


I'm leading a class at work because I'd like to learn new things. I might have spent too long as a React/Node developer that I forget the Python way of doing things or I'm just trying to force the JS way on Python. Eeeesh...

Adbot
ADBOT LOVES YOU

ArcticZombie
Sep 15, 2010
A Python garbage collection question – I've implemented a data structure in C and wrapped it with a Python module using ctypes. This module is used in a project where the data structure is an attribute of a class. Where and how is it best to free the memory allocated by the C library? Cursory searches suggest adding a __del__ method which frees the memory, but which class should have the __del__ method? Should the class which wraps the data structure free the memory, or should the class which uses the wrapped data structure have the method? If I put it on the wrapped data structure, when an object of the class in the end project is garbage collected, will it call the __del__ method of its attributes (and therefore the wrapped data structure)? Other results I found suggested that the __del__ method was evil and to be avoided, what the hell am I supposed to be doing here?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply