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
Pollyanna
Mar 5, 2005

Milk's on them.


That seems like a relatively small project with a need for a DB. Right up Flask's alley. Frameworks like Django are for much larger projects but help with a lot of boilerplate (i.e. admin interface, automatic database setup, etc.) while Flask is a lot more compact but since it doesn't come with that extra stuff, you have to figure out how to implement it yourself. (Which is a pain.)

Anyway, is there a way to alias a command to open Python on a certain path? Reason I ask is that I have Anaconda installed, and before I changed the PATH it automatically chose that install to use. I know that "conda" is a command to open Anaconda. Can I just bind the conda PATH to conda and the python PATH to python somehow?

Adbot
ADBOT LOVES YOU

My Rhythmic Crotch
Jan 13, 2011

You're on OS X right? You should be able to launch the version in question just by simply typing "python2.6" or "python2.7". I have not used Anaconda so I don't know how Anaconda interacts with the installed versions of Python.

Boz0r
Sep 7, 2006
The Rocketship in action.
I'm trying to do some blurring/unblurring of images in Python and I can't get it to work properly. The image gets blurred fine, but the inverse blur just gives me back noise.

code:
def create_image(sigma,x):
	kernel = blur.blur_kernel(sigma,shape(x))


	#kernel_fft = (fft2(kernel))
	#result = ifft2(fft2(x)*kernel_fft)
	
	#or
	
	#convolution_matrix = blur.blur_matrix(sigma,shape(x))
	#result = convolution_matrix*matrix(x)*convolution_matrix

	return result
Both methods yield the same result.
code:
def deblur_image(sigma, noise, x):
    #convolution_matrix = blur.blur_matrix(sigma,shape(x))
    #result = inv(convolution_matrix)*matrix(x)*inv(convolution_matrix)
    
    #or

    #kernel = blur.blur_kernel(sigma,shape(x))
    #result = abs(ifft2(fft2(x) * inv(fft2(kernel))))
    
    return (result)
Here, the first method returns noise and the second method looks like it's still in the frequency domain.

Can anyone see what the problem is?

Pollyanna
Mar 5, 2005

Milk's on them.


My Rhythmic Crotch posted:

You're on OS X right? You should be able to launch the version in question just by simply typing "python2.6" or "python2.7". I have not used Anaconda so I don't know how Anaconda interacts with the installed versions of Python.

Apparently I can get things working just by using the Anaconda launcher, so there's that problem fixed.

---

I'm realizing that I need a couple things when I start a new Flask project. I at least need a database, and a file that renders HTML/CSS/JS. Is there a Flask "template" I can follow so that I don't have to do a bunch of coding over and over when I start a new project? Is there one that has functionality like Django's automatic admin interface?

Thermopyle
Jul 1, 2003

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

Pollyanna posted:

Apparently I can get things working just by using the Anaconda launcher, so there's that problem fixed.

---

I'm realizing that I need a couple things when I start a new Flask project. I at least need a database, and a file that renders HTML/CSS/JS. Is there a Flask "template" I can follow so that I don't have to do a bunch of coding over and over when I start a new project? Is there one that has functionality like Django's automatic admin interface?

PyCharm can set up a lot of stuff by default when you start a new Flask project.

Pollyanna
Mar 5, 2005

Milk's on them.


Thermopyle posted:

PyCharm can set up a lot of stuff by default when you start a new Flask project.

Unfortunately, that's not the case for the Community Version. Unless there's a way to add that functionality to CE...?

Mrs. Wynand
Nov 23, 2002

DLT 4EVA

Pollyanna posted:

Apparently I can get things working just by using the Anaconda launcher, so there's that problem fixed.

---

I'm realizing that I need a couple things when I start a new Flask project. I at least need a database, and a file that renders HTML/CSS/JS. Is there a Flask "template" I can follow so that I don't have to do a bunch of coding over and over when I start a new project? Is there one that has functionality like Django's automatic admin interface?

