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

I don't really understand what happened. I ran something along the lines of "conda update pyside", it indicated that it was going to update a whole bunch of stuff, the update failed at some point, and then I was in a completely unrecoverable state because a bunch of the binaries were completely gone. Imagine my surprise

I wound up creating a fresh install

Adbot
ADBOT LOVES YOU

The March Hare
Oct 15, 2006

Je rêve d'un
Wayne's World 3
Buglord
Mock question!

If I have something like:

Python code:
# utils.py
def some_func():
    foo = db_call_to_get_an_instance_of_some_class()
    bar = foo.method(baz)

    for thing in bar:
        do_some_thing()
I want to test this function without hitting the db, so I'm currently just patching the return value of db_call_to_get_an_instance_of_some_class to be a Mock() object, but then how do I make the foo.method(baz) return an iterable for the purposes of the later for thing in bar?

Thermopyle
Jul 1, 2003

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

The March Hare posted:

Mock question!

If I have something like:

Python code:
# utils.py
def some_func():
    foo = db_call_to_get_an_instance_of_some_class()
    bar = foo.method(baz)

    for thing in bar:
        do_some_thing()
I want to test this function without hitting the db, so I'm currently just patching the return value of db_call_to_get_an_instance_of_some_class to be a Mock() object, but then how do I make the foo.method(baz) return an iterable for the purposes of the later for thing in bar?

Something like this...untested but the general idea is correct:

Python code:
@patch('blah.db_call_to_get_an_instance_of_some_class')
def test_a_thing(mocked_db_call_blah_blah):
  db_return = MagicMock()
  db_return.method.return_value = ['some', 'values', 'to', 'iterate']
  mocked_db_call_blah_blah.return_value = db_return

  # whatever your tests need to be

tef
May 30, 2004

-> some l-system crap ->

The March Hare posted:

Mock question!

If I have something like:

Python code:
# utils.py
def some_func():
    foo = db_call_to_get_an_instance_of_some_class()
    bar = foo.method(baz)

    for thing in bar:
        do_some_thing()
I want to test this function without hitting the db, so I'm currently just patching the return value of db_call_to_get_an_instance_of_some_class to be a Mock() object, but then how do I make the foo.method(baz) return an iterable for the purposes of the later for thing in bar?

unless you're using magic wizard sql, you could always test against sqlite? you've kinda already given up on testing on the db you use in production, but using sqlite might give you a much more useful mock object than one you can write yourself :v:

ItBurns
Jul 24, 2007
Is there a preferred backend for matplotlib in python3? I got some errors about GTK3Agg not being supported when I started ipython3. I'm using Qt5Agg now and it works fine, but I've never really considered the difference between them.

man in the eyeball hat
Dec 23, 2006

Capture the opening of the portal that connects this earth of 3D to one earth of 4D or 5D. Going to the 5D.

I have a collection of 3D vertices that define some faces and I would like to render these faces. I accomplished this with Matplotlib using Poly3DCollection, but the performance is very poor when I render my full set of faces (up to ~3000).

Ideally I could give the vertices that define the faces (all triangles and quadrilaterals), have the plotted/rendered, and have the ability to control the view with the mouse by dragging to rotate, scrollwheel zoom, ability to pan the view, etc. It would also be very nice to be able to render a wireframe version, where only the edges of the faces are rendered, rather than the faces themselves.

Everything I've found by searching has been about using full graphics libraries such as PyOpenGL to do this, and it seems like way more effort to learn and do than this might be worth.

Is there some existing package which does what I'd like, but isn't Matplotlib? Ideally Python 2.7, but Python 3 would work if necessary.

E- of course the next SO article has new recommendations, like PyQtGraph. Regardless I'm open to suggestions

man in the eyeball hat fucked around with this message at 19:01 on Jul 23, 2016

Nippashish
Nov 2, 2005

Let me see you dance!

Zlocista posted:

Ideally I could give the vertices that define the faces (all triangles and quadrilaterals), have the plotted/rendered, and have the ability to control the view with the mouse by dragging to rotate, scrollwheel zoom, ability to pan the view, etc. It would also be very nice to be able to render a wireframe version, where only the edges of the faces are rendered, rather than the faces themselves.

If you're willing to use a separate viewer program then you can write the model to a ply file and and open it in meshlab.

man in the eyeball hat
Dec 23, 2006

Capture the opening of the portal that connects this earth of 3D to one earth of 4D or 5D. Going to the 5D.

