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
Dominoes
Sep 20, 2007

How can I write to CSVs without getting a blank row between each real row? This page shows that the file needs to be written in binary mode to do this, but when I do it, I get the following error: 'TypeError: 'str' does not support the buffer infercace.'. Is there a way to convert a string to binary first?

I've been able to work with CSVs successfully before when downloading raw CSVs from websites, which work in binary mode. Now that I'm trying to make my own to save data, I'm running into this.

example:
Python code:
with open('file.csv', 'wb') as f:
    for row in data:
        csv.writer(f).writerow(row)
'writerow' sounds like something Scooby Doo would say


edit: Solved. The correct open line is:
Python code:
with open('file.csv', 'w', newline='') as f:

Dominoes fucked around with this message at 04:10 on May 11, 2013

Adbot
ADBOT LOVES YOU

Dominoes
Sep 20, 2007

I'm trying to delete dictionary entries based on values. I'm receiving "RuntimeError: dictionary changed size during iterations" errors despite making a copy first. Any ideas? Python3.

Python code:
mydict_copy = mydict
for key in mydict_copy:
    if mydict_copy[key].objectvalue == 0:
        del mydict[key]

Dominoes fucked around with this message at 21:36 on May 11, 2013

Dominoes
Sep 20, 2007

breaks posted:

You aren't making a copy. mydict_copy = mydict means that you have two names pointing at the same object.

Dictionaries do have a copy method that you can use to create a copy of them. That said, you don't actually want a copy of the dictionary in this case; you want a separate list of it's keys, which you can get with mydict.keys(). You can then iterate over that list and do whatever horrible things you must to that poor dictionary, you monster.

OnceIWasAnOstrich posted:

You aren't actually making a copy, just another reference to the same dict.

Do something like using the copy module or a dictionary comprehension to move all the items into a new dict.

Thanks. Replacing the first line with the following worked.
code:
mydict_copy = mydict.copy()
I looked up some info on dictionary comprehensions and found phrases like this
Python code:
d = {key: value for (key, value) in sequence}
that I'm having a hard time deciperhing. Why do I want to use .keys() instead of making a copy? I need the dictionary's values to decide which entries to cruely murder.

Dominoes fucked around with this message at 22:13 on May 11, 2013

Dominoes
Sep 20, 2007

Dren posted:

I encourage you to carefully read this: http://docs.python.org/2/library/stdtypes.html#typesmapping

Take note of the iterkeys, itervalues and iteritems methods. When might you use them instead of keys, values, and items?
I'll read it.

Nippashish posted:

You might as well just write mydict = {k:v for k,v in mydict.iteritems() if v.objectvalue != 0} and avoid this whole business of copying and deleting.
I like this; using it. Caveat of iteritems() being replaced by items() in python3.

QT issue: Anyone know how to pull data from input text and combo boxes? I've been trying to solve this one for weeks with no luck, and it's stopped development of the program. I can't find anything in a search that describes the problem, and most of what I find about text and combo boxes implies I'm doing it correctly. For text boxes, I receive a None result, and combo boxes I recieve the default selection, no matter what the current one is. Code:

code:
x = window.ui.tb_x.toPlainText()
y = window.ui.cb_y.itemData(window.ui.cb_y.currentIndex()) #or
y = window.ui.cb_y.currentText()
I've had no issues with buttons, checkboxes, menus, statusbars, tree widgets etc, but can't get this to work.

Dominoes fucked around with this message at 16:20 on May 12, 2013

Dominoes
Sep 20, 2007

PYQT question. I created a keypress event based on code I found in a google search. It works, but I don't know why.

I added this function under my main window's class:
Python code:
def keyPressEvent(self, e):
    if e.key() == PyQt4.QtCore.Qt.Key_Delete:
        Main.delete(self)  
Where Main.delete is the function I want to call when the delete key is pressed.

This function, keyPressEvent, is never called. Why does it work?

Dominoes fucked around with this message at 02:08 on May 18, 2013

Dominoes
Sep 20, 2007

So it's a special function name. I notice that changing its name makes it not work.

