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
Nippashish
Nov 2, 2005

Let me see you dance!

Plorkyeran posted:

What makes you think that?

I'm not sure what made me think that, and I realized after I made the post that that part didn't make sense, which is why I edited it out.

Adbot
ADBOT LOVES YOU

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
My IDE suggested I rewrite my conditional

code:
is_active = mydict.get('key')
if is_active == False:
    # do stuff
as

code:
is_active = mydict.get('key')
if not is_active:
    # do stuff
but that doesn't have the same behavior when 'key' is not in mydict right? I should just ignore the suggestion?

My Rhythmic Crotch
Jan 13, 2011

fletcher posted:

code:
is_active = mydict.get('key')
if not is_active:
    # do stuff
That's generally the recommended way. I'd change the variable name to active instead of is_active, though. "If not active: do stuff" - it may as well be English.

FoiledAgain
May 6, 2007

fletcher posted:

My IDE suggested I rewrite my conditional

code:
is_active = mydict.get('key')
if is_active == False:
    # do stuff
as

code:
is_active = mydict.get('key')
if not is_active:
    # do stuff
but that doesn't have the same behavior when 'key' is not in mydict right? I should just ignore the suggestion?

Should be fine. When the key is not in the dictionary, then .get() returns None, which is treated the same as False for the conditional.

Opinion Haver
Apr 9, 2007

My Rhythmic Crotch posted:

That's generally the recommended way. I'd change the variable name to active instead of is_active, though. "If not active: do stuff" - it may as well be English.

But that has different behavior if key is not in mydict.

fletcher, maybe you should use a set of active (or inactive) things and do if 'key' not in actives? It depends on what you're trying to do, what the 'default' semantics are, etc.

My Rhythmic Crotch
Jan 13, 2011

Opinion Haver posted:

But that has different behavior if key is not in mydict.
Ah I spoke too soon. I remembered None != False and thought the logic was okay.

Thermopyle
Jul 1, 2003

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

My Rhythmic Crotch posted:

I'm just going to quote this page, replacing PHP with PML.

Granted, it's not exactly the same, but you get the idea. Also don't take what he says as gospel, because this is what his desk looks like.


:stonk:

And exactly the same thing could be said about templates in any language.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Opinion Haver posted:

But that has different behavior if key is not in mydict.

fletcher, maybe you should use a set of active (or inactive) things and do if 'key' not in actives? It depends on what you're trying to do, what the 'default' semantics are, etc.

It's a boolean, doesn't always have to be in mydict though. Variable name corresponds to a field on a REST API.

If it's not specified (key does not exist in mydict), I don't want it to # do stuff. From the replies it sounds like the IDE is suggesting something that is not a logic neutral change.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
If you want to compare against a boolean explicitly, always use foo is False, as lots of things can compare to False that aren't actually False.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Thermopyle posted:

And exactly the same thing could be said about templates in any language.

No? The issue here is that the entry point is a file on disk inside your htdocs: foo.php. In contrast, most Python frameworks are deployed so that the code and templates are entirely divorced from the resources you access with GET, and it's rare that somebody will have Apache configured so that foo.py will spawn off a Python instance.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Suspicious Dish posted:

If you want to compare against a boolean explicitly, always use foo is False, as lots of things can compare to False that aren't actually False.

Ahh that makes sense, thanks!

Thermopyle
Jul 1, 2003

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

Suspicious Dish posted:

The issue here is that the entry point is a file on disk inside your htdocs

Why are we assuming that is what we're talking about?

I mean why would we assume that some company some where wanted to do something like PML as something that would be directly served by Apache or something.

That doesn't seem like a reasonable assumption to me, but maybe I'm missing something.

My Rhythmic Crotch
Jan 13, 2011

You embed the code directly into the HTML precisely because you want Apache to just serve it.

Basically, gently caress anybody who tries to PHP-ize Python, which is exactly what that PML stuff appears to be.

Pollyanna
Mar 5, 2005

Milk's on them.


Please god don't PHPize anything. I don't know poo poo about web dev or programming and even I have heard how much PHP sucks.

Thermopyle
Jul 1, 2003

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

My Rhythmic Crotch posted:

You embed the code directly into the HTML precisely because you want Apache to just serve it.

I don't see how one follows from the other.

My Rhythmic Crotch posted:

Basically, gently caress anybody who tries to PHP-ize Python, which is exactly what that PML stuff appears to be.

Agreed.