Unfortunately I need to keep everything in Python :(

Late edit- I got it working with PyQtGraph. Still need to figure out how to draw the edges that I want, but I think the capability should be there.

man in the eyeball hat fucked around with this message at 01:11 on Jul 24, 2016

Dominoes
Sep 20, 2007

I uploaded my function plotting library to PyPi. Smooths over MPL's syntax, so you can plot functions without boilerplate. Ideal for visualizing things while learning math. I'm currently using it to help with Khan Academy's multivariate calc course.

I'm open to suggestions.

Dominoes fucked around with this message at 23:51 on Jul 23, 2016

Death Zebra
May 14, 2014

Can anyone recommend an Android app to write and execute python programs? I've been using QPython but for some baffling reason it's ability to write text files has apparently been deliberately disabled by it's creators.

mystes
May 31, 2006

Death Zebra posted:

I've been using QPython but for some baffling reason it's ability to write text files has apparently been deliberately disabled by it's creators.
Huh? Why would they do that? Writing files works fine in the version of qpython on my phone. Is this something that just changed in the last version?

mystes fucked around with this message at 01:32 on Jul 26, 2016

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Anyone help with this windows (?) issue? I've made a new Anaconda env and installed Selenium (had to run pip install selenium), and written a script that uses it. If I run it from IDLE, it works completely fine. But if I run it from the command line (with the environment activated) it says
code:
    from selenium import webdriver
ImportError: No module named 'selenium'
I've tried just running python and then doing import sys; print(sys.path), and it looks fine - everything on the path is a folder in the env, including the lib\site-packages folder where selenium actually is. Anyone have any ideas? Is there something different about how IDLE runs scripts?

e- ugh I'm an idiot, I was just running script.py instead of python script.py so it must have been defaulting to the basic env that's in the system path

baka kaba fucked around with this message at 16:01 on Jul 26, 2016

onionradish
Jul 6, 2006

That's spicy.

baka kaba posted:

e- ugh I'm an idiot, I was just running script.py instead of python script.py so it must have been defaulting to the basic env that's in the system path
The vanilla Python for Windows includes the py.exe Python Windows Launcher, which allows the use of a shebang at the top of the script to determine which interpreter to use so you CAN just launch a script directly, even if it's inside an env. If I remember right, anaconda doesn't include the launcher.

Death Zebra
May 14, 2014

mystes posted:

Huh? Why would they do that? Writing files works fine in the version of qpython on my phone. Is this something that just changed in the last version?

Yeah the post I found on Stack Overflow claiming this was in error. I've just tried again and it turns out I was getting the file path wrong. Android is so drat annoying with that.

VikingofRock
Aug 24, 2008




So there are lots of times in Python when I find myself wishing I had enums. For example, let's say I'm writing a Blackjack game and I want to model the possible player actions. In C or something I would have an enum containing STAND, HIT, SPLIT, etc. But since Python doesn't have enums / ADTs / whatever, I find myself at a loss for how to model things like that. What's the idiomatic Python solution?

edit: Right after I posted this, my friend informed me of the fact that Python has enums. So that solves that, although I am curious how people accomplished this sort of thing before enums were added.

VikingofRock fucked around with this message at 00:04 on Aug 2, 2016

lifg
Dec 4, 2000
<this tag left blank>
Muldoon
By using a class without inheriting from anything. I did this in python 2.7.

class MachineState:
sold_out = 1
has_quarter = 2
no_quarter = 3
sold = 4

Baby Babbeh
Aug 2, 2005

It's hard to soar with the eagles when you work with Turkeys!!



lifg posted:

By using a class without inheriting from anything. I did this in python 2.7.

class MachineState:
sold_out = 1
has_quarter = 2
no_quarter = 3
sold = 4

What's the advantage of an enum over this approach? I read through the python enum documentation VikingofRock posted and I'm not entirely sure I get what makes them distinct. Is it just that enum is iterable? Forgive me if this is a dumb question, but I'm a beginner and I'm not familiar with languages like C where this structure is common.

Dominoes
Sep 20, 2007

I'm curious too - not sure where to use them, other than serializing categorical entries in a database.

Asymmetrikon
Oct 30, 2009

I believe you're a big dork!
The Python "class with just static members representing constants" is essentially an implementation of enums, so you use enums anywhere you'd use that. They make more sense in a statically typed language when you want to guarantee that a thing is one of a set of values - not something you can do easily in Python, but still useful sometimes when you don't want to just give something a string value.

lifg
Dec 4, 2000
<this tag left blank>
Muldoon

Baby Babbeh posted:

What's the advantage of an enum over this approach? I read through the python enum documentation VikingofRock posted and I'm not entirely sure I get what makes them distinct. Is it just that enum is iterable? Forgive me if this is a dumb question, but I'm a beginner and I'm not familiar with languages like C where this structure is common.

WIthout the enum, you're just making aliases for numbers. The "class.atttribute" is still just a number under the hood. Which is probably fine for most cases.

But some people wanted enum purity, where an enum was it's own thing, and can't be compared to numbers.

code:
from enum import Enum

class Me:
	hi = 1
	bye = 2

class You(Enum):
	hi = 1
	bye = 2

print(Me.hi)         # 1
print(type(Me.hi))   # <class 'int'>
print(Me.hi == 1)    # True

print(You.hi)        # You.hi
print(type(You.hi))  # <enum 'You'>
print(You.hi == 1)   # False
Check out PEP 435 for more. https://www.python.org/dev/peps/pep-0435/

(Edit: enum will also raise nicely specific errors if you screw up.)

lifg fucked around with this message at 07:41 on Aug 3, 2016

QuarkJets
Sep 8, 2008

Wouldn't you want enums to be able to compare to numbers, though? Like how bools can compare to numbers.

e: holy poo poo according to that PEP article the enum debate was raging as far back as 2005, and it does a good job of getting into a bunch of the little detailed arguments regarding the specificities of this enum implementation.

I like this, you basically have C-style enums if you use the functional API or old-Python-style enums but with new features by just inheriting from Enum. Clearly a lot of consideration went into this

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
There's also a subclass IntEnum for if you want enums that are directly comparable to integers, so you can choose whether your enum supports the kind of "use interchangeably with integers" behaviour you get in some other languages. You also have support for the underlying type of the members being something other than integers IIRC (so if you wanted you could have an enum with strings as the underlying type).

Plasmafountain
Jun 17, 2008

Got a question for you fine folks.

I've got a function where I'm dealing with mach numbers and angles. I need to get the angle of the sum of these mach angles.

Mu (mach angle) = sin^-1 (1/M)

I'm having a hassle as you might expect where M is exactly equal to 1. Or at least, very very close to it.

If I use:

code:

Angle  = np.tan( 0 + np.arcsin(1/1))

I get a stonkingly large number for a gradient angle. This is fine, and to be expected.

However, if I use actual numbers where 0 is a float 0.0, I get a NaN error being returned.

If I use a really long number of 0.9999999999999999999999 then I get a float being returned, but this length is in excess of the normal number of decimal places normally being passed:

code:

np.arcsin(1.0/0.99999999999)
S:/Python/MSC/sauers.py:1: RuntimeWarning: invalid value encountered in arcsin
  # -*- coding: utf-8 -*-
Out[10]: nan
np.arcsin(1.0/0.99999999999)
S:/Python/MSC/sauers.py:1: RuntimeWarning: invalid value encountered in arcsin
  # -*- coding: utf-8 -*-
Out[10]: nan

np.arcsin(1.0/0.999999999999999999999999999999)
Out[11]: 1.5707963267948966

np.tan(0 + np.arcsin(1.0/0.999999999999999999999999999999))
Out[12]: 16331239353195370.0
How can I work around this issue if the number the pre-conditioning function gives is only 0.9999999999999999 instead of its much longer brother?

Additionally, if I add in a line so that:

code:
def lambdaPosCalc(Theta,M):
    
    if M <= 1.0:
        M = 1.0
        
        L = np.tan(Theta + np.arcsin(1/M))
    
        print('L = TAN({0} + Sin^-1 (1/{1})) = {2}'.format(Theta,M,L))
    
        return L

I get some weird thing where the value of the M variable is being changed outside the function when it should be static.

Plasmafountain fucked around with this message at 23:42 on Aug 3, 2016

Dominoes
Sep 20, 2007

Are you sure your formula's right? I don't think an angle can be infinite!

VikingofRock
Aug 24, 2008




Zero Gravitas posted:

Got a question for you fine folks.

I've got a function where I'm dealing with mach numbers and angles. I need to get the angle of the sum of these mach angles.

Mu (mach angle) = sin^-1 (1/M)

I'm having a hassle as you might expect where M is exactly equal to 1. Or at least, very very close to it.

The problem here is that when you have an M which is slightly less than 1, and you take arcsin(1/M), you get NaN since 1/M > 1 and arcsin isn't defined for values > 1. When you enter the very long floating representation, probably M gets rounded to exactly 1.0 and things work out. Depending on your application, a decent work around might be to just say that if M < 1.0, M = 1.0 (if M can be <= -1 you'll need to modify this slightly).