Dominoes
Sep 20, 2007

What's the best way to get the current path a file is run from? I've been using abspath('')+ '\\folder', but this relies on the folder name not changing. Is there a way to get the actual path of the file, instead of one level up? (which abspath() seems to do)

Using __file__ with dirname seems to work, but it causes cx_freeze to glitch out.

Dominoes fucked around with this message at 23:49 on May 19, 2013

Dominoes
Sep 20, 2007

BeefofAges posted:

os.getcwd()?
I was using that until I realized it only works when running the script from its directory, ie through the editor directly. It returns my home folder when running through a command prompt or by clicking the file.

edit: Looks like abspath()'s doing the same thing cwd did. Oops - doublebroke.

Perhaps dirname(__file__) is the answer, and I just need to troubleshoot the cx_freeze error.

Dominoes fucked around with this message at 00:14 on May 20, 2013

Dominoes
Sep 20, 2007

evensevenone posted:

Think about what you want in that case. If you're planning to store a configuration file or data file in the same place as the script, it might not make sense on some platforms. That folder may not even be writable for security reasons. Chances are the home directory might make more sense.
This gets into whether I'm doing the overall structure/packaging correctly. Both of the programs I'm working on save and load information from multiple files. I plan to release this one soon, initially for Windows. (The other one's more complicated, with multiple modules, but it's mostly for personal use) How do you recommend packaging it and organizing the files?

What I'm working with:
-Single python script
-Two configuration files (YAML)
-One databasish file (YAML)
-One icon
-A temporary directory used for downloading and merging PDF files, prior to loading them to a user-specified save directory (QT dialog).

I plan on distributing the program as a standalone folder, where the user can create a shortcut to the program and place it wherever, and move the whole folder wherever. It's a simple program, so I feel an installer's overkill.

I'm open to restructuring the way I'm doing this, since I don't know wtf I'm doing.

Where would you recommend placing the config files and temporary directory? I feel like keeping it together's good for portability.

Dominoes fucked around with this message at 00:46 on May 20, 2013

Dominoes
Sep 20, 2007

Found a solution on Stack Overflow

Uses a workaround where you locate a dummy module's directory, which is the same as the one it's in. Seems to find the correct directory, and not crash the frozen program. Quark, the solution you posted is likely to give the same glitch in cx_freeze; I think it's the use of __file__ it doesn't like.

Am I correct assuming using the documents folder for config files would require using an installer? I don't want to leave pieces of the program lying around a user's drive without a way to cleanly uninstall it. The program provides a quick way to select, download and merge multiple documents from the FAA's website that are published each month. Since the program's goal is to save time and effort, I'm trying to keep things as simple as possible for the user. I do let the user select the directory to download the final product, and it defaults to their Home/Downloads folder.

Dominoes fucked around with this message at 03:43 on May 20, 2013

Dominoes
Sep 20, 2007

QuarkJets posted:

If the user selects the destination of the final product, then why do you need to know where this module is located?
I currently have the configuration files and temporary directory in the program's folder, so I need to be able to determine its path. The user selects where to put the generated PDF(s). (Don't need the temp directly if they go for the separate files option, since it can download the files directly to the specified folder.)

I'd like to avoid having the user set the temporary directory; I'd like for this to be as simple and user-friendly as possible. "I just want to download approach plates, what's a temporary directly, and why do I have to set one? I don't know where to put it."

The module locator workaround I got from Stack works by checking if the program's frozen. If so, uses dirname(sys.executable), if not, uses dirname(__file__).


evensevenone posted:

Use the tempfile module for temporary files. It'll handle creating a temp file/folder in a safe, user-writable place, not overwriting anything, and cleaning it up when done.
Cool, I'll look into it.

Dominoes fucked around with this message at 11:46 on May 20, 2013

Dominoes
Sep 20, 2007

I noticed that Python modules seem portable - I was able to install a module on Ubuntu that I couldn't get working by using build/install, by copying and pasting the folder from my Windows install's site-libs folder. Why aren't they distributed as stand-alone folders? Was it an exception that this one (PyPdf2) worked by copy/paste? I'm asking because the python setup build/install method gives me errors most of the time.