I just don't see why anyone would assume the point of this hypothetical PML was to PHP-ize python. It seems like a simplistic attempt to create a out of band templating system to me. I mean, there's already templating systems out there that use python in html exactly as I'm suggesting was the obvious intention.

Anyway, its just a dumb job interview question and there's no reason to read more in to it than that. If we're going to argue about it, we're just arguing about the hypothetical intentions of hypothetical people.

QuarkJets
Sep 8, 2008

the posted:

Python code:
import os
from textwrap import dedent

os.chdir('C:\Users\Matthew')

p = True
e = False

with open('pml.html', 'r') as f:
    for line in f:
        if '<pml>' in line:
            p = False
            e = True
        if '</pml>' in line:
            p = True
            e = False
        if p == True and e == False:
            if '</pml>' in line:
                execfile('tmp.py')
            else:
                print line
        if p == False and e == True:
            if '<pml>' in line:
                pass
            else:
                with open('tmp.py', 'a') as t:
                    t.write(line)
                    
os.remove('tmp.py') 
The only issue is that my code doesn't handle the initial indent after the <pml> tag in their example code, which seems totally pointless. If I remove the initial indent the code runs fine and it doesn't affect the look much at all.

I don't think that your solution satisfies the problem's constraints, and you should probably redesign it anyway. Here are some vague comments:

A) You don't need two opposite-value bools

B) You don't have any comments anywhere

C) You definitely shouldn't use a chown and a static file name.

D) Your employer would probably be more impressed if you put this script in a function, and the function could be activated if you called this file from the command line. This gives the script a bit more versatility.

E) What happens when a line has multiple instances of <pml> and/or </pml>? I mean something like: <pml>print "This code will run"</pml><pml>print "This code will never run"</pml>

F) You're explicitly calling tmp.py every time that you read a </pml>, and you are continuously appending to tmp.py. This allows you to have access to variables defined in earlier pml blocks, but it also means that all of the code in earlier pml blocks is going to rerun every time. I doubt that this is the behavior that they want.

G) Their instructions explicitly state that your interpreter "should be able to handle indentation dependent upon the first non-whitespace line of python code." That means handling the initial indentation too, even if you think that it's pointless.

QuarkJets fucked around with this message at 07:58 on Nov 19, 2013

'ST
Jul 24, 2003

"The world has nothing to fear from military ambition in our Government."
I took a crack at that PML problem for fun. It only handles documents with pml tags that exist on their own lines, but I wanted to keep the implementation fairly simple. Here is what I did:

Python code:
from textwrap import dedent
from itertools import takewhile

def parse(filename, local_context=None):
    parsed_doc = []
    if not local_context:
        local_context = locals()

    with open(filename, 'r') as pml_file:
        pml_lines = pml_file.readlines()
        pml_iter = pml_lines.__iter__()

        for line in pml_iter:
            if '<pml>' in line:
                pml_doc = takewhile(lambda line: '</pml>' not in line, pml_iter)
                pml_statement = dedent(''.join(pml_doc))
                exec pml_statement in globals(), local_context
                parsed_doc.append(local_context['pml'])
            else:
                parsed_doc.append(line)

        return ''.join(parsed_doc)
        
if __name__ == '__main__':
    print(parse('pml.html'))
That code turns this:
XML code:
<html>
<h1>Hello There</h1>

<p>
This is an example of a pml file
</p>

<pml>
    def f():
        return "<h2>Good Bye</h2>"

    def square(x):
    	return x ** 2

    pml = f()
</pml>

<pml>
pml = "<p>The square of 16 is {}</p>".format(square(16))
</pml>

<html>
into this:
XML code:
<html>
<h1>Hello There</h1>

<p>
This is an example of a pml file
</p>

<h2>Good Bye</h2>
<p>The square of 16 is 256</p>

<html>
So now I have a code smell question. I pulled the iterator out of the original document's sequence of lines. I'm changing the iterator's state both with a for loop and within the for loop (via takewhile). It's great because I can pass through the document once, but I feel as if there's a more readable way to get similar behavior. Any ideas, or do you think it's fine to implicitly call next() on the same iterator from different places?

Dominoes
Sep 20, 2007

Dominoes posted:

QT issue - I'm trying to make doubleclicking items in a tree widget do things.

itemDoubleClicked is a signal of tree widget.

Python code:
item = QtWidgets.QTreeWidgetItem(self.ui.tr_owned)
self.ui.tr_owned.itemDoubleClicked.connect(lambda symbol: hist_data.plot(symbol))
This works, but isn't specific to the item clicked.

