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
salisbury shake
Dec 27, 2011
click is a module by the flask guy that provides a nice interface to optparse
http://click.pocoo.org/4/

Adbot
ADBOT LOVES YOU

Edison was a dick
Apr 3, 2010

direct current :roboluv: only

salisbury shake posted:

click is a module by the flask guy that provides a nice interface to optparse
http://click.pocoo.org/4/

Interesting.

It'd be interesting to see an argument parsing library that used function parameter annotations.

duck monster
Dec 15, 2004

pip install ipdb


Then wherever you want a break point;-

import ipdb; ipdb.set_trace()

I prefer ipdb, as it uses iPython which has nice color coding and tab completion and stuff, assuming your using a platform that supports readline

Dominoes
Sep 20, 2007

Is there a way to get Pycharm to show and push to all git remotes? Currently, it only displays Origin.

QuarkJets
Sep 8, 2008

Dominoes posted:

Is there a way to get Pycharm to show and push to all git remotes? Currently, it only displays Origin.

Not even git lets you do this with one command without some setup first

What you can do instead is create an "all" remote with several URLs attached to it:

git remote add all host_origin:path/myrepo.git
git remote set-url --add all host1:path1/myrepo.git
git remote set-url --add all host2:path2/myrepo.git

And then you can use "git push all --all" to push to all of them at once

I haven't used Pycharm's git interface, but if Pycharm is only showing Origin, then you probably haven't added any remotes yet.

Dominoes
Sep 20, 2007

Thanks. With normal git, while I can't push to all at once, I can push to any individually. When I run 'git remote', it correctly shows both remotes, but Pycharm only sees one.

SurgicalOntologist
Jun 17, 2004