edit: Didn't see your edit. If you are getting in trouble with re-assigning M, you could just say M_prime = M if M >= 1.0 else 1.0. Then use M_prime in your formulae.

VikingofRock fucked around with this message at 23:48 on Aug 3, 2016

Plasmafountain
Jun 17, 2008

Dominoes posted:

Are you sure your formula's right? I don't think an angle can be infinite!

Its a function to create a gradient, in this case a vertical line for arcsin(1), so an infinite gradient is exactly what I'd expect.

Some weird stuff is going on, but im going to call it a night and look at it tomorrow. I get the feeling theres some radian/degrees fuckery going on somewhere in the remainder of the program.

QuarkJets
Sep 8, 2008

Zero Gravitas posted:

Its a function to create a gradient, in this case a vertical line for arcsin(1), so an infinite gradient is exactly what I'd expect.

Some weird stuff is going on, but im going to call it a night and look at it tomorrow. I get the feeling theres some radian/degrees fuckery going on somewhere in the remainder of the program.

I think that Dominoes is saying that there's something wrong with your labeling here:

Zero Gravitas posted:

code:

Angle  = np.tan( 0 + np.arcsin(1/1))


I think it would up just being a typo in your post, since you said that you expect a gradient (not an angle)

VikingofRock seems to have figured out the other issues, but I'm not sure why you're testing the M=0.99999999999 cases at all. Shouldn't you always have M >= 1, so testing 1.000000001 would be valid but 0.99999999999 would not? Is the issue that you're winding up with 0.9999999999 as a close-approximation to 1 from somewhere else? Then I think VikingofRock's suggestion is the right way to go:

code:
Mprime = M if M > 1.0 else 1.0
L = np.tan(Theta + np.arcsin(1/Mprime))
Also I'd like to suggest not using single-latter variables like M or L, it's pretty common to see that occurring in scientific code and it's not technically wrong but it is harder to read and modify later, in my opinion. I'd use mach_angle instead of M

Eela6
May 25, 2007
Shredded Hen
This seems like a numerical analysis problem.

Note that 0.999999999999999999999999999999 == 1 in standard floating-point arithmetic.

Since arcsin defined on -1<=x<=1, we get a nan.

code:
0.999999999999
Out[43]: 0.999999999999

0.99999999999999999
Out[44]: 1.0
Not sure what your code is supposed to do. Remember that angles are modulo 2pi; you shouldn't be able to end up with infinite angles.

Stinky_Pete
Aug 16, 2015

Stinkier than your average bear
Lipstick Apathy

Zero Gravitas posted:

Its a function to create a gradient, in this case a vertical line for arcsin(1), so an infinite gradient is exactly what I'd expect.

Some weird stuff is going on, but im going to call it a night and look at it tomorrow. I get the feeling theres some radian/degrees fuckery going on somewhere in the remainder of the program.

How do you use the gradient?

The Gasmask
Nov 30, 2006

Breaking fingers like fractals
Just want to pop in and say I'm having fun with Python! And I've got some super beginner questions, but for now I'll just ask one to avoid embarrassing myself too much.

Been using a Python-based plugin for Blender that's in open development, and out of necessity had to figure out how to make some changes to it to correct a bug. That led to me forking the github repo and making some changes that got the pull request accepted and merged, and now I want to keep on doing this because I think I can actually learn it!

So I've noticed in the code, some statements (is that the right term?) will have something like scene.current_frame, and elsewhere be bpy.scene.current_frame. From how it looks I'm assuming the bpy is referring to some Blender-specific Python - would this be a decent assumption? I haven't done enough playing with it to see the difference in outcome with or without the "bpy" (or "renderman" or whatever else it might be), but knowing where the code is coming from would definitely help me search out the specific libraries/modules and start to figure out how it's all put together.

lifg
Dec 4, 2000
<this tag left blank>
Muldoon
You got it.

code:

import bpy
bpy.scene.current_frame

In here, the "bpy.scene.current_frame" is referring to something in the blender library.

"scene.current_frame" would probably refer to a local variable "scene". But I'd bet that "scene" is initialized, earlier in the code, to something from bpy.

The Gasmask
Nov 30, 2006

Breaking fingers like fractals
Alright thanks! Good to know my assumption was correct.

I'm surprised at how easy Python is to understand even though my programming knowledge consists of a C/C++ course 18 years ago and some super simple assembly stuff from the same time period, all of which I've mostly forgotten. I can see why people say it's the easiest to jump into.