The QT documentation lists its parameters as this: void QTreeWidget::itemDoubleClicked(QTreeWidgetItem * item, int column) [signal]

Python code:
item = QtWidgets.QTreeWidgetItem(self.ui.tr_owned)
self.ui.tr_owned.itemDoubleClicked(item, 4).connect(lambda symbol: hist_data.plot(symbol))
This doesn't work: TypeError: native Qt signal is not callable

Solution:

Python code:
self.ui.tr_owned.itemDoubleClicked.connect(self.dclick)

def dclick(self, item):
    hist_data.chart(item.text(0))
The key is that the tree item is implicitly sent as the first argument from the itemDoubleClicked signal. I believe that is what the 'QTreeWidgetItem * item' bit from the docs is saying. It also appears that the column selected is passed as the second argument.

Dominoes fucked around with this message at 18:03 on Nov 19, 2013

BigRedDot
Mar 6, 2008

Hey guys I just wanted to mention that we released Bokeh 0.3 today. It is easily installable via conda or pip. This particular release was mostly an internal refractor to put us on better footing for additional features coming down the road. But we did add lots of new examples, improve the docs, and squash several bugs.



Dren
Jan 5, 2001

Pillbug
I'm currently using matplotlib for plotting rather than d3.js primarily because I can generate a bunch of svg/png/whatever files with matplotlib and ship them off somewhere. As far as I can tell, d3.js needs the browser in order to render.

Is bokeh able to render directly to disk?

Malcolm XML
Aug 8, 2009

I always knew it would end like this.

'ST posted:

I took a crack at that PML problem for fun. It only handles documents with pml tags that exist on their own lines, but I wanted to keep the implementation fairly simple. Here is what I did:

Python code:
from textwrap import dedent
from itertools import takewhile

def parse(filename, local_context=None):
    parsed_doc = []
    if not local_context:
        local_context = locals()

    with open(filename, 'r') as pml_file:
        pml_lines = pml_file.readlines()
        pml_iter = pml_lines.__iter__()

        for line in pml_iter:
            if '<pml>' in line:
                pml_doc = takewhile(lambda line: '</pml>' not in line, pml_iter)
                pml_statement = dedent(''.join(pml_doc))
                exec pml_statement in globals(), local_context
                parsed_doc.append(local_context['pml'])
            else:
                parsed_doc.append(line)

        return ''.join(parsed_doc)
        
if __name__ == '__main__':
    print(parse('pml.html'))
That code turns this:
XML code:
<html>
<h1>Hello There</h1>

<p>
This is an example of a pml file
</p>

<pml>
    def f():
        return "<h2>Good Bye</h2>"

    def square(x):
    	return x ** 2

    pml = f()
</pml>

<pml>
pml = "<p>The square of 16 is {}</p>".format(square(16))
</pml>

<html>
into this:
XML code:
<html>
<h1>Hello There</h1>

<p>
This is an example of a pml file
</p>

<h2>Good Bye</h2>
<p>The square of 16 is 256</p>

<html>
So now I have a code smell question. I pulled the iterator out of the original document's sequence of lines. I'm changing the iterator's state both with a for loop and within the for loop (via takewhile). It's great because I can pass through the document once, but I feel as if there's a more readable way to get similar behavior. Any ideas, or do you think it's fine to implicitly call next() on the same iterator from different places?

This will break horribly if you have quoted <pml> in say JS, embedded in a script tag.

I wouldn't handroll a parser here, HTML parsers will likely treat the pml tag as an unknown and will keep it around. XML parsers will be stricter. Maybe I'm misunderstanding what they want.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

Malcolm XML posted:

This will break horribly if you have quoted <pml> in say JS, embedded in a script tag.
That may be the desired behavior (it usually is for templating engines).

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Malcolm XML posted:

This will break horribly if you have quoted <pml> in say JS, embedded in a script tag.

document.write('<p' + 'ml>');

BigRedDot
Mar 6, 2008

Dren posted:

I'm currently using matplotlib for plotting rather than d3.js primarily because I can generate a bunch of svg/png/whatever files with matplotlib and ship them off somewhere. As far as I can tell, d3.js needs the browser in order to render.

Is bokeh able to render directly to disk?

Not currently. Our emphasis is really on interactive plots as well as plots that can be created and updated in-browser from python. That said, I would like to see better facilities for saving static plots, it's just a matter of prioritizing. Or finding interested new devs. :)