Dominoes fucked around with this message at 03:07 on May 22, 2013

Dominoes
Sep 20, 2007

Thank you.

Dominoes
Sep 20, 2007

Sab669 posted:

So a buddy of mine is going back to college to get a BS in Comp Sci in a few months, and I have a really dumb question. He decided to start with the MIT lecture last night and I guess it starts off having him use Python. I don't know the first thing about Python or the Python Shell application it was having him use (Or any scripting language for that matter, I'm a newbie C# guy). He was having a problem trying to "understand" how he would actually use this in the real world. By that I mean, if he saved a file and ran it, a command window would pop up and immediately disappear, even though the script requests user input.

I also think part of it for him is he expects to be creating full blown desktop applications, but you need to learn to walk before you can run. Most day-to-day users would poop themselves if they had to deal with the command line in any way.

He was just texting me about it this morning as I was getting ready for work, so I didn't have a chance to sit down and try to learn anything, though I figured while he's taking this course I probably should too :)
I had your friend's mindset two months ago. Advice:

1: Go through all of the Python tutorials on Codeacademy. They're very good.

2: Install a text editor that will run code automatically. I use Notepad++ with the NPP plugin. I can press alt+shift+f5, and the code will immediately run in a Windows command prompt that doesn't close after running.

3: Install Pip - this will make installing some packages painless. I don't remember how to do it offhand; I thought there was an installer, but I can't find it.

4: To make a program others can use, you need Cx_freeze and a GUI toolkit. Toolkits include TKinter, WxWidgets, QT and GTK. I've only used QT, but learning it was more difficult than learning Python itself, due to a lack of good or interactive tutorials like CodeAcademy. The official QT docs describe the properties of each GUI element without explaining what they do. You will need to package msvcp100.dll and msvcr100.dll, found somewhere in your windows directly with the program when distributing it, or ensure the user has Microsoft Visual C++ 2010 redistributable installed.

Dominoes fucked around with this message at 22:51 on May 22, 2013

Dominoes
Sep 20, 2007

accipter posted:

What docs are you using? The PySide documentation is pretty nice. Here is an example.
The official QT ones. For example, here's the QFileDialog page. I spent a while trying to figure out how to set the "Save as type" dropdown, and only found the answer after asking on the QT forums. It's a property called filter. It's mentioned in the document, but not explicitly, or with other common names associated with it, like extension, type or suffix.

The docs are thorough, but there's no available tutorials on par with Codeacademy, and figuring out how to structure your documents, and how the QT code fits with python takes work.

Dominoes fucked around with this message at 22:38 on May 22, 2013

Dominoes
Sep 20, 2007

evensevenone posted:

Use the tempfile module for temporary files. It'll handle creating a temp file/folder in a safe, user-writable place, not overwriting anything, and cleaning it up when done.
Is there a way to use this with strings?

For example,
Python code:
with open(tempfile.TemporaryDirectory() + '\\filename', 'wb') as f:
Doesn't work - TypeError, unsupported operand types for tempdirectory and str. Is there another way to specify/save/open a file in a temporary directory?

Dominoes
Sep 20, 2007

accipter posted:

Just work with tempfile.NamedTemporaryFile() and look at the name attribute for its name. This might not be a meaningful name, but that shouldn't make a difference because it is a temporary file.
Like this?

Python code:
file = tempfile.NamedTemporaryFile().name + filename
    with open(file, 'wb') as f:
Leaving out the filename variable works, but then I don't know how to access the files. Using NamedTemporaryFile instead of directory, can I still look at all the files in the directory and then perform operations on them? I have working code using my own temporary folder.


Example code using a temp directory I made. Dir is a global variable that represents the program's path. empty_temp is a function that deletes all .pdf files in my temporary directory. Omitted some unnecessary-for-example code. Is it possible/worthwhile to use the tempfile module for this case?
Python code:
path = dir + '\\temporary\\'
empty_temp()
for plate in plates:
    filename = ...
    url = ...
    web_file = get(url).content
    save_path = path + filename
    with open(save_path, 'wb') as f:
            f.write(web_file)
    combine()
    with open(path + 'Plates.pdf', 'rb') as f: 
        return f.read()