E: another quick one -
Does it matter if, when doing the
code:

butt = scene.frame_current
thing to make the code simpler/more readable that butt is used elsewhere as a name (not a variable though)? My first guess would be not to reuse names like that, but since they seem to be defined at the start of a code block for that specific bit of code maybe they can.

The Gasmask fucked around with this message at 14:30 on Aug 11, 2016

lifg
Dec 4, 2000
<this tag left blank>
Muldoon
What do you mean "use elsewhere as a name but not a variable"? Can you give an example?

The Gasmask
Nov 30, 2006

Breaking fingers like fractals

lifg posted:

What do you mean "use elsewhere as a name but not a variable"? Can you give an example?

Sorry, I didn't phrase it the best, but I figured it out. That part you quoted was incorrect of course, it's a variable regardless, but I just wasn't sure if I could reuse those shortened variable names for different blocks of code.

Proteus Jones
Feb 28, 2013



The Gasmask posted:

Sorry, I didn't phrase it the best, but I figured it out. That part you quoted was incorrect of course, it's a variable regardless, but I just wasn't sure if I could reuse those shortened variable names for different blocks of code.

Technically yes. But in practice, it's not recommended.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

flosofl posted:

Technically yes. But in practice, it's not recommended.

Assuming we're talking about the same name in different scopes, is there any reason for this? I've seen... uh, something complaining about using names for method parameters that are already being used in the main block, but there's no actual conflict right? Is it just to avoid weird bugs if you delete the local declaration and end up referring to another variable in an outer scope, or something?

The Gasmask
Nov 30, 2006

Breaking fingers like fractals

flosofl posted:

Technically yes. But in practice, it's not recommended.

Yeah, I'm used to needing them to be unique from what little bit of coding I know so I'm keeping them that way, but I've noticed some repeating names in a module I'm working on, which is what prompted the question to begin with.

Thanks again!

lifg
Dec 4, 2000
<this tag left blank>
Muldoon

baka kaba posted:

Assuming we're talking about the same name in different scopes, is there any reason for this? I've seen... uh, something complaining about using names for method parameters that are already being used in the main block, but there's no actual conflict right? Is it just to avoid weird bugs if you delete the local declaration and end up referring to another variable in an outer scope, or something?

There *may* not be a strict conflict, but it's recommended against because...

1) It can lead to confusion when you're reading the code quickly. You want to have everything that can affect a function be clearly defined right in that function. (Which should fit on a screen.)

2) If you make a mistake programming, like a typo, it can be hard to track down the bug if you mix local and global variable names. You'll spend hours asking yourself, "why is this variable set? I never set this."

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Well I'm talking about declaring a local variable, that just happens to share a name with a variable in an outer scope. So you are defining it in the function, and you're not referring to a global variable outside of that function's local scope. (Well you could be if you do a typo, but lots of things can go wrong if you type the wrong variable name!)

I mean something like this

Python code:
def fart(butt):
    print("g'day " + butt)


def fart2(rear end):
    butt = rear end
    print(butt)


if __name__ == "__main__":
    butt = "butte"
    fart(butt)
in PyCharm gives a lint warning for the method parameter, "shadows name 'butt' from outer scope". Same for calling some rando variable 'butt' inside a method. So to avoid that warning (which I'm assuming exists for a good reason) you need to arbitrarily rename all your local butts even though there's no actual conflict in scope? It turns simple naming schemes into something awkward.

You can't accidentally write to a global variable from a local scope unless you specifically enable it - you can't read the global variable if you shadow it either, but that's true for every other language I've used, and I don't get a 'whoa now you already used this name in an outer scope' warning in say Java. So is it really just a warning that this might not be best practice in case you mess up changing things later? Seems weird

baka kaba fucked around with this message at 01:20 on Aug 13, 2016

Adbot
ADBOT LOVES YOU

Nippashish
Nov 2, 2005

Let me see you dance!

baka kaba posted:

in PyCharm gives a lint warning for the method parameter, "shadows name 'butt' from outer scope". Same for calling some rando variable 'butt' inside a method. So to avoid that warning (which I'm assuming exists for a good reason) you need to arbitrarily rename all your local butts even though there's no actual conflict in scope? It turns simple naming schemes into something awkward.

You'll avoid 99% of the cases this shows up if you do
code:
def main():
    # your code here

if __name__ == '__main__':
    main()
instead of writing code in the "main block" directly.

  • Locked thread