Edit: I should say there is an old, out-of date, beginning of a chaco backend that was used for some prototyping. If that could be cleaned up and made to work again with the new glyph types then it would be possible. My personal plan though, is to try browser-less plot generation with phantomJS. But that won't be until sometime into 2014 unless a someone new decides to get involved.

BigRedDot fucked around with this message at 17:17 on Nov 20, 2013

The March Hare
Oct 15, 2006

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

BigRedDot posted:

Hey guys I just wanted to mention that we released Bokeh 0.3 today. It is easily installable via conda or pip. This particular release was mostly an internal refractor to put us on better footing for additional features coming down the road. But we did add lots of new examples, improve the docs, and squash several bugs.





Congrats on hitting top 10 on HN :) -- the project looks cool, I might mess around with it at some point.

Red Robin Hood
Jun 24, 2008


Buglord
I have nearly 0 coding experience. I've done a fair bit of HTML, some CSS, and basic batch file scripting. Dabbled with PowerShell.

Is Python a good first language?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Red Robin Hood posted:

I have nearly 0 coding experience. I've done a fair bit of HTML, some CSS, and basic batch file scripting. Dabbled with PowerShell.

Is Python a good first language?

Yes, definitely!

Red Robin Hood
Jun 24, 2008


Buglord

fletcher posted:

Yes, definitely!

Out of all the links and tutorials in the OP can you recommend one or a few that teaches you a few basics, sets goals for you, gives you think to do, etc?

Sylink
Apr 17, 2004

I don't know your background but there is some decent info in the readings here through MIT.

http://ocw.mit.edu/courses/electric...-2011/index.htm

Dren
Jan 5, 2001

Pillbug

Red Robin Hood posted:

I have nearly 0 coding experience. I've done a fair bit of HTML, some CSS, and basic batch file scripting. Dabbled with PowerShell.

Is Python a good first language?

I love Python and I think it's a great first language but I am surprised you are interested in it over Javascript given your background w/ HTML and CSS.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Dren posted:

I love Python and I think it's a great first language but I am surprised you are interested in it over Javascript given your background w/ HTML and CSS.

While JavaScript is a language thats got so much growth now (as a front end dev it encompasses most of my work these days), however Python is a good language for experiencing what a generally mature server side eco system is supposed to look like. You'll be working with well tested and documented libraries most of time, where as Node and the front end in general has so much experimental kit out there at the moment, that its much harder as a beginner to separate the wheat from the chaff.

Red Robin Hood
Jun 24, 2008


Buglord
I guess what I'm really hunting for is how to build a really basic spreadsheet pretty much exactly like Google Spreadsheet on Drive.

Problem is my job is pretty paranoid about the information we would be putting in it so they want to keep it internal only. Right now we're using an Excel spreadsheet that gets locked down when one person is in it. I want to create an internal web page that can be edited by multiple users at once. I thought this would be a good chance to get some experience in and was hoping it could be easily accomplish with Python.

I know this could probably be easily done with Access but I'd rather learn something in the process.

Should I take this to the general questions megathread?

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Red Robin Hood posted:

I guess what I'm really hunting for is how to build a really basic spreadsheet pretty much exactly like Google Spreadsheet on Drive.

Problem is my job is pretty paranoid about the information we would be putting in it so they want to keep it internal only. Right now we're using an Excel spreadsheet that gets locked down when one person is in it. I want to create an internal web page that can be edited by multiple users at once. I thought this would be a good chance to get some experience in and was hoping it could be easily accomplish with Python.

I know this could probably be easily done with Access but I'd rather learn something in the process.

Should I take this to the general questions megathread?

Concurrent editing is no trivial problem, and is essentially front end work. That said though, it really depends on what you're actually building. Is an excel sheet what you need, or is it more like data with rows & fields. If its the latter then check out Django and its automatic admin. You might get something built quicker than you realise.

Red Robin Hood
Jun 24, 2008


Buglord

Maluco Marinero posted:

Concurrent editing is no trivial problem, and is essentially front end work. That said though, it really depends on what you're actually building. Is an excel sheet what you need, or is it more like data with rows & fields. If its the latter then check out Django and its automatic admin. You might get something built quicker than you realise.

I don't need any "e7+e8=e10" poo poo. I really only need editable rows and columns. Something like:

Server # VHOST location recent changes change history

Still think Django is a good route?

Lurchington
Jan 2, 2003

Forums Dragoon

Red Robin Hood posted:

I don't need any "e7+e8=e10" poo poo. I really only need editable rows and columns. Something like:

Server # VHOST location recent changes change history

Still think Django is a good route?