def combine():
    path = dir + '\\temporary\\'
    filenames = [f for f in listdir(path) if f.endswith('.pdf')]     
    if len(filenames) > 0:
        merger = PdfFileMerger()
        for f in filenames:
            merger.append(fileobj = path + f)
        with open(path + 'Plates.pdf', 'wb') as f: 
            merger.write(f)
        merger.close()

Dominoes fucked around with this message at 00:47 on May 23, 2013

Dominoes
Sep 20, 2007

accipter posted:

Like this:

Python code:
>>> import tempfile
>>> with tempfile.NamedTemporaryFile() as fp:
>>>     print(fp.name)
c:\temp\tmpx3n3vl
Thanks. Got it working!

Python code:
def download_combined(window, plates):
    global d2
    d = tempfile.TemporaryDirectory()
    d2 = d.name
    for plate in plates:
        filename = ...
        url = ...
        web_file = get(url).content
        with open(d2 + '\\' + filename, 'wb')  as f:
            f.write(web_file)
    combine()
    window.ui.statusbar.showMessage("Download complete") 
    with open(d2 + '\\Plates.pdf', 'rb') as f:
        return f.read()

        
def combine():
    filenames = [f for f in listdir(d2) if f.endswith('.pdf')]     
    if len(filenames) > 0:
        merger = PdfFileMerger()
        for f in filenames:
            merger.append(fileobj = d2 + '\\' + f)
        with open(d2 + '\\Plates.pdf', 'wb') as f: 
            merger.write(f)
        merger.close()
If I read the docs correctly, the files/folder will delete themselves when done. How does it know it's done? Should I use cleanup()?

Dominoes fucked around with this message at 02:55 on May 23, 2013

Dominoes
Sep 20, 2007

Issue/question with PyQT / resources / cx_freeze.

I'm using QT's resource system to set an application icon. (Goes in the top left corner of the Window for Windows programs) I created the resource in Designer, then used pyrcc4 to create a rc.py file. It works properly on my uncompiled program, but fails to show (Shows the generic windows program icon instead) when compiling the script with cx_freeze. Note that I am not referring to the icon you click to launch the program - that's not handled by QT, and works properly. Any ideas? This is my setup.py.

Python code:
from sys import platform
from cx_Freeze import setup, Executable

import module_locator

_dir = module_locator.module_path()

base = None
if platform == "win32":
    base = "Win32GUI"

setup(
    name = "Plates",
    version = "0.1",
    description = "Downloads approach plates",
    executables = [Executable(_dir + '\\plates.pyw',
    base = base, icon = _dir + '\\icon.ico')],
    )
I get no errors when building the program. My rc file does exist (as a compiled python file) in library.zip.

edit: Solved, from Stack Overflow. The solution is to copy the imageformats folder from the PyQT directory to my program's directory. The image folder was (Windows) in Python33\Lib\site-packages\PyQt4\plugins.

Dominoes fucked around with this message at 01:47 on May 31, 2013

Dominoes
Sep 20, 2007

edit: nvm

Dominoes fucked around with this message at 02:49 on Jun 1, 2013

Dominoes
Sep 20, 2007

I'm getting ready to release my first program. Since I'm new to programming and don't know what the hell I'm doing, I'm looking for feedback on the overall layout of my code. It seems functional, but may appear hideously disfigured on the inside to an experienced coder. Let me know what you think, and if you have any suggestions.

Main Python file (should open directly in browser)

Standalone Windows binary

Dominoes fucked around with this message at 00:27 on Jun 4, 2013

Dominoes
Sep 20, 2007

Thermopyle posted:

Some general thoughts here, but none if it's that big of a deal:

I try to avoid doing "from X import Y". Throughout your code where you use Y, it's better if you know that it came from X. Explicit is better than impicit.
code:
def add(self):
#Adds a plate input by the user
    ident = self.ui.le_ident.text()