IMHO the "simplicity" of Flask is not doing you any favors here. You want something reasonably quick that works out of the box. Django is that thing. Sure it can also do a gazillion other things you don't need, but just don't use those - it is reasonably well factored.

Yes you can build the same thing in Flask, yes there exist template projects with most bells and whistles set up, yes there is an admin UI, but it just wont' be as smooth or straight-forward as django if that's what you want to do.

There is a lot of wiring you have to do yourself with Flask (I know this because I just last week had to do it). I like this in my case because this is a long term project that I can afford to be fussy about and I want it set up just so. It's generally speaking useful for projects that you know for a fact start simple (in terms of dependencies) but you want the option to add to them later.

Your case seems like the opposite of that: You are gunning straight for an admin-ui-ish arrangement. That's a big-rear end dependency, it ends up touching on pretty much all major components from django.

jony neuemonic
Nov 13, 2009

Pollyanna posted:

Unfortunately, that's not the case for the Community Version. Unless there's a way to add that functionality to CE...?

Sure is! :10bux:

QuarkJets
Sep 8, 2008

Boz0r posted:

I'm trying to do some blurring/unblurring of images in Python and I can't get it to work properly. The image gets blurred fine, but the inverse blur just gives me back noise.

code:
def create_image(sigma,x):
	kernel = blur.blur_kernel(sigma,shape(x))


	#kernel_fft = (fft2(kernel))
	#result = ifft2(fft2(x)*kernel_fft)
	
	#or
	
	#convolution_matrix = blur.blur_matrix(sigma,shape(x))
	#result = convolution_matrix*matrix(x)*convolution_matrix

	return result
Both methods yield the same result.
code:
def deblur_image(sigma, noise, x):
    #convolution_matrix = blur.blur_matrix(sigma,shape(x))
    #result = inv(convolution_matrix)*matrix(x)*inv(convolution_matrix)
    
    #or

    #kernel = blur.blur_kernel(sigma,shape(x))
    #result = abs(ifft2(fft2(x) * inv(fft2(kernel))))
    
    return (result)
Here, the first method returns noise and the second method looks like it's still in the frequency domain.

Can anyone see what the problem is?

What modules are you using? I'm not familiar with the blur module, is that something that you wrote?

Also, in deblur_image it appears that you're doing nothing with the noise that you're passing in, and when that kind of thing happens usually the developer is also mixing up the order of their arguments, IE treating noise as x.

suffix
Jul 27, 2013

Wheeee!

Boz0r posted:

Both methods yield the same result.
code:
def deblur_image(sigma, noise, x):
    #convolution_matrix = blur.blur_matrix(sigma,shape(x))
    #result = inv(convolution_matrix)*matrix(x)*inv(convolution_matrix)
    
    #or

    #kernel = blur.blur_kernel(sigma,shape(x))
    #result = abs(ifft2(fft2(x) * inv(fft2(kernel))))
    
    return (result)
Here, the first method returns noise and the second method looks like it's still in the frequency domain.

Can anyone see what the problem is?

What formulas are you trying to implement? inv(convolution_matrix)*matrix(x)*inv(convolution_matrix) looks weird. Are you doing element-wise multiplication or matrix multiplication?

e: I'm guessing for the second version, you want "fft2(x) / fft2(kernel)" instead of "fft2(x) * inv(fft2(kernel))". inv() is the inverse matrix, which is the inverse under matrix multiplication.

suffix fucked around with this message at 23:53 on Dec 5, 2013

My Rhythmic Crotch
Jan 13, 2011

Pollyanna posted:

Apparently I can get things working just by using the Anaconda launcher, so there's that problem fixed.

---

I'm realizing that I need a couple things when I start a new Flask project. I at least need a database, and a file that renders HTML/CSS/JS. Is there a Flask "template" I can follow so that I don't have to do a bunch of coding over and over when I start a new project? Is there one that has functionality like Django's automatic admin interface?
You might look at flask-peewee. You can add one like of code and it will create the table for you in your DB.

It does also provide you with an admin interface.

And what do you mean "a file that renders HTML"? That's a template. Templates can be like, one line long. Or you can output raw text directly with no fancy templates and HTML. :raise:

My Rhythmic Crotch
Jan 13, 2011

Mr. Wynand posted:

IMHO the "simplicity" of Flask is not doing you any favors here. You want something reasonably quick that works out of the box. Django is that thing. Sure it can also do a gazillion other things you don't need, but just don't use those - it is reasonably well factored.

Yes you can build the same thing in Flask, yes there exist template projects with most bells and whistles set up, yes there is an admin UI, but it just wont' be as smooth or straight-forward as django if that's what you want to do.

There is a lot of wiring you have to do yourself with Flask (I know this because I just last week had to do it). I like this in my case because this is a long term project that I can afford to be fussy about and I want it set up just so. It's generally speaking useful for projects that you know for a fact start simple (in terms of dependencies) but you want the option to add to them later.

Your case seems like the opposite of that: You are gunning straight for an admin-ui-ish arrangement. That's a big-rear end dependency, it ends up touching on pretty much all major components from django.
The last time I was heavily in Django was like a year ago, and I'd disagree with your assessment. I felt like there was a lot of cruft and bloat to sort through with Django - especially because it was the first web framework I had touched. What I really didn't like was that it was heavily opinionated. Something as simple as adding an extra field to the user model was pointlessly complicated (I know the user model has since changed, but its just one example). Tastypie was where I finally threw in the towel. More specifically the guts of Tastypie, which is some mind bending poo poo. While I don't agree with every design choice in Flask, I can actually read and understand the code that Flask and its related modules are made of.

breaks
May 12, 2001