Django is, in my opinion, not a particular good route for that. Django is really designed about the server keeping a copy of the information and rendering the template that it sends back to the user. That being said, Django is so widely used you're going to get a lot more documentation for it relative to alternatives, that I won't dissuade you. *

To say another way, this kind of thing will be extremely front-end javascript heavy. As a result, Django will be a lot more heavyweight than you really need (and once you know what you're doing might actually get in the way a bit).

* for example, searching "django spreadsheet" actually returns relevant links: http://www.ibm.com/developerworks/library/wa-django/

Dren
Jan 5, 2001

Pillbug

Red Robin Hood posted:

I guess what I'm really hunting for is how to build a really basic spreadsheet pretty much exactly like Google Spreadsheet on Drive.

Problem is my job is pretty paranoid about the information we would be putting in it so they want to keep it internal only. Right now we're using an Excel spreadsheet that gets locked down when one person is in it. I want to create an internal web page that can be edited by multiple users at once. I thought this would be a good chance to get some experience in and was hoping it could be easily accomplish with Python.

I know this could probably be easily done with Access but I'd rather learn something in the process.

Should I take this to the general questions megathread?

Not to dissuade you but this seems like a fairly large undertaking. Perhaps there is a web spreadsheet product with group editing available that you could set up for your company? I know you said you have privacy concerns but perhaps google apps for business could work.

Dominoes
Sep 20, 2007

Is there a trick to getting matplotlib plots to not freeze the GUI?

Threading doesn’t work.

I can't get plt.draw() to work. (still freezes the GUI)

plt.ion() prevents the freezing, but also prevents me from closing the plot window, or opening additional ones.

I'm also looking for info on changing the plot window size (without having to adjust it with the mouse after it opens). The guides show using figure() objects, but I'm trying to use a plot.
Nonworking example code demonstrating some troubleshooting.
Python code:
        
        plt.plot_date(dates_num_recent, values_recent, '-', markersize=3)
        plt.show()     
        #fig = plt.figure(figsize=(800, 600))
        #plt.draw()
        #plt.ion()
        #fig.show()

Dominoes fucked around with this message at 23:18 on Nov 21, 2013

Thermopyle
Jul 1, 2003

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

One of you is saying on the new OP document to not suggest Windows users download the python.org Windows version but to instead download a Windows-specific distribution like...well like, I don't know what. But anyway...

My personal feelings on it are that when I was doing dev work on Windows I always preferred to use the official distribution and install whatever packages I wanted or needed. However, I must say that I didn't spend a lot of time evaluating other options as the whole idea of it just rubbed me the wrong way.

Does anyone have any thoughts about whether recommending Windows users use something other than the official distribution is a good idea?

In particular I'd like some thoughts from non-scientific users whom I think probably have different requirements than your average beginner. They're almost always whom I see talking about alternative distributions...

Red Robin Hood
Jun 24, 2008


Buglord

Dren posted:

Not to dissuade you but this seems like a fairly large undertaking. Perhaps there is a web spreadsheet product with group editing available that you could set up for your company? I know you said you have privacy concerns but perhaps google apps for business could work.

I think you're right. I spoke with one of our developers and he started talking about a lot of things I didn't understand.

Thanks for the suggestion!

Adbot
ADBOT LOVES YOU

Dominoes
Sep 20, 2007

I prefer the official version on Windows by default, from the perspective of a beginner with no interest in scientific computing, and later, as someone who uses it.

There's no need to add scientific packages by default if you have no intention of using them. If you need them, the LFCI website makes installing them very easy.

I get the impression that the target market for pre-packaged versions are scientists who have no interest in learning more programming concepts than they need to.


What's the deal with @property? PyCharm suggests adding this decorator to methods that have no arguments other than 'self'. As a result, the method names are then called as class variables instead of methods, ie without the (). So, it's a way of saying "this is a class variable that changes automatically".

For example:
Python code:
class MyClass:
...
    def my_method(self):
        return "hi"

my_instance = MyClass()
print(my_instance.my_method())
appears equivalent to:

Python code:
class MyClass:
...
    @property
    def my_method(self):
        return "hi"

my_instance = MyClass()
print(my_instance.my_method)
It seems like a straightforward syntax alteration, but I'm confused because the docs and other material online are pretty complicated, and talk about getters and setters (without explaining what they are - I assumed that might be terminology for a class method that doesn’t use property, but there's apparently '@x.setter' syntax too), and a lot of other stuff that's not the simple explanation I posted above.

Dominoes fucked around with this message at 02:50 on Nov 22, 2013

  • Locked thread