is usually...
code:
def add(self):
    #Adds a plate input by the user
    ident = self.ui.le_ident.text()
or even better...
code:
def add(self):
    """
    Adds a plate input by the user
    """
    ident = self.ui.le_ident.text()
Instead of this:
code:
save(_plates, dir + 'save.yaml')
do this:
code:
save(_plates, os.path.join(dir,' save.yaml'))
In fact, I don't like that you have a save() function and a save() method. I'd probably just have the save() method, but maybe you have a good reason for having the save functionality in its own function. Even if you do, I don't like them having the same name.

Thank you. I've indented the function descriptor comments. I thought I read somewhere that docstring notation should only be used for long strings, not comments. Is this valid, or did I misinterpret something?

I've been using 'from x import y' to make the code easier to read. I have an easier time comprehending shorter lines, especially in cases like this where the additional code is always the same. I've been looking at it similar to functions' importance: It allows me to reuse code instead of typing the same thing multiple times. Is my reasoning valid/common, or should I use 'import x' for everything? I also have a counter-reason for the downside of not knowing where an expression in the program body came from: Not knowing what a module from the import list is used for. Along the same reasoning with shorter code, what's the reason for using os.path.join() instead of + ?

I've changed the names of the save() Main class methods to save_gui. I don't have a good grasp on the layout of QT code, and agree that having separate methods and functions for save() is messy. It's set up that way, because things involving input from the GUI seem to only work if they're in the Main() QT class. So, I send the input to these class methods, then have them call my main program's functions, which do most of the work. I like to keep as much of my code as possible in my own functions and classes.

Dominoes fucked around with this message at 03:04 on Jun 4, 2013

Dominoes
Sep 20, 2007

Lysidas posted:

The term "docstring" specifically refers to a string literal that is the first statement in a module, function, class or method definition. These strings serve as documentation for the user of the function/class/module and are accessible programmatically through __doc__ attributes. IPython lets you easily view these:

Triple-quoted strings, in general, are not called "docstrings". Using triple quotes simply lets you write a string literal across multiple lines without having to use \n escape sequences. You are right that you shouldn't use triple-quoted strings as comments in the middle of a function/class/module.
Thank you. I assumed triple-quoting and docstrings were synonymous. The only place I'd used one is in a different program that uses a markup language called FIXML. I used them to enclose the FIXML, to send in a POST request. I'll take a look at using it at the beginning of functions instead of #.

Lysidas posted:

I was unable to run your code on my (Linux) laptop since you've hard-coded Windows path separators. os.path.join uses / or \ as appropriate on different platforms and has a few other advantages over manually concatenating filesystem paths. I also do from os.path import join as ospj to use a shorter (but still descriptive and greppable) function name.
That's a drat good reason; changed. Stealing ospj too, so as not to conflict with the normal join().

Dominoes fucked around with this message at 03:06 on Jun 4, 2013

Dominoes
Sep 20, 2007

Thermopyle posted:

It's not as big of an issue on a small file like yours, especially when it's all fresh in your mind. However, in 12 months, after the code has quadrupled in size, seeing a reference to load() in the middle of your code instead of yaml.load() is going to be confusing. Where did this load() come from? Wait, why is there a loads() in here as well? ITS SO CONFUSING!

Lysidas posted:

For this reason, json is one module that I always import in its entirety. You're right that load() is too general when you're looking at the file a few months from now.
So I went in and changed the json and yaml imports 'import json' and 'import yaml'. Json uses 'loads', yaml uses 'load'. Neither are very specific on their own, and especially not when using both. I'm using both since JSON seems more universal, but doesn't support objects, while YAML does. It turns out, I left off an 's' in the code that reads a JSON file some time ago... The YAML module was loading the JSON file the whole time, which I didn't know it could do. Reason for being careful about imported method names demonstrated!

Dominoes fucked around with this message at 04:23 on Jun 4, 2013

Dominoes
Sep 20, 2007

n0manarmy posted:

Going crazy with Python GUI crap. I've switched from TKinter to PyQt (using pyside) and cannot seem to figure out how to approach the below program concept. It could be that the concept is all wrong as well, so if it is, be gentle and provide some direction on how re-evaluate the concept.