I much prefer docopt over click (and I've used both, extensively).

Ghost of Reagan Past
Oct 7, 2003

rock and roll fun
I'm making some charts with matplotlib, and on one sort of chart, over time, everything is right but the x-axis labels are ugly times like '13:43:00.0000000' and I can't understand the documentation well enough to know what to even do to format this better :psyduck: I mean, it's almost correct, but it could be so much better. How do I do this?

I'm using plot_date instead of plain old plot, if that makes a difference.

QuarkJets
Sep 8, 2008

Ghost of Reagan Past posted:

I'm making some charts with matplotlib, and on one sort of chart, over time, everything is right but the x-axis labels are ugly times like '13:43:00.0000000' and I can't understand the documentation well enough to know what to even do to format this better :psyduck: I mean, it's almost correct, but it could be so much better. How do I do this?

I'm using plot_date instead of plain old plot, if that makes a difference.

Try using the formatting argument (I think it's "fmt")

Ghost of Reagan Past
Oct 7, 2003

rock and roll fun

QuarkJets posted:

Try using the formatting argument (I think it's "fmt")
The formatting argument in plot_date() is for the line, not the axes.

goodness
Jan 3, 2012

When the light turns green, you go. When the light turns red, you stop. But what do you do when the light turns blue with orange and lavender spots?
.

SirPablo
May 1, 2004

Pillbug

Ghost of Reagan Past posted:

I'm making some charts with matplotlib, and on one sort of chart, over time, everything is right but the x-axis labels are ugly times like '13:43:00.0000000' and I can't understand the documentation well enough to know what to even do to format this better :psyduck: I mean, it's almost correct, but it could be so much better. How do I do this?

I'm using plot_date instead of plain old plot, if that makes a difference.

How about plotting with pandas?

vikingstrike
Sep 23, 2007

whats happening, captain
If you don't have many labels, just pass them in explicitly and be done with it.

Ghost of Reagan Past
Oct 7, 2003

rock and roll fun

vikingstrike posted:

If you don't have many labels, just pass them in explicitly and be done with it.
I ended up figuring out how to grab the axes and set the major formatter to DateFormatter with the right format string :shrug:. It worked.

Horse Inspector
Aug 11, 2005
privacy publicly displayed
Recently started learning Python and numpy/Scipy and ran in to the usual floating point issues. A quick and dirty example for illustration purposes:
code:
>>> sp.expit(-15 + (10*b) + (10*a))
0.0071527881888964915
>>> sp.expit(-15 + (10*a) + (10*b))
0.0071527881888964846
numpy/scipy does not to my knowledge support the Decimal type, but precision is very important to me. Am I missing a really dumb solution to this?

OnceIWasAnOstrich
Jul 22, 2006

embarrasing tank posted:

numpy/scipy does not to my knowledge support the Decimal type, but precision is very important to me. Am I missing a really dumb solution to this?

No, numpy is for doing math with normal sorts of datatypes, and if you have precision problems with your floats it doesn't have any intrinsic way to fix that problem. If you need essentially arbitrary precision and can't do fuzzy comparisons you could try a different library like SymPy or mpmath. Alternatively if you just need MORE precision you might be able to force a numpy.float128 dtype.

Horse Inspector
Aug 11, 2005
privacy publicly displayed

OnceIWasAnOstrich posted:

No, numpy is for doing math with normal sorts of datatypes, and if you have precision problems with your floats it doesn't have any intrinsic way to fix that problem. If you need essentially arbitrary precision and can't do fuzzy comparisons you could try a different library like SymPy or mpmath. Alternatively if you just need MORE precision you might be able to force a numpy.float128 dtype.

Thank you for this info!

Spaseman
Aug 26, 2007

I'm a Securitron
RobCo security model 2060-B.
If you ever see any of my brothers tell them Victor says howdy.
Fallen Rib
Can someone explain why this code is running the way it is? As far as I am aware the any statements should be returning TRUE every time.

code:
class Class001(object):
    def __init__(self, mylist = None):
        self.mylist = []

class Class002(object):
    def __init__(self):
        pass

testclass001 = Class001()
testclass002 = Class002()

testclass001.mylist.append(testclass002)
testclass001.mylist.append("Dogs")
testclass001.mylist.append(15)

print (testclass001.mylist)

if any(1 == testclass001 for l in testclass001.mylist):
    print ("YES")
else:
    print ("NO")
    
if any(1 == "Dogs" for l in testclass001.mylist):
    print ("YES")
else:
    print ("NO")

if any(1 == 15 for l in testclass001.mylist):
    print ("YES")
else:
    print ("NO")

csammis
Aug 26, 2003

Mental Institution
For starters, your predicate says "1 is equal to <whatever>", the numeral '1', and I think you meant lower-case "L". You might want to look into using a better font :)

SirPablo
May 1, 2004

Pillbug

BigRedDot posted:

Welp. https://news.ycombinator.com/item?id=9936295

If there's things you want to see in Anaconda, let us know, we are moving ahead full bore :)

Something to read grib files (like pygrib) would be great.

KICK BAMA KICK
Mar 2, 2009

Spaseman posted:

Can someone explain why this code is running the way it is? As far as I am aware the any statements should be returning TRUE every time.
Aside from the aforementioned numeral "1" vs. lowercase "L" confusion, your first test should be false because the object testclass001 is not in testclass001.mylist, but testclass002 is.

Minor Pythonic points: the way to write those comparisons is if 'Dogs' in testclass001.mylist; you can just put the pass right under class Class002(object):, you don't need to declare the constructor if it doesn't do anything; and it's fine to define the instance attribute mylist of Class001 without listing it among the parameters of the constructor since you aren't doing anything with the value of the argument.

salisbury shake
Dec 27, 2011

SurgicalOntologist posted:

I much prefer docopt over click (and I've used both, extensively).

This owns

pmchem
Jan 22, 2010


embarrasing tank posted:

Recently started learning Python and numpy/Scipy and ran in to the usual floating point issues. A quick and dirty example for illustration purposes:
code:
>>> sp.expit(-15 + (10*b) + (10*a))
0.0071527881888964915
>>> sp.expit(-15 + (10*a) + (10*b))
0.0071527881888964846
numpy/scipy does not to my knowledge support the Decimal type, but precision is very important to me. Am I missing a really dumb solution to this?

just curious, but why do you want precision more than IEEE-754 provides, when doing math with exponentials? what's your use case?

Spaseman
Aug 26, 2007

I'm a Securitron
RobCo security model 2060-B.
If you ever see any of my brothers tell them Victor says howdy.
Fallen Rib
Thanks for the help everyone. I can't believe the problem was something so dumb.

The reason I asked about that code is that I am trying to recreate the code I'm using in my actual project to fix a different problem I am having.

No matter what method I try, I can never get the following code to work correctly:

code:
                if AreaOneItemRoulette == 0:
                    self.WoodSword001 = WoodenSword()
                    
                    if any(k == self.WoodSword001 for k in Spaseman.items_held):
                        print ("You find nothing.")
                    else:
                        Spaseman.items_held.append(self.WoodSword001)
This code is a part of a larger project and every time I rerun the loop that this code is a part of it always believes that WoodSword001 is not in Spaseman.items_held and therefore places a new instance of WoodSword001 into Spaseman.items_held when it shouldn't because there already is an instance inside.

I have no formal programming experience so please tell me if something doesn't make sense.

Stringent
Dec 22, 2004


image text goes here

Spaseman posted:

Thanks for the help everyone. I can't believe the problem was something so dumb.

The reason I asked about that code is that I am trying to recreate the code I'm using in my actual project to fix a different problem I am having.

No matter what method I try, I can never get the following code to work correctly:

code:
                if AreaOneItemRoulette == 0:
                    self.WoodSword001 = WoodenSword()
                    
                    if any(k == self.WoodSword001 for k in Spaseman.items_held):
                        print ("You find nothing.")
                    else:
                        Spaseman.items_held.append(self.WoodSword001)
This code is a part of a larger project and every time I rerun the loop that this code is a part of it always believes that WoodSword001 is not in Spaseman.items_held and therefore places a new instance of WoodSword001 into Spaseman.items_held when it shouldn't because there already is an instance inside.

I have no formal programming experience so please tell me if something doesn't make sense.

I think your comparison needs to be:
Python code:
                    if any(isinstance(k, WoodenSword) for k in Spaseman.items_held):
Also this makes more sense to me, but maybe there's some additional context?
Python code:
                if AreaOneItemRoulette == 0:
                    if any(isinstance(k, WoodenSword) for k in Spaseman.items_held):
                        print ("You find nothing.")
                    else:
                        self.WoodSword001 = WoodenSword()
                        Spaseman.items_held.append(self.WoodSword001)

Spaseman
Aug 26, 2007

I'm a Securitron
RobCo security model 2060-B.
If you ever see any of my brothers tell them Victor says howdy.
Fallen Rib

Stringent posted:

I think your comparison needs to be:
Python code:
                    if any(isinstance(k, WoodenSword) for k in Spaseman.items_held):
Also this makes more sense to me, but maybe there's some additional context?
Python code:
                if AreaOneItemRoulette == 0:
                    if any(isinstance(k, WoodenSword) for k in Spaseman.items_held):
                        print ("You find nothing.")
                    else:
                        self.WoodSword001 = WoodenSword()
                        Spaseman.items_held.append(self.WoodSword001)

That is EXACTLY what I needed, thank you so much. I've been fighting that problem for days and now I can finally move on.

Horse Inspector
Aug 11, 2005
privacy publicly displayed

pmchem posted:

just curious, but why do you want precision more than IEEE-754 provides, when doing math with exponentials? what's your use case?

Honestly it was disingenuous to use the term precision, I'm not sure why I did. What I was really after was consistency. OnceIWasAnOstrich's answer put me on the right track and I have ended up starting to use Theano.

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

Spaseman posted:

That is EXACTLY what I needed, thank you so much. I've been fighting that problem for days and now I can finally move on.

Do you understand why though? When you create a new object it's a unique instance, so you can't just check new_sword == old_sword because they refer to two different, individual objects, even though they're instances of the same class

It's important because it comes up a lot, and you might have your own equality checking code so you can do simple comparisons (like keyring_1 comparing the list of doors it opens to the list that keyring_2 opens)

Nippashish
Nov 2, 2005

Let me see you dance!

embarrasing tank posted:

Honestly it was disingenuous to use the term precision, I'm not sure why I did. What I was really after was consistency. OnceIWasAnOstrich's answer put me on the right track and I have ended up starting to use Theano.

Theano should not help with this, it's basically a more complicated way to use numpy. What is the input you're giving to expit that it returns different values on different runs?

FoiledAgain
May 6, 2007

PyQt question. I'm having a hard time understanding how the model/view concept works. Right now, I'm trying to set up a table, but when I call QTableView.setModel(Model), I get "RuntimeError: super-class __init__() of type Model was never called". However, I'm dead certain that __init__ is called. What have I done wrong? Here's the skeleton of the code:

code:
class Player(object):
    def __init__(self):
        self.inventory = Inventory()

class Inventory(QAbstractTableModel):
    def __init__(self):
        super().__init__() #See! This line does exist!
        #load data into the model...

class InventoryManager(QDialog):
    def __init__(self, player):
        super().__init__()
        self.display = InventoryTable(player.inventory)

class InventoryTable(QTableView):
    def __init__(self,model):
        super().__init__()
        self.setModel(model) #this is where the RuntimeError occurs

p = Player()
im = InventoryManager(p) #RuntimeError - super-class __init__() of type Inventory was never called

Horse Inspector
Aug 11, 2005
privacy publicly displayed

Nippashish posted:

Theano should not help with this, it's basically a more complicated way to use numpy. What is the input you're giving to expit that it returns different values on different runs?

I'm deliberately not going in to detail as I don't want to clog up the short questions thread with a long question and my idiocy, but the short version is you are right, I misinterpreted the Theano documentation on first reading. However Sympy's symbolic versions of variables seem to give me what I want when I evaluate them. By that I mean if I have two expressions that are exactly the same, just slightly rearranged (and not in a way that would effect output) then I should get the same output.

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES
So I am trying to modify some existing tools we have to query a web database. We use a proxy, so the setup is very much like it is in the python docs, specifically:

code:
PROXY_ADDR = 'blah'
proxy_support = urllib2.ProxyHandler({'http://': PROXY_ADDR})
opener = urllib.build_opener(proxy_support)
data = opener.open(query)
This works in what it does now, resulting in an object that is then handed off to csv.reader() to be read in and then dumped out to STDOUT. I don't want that, I want the results as a list.

Everything Im finding seems to imply I can just read() off the data object and merrily take it (line by line if I have to), but that only results in blanks. If I try to read out lines after the csv.reader() takes it, I also get nothing. Right now the only way I know of to get what I want would be to write to a tempfile and then read it back in. There's gotta be a better way, and I'm most certainly missing something obvious.

Thanks in advance y'all.

Communist Pie
Mar 11, 2007

...Robot!
How do you get IPython to display HTML?

In an IPython console in spyder, I'm using %%cython -a to display the generated code for a cython function, but on a new version of WinPython, all I get is Out[12]: <IPython.core.display.HTML object>. On an old install of Anaconda, doing the same displays the annotated cython output in the console.

EDIT: Well, it seems like the only way to do this is to use an old version of IPython. Lame, it was nice being able to do everything without leaving spyder.

Communist Pie fucked around with this message at 05:30 on Aug 9, 2015

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES

JetsGuy posted:

So I am trying to modify some existing tools we have to query a web database. We use a proxy, so the setup is very much like it is in the python docs, specifically:

code:
PROXY_ADDR = 'blah'
proxy_support = urllib2.ProxyHandler({'http://': PROXY_ADDR})
opener = urllib.build_opener(proxy_support)
data = opener.open(query)
This works in what it does now, resulting in an object that is then handed off to csv.reader() to be read in and then dumped out to STDOUT. I don't want that, I want the results as a list.

Everything Im finding seems to imply I can just read() off the data object and merrily take it (line by line if I have to), but that only results in blanks. If I try to read out lines after the csv.reader() takes it, I also get nothing. Right now the only way I know of to get what I want would be to write to a tempfile and then read it back in. There's gotta be a better way, and I'm most certainly missing something obvious.

Thanks in advance y'all.

I don't know what the hell happened but when I loaded my machine this morning, it was working the way I figured it would. That is, I could do just a straight "for line in data" to get what was being queried. Guess it was just one of those things.

Begall
Jul 28, 2008
I'm writing a Web Services server using flask, with a back end of sqlite3. I want to output data in a JSON format directly from the database, including the column headings like so:

JavaScript code:
{
  "Data Items": [
    {
      "Item 1": "A", 
      "Item 2": "ABC12345667W01", 
      "Item 3": "F", 
    }, 
    {
      "Item 1": null, 
      "Item 2": "AFFFFF123", 
      "Item 3": "D", 
    }, 
    {
      "Item 1": null, 
      "Item 2": "AB", 
      "Item 3": "X", 
    }
  ]
}
The first method I've come up with is to do something like this, but it seems messy enough that I feel like I must be missing a trick. In addition, I would need to add further code/another variable if I wanted the key fields not to be direct copy of the DB field names, which would be preferrable:

Python code:
    d = ["item1", "item2", "item3"]
    x = db.query("SELECT %s FROM table1 WHERE internalid = ?" %(', '.join(d)), (id,)).fetchall() # db.query is just a proxy to the sqlite3 object
    f = {'Data Items' : []}
    for result in x:
        n = {}
        for i, field in enumerate(result):
            n[d[i]] = field
                    
        f['Data Items'].append(n)
    return jsonify(f)  

Any thoughts?

Xeno54
Apr 25, 2004
bread

Begall posted:

The first method I've come up with is to do something like this, but it seems messy enough that I feel like I must be missing a trick.

If you have separate iterables containing keys and values, a trick you can use for creating dictionaries is:
Python code:
my_dict = dict(zip(keys, values))
This essentially replaces the dictionary initialization and enumerate within your for loop:
Python code:
f = {'Data Items' : []}   
for result in x:
    n = dict(zip(d, result))
    f['Data Items'].append(n)
You can also combine this trick with a list comprehension to create the Data Items list more compactly:
Python code:
f = {}
f['Data Items'] = [dict(zip(d, result)) for result in x]
If you wanted to, you could even combine the above code into a single line. It seems a little convoluted for a single line, but it comes down to your coding preferences.
Python code:
f = {'Data Items': [dict(zip(d, result)) for result in x]}

Begall posted:

In addition, I would need to add further code/another variable if I wanted the key fields not to be direct copy of the DB field names, which would be preferrable.
Using the above trick, all you need to do is define a new list of key fields and use it as the first parameter of the zip.

Xeno54 fucked around with this message at 18:45 on Aug 8, 2015

Spaseman
Aug 26, 2007

I'm a Securitron
RobCo security model 2060-B.
If you ever see any of my brothers tell them Victor says howdy.
Fallen Rib
Can someone explain how to make the line "BaconTest001.Pit001" in the "AreaOne" class run? I'm working on deepening my understanding of classes and their interctions but nothing I do can make this particular line run. I know the code is a mess but that was the point.
code:
class BaconTest(object):
    def __init__(self):
        pass
    def test(self):
        print ("test")
        self.Pit001 = Pit()
        self.Stream001 = Stream()
        print ("test002")
        
class AreaOne(object):
    def __init__(self):
        print ("uxuxuxuxu")
    def areaonetest(self):
        print ("jhjhjhjhjhj")
        BaconTest001.Pit001 #Cannot Run#
        print ("4343434343")

class Pit(object):
    def __init__(self):
        print ("test3333")

class Stream(object):
    def __init__(self):
        pass

class Events(object):
    def __init__(self):
        print ("tertrtrt")
        self.BaconTest001 = BaconTest()
        self.BaconTest001.test()
        print ("dpdpdpdpd")
        self.AreaOne001 = AreaOne()
        print ("sdsdsdsd")
        self.AreaOne001.areaonetest()
        print ("po po po ")
    def MainMenu(self):
        self.AreaOne001

Game = Events()

print (Game.BaconTest001)
Game.BaconTest001.test()
print ("------")
Game.MainMenu()
Without that one line of code, everything runs fine but for some reason trying to call an object from within a class that is different from the class that created the object doesn't seem to work.

Nippashish
Nov 2, 2005

Let me see you dance!

Spaseman posted:

Can someone explain how to make the line "BaconTest001.Pit001" in the "AreaOne" class run?

I think you are not understanding the difference between a class and an instance of a class. Nothing about classes makes any sense at all if you don't understand this distinction.

Spaseman
Aug 26, 2007

I'm a Securitron
RobCo security model 2060-B.
If you ever see any of my brothers tell them Victor says howdy.
Fallen Rib

Nippashish posted:

I think you are not understanding the difference between a class and an instance of a class. Nothing about classes makes any sense at all if you don't understand this distinction.

A class is the constructor or blueprint that is used to create instances that can be edited but the constructor itself is not actually changed in any way, correct?

Adbot
ADBOT LOVES YOU

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Well, BaconTest001 doesn't exist "globally". It's owned by the Events object, so the Area object can't access it. You either need to make the Area class have its own BaconTest instance, or pass it into Area.

  • Locked thread