Are there any decent documentation generators out there that can spit out Confluence pages? I was hoping someone would have written something for Sphinx, but no such luck so far. :(

Mrs. Wynand
Nov 23, 2002

DLT 4EVA

My Rhythmic Crotch posted:

Something as simple as adding an extra field to the user model was pointlessly complicated (I know the user model has since changed, but its just one example).
The User model is a somewhat notable/famous django fuckup. It came with a number of bad decisions early in django's history that they are still paying for now. It's not worth defending or anything, but it really is about as bad as django gets...

quote:

Tastypie was where I finally threw in the towel. More specifically the guts of Tastypie, which is some mind bending poo poo. While I don't agree with every design choice in Flask, I can actually read and understand the code that Flask and its related modules are made of.

My general rule of thumb is that libraries with "clever" names that have obvious descriptive alternatives (e.g. something including the words "django" and "rest") should be viewed with extreme suspicion and discarded at the first signs of trouble.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Speaking as someone who entered Python programmer as a total beginner (only HTML & CSS experience) Django was a much better place for me to start. Simply put, batteries included meant I didnt have to gently caress around with sessions, authentication, choosing how to bind to a database, or any of that. I could just start building something that worked for better or worse.

The tutorial got you far enough that you could feel your way around from there trying to build an app. Sure, its hand holding, but at that point you pretty much need it if you're a raw beginner.


I'm making an assumption here but I reckon most people who recommend Flask were already had some sort of programming experience when they started. Its the no brainer choice when you know how to build your app just the way you like it, because you don't get saddled with bloat, but that's just not practical for a genuine beginner. When I was starting the batteries let me get the runs on the board, which is critical motivation for a self guided project.

Boz0r
Sep 7, 2006
The Rocketship in action.

QuarkJets posted:

What modules are you using? I'm not familiar with the blur module, is that something that you wrote?

Also, in deblur_image it appears that you're doing nothing with the noise that you're passing in, and when that kind of thing happens usually the developer is also mixing up the order of their arguments, IE treating noise as x.

Yeah, sorry, that module is one I have from our instructor, it just returns a simple gaussian blur kernel.

In this particular example, there is no noise.

suffix posted:

What formulas are you trying to implement? inv(convolution_matrix)*matrix(x)*inv(convolution_matrix) looks weird. Are you doing element-wise multiplication or matrix multiplication?

e: I'm guessing for the second version, you want "fft2(x) / fft2(kernel)" instead of "fft2(x) * inv(fft2(kernel))". inv() is the inverse matrix, which is the inverse under matrix multiplication.

http://www.siam.org/books/fa03/FA03Chapter1.pdf
In section 1.2 and 1.3 of this paper they present a method of blurring and a naive method of unblurring when noise hasn't been added.

I changed the code to fft2(x) / fft2(kernel) instead, and now it looks like something that could become a picture in the future. Isn't matrix division defined as multiplying with the inverse, though?

suffix
Jul 27, 2013

Wheeee!

Boz0r posted:

http://www.siam.org/books/fa03/FA03Chapter1.pdf
In section 1.2 and 1.3 of this paper they present a method of blurring and a naive method of unblurring when noise hasn't been added.

I changed the code to fft2(x) / fft2(kernel) instead, and now it looks like something that could become a picture in the future. Isn't matrix division defined as multiplying with the inverse, though?

You have to be careful because Numpy has two ways to multiply arrays, depending on their type:
Python code:
>>> numpy.matrix([[1, 2], [3, 4]]) * numpy.matrix([[1, 2], [3, 4]])
matrix([[ 7, 10],
        [15, 22]])

>>> numpy.array([[1, 2], [3, 4]]) * numpy.array([[1, 2], [3, 4]])
array([[ 1,  4],
       [ 9, 16]])
Your image data are probably stored in Numpy arrays, so when you multiply/divide them, that happens element-wise.
If you want to be sure you are doing matrix multiplication, you can use .dot(), which works on both matrices and arrays:
Python code:
>>> np.array([[1, 2], [3, 4]]).dot(np.array([[1, 2], [3, 4]]))
array([[ 7, 10],
       [15, 22]])
You want different things for your different methods; for the straight convolution, you want to use matrix multiplication, since those formula are using matrices. When you're doing frequency transform and using the convolution theorem, you want to do element-wise multiplication.

You may want to toy around a bit with the interpreter to get a feel for what the different operations do and check that your data looks like you expect, especially if you've got ipython running.

salisbury shake
Dec 27, 2011

Mr. Wynand posted:

Does the community edition do that remote interpeter vagrant magic? I sort of discounted using pycharm out of hand since I assumed it needed to run on the local python env and I always always always run the actual servers in a headless VM. But turns out it can absolutely do that that workflow, so now I am interested.

Pollyanna posted:

Unfortunately, that's not the case for the Community Version. Unless there's a way to add that functionality to CE...?

quote:

I said this last page, but Jetbrains are very lenient w/r/t handing out full licenses for open-source projects.
Literally throw up a quick and dirty project on githup + LICENSE file that is open-source and they'll give you a full license. Obviously work on it or other OSS projects so you can renew it in a year. Or ask your employer if you're using it for work. Or just buy it.



Pollyanna posted:

Dang. How do I change my current Python version, again? I tried editing .bash_profile but it didn't change whether or not I used Anaconda.

As for the current interpreter, calling sys.version tells me that it's the Anaconda interpreter. v:confused:v

Pollyanna posted:

Anyway, is there a way to alias a command to open Python on a certain path? Reason I ask is that I have Anaconda installed, and before I changed the PATH it automatically chose that install to use. I know that "conda" is a command to open Anaconda. Can I just bind the conda PATH to conda and the python PATH to python somehow?

I'm not sure I understand what it is you're trying to do, and you aren't talking about the PATH variable in the conventional sense. There's one PATH your shell will use to resolve non-builtins.

Check your symlink to see if its pointing to your preferred interpreter:
code:
alex@macbuntu:~$ ls -l /usr/bin/python
lrwxrwxrwx 1 root root 9 Sep 19 14:26 /usr/bin/python -> python2.7
or append/pre-pend your default PATH var to the Anaconda path in whatever file is modifying it:
code:
export PATH=$PATH:/path/to/anaconda/bin

or

export PATH=/path/to/anaconda/bin:$PATH
If you type 'python' it will default to the file in /usr/bin, or if you appended the default path to the Anaconda path then it would launch ~/path/to/anaconda/bin/python.

salisbury shake fucked around with this message at 22:40 on Dec 6, 2013

fritz
Jul 26, 2003

Boz0r posted:

Here, the first method returns noise and the second method looks like it's still in the frequency domain.


If nothing else, going by the text you linked (figure 1.3), the naive method should be giving noise, because it's a bad method.

But I think suffix has it right, use .dot() instead. If you look at the help for, for example, fft2:

quote:

This function computes the *n*-dimensional discrete Fourier Transform
over any axes in an *M*-dimensional array by means of the
Fast Fourier Transform (FFT). By default, the transform is computed over
the last two axes of the input array, i.e., a 2-dimensional FFT.
you see that it's using an array, not a matrix, and if you don't want pointwise multiplication you use .dot().

Lurchington
Jan 2, 2003

Forums Dragoon

breaks posted:

Are there any decent documentation generators out there that can spit out Confluence pages? I was hoping someone would have written something for Sphinx, but no such luck so far. :(

https://developer.atlassian.com/dis...ion1andversion2

Last time I looked into this confluence accepts (and kind of demands) html anyway, so it seems reasonable to still use the output from sphinx as long you're taking care of pushing one logical sphinx page to one confluence page

Pollyanna
Mar 5, 2005

Milk's on them.


Based on the wonderful stylings of the shit_that_didn't_happen.txt thread, I put together a really small STDH-themed Mad Libs program (pastebin). This is the typical output:

quote:

SOOOO I was at a cafe with MY GIRLFRIEND and Megan Fox getting a bite to eat. There I was, blindly eating my crazy meal of Doritos and Doritos, when suddenly this crazy crazy guy ran up to me and said "Coconut sucks!"

I was loving pissed! So I drew my trusty Desert Eagle and farted "I EXPECTED GOATSE!!"

The guy farted and ran away blindly. Everyone in the room stood up and farted, Bill Murray appeared and gave me $726474624 and the Managed to Not poo poo My Pants Award, and Megan Fox asked me if she could be my poo poo wrangler forever. It was awesome.

(And that person's name was Albert Einstein.)

Aside from badly needing more fill-in-the-blank choices and a better written story, there's a clear bug here: only one answer for a field can exist at a time. So, I can't have more than one adjective at a time :downs: What's a better way to do this so that I don't run into problems like these? (You can review my program at that Pastebin link up there.)

(edit: This is part of my webapp :ssh:)

Pollyanna fucked around with this message at 09:30 on Dec 7, 2013

ManoliIsFat
Oct 4, 2002

What do you want it to do, randomly choose a 1->maxNumberOfChoices, command seperate them? http://docs.python.org/2/library/string.html#string.join
Or do you want to define an array of adjectives first, and then define separate 'adjective_1', 'adjective_2' fields in your libs array? I don't understand your trouble.

Pollyanna
Mar 5, 2005

Milk's on them.


Well...looks like the second approach will be the easiest. v:shobon:v I updated it. I keep thinking that there's got to be a more efficient, simpler approach to it, though...is there?

breaks
May 12, 2001

You could extract the keywords used in the madlib using string.Formatter().parse(). With that information, you can write a function to create the dict to provide to .format() for a given madlib, instead of having to make each one by hand.

evensevenone
May 12, 2001
Glass is a solid.
If you want to be an actual Aspiring Computer Programmer, you write a Markov chain generator and use that thread as a training source.

Suspicious Dish
Sep 24, 2011

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

breaks posted:

You could extract the keywords used in the madlib using string.Formatter().parse(). With that information, you can write a function to create the dict to provide to .format() for a given madlib, instead of having to make each one by hand.

I think it's just fine the way it is. The less metaprogramming the better...

breaks
May 12, 2001

I don't know that I'm really buying that pulling some strings out of a longer string and looking them up in a dictionary is "metaprogramming." It seems reasonable to turn this into a more purely data driven program. Is your complaint just about the use of string.Formatter.parse and you feel that some other means of extracting the tags should be used?

breaks fucked around with this message at 22:30 on Dec 7, 2013

Pollyanna
Mar 5, 2005

Milk's on them.


evensevenone posted:

If you want to be an actual Aspiring Computer Programmer, you write a Markov chain generator and use that thread as a training source.

I might just have to do this :unsmigghh:

And the one thing that bugs me is that having to do this with string interpolation (CoffeeScript, but similar enough to Python):

code:
place = places(Math.floor(Math.random() * places.length)
hot_chick = hot_chicks(Math.floor(Math.random() * hot_chicks.length)
adverb1 = adverbs(Math.floor(Math.random() * adverbs.length)
adjective1 = adjectives(Math.floor(Math.random() * adjective.length)
goony_food1 = goony_foods(Math.floor(Math.random() * past_verbs.length)
goony_food2 = goony_foods(Math.floor(Math.random() * past_verbs.length)
adjective2 = adjectives(Math.floor(Math.random() * adjective.length)
adjective3 = adjectives(Math.floor(Math.random() * adjective.length)
offensive_phrase = offensive_phrases(Math.floor(Math.random() * offensive_phrases.length)
goony_weapon = goony_weapons(Math.floor(Math.random() * goony_weapons.length)
past_verb1 = past_verbs(Math.floor(Math.random() * past_verbs.length)
goony_catchphrase = goony_catchphrases(Math.floor(Math.random() * goony_catchphrases.length)
past_verb2 = past_verbs(Math.floor(Math.random() * past_verbs.length)
adverb2 = adverbs(Math.floor(Math.random() * adverbs.length)
past_verb3 = past_verbs(Math.floor(Math.random() * past_verbs.length)
famous_name = famous_names(Math.floor(Math.random() * famous_names.length)
trophy_blurb = trophy_blurbs(Math.floor(Math.random() * trophy blurbs.length)
relation = relations(Math.floor(Math.random() * relations.length)
einstein = einsteins(Math.floor(Math.random() * einsteins.length)

story = 
'SOOOO I was at #{place} with MY GIRLFRIEND and #{hot_chick} getting a bite to eat. There I was, #{adverb1} eating my #{adjective1} meal of #{goony_food1} and #{goony_food2}, when suddenly this #{adjective2} #{adjective3} guy ran up to me and said "#{offensive_phrase}"

I was loving pissed! So I drew my trusty {#goony_weapon} and #{past_verb1}: "#{goony_catchphrase}"

The guy #{past_verb2} and #{adverb2} ran away. Everyone in the room stood up and #{past_verb3}, #{famous_name} appeared and gave me $1,000,000 and the #{trophy_blurb} Award, and #{hot_chick} asked me if she could be my #{relation} forever. It was awesome.

(And that person\'s name was #{einstein}.)'
is a pain in the rear end, and if something's a pain in the rear end, there's always a better way to do it.

edit: If I were to implement a Markov text generator, is it worth it to try and write it on my own or is it better to use a module someone else wrote? On the one hand, trying to write one of my own would be good experience and I could claim it was all me, but on the other there's the whole "stand on the shoulders of giants" thing.

Pollyanna fucked around with this message at 01:50 on Dec 8, 2013

Computer viking
May 30, 2011
Now with less breakage.

For learning? Write one yourself. With the data types python provides, it's fairly easy, and it won't be that much code. Merely finding/installing/understanding/feeding/using an existing one might end up being more work.

Pollyanna
Mar 5, 2005

Milk's on them.


I tried implementing a Markov chain, but I got stuck at the "map elements of the list to the words that follow them" part. I tried writing this:

Python code:

import numpy as np

text = "the quick brown fox jumped over the lazy dog"

split_text = np.array(text.split())

split_length = len(text.split())

frequency_table = {}

print split_text
search_array = np.array(list(set(split_text)))
print search_array

for i in search_array:
	ii = list(np.where(split_text == i)[0])
	print ii

	for a in ii:
		if ii.index(a) != 0:
			frequency_table[i].append[split_text[a]]
		else:
			frequency_table[i] = split_text[a]

But I get AttributeError: 'numpy.string_' object has no attribute 'append'. :saddowns:

Is there a name for doing something like this? "Getting the successors of each element" or whatever?

salisbury shake
Dec 27, 2011

quote:

But I get AttributeError: 'numpy.string_' object has no attribute 'append'. :saddowns:

You are using square brackets instead of parens in your call to whatever.append()

Dren
Jan 5, 2001

Pillbug
Hey BigRedDot I just fired up Anaconda on Windows and it's pretty stellar. All the packages I needed were installed out of the box except for docopt and I was pleasantly surprised that all I had to do to get it was a pip install since it's a pure python package. It was actually easier to use than Ubuntu.

I saw the numpy guy's blogpost about packaging and anaconda, is that you? He makes some of the same points you make.

Dominoes
Sep 20, 2007

With statements.

I decided to try with statements for setting up and tearing down an sqlite connection.

Python code:
class DBSetup():
    def __init__(self, filename):
        self.filename = filename

    def __enter__(self):
        self.db = sqlite3.connect(os.path.join(DIR_RES, self.filename))
        self.cursor = self.db.cursor()

    def __exit__(self, type, value, traceback):
        self.db.commit()
        self.db.close()


with DBSetup('hist_data.db'):
    cursor.execute("...")
How do I pull cursor (or any variable) from the with class? Is this an appropriate use? I've read 'with' is targeted at replacing try/finally scenarios, but this seems similar to the 'with open' style.

Edison was a dick
Apr 3, 2010

direct current :roboluv: only

Dominoes posted:

How do I pull cursor (or any variable) from the with class? Is this an appropriate use? I've read 'with' is targeted at replacing try/finally scenarios, but this seems similar to the 'with open' style.

Have the __enter__ return self and use with foo as bar:

Python code:

class DBSetup(object):
...
    def __enter__(self):
        self.db = sqlite3.connect(os.path.join(DIR_RES, self.filename))
        self.cursor = self.db.cursor()
        return self
...

with DBSetup('hist_data.db') as db:
    db.cursor.execute(...)
Also, you can use contextlib.contextmanager to construct it from a function, this is more readable for some uses.

Python code:
import contextlib
import os
import sqlite3

@contextlib.contextmanager
def DBSetup(filename):
    db = sqlite3.connect(os.path.join(DIR_RES, self.filename)
    cursor = self.db.cursor()
    try:
        yield db, cursor
    else:
        db.commit() # I assume you only want to commit when there's no exception
    finally:
        db.close()

with DBSetup('hist_data.db') as (db, cursor):
    cursor.execute("...")
Alternatively, since the database's cleanup function is called close, you can use contextlib.closing

Python code:
with contextlib.closing(sqlite3.connect(os.path.join(DIR_RES, 'hist_data.db'))) as db:
    cursor = db.cursor()
    cursor.execute("...")
    db.commit()

Edison was a dick fucked around with this message at 18:47 on Dec 8, 2013

Dominoes
Sep 20, 2007

Edison was a dick posted:

Have the __enter__ return self and use with foo as bar:

Python code:

class DBSetup(object):
...
    def __enter__(self):
        self.db = sqlite3.connect(os.path.join(DIR_RES, self.filename))
        self.cursor = self.db.cursor()
        return self
...

with DBSetup('hist_data.db') as db:
    db.cursor.execute(...)
Thanks; it works. Going to experiment with the other methods as well.

BigRedDot
Mar 6, 2008

Dren posted:

Hey BigRedDot I just fired up Anaconda on Windows and it's pretty stellar. All the packages I needed were installed out of the box except for docopt and I was pleasantly surprised that all I had to do to get it was a pip install since it's a pure python package. It was actually easier to use than Ubuntu.

I saw the numpy guy's blogpost about packaging and anaconda, is that you? He makes some of the same points you make.

No that's Travis Oliphant, the author of NumPy, he's my boss. :)

salisbury shake
Dec 27, 2011
Pycharm question:

I wrote a quick and dirty script to test out a poc:
Python code:
from yada import yada

global_var = "balls"

def func(x, y, z):
  other_func(global_var, x)

def other_func(ffff, x):
  yada(ffff, x)
  accesses more global poo poo here
I was hoping that it would be easy to wrap this mess up in a class, but the biggest issue here is going through and appending self. to calls and variables. The Rename item in the Refactor menu usually works, but changing "global_var" to "self.global_var" causes it to laugh at me.

Any way to do this with the IDE that doesn't essentially involve doing a manual regex?

QuarkJets
Sep 8, 2008

salisbury shake posted:

Pycharm question:

I wrote a quick and dirty script to test out a poc:
Python code:
from yada import yada

global_var = "balls"

def func(x, y, z):
  other_func(global_var, x)

def other_func(ffff, x):
  yada(ffff, x)
  accesses more global poo poo here
I was hoping that it would be easy to wrap this mess up in a class, but the biggest issue here is going through and appending self. to calls and variables. The Rename item in the Refactor menu usually works, but changing "global_var" to "self.global_var" causes it to laugh at me.

Any way to do this with the IDE that doesn't essentially involve doing a manual regex?

This is possibly PyCharm trying to tell you to not use global variables

A rename to self.global_var is going to fail because self is not defined for the first instance of global_var, even if it's inside of a class. You need to put global_var inside of a class method first, ideally inside of __init__(self), and then it should work

salisbury shake
Dec 27, 2011

QuarkJets posted:

This is possibly PyCharm trying to tell you to not use global variables

A rename to self.global_var is going to fail because self is not defined for the first instance of global_var, even if it's inside of a class. You need to put global_var inside of a class method first, ideally inside of __init__(self), and then it should work

Already tried to stick it in __init__, no dice. Every method that accesses it is in the same class, __init__ + the other methods have self as the first parameter.
Just used Replace, though it was a bit tedious. Lesson here is to not half-rear end poo poo because it might save time.

Adbot
ADBOT LOVES YOU

duck monster
Dec 15, 2004

Presenting......... The worlds most ill-concieved web framework, Appy!

http://appyframework.org/principles.html

quote:


appy.gen works at a higher level of abstraction than most other frameworks or approaches. With gen, you are not going to write a function that returns dynamic HTML when some URL is hit. You are going to define classes and relationships, and methods will be like hooks that will react when some events occur (an object is created, edited, deleted, etc). You don't have to write a single line of HTML, CSS or Javascript to write basic Appy applications. Only pure Python. This is what I call conceptual. But unlike most conceptual approaches, you will not draw any diagram or anything that is not Python code. Pure Python, pure simplicity, no repetition, no transformation: optimal efficiency, optimal maintainability. Other conceptual approaches like the idea of starting from some abstract vision like a (graphical) model (boxes, arrows...); from it, tools generate code skeletons that need to be completed in a subsequent "development" phase. Such "transformational" approaches may even count more than two phases and manipulate different models at different abstraction levels before producing code (this is what I have learned at the university). Such approaches spread the information in several places, because every model or representation has limited expressivity. In my opinion, it produces redundancy and eventually leads to maintenance problems. It violates the DRY principle, which is closely related to our Null-IT principle (see above) On the contrary, gen knows only about code. The "model" you write is a Python package. Being written in a high-level programming language, it does not constrain your expressivity in any way. More important: this code is the running code, and thus the only place where you describe your software. Simply, "wrappers" are added to it in order to plug him into the low-level Zope machinery. A gen-powered Python program acts like a comedian manipulating a tuned marionette: simple moves from the comedian produce complex, cascading and funny behaviours at the puppet level.

quote:


Design patterns are elegant low-level constructs used to overcome the limitations of programming languages (ie statically-typed languages like Java) or frameworks. Using them implies adding classes just for making the plumbery work; it augments code complexity and, again, spreads information at several places. Separating code describing data from code presenting it produces the same problem. appy.gen takes the approach of grouping everything at the same place. For example, information that dictates how a given field will be displayed is part of the field definition.

All-in-one objects.

:downsbravo:

  • Locked thread