I'm creating a class for the GUI components and am trying to create buttons to switch between one layout and another. I was able to do this in TKinter by obfuscating the create/destroy of the frames that contained the various functions of each menu.

main python file:
-Class
--Intro Menu
--Player Select Menu
--Difficulty Settings Menu
--Main Game Window
--etc...

-main
--Create class
-if name main
--main

Through out my googling, I've not really found any good tutorials on how to handle multiple windowed applications. I understand that Python might not be the best programming language for this but its the language I prefer right now. I've found references to QStackedlayout and setlayout, however I have not found anything to help with the concept of how to best build multiple windowed apps like above. Also reading the QT libraries are difficult for me because they tend to be in a C/C++ style for function use.


Reasoning:
I'm attempting to remake a very old game as a way to dig myself in to Python and GUI programming. The repetition of programming the game should help the language stick a bit, as well as allow me to further improve on the application as my programming progresses.

The game is Jones In The Fastlane and all I've done so far is load up the original and collect all the data points and GUI windows in to notes. I know what needs to go in and have an idea of what to expect. I was planning on building all of the menu components, creating all the variables in the process, and then putting it all together with the engine.
Throwing in a disclaimer of I don't know what I'm doing, but here's what I've been doing, which seems to work for standard GUI elements. No idea if the same layout works for custom graphics.

Main program file:
-QT class that is an instance of QtGui.QMainWindow. Looks like this:
code:
from plates_gui import Ui_Main
from about_gui import Ui_About

class Main(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Main()
        self.ui.setupUi(self)
        self.ui.btn.clicked.connect(self.signal)
	
    def method(self):
        x = self.ui.inputfield.text()
It contains some boilerplate stuff, and functions that take input directly from the QT window.
-Separate classes for each window. ie:
code:
class About(QtGui.QWidget):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_About()
        self.ui.setupUi(self)
-Main program body. Able to manipulate the GUI elements, but not accept user input from them.
-boilerplate stuff at the end. Also put global variables that affect the GUI, and anything that needs to happen with the GUI at startup here.
code:
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    main = Main()
    main.show()
    sys.exit(app.exec_())
I've been using QT designer, and have separate files, called by the QT class in the main program, for the GUI layout. You could write the code yourself if you wanted.

Example I posted last night. Has a link to the main program file, and the full, compiled Windows program with source code.

Dominoes fucked around with this message at 15:06 on Jun 4, 2013

Dominoes
Sep 20, 2007

Dren posted:

Dominoes, I noticed you have the idea that you should write as little code as possible. That's not quite the right idea. The right idea is to avoid reusing code, not to write the shortest possible syntactically correct code. It's often better to write a little more code for the sake of clarity. e.g. os.path.join(dir, "filename") as opposed to dir + "filename". Not to mention that in the former case you get cross platform compatibility.
I'm coming from a perspective of someone new to programming. It's easier to comprehend code that's more succinct, especially if you don't know what all of it does.

For example:
Python code:
pyqt4.QtGui.QFileDialog.getSaveFileName(os.path.join(dir, filename), QtCore.QDir.homePath()))

QFileDialog.getSaveFileName(ospj(dir, filename), homePath()))
The second example's easier to read. It's conveying the same information if you know what QFileDialog, ospj and homePath do. I don't look at short code as a goal, but given a choice, I prefer it, providing it's worth associated downsides.

Dominoes
Sep 20, 2007

Thermopyle posted:

Python code:
from pyqt4.QtGui import QFileDialog

path = os.path.join(dir, filename)
homepath = QtCore.QDir.homePath()

QfileDialog.getSaveFileName(path, homepath)

Dren posted:

Pardon my language, but you have this rear end backwards. The appropriate way to approach making code more succinct is to stick to one or two operations per line the way Thermopyle showed, not by creating custom aliases for operations so that they take up less visual space on the line.

For something like pyqt4.QtGui.QFileDialog.getSaveFileName I agree that using from to import QFileDialog is helpful if not necessary. os.path.join() --> ospj(), on the other hand, threw me for a loop. That's a fairly strange thing to do.
That makes sense.

Dominoes
Sep 20, 2007

Is there a trick to installing Numpy? I tried PIP, but get a list of errors, the final being "Command python setup.py egg_info failed with error code 1". Googling this brings up links to mostly Mac issues, but I'm using Windows/Python 3.

edit: Got it working with a binary from this website. Kind of surprised Pip didn't work - it's been great so far.

Dominoes fucked around with this message at 00:52 on Jun 9, 2013

Dominoes
Sep 20, 2007

The Gripper posted:

A friend of mine is currently in a job where his team leader uses sloc as a performance metric, giving pretty graphs straight to upper management. Currently nobody on his team is allowed to make changes to existing lines of code at all because if they do it's reported as "cosmetic changes" or "replacing existing working code" and looked on negatively, so their codebase in some parts has 5-10 copies of the same code smashed together to avoid touching existing variables/commenting anything out.

There's a particular data-heavy task that used to take ~30 seconds to complete that now takes over 8 minutes because the function is running variations on the same code multiple times.

Upper management is still "very happy" with the improvements the team has made in the number of lines of code they've written (therefore their intervention has been a success), so nobody on the team even cares that they're writing the most horrible thing. It's amazing.

Edit; I forgot the best part - in code that writes to the database each iteration of the code deletes the previous iterations from the table. By that I mean the program flow for those functions goes Write 1->Delete 1->Write 2->Delete 2->Write 3->Delete 3->Write Final->Return success. Each of those writes is the same thing, they just don't want to remove the previous writes from old code because of the above bullshit.
Is this why most corporate and government computers run so slowly?

Dominoes
Sep 20, 2007

fritz posted:

Until PEP8 goes in the parser, you can use whatever names you drat well please.
Hey time to open another can of worms! I read through PEP8 a few weeks ago, and made my code compliant, mostly - I don't understand the 79 char limit-per-line recommendation. The reasons given are that some text editors don't handle more than 79 characters well, and you can have multiple windows open. I don't like more than 100 or so characters to reduce eye movement, but find 79 restrictive when using indented lines or comments. I'm running portrait monitors, and don't have a problem pushing more than 79. Do y'all use that limit?

Dominoes fucked around with this message at 01:42 on Jun 12, 2013

Dominoes
Sep 20, 2007

Jon Joe posted:

Could I, perhaps, get a better tutorial?
I learned using Codeacademy. It's oustanding - made learning easy by using interactive tutorials that force you to solve problems as you learn.

Dominoes
Sep 20, 2007

Do you need access to a machine running the target OS when making a binary? I've been making Windows x64 files using CX_freeze, but ideally would like mac, linux and win-32 ones. I got my program to work on Ubuntu running from source - everything works. (although the GUI fonts are too big for their buttons - easy fix) I looked up making a .deb file, and the instructions were complex, and seemed to require being on Linux to do it. It looks like to create a Mac version, I need to be on a Mac. For a 32-bit Win version, I think I can do it from a 64-bit OS, but need a 32-bit installation of Python. Is this accurate, or is there a way to make different binaries without jumping on different computers/OSes/versions of Python?

Dominoes fucked around with this message at 22:19 on Jun 12, 2013

Dominoes
Sep 20, 2007

accipter posted:

Why have you decided to distribute a compiled version of your program?
So people other than myself can use it.

Dominoes fucked around with this message at 22:21 on Jun 12, 2013

Dominoes
Sep 20, 2007

Dren posted:

If your intended result is cx freeze binaries packaged natively for various operating systems you will most likely need to get access to those platforms. Cross compiling is difficult. Cross-creating packages seems incredibly hard, if not impossible, since you generally need a platform specific toolchain to do that sort of thing. Besides, you'll need those access to those platforms in order to test the packages you create.

PS - Creating a .deb file is supported by setup.py but maybe not for something compiled with cx freeze. I used setup.py to create an rpm for me the other day and was pleasantly surprised by how simple and nice it was.
Thank you. I'll try to get Python 32-bit (probalby cx_freeze and QT 32-bit too) installed on my laptop's Windows drive, to prevent confusion on my main computer with two versions of Python. I'd imagine I wouldn't need to change anything, other than the packaged DLLs. I followed this official Ubuntu tutorial, but ran into multiple errors. The line at the top states "Note: These instructions are only for creating packages for personal use.", but the overall package guide seems more geared towards best practices, and isn't Python specific.

Dominoes fucked around with this message at 22:36 on Jun 12, 2013

Dominoes
Sep 20, 2007

madkapitolist posted:

I'm trying to grab a column of values from a csv file, then pass those values as a parameter through to a url (my example url is madkapitolist.com). Then I want to hit those url's.

I can grab the values and append to the url, and print properly with the below code, but I don't know how to hit the URL's. I have been looking at urllib/ urllib2 but those want to be passed a url to hit, not a variable. My variable is sid in the below code.

How do I hit url's stored in a variable?

Thanks


Python code:
#!/usr/bin/python
import csv

csvfile = list(csv.reader(open('today.csv')))
for row in csvfile:
  sid = "http://madkapitolist.com?sid="+row[13]
  print "%s" %sid


I'm not clear on what you're asking, so here's a guess. Are you trying to copy text from the url? Download a file? JSON/XML data?
Python code:
import csv
import requests # Third party module that's better than urllib. Urllib's been a headache for me.

csvfile = list(csv.reader(open('today.csv')))
for row in csvfile:
    sid = "http://madkapitolist.com?sid=%s" % (row[13])
    x = requests.get(sid) #I'm not sure what you're going to do with the url, so you will need to alter this line accordingly.
    print sid

Dominoes fucked around with this message at 22:24 on Jun 16, 2013

Dominoes
Sep 20, 2007

Jon Joe posted:

I've learned the basics of python, how do I go about expanding my knowledge? Specifically, how do I learn more functions?

edit: Okay maybe functions isn't the right word, that'd just be a subsection of what I want. I don't know the word I want. Stuff that's built in that I can do?
Figure out a program you want to make. Solve every challenge doing so presents. When finished, do it for another program idea.

For example: I started python (and programming in general) a few months ago. I learned the basics from the Codeacademy interactive tutorial. I decided I wanted to make a stock screener. I learned how to apply what I learned from Codeacademy, how to use Oauth authentication, how to use dates and times, HTTP requests, managing CSV and JSON data, and how to save data. When I later decided to make it automated, I learned how to run programs in continuous loops, how to use FIXML, when to split into multiple files, how to use exception handling, and how to set up built-in-tests.

I decided I wanted to make a program to simplify downloading items from the internet. I learned how to merge PDF files, how to code a GUI, and how to compile code in a standalone program. I recently decided I'd like to make an instrument tuner and metronome, so I'm learning how to use arrays, FFT algorithms, sampling etc. I got a lot of help here and from Stack overflow.

Dominoes
Sep 20, 2007

I looked up logarithms in the python docs, where it's listed as 'math.log(x[, base])'

It seems like the actual syntax is 'math.log(x, base)', as the above doesn't work, and the docs later refer to 'math.log(x, base)'. What are the docs conveying with the bracketed notation?

Dominoes
Sep 20, 2007

So "[, base]" means "either 'base' or blank" ?

Thanks.

Dominoes fucked around with this message at 14:26 on Jun 17, 2013

Dominoes
Sep 20, 2007

I can't recommend LFD.UCI's pythonlibs website enough for Windows users. I recommend putting it in the OP. I've spend a lot of time over the past few days troubleshooting how to install PyAudio from source. (No win64 binary on their official page; 32 only) I ran into many errors, as always. Found a precompiled 64-bit version on this website; headache over.

Dominoes fucked around with this message at 14:54 on Jun 22, 2013

Adbot
ADBOT LOVES YOU

Dominoes
Sep 20, 2007

Is there a good reason the datetime module has a type named datetime? It seems confusing. Why not name the type date_time, or something else that isn't the exact name of its parent?

  • Locked thread