content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python list comprehension - simple I have a list and I want to use a certain function only on those entries of it that fulfills a certain condition - leaving the other entries unmodified. Example: Say I want to multiply by 2 only those elements who are even. a_list = [1, 2, 3, 4, 5] Wanted result: a_list => [1, ...
Python list comprehension - simple
I have a list and I want to use a certain function only on those entries of it that fulfills a certain condition - leaving the other entries unmodified. Example: Say I want to multiply by 2 only those elements who are even. a_list = [1, 2, 3, 4, 5] Wanted result: a_list => [1, 4, 3, 8, 5] But [elem * 2 for elem in a...
[ "Use a conditional expression:\n[x * 2 if x % 2 == 0 else x\n for x in a_list]\n\n(Math geek's note: you can also solve this particular case with\n[x * (2 - x % 2) for x in a_list]\n\nbut I'd prefer the first option anyway ;)\n", "a_list = [1, 2, 3, 4, 5]\n\nprint [elem*2 if elem%2==0 else elem for elem in a_lis...
[ 18, 2, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0007619868_list_comprehension_python.txt
Q: Interested in Collective Programming for the web -- Ruby or Python or PHP? For something like a personal recommendation system, machine learning type of stuff on a website, what language would be best? A: The language you know best would be best. I mean that half-seriously. Given the brief description of your p...
Interested in Collective Programming for the web -- Ruby or Python or PHP?
For something like a personal recommendation system, machine learning type of stuff on a website, what language would be best?
[ "The language you know best would be best.\nI mean that half-seriously. Given the brief description of your project, there's no reason to believe any of the languages you list would be any better or worse than the others. Those three languages are adequate for approximately similar tasks, so you should pick the o...
[ 16, 1, 0, 0 ]
[ "I recently did some research into this for a project at my day job. It was for a recommendation system and the options were php,perl or python.\nPHP was out almost immediately, there were no good 3rd party open source libraries and the language itself is not as well suited to any kind of complex real programming.\...
[ -2 ]
[ "artificial_intelligence", "php", "python", "recommendation_engine", "ruby" ]
stackoverflow_0000410183_artificial_intelligence_php_python_recommendation_engine_ruby.txt
Q: Python get a "sub" 2d list from bigger 2d list? How would you get a 2d sublist from a bigger 2d list? gridx = 10 gridy = 16 grid = [[0]*gridx for i in range(gridy)] subgrid = None # I want to get a subgrid given an x,y grid origin (bottom-left) and x,y subgrid size A: If you want to slice your 2D list at the li...
Python get a "sub" 2d list from bigger 2d list?
How would you get a 2d sublist from a bigger 2d list? gridx = 10 gridy = 16 grid = [[0]*gridx for i in range(gridy)] subgrid = None # I want to get a subgrid given an x,y grid origin (bottom-left) and x,y subgrid size
[ "If you want to slice your 2D list at the limits x1, y1, x2, y2 you can do:\ndef getsubgrid(x1, y1, x2, y2, grid):\n return [item[x1:x2] for item in grid[y1:y2]]\n\nfor example:\ngrid = [[1, 2, 3, 4, 5, 6, 7, 8, 9],\n [11,12,13,14,15,16,17,18,19],\n [21,22,23,24,25,26,27,28,29],\n [31,32,33,...
[ 7, 1 ]
[]
[]
[ "2d", "grid", "list", "python" ]
stackoverflow_0007620482_2d_grid_list_python.txt
Q: get formated output from mysql via python Hi I want the following output from my query: OK|Abortedclients=119063 Aborted_connects=67591 Binlog_cache_disk_use=0 But I dont know how to generate it. this is my script: #!/usr/bin/env python import MySQLdb conn = MySQLdb.connect (host = "...", user="...", passwd="......
get formated output from mysql via python
Hi I want the following output from my query: OK|Abortedclients=119063 Aborted_connects=67591 Binlog_cache_disk_use=0 But I dont know how to generate it. this is my script: #!/usr/bin/env python import MySQLdb conn = MySQLdb.connect (host = "...", user="...", passwd="...") cursor = conn.cursor () cursor.execute ("SHO...
[ "Build the string using join:\nprint('OK|'+' '.join(['{0}={1}'.format(*row) for row in rs]))\n\n' '.join(iterable) creates a string out of the strings in iterable, joined together with a space ' ' in between the strings.\n\nTo fix the code you posted with minimal changes, you could add a comma at the end of the pri...
[ 0, 0, 0 ]
[]
[]
[ "format", "mysql", "python" ]
stackoverflow_0007620360_format_mysql_python.txt
Q: Python Code Organization Question : Eggs + Packages + Buildout + Unit Tests + SVN I have several python projects that share common modules. Until now, I've been ... ahem ... keeping multiple copies of the common code and synchronizing by hand. But I'd clearly prefer to do something else. It looks to me now, as if ...
Python Code Organization Question : Eggs + Packages + Buildout + Unit Tests + SVN
I have several python projects that share common modules. Until now, I've been ... ahem ... keeping multiple copies of the common code and synchronizing by hand. But I'd clearly prefer to do something else. It looks to me now, as if zc.Buildout maybe what I need. I guess that what I should be doing is putting each reus...
[ "Do not separate the tests from your code, you need to keep the two closely together. It's not as if tests take up that much disk space or any memory! And tests can be extremely instructive to your library users.\nFor library packages, include a buildout.cfg and bootstrap.py file with your package to make running t...
[ 5, 2, 2, 1 ]
[]
[]
[ "buildout", "code_organization", "egg", "python", "svn" ]
stackoverflow_0000194339_buildout_code_organization_egg_python_svn.txt
Q: Which class owns methods and attributes Let's say we have this code: class C(CC): a = 1 b = 2 def __init__(self): self.x = None self.y = 1 How can I quickly find out in Python where is the attribute or method defined? If it belongs to ancestor class or if it's the method of class C. You can see attr...
Which class owns methods and attributes
Let's say we have this code: class C(CC): a = 1 b = 2 def __init__(self): self.x = None self.y = 1 How can I quickly find out in Python where is the attribute or method defined? If it belongs to ancestor class or if it's the method of class C. You can see attributes a, b, x, y . Must they belong to class...
[ "In the first example, a and b are attributes of the C class object. (Think \"static\" attributes.) And x and y are attributes of C instances. (So, regular instance attributes.)\nIn the second example, all four are attributes of C, not of its instances.\nIn Python, you can't \"declare\" attributes as defined by a s...
[ 4, 1 ]
[]
[]
[ "attributes", "inheritance", "python", "self" ]
stackoverflow_0007620741_attributes_inheritance_python_self.txt
Q: How can I select URLs of a particular type with XPath & Scrapy I am trying to select only links of the type http://lyricsindia.net/songs/show/* from an HTML which contains links likes this: <a href="http://lyricsindia.net/songs/show/550" class=l>LyricsIndia.net dhiimii </a> <a href="http://smriti.com/hindi-songs/d...
How can I select URLs of a particular type with XPath & Scrapy
I am trying to select only links of the type http://lyricsindia.net/songs/show/* from an HTML which contains links likes this: <a href="http://lyricsindia.net/songs/show/550" class=l>LyricsIndia.net dhiimii </a> <a href="http://smriti.com/hindi-songs/dhiimii-dhiimii-bhiinii-bhiinii-utf8" class=l>dhiimii Songs Archive</...
[ "Try this XPath:\n//a[starts-with(@href, 'http://lyricsindia.net/songs/show/')]\n\n" ]
[ 3 ]
[]
[]
[ "python", "regex", "scrapy", "xml", "xpath" ]
stackoverflow_0007620651_python_regex_scrapy_xml_xpath.txt
Q: python SMTP header format The following piece of code is formatting my email script correctly. It is placing the to, from, subject, and body in the correct parts of the email. My problem is that I can't figure out why it needs two returns and two newlines ("\r\n\r\n") in my connect function to display the body i...
python SMTP header format
The following piece of code is formatting my email script correctly. It is placing the to, from, subject, and body in the correct parts of the email. My problem is that I can't figure out why it needs two returns and two newlines ("\r\n\r\n") in my connect function to display the body in the email when the rest of th...
[ "Because of the standard, body must be separated from the headers with an empty line.\n\nA message consists of header fields and, optionally, a body. The body\n is simply a sequence of lines containing ASCII characters. It is\n separated from the headers by a null line (i.e., a line with nothing\n preceding the ...
[ 3 ]
[]
[]
[ "email", "gmail", "header", "python", "smtp" ]
stackoverflow_0007620745_email_gmail_header_python_smtp.txt
Q: Stupid thing on checks and sums - Python Which is more CPU intensive, to do an if(x==num): check, or to do a sum x+y? A: Your question is somewhat incomplete because you are comparing two different operations. If you need to add two things together then testing x==y isn't going to get you anywhere. So presumably...
Stupid thing on checks and sums - Python
Which is more CPU intensive, to do an if(x==num): check, or to do a sum x+y?
[ "Your question is somewhat incomplete because you are comparing two different operations. If you need to add two things together then testing x==y isn't going to get you anywhere. So presumably you want to compare\nif y != 0:\n sum += y\n\nwith\nsum +=y\n\nIt's a lot more complex for interpreted languages like P...
[ 1 ]
[]
[]
[ "if_statement", "python", "sum" ]
stackoverflow_0007620775_if_statement_python_sum.txt
Q: SQLAlchemy: query custom property based on table field I'm using SQLAlchemy declarative base to define my model. I defined a property name that is computed from one the columns (title): class Entry(Base): __tablename__ = "blog_entry" id = Column(Integer, primary_key=True) title = Column(Unicode(255)) ...
SQLAlchemy: query custom property based on table field
I'm using SQLAlchemy declarative base to define my model. I defined a property name that is computed from one the columns (title): class Entry(Base): __tablename__ = "blog_entry" id = Column(Integer, primary_key=True) title = Column(Unicode(255)) ... @property def name(self): return re....
[ "From SqlAlchemy 0.7 you can achieve this using hybrid_property\nsee the docs here: http://www.sqlalchemy.org/docs/orm/extensions/hybrid.html\n", "Can you imagine what SQL should be issued for your query? The database knows nothing about name, it has neither a way to calculate it, nor to use any index to speed up...
[ 13, 4 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0004738259_python_sqlalchemy.txt
Q: PyQt4: set size of QGridLayout depending on size of QMainWindow I'm writing a little Qt application with Python. I've created QMainWindow, which have a QGridLayout. In each grid I'm adding QTextBrowser Widget. I want left side of my grid to be not bigger than 25% of window. So I'll have two QTextBrowsers: one is 2...
PyQt4: set size of QGridLayout depending on size of QMainWindow
I'm writing a little Qt application with Python. I've created QMainWindow, which have a QGridLayout. In each grid I'm adding QTextBrowser Widget. I want left side of my grid to be not bigger than 25% of window. So I'll have two QTextBrowsers: one is 25% of window's width, and another is 75% of window's width. How can I...
[ "You can specify relative width by giving each cell a stretch with setStretch(). They will get sizes proportional to the given stretches. Here is a simple example that makes the right widget 3 times greater than the left widget.\nimport sys\nfrom PyQt4 import QtGui\n\nif __name__ == \"__main__\":\n app = QtGui.Q...
[ 2 ]
[]
[]
[ "pyqt", "python", "qt", "qwidget" ]
stackoverflow_0007619121_pyqt_python_qt_qwidget.txt
Q: Python Pmw and cx_Freeze? I am unable to make an executable from my python program which uses Pmw (Python mega widgets). I use cx_Freeze (through gui backend "Gui2Exe"). Searching Pmw site I've found that it's caused by how the Pmw library checks for modules when ran and it doesn't work when you use py2exe or simi...
Python Pmw and cx_Freeze?
I am unable to make an executable from my python program which uses Pmw (Python mega widgets). I use cx_Freeze (through gui backend "Gui2Exe"). Searching Pmw site I've found that it's caused by how the Pmw library checks for modules when ran and it doesn't work when you use py2exe or similar programs because the librar...
[ "Unfortunately, the original file has some problems with tabs and spaces (just look at the while indentation in expandlinks).\nI fixed those indentation problems, changed regsub.gsub with re.sub and eliminated the string import, using the string type methods.\nAfter that the script worked perfect:\n Pmw.py has be...
[ 2 ]
[]
[]
[ "cx_freeze", "exe", "freeze", "python" ]
stackoverflow_0006772916_cx_freeze_exe_freeze_python.txt
Q: Searching (x,y) pair in sequence I would like to find match (x,y) in string. Is the following seem good ? Or better alternative you can suggest. Please note that between (x,y) pairs several white spaces or commas may exists in mystring. #!/usr/bin/env python import re mystring="(3,4) , (2, 4),(5,4), (2,3), " tmp...
Searching (x,y) pair in sequence
I would like to find match (x,y) in string. Is the following seem good ? Or better alternative you can suggest. Please note that between (x,y) pairs several white spaces or commas may exists in mystring. #!/usr/bin/env python import re mystring="(3,4) , (2, 4),(5,4), (2,3), " tmp= re.findall(r'\(\d+,\d\)+', mystring)...
[ "Instead of\nre.findall(r'\\(\\d+,\\d\\)+', mystring)\n\nUse\nre.findall(r'\\(5,4\\)', mystring)\n\nand it will only find the pair you want\n", "Why not search for the pair you want? Also, you can use \\s to match whitespace.\nimport re\n\ndef find_pair(x, y, mystring):\n return re.findall(r'\\(\\s*?%d,\\s*?%d...
[ 3, 2, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007621366_python_regex.txt
Q: Struct Alignment with PyOpenCL update: the int4 in my kernel was wrong. I am using pyopencl but am unable to get struct alignment to work correctly. In the code below, which calls the kernel twice, the b value is returned correctly (as 1), but the c value has some "random" value. In other words: I am trying to re...
Struct Alignment with PyOpenCL
update: the int4 in my kernel was wrong. I am using pyopencl but am unable to get struct alignment to work correctly. In the code below, which calls the kernel twice, the b value is returned correctly (as 1), but the c value has some "random" value. In other words: I am trying to read two members of a struct. I can r...
[ "In the OpenCL program, try the packed attribute on the struct itself, instead of one of the members:\ntypedef struct s {\n int4 f0;\n int4 f1;\n} __attribute__((packed)) s;\n\nIt might be that because you only had the packed attribute on a single member of the struct, it might not have been packing t...
[ 0, -1 ]
[]
[]
[ "c", "opencl", "pyopencl", "python", "struct" ]
stackoverflow_0007620999_c_opencl_pyopencl_python_struct.txt
Q: How to ask the user for an output file in python I have to ask the user for an output file and then append data to it but whenever I try it tells me that the data has no append attribute. I think this is because when I try to open the file it is seeing it as a string and not an actual file to append data too. I ha...
How to ask the user for an output file in python
I have to ask the user for an output file and then append data to it but whenever I try it tells me that the data has no append attribute. I think this is because when I try to open the file it is seeing it as a string and not an actual file to append data too. I have tried multiple ways of doing this but right now I a...
[ "Your error is at this line:\nfileObject.append(Output, '\\n')\n\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'file' object has no attribute 'append'\n\nUse the write method of a file object:\nfileObject.write(Output+'\\n')\n\n", "File objects have no append method...
[ 4, 2, 1, 0 ]
[]
[]
[ "append", "file_io", "python", "user_input" ]
stackoverflow_0007621442_append_file_io_python_user_input.txt
Q: opening files from a website I asked a similar question yesterday but I included some code that basically took my question on a different tangent than I had intended. So I shall try again. I am rewriting a python script that crawls a website to find a few hundred text files, I have no interest in any content of t...
opening files from a website
I asked a similar question yesterday but I included some code that basically took my question on a different tangent than I had intended. So I shall try again. I am rewriting a python script that crawls a website to find a few hundred text files, I have no interest in any content of the text file beyond the second lin...
[ "Well, you could use urllib2.urlopen() to just get the file contents into memory, extract the second line, and then immediately discard the file from memory, if you wanted, without ever hitting your disk.\nYou are going to have to download the contents over the internet, though.\n", "You could try something like ...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007621249_python.txt
Q: Matrix Multiplication in Python Changes the Result Dimension I have 1X2 matrix, Mu_I.transpose(), and a 2x2 matrix, Covariance_I_Inverse. The result of multiplication should be a 1x2 matrix, but my output is a 2x2 matrix. Why? How can I get a 1x2 Matrix? >>> Mu_I.transpose() [[ 10.02010924 9.99184818]] >>> Mu_I...
Matrix Multiplication in Python Changes the Result Dimension
I have 1X2 matrix, Mu_I.transpose(), and a 2x2 matrix, Covariance_I_Inverse. The result of multiplication should be a 1x2 matrix, but my output is a 2x2 matrix. Why? How can I get a 1x2 Matrix? >>> Mu_I.transpose() [[ 10.02010924 9.99184818]] >>> Mu_I.transpose().shape (1, 2) >>> Covariance_I_Inverse [[ 0.72006911 ...
[ "I'm guessing those variables are numpy.array, but not numpy.matrix. For numpy.array, * is defined as element-wise multiplication. In that case use numpy.dot(). That will give you matrix multiplication.\nOr simply use numpy.matrix and * operator will be matrix multiplication.\n" ]
[ 6 ]
[]
[]
[ "matrix", "numpy", "python" ]
stackoverflow_0007621656_matrix_numpy_python.txt
Q: float to integer in python If I want to convert a float to an integer in Python, what function do I use? The problem is that I have to use a variable passed through the function math.fabs (Absolute Value) as an index for a list, so it has to be an int, while the function math.fabs returns a float. A: Use the int...
float to integer in python
If I want to convert a float to an integer in Python, what function do I use? The problem is that I have to use a variable passed through the function math.fabs (Absolute Value) as an index for a list, so it has to be an int, while the function math.fabs returns a float.
[ "Use the int() constructor:\n>>> foo = 7.6\n>>> int(foo)\n7\n\nNote that if you use the built-in abs() function with an integer argument, you'll get an integer result in the first place:\n>>> type(abs(-7))\n<type 'int'>\n\n", "Probably you're looking for both round and int:\n>>> foo = 1.9\n>>> int(foo)\n1\n>>> in...
[ 4, 2 ]
[]
[]
[ "absolute_value", "floating_point", "integer", "python" ]
stackoverflow_0007621903_absolute_value_floating_point_integer_python.txt
Q: Emulating Django models ? (Simple implementation - Missing something) I am trying to emulate django models : In Django : from django.contrib.auth.models import User if User.objects.get(pk=1) == User.objects.get(username='root') print 'True' else: print 'False' # True is printed My implementation : cla...
Emulating Django models ? (Simple implementation - Missing something)
I am trying to emulate django models : In Django : from django.contrib.auth.models import User if User.objects.get(pk=1) == User.objects.get(username='root') print 'True' else: print 'False' # True is printed My implementation : class MyUser: def __init__(self, id): self.id = id class Us...
[ "The issue is simply that you haven't defined __eq__ on your class, so Python has no idea how to compare them. Something like this would work:\nclass MyUser(object):\n def __init__(self, id):\n self.id = id\n\n def __eq__(self, other):\n return self.id == other.id\n\n", "This is because Django...
[ 2, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007621904_django_django_models_python.txt
Q: Tkinter menu for chosing a date I am building a dropdown menu that would be used to choose a starting date. It has 3 cascades named year, month, day. The contents of the day cascade is generated so that the available days are true to the chosen year and month. It is possible/probable that the user is going to chan...
Tkinter menu for chosing a date
I am building a dropdown menu that would be used to choose a starting date. It has 3 cascades named year, month, day. The contents of the day cascade is generated so that the available days are true to the chosen year and month. It is possible/probable that the user is going to change the date several times during a si...
[ "You could delete all entries in daymenu before adding new ones:\ndef make_daymenu():\n daymenu.delete(0,31) \n for the_day in list_of_days:\n daymenu.add_command(label=the_day, command=lambda : day_setter(the_day))\n window.config(menu=menubar)\n\n", "came across your code to select a date. Recen...
[ 2, 0 ]
[]
[]
[ "drop_down_menu", "python", "tkinter" ]
stackoverflow_0007545315_drop_down_menu_python_tkinter.txt
Q: Python Newbie Questions - Not printing correct values I am newbie to python and I doing doing some OOPS concept exploring in Python. Following is my Account class: class Account: def __init__(self,balance): self.__balance=int(balance) def deposit(self,deposit_amt): self.__balance=self.__ba...
Python Newbie Questions - Not printing correct values
I am newbie to python and I doing doing some OOPS concept exploring in Python. Following is my Account class: class Account: def __init__(self,balance): self.__balance=int(balance) def deposit(self,deposit_amt): self.__balance=self.__balance + int(deposit_amt) def withdraw(self,withdraw_am...
[ "With the double -- (negative) you are subtracting a negative value (i.e. adding a positive value).\nA more clear explanation would look like:\nself.__balance = self.__balance - (0 - int(withdraw_amt))\n\nTherefore, change this:\nself.__balance=self.__balance -- int(withdraw_amt)\n\nTo this:\nself.__balance=self.__...
[ 2, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007622159_python_python_3.x.txt
Q: lookuperror unknown encoding cp720 in django when running on diffrent computer I have a django site that when I run it on my computer,every thing is good,but when I run it on another computer,I can't login with my username and password and that sounds like the user is not in my database while the user is in user a...
lookuperror unknown encoding cp720 in django when running on diffrent computer
I have a django site that when I run it on my computer,every thing is good,but when I run it on another computer,I can't login with my username and password and that sounds like the user is not in my database while the user is in user auth table in sqlite. then I go to shell to create another user,but it doesn't let me...
[ "You should find out why the other machine doesn't have the full set of codecs installed, and rectify that.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007622129_django_python.txt
Q: Python SIP expose function I'm writing a Python module for some C++ code using SIP. However whilst I can easily expose classes, I cannot find a way to expose standalone functions. Here is my header file defining the functions that I wish to expose to Python: ProxySettings.h #include <Windows.h> #include <Wininet.h...
Python SIP expose function
I'm writing a Python module for some C++ code using SIP. However whilst I can easily expose classes, I cannot find a way to expose standalone functions. Here is my header file defining the functions that I wish to expose to Python: ProxySettings.h #include <Windows.h> #include <Wininet.h> bool SetConnectionOptions(con...
[ "Try this:\n%Module ieproxy 0 \n\n%UnitCode\n#include <ProxySettings.h>\n%End\n\nbool SetConnectionOptions(const char * proxy_full_addr); \nbool DisableConnectionProxy(); \n\n" ]
[ 2 ]
[]
[]
[ "c++", "python", "python_sip" ]
stackoverflow_0005614979_c++_python_python_sip.txt
Q: Wrapping C library I have a private.h, public.h and the file.c, and I need to wrap it into Cython. How do I wrap the function Person_ptr Person_create(const char* name);? private.h: #ifndef __PERSON_PRIVATE_H__ #define __PERSON_PRIVATE_H__ #include "Person.h" typedef struct Person_TAG { char* name; int a...
Wrapping C library
I have a private.h, public.h and the file.c, and I need to wrap it into Cython. How do I wrap the function Person_ptr Person_create(const char* name);? private.h: #ifndef __PERSON_PRIVATE_H__ #define __PERSON_PRIVATE_H__ #include "Person.h" typedef struct Person_TAG { char* name; int age; } Person; void per...
[ "cperson.pxd:\ncdef extern from \"Person.h\":\n cdef struct Person_TAG:\n pass\n ctypedef Person_TAG* Person_ptr\n\n Person_ptr Person_create(char* name)\n void Person_destroy(Person_ptr self)\n\n char* Person_get_name(Person_ptr self)\n\nperson.pyx:\nfrom cperson cimport Person_ptr, Person_cr...
[ 7, 1 ]
[]
[]
[ "c", "cython", "python" ]
stackoverflow_0007619785_c_cython_python.txt
Q: How to use Google Libraries API (jQuery) with Google App Engine? I am trying to add this jQuery Hover effect to my site. Instead of downloading jQuery I decided to use Google Libraries API for jQuery. I got a key and copied the code that goes to the header then I copied the jQuery for the hover effect but nothing ...
How to use Google Libraries API (jQuery) with Google App Engine?
I am trying to add this jQuery Hover effect to my site. Instead of downloading jQuery I decided to use Google Libraries API for jQuery. I got a key and copied the code that goes to the header then I copied the jQuery for the hover effect but nothing is happenning. What am I doing wrong? This is where my test page is an...
[ "You're not wrapping your jQuery code in $(document).ready(), so the DOM doesn't exist yet at the time you're trying to attach the handlers. In general, any time you need to reference DOM elements in the page (as opposed to just defining functions to be called later), you have to wrap it all in a .ready() callback ...
[ 3 ]
[]
[]
[ "css", "jquery", "python" ]
stackoverflow_0007622592_css_jquery_python.txt
Q: Performance Bottleneck with python mapping data structure I am facing a little performance problem with one of my data structures used for a bigger project in python. Basically, I am importing a tabular delimited file. Using the normal python open(...) file iterator I am splitting the lines with line.split("\t"). ...
Performance Bottleneck with python mapping data structure
I am facing a little performance problem with one of my data structures used for a bigger project in python. Basically, I am importing a tabular delimited file. Using the normal python open(...) file iterator I am splitting the lines with line.split("\t"). Now I want the actual value of a column be inserted in some sor...
[ "If keys and values are unique, you can use a bidirectional dictionary. There is one python package here\n" ]
[ 1 ]
[]
[]
[ "dictionary", "list", "mapping", "python" ]
stackoverflow_0007622618_dictionary_list_mapping_python.txt
Q: Convert SHA256 hash string to SHA256 hash object in Python I have a string which is a SHA256 hash, and I want to pass it to a Python script which will convert it to a SHA256 object. If I do this: my_hashed_string = // my hashed string here m = hashlib.SHA256() m.update( my_hashed_string ) it will just hash my ha...
Convert SHA256 hash string to SHA256 hash object in Python
I have a string which is a SHA256 hash, and I want to pass it to a Python script which will convert it to a SHA256 object. If I do this: my_hashed_string = // my hashed string here m = hashlib.SHA256() m.update( my_hashed_string ) it will just hash my hash. I don't want to hash twice...it's already been hashed. I jus...
[ "Unfortunately the hash alone isn't enough info to reconstruct the hash object. The hash algorithm itself is temporal, depending on both internal structures and further input in order to generate hashes for subsequent input; the hash itself is only a small piece of the cross section of the algorithm's data, and can...
[ 4 ]
[]
[]
[ "encryption", "python" ]
stackoverflow_0007622649_encryption_python.txt
Q: Why has this approach been taken in this class? In the base class inside generic views django creates a method view at runtime , attaches it to the generic view class and then calls the dispatch method on that class I did not understand the purpose of this approach , why did not the dispatch method was called dire...
Why has this approach been taken in this class?
In the base class inside generic views django creates a method view at runtime , attaches it to the generic view class and then calls the dispatch method on that class I did not understand the purpose of this approach , why did not the dispatch method was called directly from the as_view method ? class View(object): ...
[ "In class based generic views, any request should have it's own instance of the MyView class.\nHere is our urls.py:\nfrom foo.views import AboutView\n....\n(r'^about/', AboutView.as_view()),\n\nurls.py is imported once per django thread. This means that calling as_view does not create an instance of AboutView.\nWhe...
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007622262_django_python.txt
Q: Python: adding calculated list elements I have a list of lists list_1 = [['good', 2, 2], ['bad', 2, 2], ['be', 1, 1], ['brown', 1, 3]] I would like to add new element to the inner list by summing the two numbers. So my list should look like list_1 = [['good', 2, 2, 4], ['bad', 2, 2, 4], ['be', 1, 1, 2], ['brown',...
Python: adding calculated list elements
I have a list of lists list_1 = [['good', 2, 2], ['bad', 2, 2], ['be', 1, 1], ['brown', 1, 3]] I would like to add new element to the inner list by summing the two numbers. So my list should look like list_1 = [['good', 2, 2, 4], ['bad', 2, 2, 4], ['be', 1, 1, 2], ['brown', 1, 2, 3]] How do I add insert new element i...
[ "for lst in list_1:\n lst.append(lst[1]+lst[2])\n\n", "\nIterate over your list of lists.\nFor each list in your list of lists,\nCompute your new element, and append it to the list.\n\n", "list_1 = [['good', 2, 2], ['bad', 2, 2], ['be', 1, 1], ['brown', 1, 3]]\nprint(list_1)\nfor i in range(len(list_1)):\n ...
[ 4, 3, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007622754_list_python.txt
Q: Get function given a list of values Is there a way that I can give python a list of values like [ 1, 3, 4.5, 1] and obtain a function that relates to those values? like y = 3x+4 or something like that? I don't want to plot it or anything, I just want to substitute values in that function and see what the result wo...
Get function given a list of values
Is there a way that I can give python a list of values like [ 1, 3, 4.5, 1] and obtain a function that relates to those values? like y = 3x+4 or something like that? I don't want to plot it or anything, I just want to substitute values in that function and see what the result would be. edit: is there a way that python ...
[ "Based on your comments to David Heffernan's answer,\n\nI want is to know what the relation between the values is, I have thousands of values stored in a list and I want to know if python can tell me how they are related..\n\nit seems like you are trying do a regression analysis (probably a linear regression) and f...
[ 3, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007622477_python.txt
Q: Fastest method to filter and get a chunk of a list of strings I have a huge list of tag strings that should be filtered by a given tag_filter. The returned joined string should contain 20 max tags \n separated. The code, right now, looks like this: tags = Tag.get_tags() #This returns the list of tags strings retur...
Fastest method to filter and get a chunk of a list of strings
I have a huge list of tag strings that should be filtered by a given tag_filter. The returned joined string should contain 20 max tags \n separated. The code, right now, looks like this: tags = Tag.get_tags() #This returns the list of tags strings return '\n'.join([tag for tag in tags if tag.startswith(tag_filter)][:20...
[ "Use a genex and itertools.islice().\n'\\n'.join(itertools.islice((tag for tag in tags if tag.startswith(tag_filter)), 20))\n\n", "See the itertools recipies:\ndef take(n, iterable):\n \"Return first n items of the iterable as a list\"\n return list(islice(iterable, n))\n\nso in your case\nreturn '\\n'.join...
[ 3, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007622910_list_python.txt
Q: Using SSH in python I need to connect with other server via SSH using Python, execute few comands and assign result of each command to differrent variables. What is the simplest way to do it? I've tried SSHController, but I think, I've screwed up something with prompt, and the script is waiting for it endlessly. I...
Using SSH in python
I need to connect with other server via SSH using Python, execute few comands and assign result of each command to differrent variables. What is the simplest way to do it? I've tried SSHController, but I think, I've screwed up something with prompt, and the script is waiting for it endlessly. I'll be so grateful for an...
[ "There are a number of ways to use SSH from within Python. The general approaches are:\n\nCall the local ssh binary using subprocess.Popen() or similar (suitable only for gathering the results in batch)\nCall and control the local ssh binary using pexpect or a similar pty (psuedo-TTY) process control mechanism (fo...
[ 13 ]
[]
[]
[ "python", "ssh" ]
stackoverflow_0007622739_python_ssh.txt
Q: Combining generators I have a function that returns a list via yield. I use this function as follows: myList = [] for i in range(10): myList = myList + list(myListGenerator(i)) pickleFile = open("mystuff.dat", "wb") pickle.dump(myList, pickleFile) pickleFile.close() I'm just wondering if this is the most ef...
Combining generators
I have a function that returns a list via yield. I use this function as follows: myList = [] for i in range(10): myList = myList + list(myListGenerator(i)) pickleFile = open("mystuff.dat", "wb") pickle.dump(myList, pickleFile) pickleFile.close() I'm just wondering if this is the most efficient way to pickle the ...
[ "You can combine the results of the generators (created using a generator expression) into a single list with itertools.chain.from_iterable:\npickle.dump(list(itertools.chain.from_iterable(\n myListGenerator(i) for i in range(10))), pickleFile)\n\nOr rewrite the generator to include the range call inte...
[ 7 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007623052_python_python_3.x.txt
Q: How can I improve my Trie implementation in terms of initialization? I'm trying to read in from a huge list of words and store them in a way that allows me to make quick retrievals later on. I first thought of using a trie and I'll admit my implementation is naive, it's basically nested hash tables with each key ...
How can I improve my Trie implementation in terms of initialization?
I'm trying to read in from a huge list of words and store them in a way that allows me to make quick retrievals later on. I first thought of using a trie and I'll admit my implementation is naive, it's basically nested hash tables with each key being a different letter. Right now it takes forever to insert a word into...
[ "It is utterly pointless working on speeding up your trie initialisation before you have considered whether your search facility is working or not.\nIn the code that @unutbu referred to, why do you imagine it is mucking about with {'end':False} and pt['end']=True ?\nHere is some test data for you:\nwords_to_insert ...
[ 0 ]
[ "There is an alternate implementation of Trie here.\nCompare Trie.insert_word to build:\ndef build(words,trie={'end':False}):\n '''\n build builds a trie in O(M*L) time, where\n M = len(words)\n L = max(map(len,words))\n '''\n for word in words:\n pt=trie\n for letter in word...
[ -1 ]
[ "data_structures", "optimization", "python", "trie" ]
stackoverflow_0007622843_data_structures_optimization_python_trie.txt
Q: Replacing the elements that meet special condition in List with Python in a functional way I have a list [1, 2, 3, -100, 2, -100]. I need to replace -100 with "ERROR", and others to their corresponding string. I could code like this. resList = [] for val in list: if val == -100: resList.append("ERROR"...
Replacing the elements that meet special condition in List with Python in a functional way
I have a list [1, 2, 3, -100, 2, -100]. I need to replace -100 with "ERROR", and others to their corresponding string. I could code like this. resList = [] for val in list: if val == -100: resList.append("ERROR") else: resList.append("%d" % val) How can I do the same thing in a functional way....
[ "This one doesn't work:\nresList = map(lambda w: if w == -100: \"ERROR\" else:(\"%d\" % val), list)\n\nIt fails because you can't have a block inside a lambda expression.\nI prefer the list comprehension approach:\nresList = ['ERROR' if item == -100 else item for item in yourlist]\n\nThis shouldn't generate any err...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "functional_programming", "list_comprehension", "python" ]
stackoverflow_0007623378_functional_programming_list_comprehension_python.txt
Q: Exception handling in Python Tornado I am trying to handle exception occurred in AsyncClient.fetch in this way: from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPRequest from tornado.stack_context import ExceptionStackContext from tornado import ioloop def handle_exc(*args): p...
Exception handling in Python Tornado
I am trying to handle exception occurred in AsyncClient.fetch in this way: from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPRequest from tornado.stack_context import ExceptionStackContext from tornado import ioloop def handle_exc(*args): print('Exception occured') return True ...
[ "According to the Tornado documentation:\nIf an error occurs during the fetch, the HTTPResponse given to the callback has a non-None error attribute that contains the exception encountered during the request.\nYou can call response.rethrow() to throw the exception (if any) in the callback.\nfrom tornado.httpclient ...
[ 9, 3 ]
[]
[]
[ "exception_handling", "python", "tornado" ]
stackoverflow_0007549120_exception_handling_python_tornado.txt
Q: Where is sublime.py? Sublime Text2 text editor is extended via python scripts, using these modules: import sublime, sublime_plugin I've searched my computer and found sublime_plugin.py file. But where is sublime.py? A: I believe that Sublime is provided dynamically when you call the plugin via the console. Reme...
Where is sublime.py?
Sublime Text2 text editor is extended via python scripts, using these modules: import sublime, sublime_plugin I've searched my computer and found sublime_plugin.py file. But where is sublime.py?
[ "I believe that Sublime is provided dynamically when you call the plugin via the console.\nRemember that an import doesn't have to be a physical .py file, it can be a library or an in-memory representation.\nI found a decent reference to the confusions often related to Import, it's a little old now but I believe it...
[ 5 ]
[]
[]
[ "plugins", "python", "sublimetext", "text_editor" ]
stackoverflow_0007623547_plugins_python_sublimetext_text_editor.txt
Q: Antialiasing PNG resize in Qt? In a PyQt based GUI program, I'm drawing a few PNG file as QPixmap after resize. So here is basically what happens: bitmap = QPixmap( "foo.png" ) bitmap.scaleToHeight(38) # original is larger than this scene.addItem(QGraphicsPixmapItem(bitmap)) # Add to graphics scene The problem is...
Antialiasing PNG resize in Qt?
In a PyQt based GUI program, I'm drawing a few PNG file as QPixmap after resize. So here is basically what happens: bitmap = QPixmap( "foo.png" ) bitmap.scaleToHeight(38) # original is larger than this scene.addItem(QGraphicsPixmapItem(bitmap)) # Add to graphics scene The problem is: afterwards, the bitmap is rather u...
[ "See the documentation.\nbitmap = bitmap.scaledToHeight(38, Qt.SmoothTransformation)\n\n" ]
[ 11 ]
[]
[]
[ "python", "qt", "user_interface" ]
stackoverflow_0007623631_python_qt_user_interface.txt
Q: Deleting list elements based on condition I have a list of lists: [word, good freq, bad freq, change_status] list_1 = [['good',100, 20, 0.2],['bad', 10, 0, 0.0],['change', 1, 2, 2]] I would like to delete from the list all elements which don't satisfy a condition. So if change_status > 0.3 and bad_freq < 5 then I...
Deleting list elements based on condition
I have a list of lists: [word, good freq, bad freq, change_status] list_1 = [['good',100, 20, 0.2],['bad', 10, 0, 0.0],['change', 1, 2, 2]] I would like to delete from the list all elements which don't satisfy a condition. So if change_status > 0.3 and bad_freq < 5 then I would like to delete that the elements corresp...
[ "list_1 = [['good',100, 20, 0.2],['bad', 10, 0, 0.0],['change', 1, 2, 2]]\nlist_1 = [item for item in list_1 if item[2] >= 5 or item[3] >= 0.3]\n\nYou can also use if not (item[2] < 5 and item[3] < 0.3) for the condition if you want.\n", "Use the filter function with an appropriate function.\nlist_1 = filter(lamb...
[ 76, 19 ]
[]
[]
[ "python" ]
stackoverflow_0007623715_python.txt
Q: Python - Interactive mode vs. normal invocation of the interpreter Is there a difference between the two modes in terms of resources, especially memory? I'm referring to Python in the title but if there is a common explanation to many interpreted languages (Octave, etc...) that would be very helpful. Thanks A: I...
Python - Interactive mode vs. normal invocation of the interpreter
Is there a difference between the two modes in terms of resources, especially memory? I'm referring to Python in the title but if there is a common explanation to many interpreted languages (Octave, etc...) that would be very helpful. Thanks
[ "It looks like an interactive process does use somewhat more memory: compare\nmalkovich@malkovich:/etc$\nmalkovich@malkovich:/etc$ python -c 'import time; time.sleep(20000)' &\n[1] 3559\nmalkovich@malkovich:/etc$ pidstat -r -p $!\nLinux 2.6... (malkovich) 11-10-01 _x86_64_ (4 CPU)\n\n08:11:41 P...
[ 1 ]
[]
[]
[ "interactive_mode", "interpreted_language", "python" ]
stackoverflow_0007622462_interactive_mode_interpreted_language_python.txt
Q: Python if statement doesn't work as expected I currently have the code: fleechance = random.randrange(1,5) print fleechance if fleechance == 1 or 2: print "You failed to run away!" elif fleechance == 4 or 3: print "You got away safely!" fleechance is constantly printing as 3 or 4, but I continue to get th...
Python if statement doesn't work as expected
I currently have the code: fleechance = random.randrange(1,5) print fleechance if fleechance == 1 or 2: print "You failed to run away!" elif fleechance == 4 or 3: print "You got away safely!" fleechance is constantly printing as 3 or 4, but I continue to get the result "You failed to run away!" ,can anyone tel...
[ "The expression fleechance == 1 or 2 is equivalent to (fleechance == 1) or (2). The number 2 is always considered “true”.\nTry this:\nif fleechance in (1, 2):\n\nEDIT: In your situation (only 2 possibilities), the following will be even better:\nif fleechance <= 2:\n print \"You failed to run away!\"\nelse:\n ...
[ 9, 3, 1, 1, 1 ]
[]
[]
[ "if_statement", "printing", "python", "random" ]
stackoverflow_0007623818_if_statement_printing_python_random.txt
Q: How can encode('ascii', 'ignore') throw a UnicodeDecodeError? This line data = get_url_contents(r[0]).encode('ascii', 'ignore') produces this error UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 11450: ordinal not in range(128) Why? I assumed that because I'm using 'ignore' that it should b...
How can encode('ascii', 'ignore') throw a UnicodeDecodeError?
This line data = get_url_contents(r[0]).encode('ascii', 'ignore') produces this error UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 11450: ordinal not in range(128) Why? I assumed that because I'm using 'ignore' that it should be impossible to have decode errors when saving the output to a valu...
[ "Due to a quirk of Python 2, you can call encode on a byte string (i.e. text that's already encoded). In this case, it first tries to convert it to a unicode object by decoding with ascii. So, if get_url_contents is returning a byte string, your line effectively does this:\nget_url_contents(r[0]).decode('ascii').en...
[ 3 ]
[]
[]
[ "python", "unicode_string" ]
stackoverflow_0007623476_python_unicode_string.txt
Q: Printing numbered nested lists on separate lines using enumerate in python I've come to some grief in trying to achieve the following though I suspect it has a simple fix that has temporarily leaked from my brain. I need to be able to to print a grid of variable dimensions that has numbers down the left-hand side ...
Printing numbered nested lists on separate lines using enumerate in python
I've come to some grief in trying to achieve the following though I suspect it has a simple fix that has temporarily leaked from my brain. I need to be able to to print a grid of variable dimensions that has numbers down the left-hand side like below 1 - + - 2 + - + 3 - + - the grid is composed in nested lists, usin...
[ "You can join each list into a single string:\nfor i, line in enumerate(grid, 1):\n print i, ' '.join(line)\n\n", "Are you looking for this?\nfor i, line in enumerate(grid):\n print i,\n for char in line:\n print char,\n print\n\n" ]
[ 3, 1 ]
[]
[]
[ "enumerate", "python" ]
stackoverflow_0007623867_enumerate_python.txt
Q: How to make my home page very fast? It works and I want to make it super fast. The index page is very static, doesn't really change for days unless date updates or a map updates. So it should be possible to optimize to very fast since it doesn't change much. I recently migrated to HRD and my URI is montaoproject.a...
How to make my home page very fast?
It works and I want to make it super fast. The index page is very static, doesn't really change for days unless date updates or a map updates. So it should be possible to optimize to very fast since it doesn't change much. I recently migrated to HRD and my URI is montaoproject.appspot.com I rewrote this so that it is o...
[ "I don't know python, but if it doesn't change for days I am sure you could write something to convert the above into HTML (say every hour), and then just serve the HTML version. That will give you one of the largest optimisations possible, since your home page then doesn't have to be processed by a script engine a...
[ 2, 1 ]
[]
[]
[ "caching", "google_app_engine", "gzip", "memcached", "python" ]
stackoverflow_0007619695_caching_google_app_engine_gzip_memcached_python.txt
Q: Working with a remainder of Zero with modulo operation? I'm having some difficulty working with a remainder of zero with the modulo operator. Basically this is a line of my code fday= (day+24) % 30 I'm trying to just add 24 to any day and take the remainder of it. However, if a user enters 6 for the day, the r...
Working with a remainder of Zero with modulo operation?
I'm having some difficulty working with a remainder of zero with the modulo operator. Basically this is a line of my code fday= (day+24) % 30 I'm trying to just add 24 to any day and take the remainder of it. However, if a user enters 6 for the day, the result is zero which I don't want. How can I make the operati...
[ "You say in the comments that for 5 you want 29, for 6 you want 6, and for 7 you want 1. That doesn't make sense. The correct value for 6 is 30 not 6 or 0 when you're calculating a day modulo 30.\nIn math, division by 30 gives a remainder between 0 and 29 -- that's what modulo 30 is. What you want is a number betwe...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007623373_python.txt
Q: Pygame not working with sockets I created one program with pygame, imageGrab and sockets but it doesn't work. It should take a printscreen of the server with ImageGrab, convert it to a string, and send it to the client. However, the client upon receiving the information and converting it to an image raises an err...
Pygame not working with sockets
I created one program with pygame, imageGrab and sockets but it doesn't work. It should take a printscreen of the server with ImageGrab, convert it to a string, and send it to the client. However, the client upon receiving the information and converting it to an image raises an error: image = pygame.image.frombuffer(...
[ "The deal with sockets is you have to know exactly how long the message you're receiving is if you plan keep using the same socket connection. You seem to have some idea of this with your q_bytes = raw_input(\"Enter the number of MBs to transfer: \"), but we need to know exactly, not to the nearest MB. Sometimes ...
[ 2 ]
[]
[]
[ "pygame", "python", "sockets" ]
stackoverflow_0007622019_pygame_python_sockets.txt
Q: Django CheckboxSelectMultiple with django uni-form I have a form in my django project with a ModelMultipleChoiceField rendered as a CheckboxSelectMultiple widget: class EventCreateForm(forms.Form): ... event_types = forms.ModelMultipleChoiceField(EventType.objects.all(), widget=forms.CheckboxSelectMultiple...
Django CheckboxSelectMultiple with django uni-form
I have a form in my django project with a ModelMultipleChoiceField rendered as a CheckboxSelectMultiple widget: class EventCreateForm(forms.Form): ... event_types = forms.ModelMultipleChoiceField(EventType.objects.all(), widget=forms.CheckboxSelectMultiple()) ... I'm using django uni-form to render this fo...
[ "I solved my issue. The problem was when I was prepopulating the data, I was passing event.event_types (a manager instance) rather than event.event_types.all().\n" ]
[ 0 ]
[]
[]
[ "django", "python", "uniform" ]
stackoverflow_0007539662_django_python_uniform.txt
Q: Python 'in' Operator Inexplicably Failing My simple script to check for a certain word in files seems to be failing, and I cannot seem to explain it through documentation or searching. The code is below. I believe I have narrowed it down to the 'in' operator failing by printing the code itself and finding the word...
Python 'in' Operator Inexplicably Failing
My simple script to check for a certain word in files seems to be failing, and I cannot seem to explain it through documentation or searching. The code is below. I believe I have narrowed it down to the 'in' operator failing by printing the code itself and finding the word that I am looking for. If curious, this script...
[ "The reason it is failing is because you are checking if the word is within the text's lines. Just use the read() method and check in there or iterate through all the lines and each each individually. \n# first method\ntext = file.read()\n\nif word in text:\n print \"Yep!\"\n\n# second method\n# goes through eac...
[ 7, 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007624227_python.txt
Q: Python: Novice Class object prac and __main__ I've been trying to practice testing my modules by adding if __name__ == '__main__': to the end of the module. The idea is to run the module as a script, and get an output and able to import it from another script or an interactive python session. I'm using Python 2....
Python: Novice Class object prac and __main__
I've been trying to practice testing my modules by adding if __name__ == '__main__': to the end of the module. The idea is to run the module as a script, and get an output and able to import it from another script or an interactive python session. I'm using Python 2.6.6 here's the whole code class Prac: ''' T...
[ "That isn't a function, it's a method. You need to call the method off an object.\np = Prac()\np.Fun()\n\nRead this.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007624372_python.txt
Q: How to return a website and automatically redirect to another side which takes long to load I ask the user to input some data, after that I redirect him to a 'result' website which takes several seconds to load. I don't like this, because there is no user feedback telling him, that the server has not crashed and ...
How to return a website and automatically redirect to another side which takes long to load
I ask the user to input some data, after that I redirect him to a 'result' website which takes several seconds to load. I don't like this, because there is no user feedback telling him, that the server has not crashed and that his result is coming. So I was thinking about showing the user a 'loading' website stating '...
[ "I was going to suggest Celery for this, but someone just posted this on the Flask mailing list, and this might be a more simpler solution: Hello-Redis-Tasks. If you still want to use Celery though, this is what you should check out: Custom states in celery\n", "Flask's documentation for file uploads includes a s...
[ 2, 1 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0007589427_flask_python.txt
Q: Changing values in nested lists with python Ok, with the same program previously I've now hit a problem I should have anticipated; the grid (of variable width and height) is constructed based on a code to alternate the symbols which creates a list, those lists are then stored in the grid as nested lists. below is ...
Changing values in nested lists with python
Ok, with the same program previously I've now hit a problem I should have anticipated; the grid (of variable width and height) is constructed based on a code to alternate the symbols which creates a list, those lists are then stored in the grid as nested lists. below is a section of code for making the list (called lin...
[ "The easiest way is to make copies of the lists when you add them:\ngrid = []\nfor i in range(height):\n if i % 2 == 0:\n grid.append(line[:])\n else:\n board.append(linerev[:])\n\n" ]
[ 3 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007624468_list_python.txt
Q: how to run .py file in browser using python webserver i have running a python webserver by using this simple script - from http.server import SimpleHTTPRequestHandler as RH from socketserver import TCPServer ServerName='localhost' OnPort=8000 print ("Server is running at Port 8000") TCPSer...
how to run .py file in browser using python webserver
i have running a python webserver by using this simple script - from http.server import SimpleHTTPRequestHandler as RH from socketserver import TCPServer ServerName='localhost' OnPort=8000 print ("Server is running at Port 8000") TCPServer((ServerName, OnPort), RH).serve_forever() it is runnin...
[ "The problem is that SimpleHTTPRequestHandler only serves files out of a directory, it does not execute them. You must override the do_GET method if you want it to execute code.\n", "You might want to check out CGIHTTPRequestHandler instead. I very briefly played with it on a linux based system and the CGI crit...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007624435_python.txt
Q: Python: Is there a python module for ssh that supports lots of tunnels? I am writing a program that creates reverse tunnels with ssh. I am using Popen currently, but I am receiving an error because I have too many arguments. So my question is: Is there any python module that supports a lot of tunnels? (Preferably ...
Python: Is there a python module for ssh that supports lots of tunnels?
I am writing a program that creates reverse tunnels with ssh. I am using Popen currently, but I am receiving an error because I have too many arguments. So my question is: Is there any python module that supports a lot of tunnels? (Preferably 1000+)
[ "Not so much a module as a library, Twisted.Conch might be a better approach... but be warned that of all the modules in Twisted, conch can be one of the most intimidating ( atleast IMHO ).\n" ]
[ 1 ]
[]
[]
[ "module", "popen", "python", "ssh", "tunnel" ]
stackoverflow_0007624551_module_popen_python_ssh_tunnel.txt
Q: How do I stub a class in a module in Python for testing? I have a module I am using which uses RealClass, so it is an internal dependency I don't have access to. I want to be able to create a FakeClass which replaces the functionality of the RealClass for testing. I don't want to replace individual methods but th...
How do I stub a class in a module in Python for testing?
I have a module I am using which uses RealClass, so it is an internal dependency I don't have access to. I want to be able to create a FakeClass which replaces the functionality of the RealClass for testing. I don't want to replace individual methods but the entire class. I looked at stubble which seems to be what I w...
[ "I think you want opinions/experiences so I'm just giving my 2 cents.\nAs you noticed there are a few Python testing tools/classes/frameworks, but most of the time given the simplicity/dynamism/openness of Python you will limit yourself to using ad-hoc relevant test cases which involve stubbing at the interface lev...
[ 8 ]
[]
[]
[ "python", "stub" ]
stackoverflow_0007601228_python_stub.txt
Q: port only a single method of class to C? I have a class with few methods and I'm happy with the performance of all of them except one method. We want to port that to C++. However we don't want to spend too much time porting the whole class to C++, just that single method. Is this possible? How should I do it? Shou...
port only a single method of class to C?
I have a class with few methods and I'm happy with the performance of all of them except one method. We want to port that to C++. However we don't want to spend too much time porting the whole class to C++, just that single method. Is this possible? How should I do it? Should it be in a blank class? Not in a class? Wha...
[ "Depending on the complexity of your code, you could look into using Weave, which is part of SciPy. It allows you to embed C/C++ code in your python module. There's a tutorial here. \nAnother option you could look at is Boost::Python, which may be a bit more complex to use.\n" ]
[ 1 ]
[]
[]
[ "c++", "methods", "pyd", "python", "wrapper" ]
stackoverflow_0007624740_c++_methods_pyd_python_wrapper.txt
Q: How to decorate an object method? I need to decorate a object's method. It needs to be at runtime because the decorators applied on the object depends on the arguments that the user gave when calling the program (arguments supplied with argv), so a same object could be decorated 3 times, 2 times, or not be decorat...
How to decorate an object method?
I need to decorate a object's method. It needs to be at runtime because the decorators applied on the object depends on the arguments that the user gave when calling the program (arguments supplied with argv), so a same object could be decorated 3 times, 2 times, or not be decorated at all. Here is some context, the pr...
[ "The problem was that I couldn't use func(self) as a method. The reason is that setattr() method does not bound the function, and the function acts like it a static method - not a class method -, thanks to the introspective nature of python I've able to come up with this solution:\ndef decorator(obj):\n old_func...
[ 1, 0, 0, 0 ]
[]
[]
[ "decorator", "python", "python_3.x", "runtime" ]
stackoverflow_0005950652_decorator_python_python_3.x_runtime.txt
Q: python: is it possible to require that arguments to the functions are all keyword? To avoid the obvious bugs, I'd like to prevent the use of positional arguments with some functions. Is there any way to achieve that? A: Only Python 3 can do it properly (and you used the python3 tag, so it's fine): def function(*...
python: is it possible to require that arguments to the functions are all keyword?
To avoid the obvious bugs, I'd like to prevent the use of positional arguments with some functions. Is there any way to achieve that?
[ "Only Python 3 can do it properly (and you used the python3 tag, so it's fine):\ndef function(*, x, y, z):\n print(x,y,z)\n\nusing **kwargs will let the user input any argument unless you check later. Also, it will hide the real arguments names from introspection.\n**kwargs is not the answer for this problem.\nT...
[ 40, 8, 1 ]
[]
[]
[ "coding_style", "function", "python", "python_3.x" ]
stackoverflow_0007624840_coding_style_function_python_python_3.x.txt
Q: python -- trying to change the contents of a file i have a file named "hello.txt" which has the content "Hello,there!". I want to remove the "," and "!" and then print the new content. With the code i made ,the program runs without errors but ,it erases all the contents and leaves an empty file. def myfunc(filenam...
python -- trying to change the contents of a file
i have a file named "hello.txt" which has the content "Hello,there!". I want to remove the "," and "!" and then print the new content. With the code i made ,the program runs without errors but ,it erases all the contents and leaves an empty file. def myfunc(filename): filename=open('hello.txt','r') lines=filename.rea...
[ "you should print the modified content line by line, not only at the end.\nfor line in lines:\n for punc in \",!\":\n\n # note that we're assigning to line again\n # because we're executing this once for\n # each character\n line=line.replace(punc,\"\")\n\n # write the transformed ...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007516580_python.txt
Q: Django custom order_by I've got a model eg. Car with a foreign key eg. Owner, which may or may not be blank. The Car has a creation_date. I would like to order these cars by date, but if the car has an owner, the date of birth of the owner must be taken instead of the creation_date of the car. Is this possible? A...
Django custom order_by
I've got a model eg. Car with a foreign key eg. Owner, which may or may not be blank. The Car has a creation_date. I would like to order these cars by date, but if the car has an owner, the date of birth of the owner must be taken instead of the creation_date of the car. Is this possible?
[ "This is possible by falling back to SQL:\nCar.objects.filter(...).extra(select={'odate': '''\n if(owner_id,\n (select date_of_birth from owner_table where id=owner_id),\n creation_date\n )\n'''}).order_by('odate')\n\nif function is MySQL-specific. In case of SQLite or Postgres you should use case statem...
[ 6, 5, 1 ]
[]
[]
[ "django", "python", "sql_order_by" ]
stackoverflow_0007619554_django_python_sql_order_by.txt
Q: Download CSV directly into Python CSV parser I'm trying to download CSV content from morningstar and then parse its contents. If I inject the HTTP content directly into Python's CSV parser, the result is not formatted correctly. Yet, if I save the HTTP content to a file (/tmp/tmp.csv), and then import the file in ...
Download CSV directly into Python CSV parser
I'm trying to download CSV content from morningstar and then parse its contents. If I inject the HTTP content directly into Python's CSV parser, the result is not formatted correctly. Yet, if I save the HTTP content to a file (/tmp/tmp.csv), and then import the file in the python's csv parser the result is correct. In ...
[ "The problem results from the fact that iteration over a file is done line-by-line whereas iteration over a string is done character-by-character.\nYou want StringIO/cStringIO (Python 2) or io.StringIO (Python 3, thanks to John Machin for pointing me to it) so a string can be treated as a file-like object:\nPython ...
[ 9 ]
[]
[]
[ "csv", "parsing", "python" ]
stackoverflow_0007625079_csv_parsing_python.txt
Q: unsupported operand type(s) for /: 'str' and 'int' I am new to Python and am learning some basics. I would like to know why I am getting this error. The code is: Hours = raw_input ("How many Hours you worked for today : ") minutes = (Hours * 60) Percentage = (minutes * 100) / 60 print "Today you worked : ", "perce...
unsupported operand type(s) for /: 'str' and 'int'
I am new to Python and am learning some basics. I would like to know why I am getting this error. The code is: Hours = raw_input ("How many Hours you worked for today : ") minutes = (Hours * 60) Percentage = (minutes * 100) / 60 print "Today you worked : ", "percentage"
[ "You have to convert your Hours variable to a number, since raw_input() gives you a string:\nHours = int(raw_input(\"How many hours you worked for today: \"))\n\nThe reason why this is failing so late is because * is defined for string and int: it \"multiplies\" the string by the int argument. So if you type 7 at t...
[ 7, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007625132_python.txt
Q: python - single item tuple throws exception in for statement Im curious as to why this happens. Im using Mako templates to iterate over a tuple, that contains a number of number of dictionaries, that in turn contain link information: links = ( { 'path' : request.route_url('home'), '...
python - single item tuple throws exception in for statement
Im curious as to why this happens. Im using Mako templates to iterate over a tuple, that contains a number of number of dictionaries, that in turn contain link information: links = ( { 'path' : request.route_url('home'), 'text' : 'Home' }, { 'path' : "http://w...
[ "\nif i put a comma after the end of the dictionary, things start working\n again. Can anyone explain what is going on?\n\nThe comma makes the tuple. Without it you just have a single value in brackets.\nx = ({}) # brackets around a dict\nx = {}, # a 1-tuple\nx = ({},) # a 1-tuple in brackets\n\nOften it appears t...
[ 5 ]
[]
[]
[ "dictionary", "exception", "python" ]
stackoverflow_0007625734_dictionary_exception_python.txt
Q: How do I configure the behavior of the Qt4Agg backend? In an earlier question I learned that the behavior on show() was dependent on the backend in use by matplotlib. At that time I was looking for a way to keep show() from deleting the drawing elements of a figure, concluding that by switching from Qt4Agg to TkA...
How do I configure the behavior of the Qt4Agg backend?
In an earlier question I learned that the behavior on show() was dependent on the backend in use by matplotlib. At that time I was looking for a way to keep show() from deleting the drawing elements of a figure, concluding that by switching from Qt4Agg to TkAgg, the drawing elements would be preserved even if the figu...
[ "Instead of trying to exercise extra control over the backend, just create the figures and keep references to them yourself, as shown in the highest-rated answer to your first question. The problem with trying to manipulate the backend, as you are asking to do here, is that the backend is not intended to hand your ...
[ 2 ]
[]
[]
[ "matplotlib", "pyqt", "python" ]
stackoverflow_0006050315_matplotlib_pyqt_python.txt
Q: How to access a password protected site using python? I was thinking that, if I access a password protected site using python's mechanism, I would get a 401 Unauthorized error which needs authentication data. So inside my script, I tried to access my yahoo mail box which apparently needs username and password, I t...
How to access a password protected site using python?
I was thinking that, if I access a password protected site using python's mechanism, I would get a 401 Unauthorized error which needs authentication data. So inside my script, I tried to access my yahoo mail box which apparently needs username and password, I thought I would get 401, but I didn't. Code: yahoo_mail = 'h...
[ "Most web sites these days do not use HTTP Authentication. So 401 is not returned if you fail to log in; instead, a normal 200 successful response is returned, and the text inside the web page says you did not log in.\nInstead, sites use cookies. This means that your browser does not actually know what sites it is ...
[ 5, 0, 0 ]
[]
[]
[ "authentication", "mechanize", "python" ]
stackoverflow_0007625865_authentication_mechanize_python.txt
Q: Comparing Strings in IronPython I am trying to compare two strings while searching for WSUS groups to update. However, my comparison is failing even though they appear to be the same visually, and are of the same type. Since this is IronPython, I don't have a debugger available in Komodo (anyone know of one for ...
Comparing Strings in IronPython
I am trying to compare two strings while searching for WSUS groups to update. However, my comparison is failing even though they appear to be the same visually, and are of the same type. Since this is IronPython, I don't have a debugger available in Komodo (anyone know of one for IP?) Anyway, can someone spot what I ...
[ "On Python 2.x, Use repr() to see visually if two strings are the same. print basically calls str, so you can't see unprintable characters and it's hard to see differences in whitespace.\nSo, do:\nprint repr(computerTarget.Name.ToString())\nprint repr(apprvGrpName)\n\nto find out why they aren't equivalent.\nSee Jo...
[ 1, 0 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0007626184_ironpython_python.txt
Q: Python web.py template, how to escape (.) dot In web.py template: index.html I wrote: $def with(s) <img src="$s.filename.png" /> s.filename's value is "picuture" so I want to print <img src="picture.png" /> but how can I tell web.py templating system do not to use $s.filename.png just use $s.filename and add "...
Python web.py template, how to escape (.) dot
In web.py template: index.html I wrote: $def with(s) <img src="$s.filename.png" /> s.filename's value is "picuture" so I want to print <img src="picture.png" /> but how can I tell web.py templating system do not to use $s.filename.png just use $s.filename and add ".png" to it?
[ "See the Templetor docs:\n\nExpression can be enclosed in () or {} for explicit grouping.\n\nSo, in your case,\n<img src=\"${s.filename}.png\" />\n\n" ]
[ 5 ]
[]
[]
[ "escaping", "python", "templates", "web.py" ]
stackoverflow_0007626394_escaping_python_templates_web.py.txt
Q: Removing indent in PYDEV I am using pydev for python development. I am facing issue while removing indentation for a block of statement. If I have to add indentation I used to press SHIFT + down arrow key until I reach the end of block of statements which I want to indent and then press the TAB key.This is how i ...
Removing indent in PYDEV
I am using pydev for python development. I am facing issue while removing indentation for a block of statement. If I have to add indentation I used to press SHIFT + down arrow key until I reach the end of block of statements which I want to indent and then press the TAB key.This is how i used to add indent for a block...
[ "I don't know Pydev, but in most editors Shift+Tab will do the trick.\n", "From pydev.org, their page:\nBlock indent (and dedent) Tab / Shift-Tab\nSmart indent (and dedent) Enter / Backspace\n" ]
[ 7, 2 ]
[]
[]
[ "pydev", "python" ]
stackoverflow_0007623795_pydev_python.txt
Q: Why my python mechanize script cannot work for this specific site I need to simulate the process of inputting an item name and clicking the search button on http://ccclub.cmbchina.com/ccclubnew/. if I inspect directly in HTML, the search form is described with name "searchKey" <span class="searchinput"> <inpu...
Why my python mechanize script cannot work for this specific site
I need to simulate the process of inputting an item name and clicking the search button on http://ccclub.cmbchina.com/ccclubnew/. if I inspect directly in HTML, the search form is described with name "searchKey" <span class="searchinput"> <input type="text" name="searchKey" id="searchKey" maxlength="25"> </span> ...
[ "The input with name searchKey itself is no form. A form comes with the <form> tag, but honestly, this searchbox appears not to be part of a form; you'll have to simulate setting the text of the input and pressing it.\n\n", "How about using lxml or BeatifulSoup?\n" ]
[ 2, 1 ]
[]
[]
[ "forms", "mechanize", "python", "search" ]
stackoverflow_0007626381_forms_mechanize_python_search.txt
Q: Massage model data before save in Django I'm not sure if this is the best way to do this, but I have some data that is being sent by a form. I have a ModelForm that takes the the request.POST of that form data. All the data that is being sent is a description, amount and deposit (boolean). When the person submit...
Massage model data before save in Django
I'm not sure if this is the best way to do this, but I have some data that is being sent by a form. I have a ModelForm that takes the the request.POST of that form data. All the data that is being sent is a description, amount and deposit (boolean). When the person submits the data, the amount will be a positive numb...
[ "ModelForm's save() method is a good place for this:\nclass MyForm(models.ModelForm):\n ...\n def save(self):\n instance = super(MyForm, self).save(commit=False)\n if not self.deposit:\n self.amount = -self.amount\n instance.save()\n return instance\n\n", "Overwrite mo...
[ 4, 2 ]
[]
[]
[ "django", "forms", "model", "python" ]
stackoverflow_0007623841_django_forms_model_python.txt
Q: Unidentified Errors.Please notify... error instead of my simple forms.ValidationError OK, trying to add a clean method to a ModelForm in Django. I'm adding a simple raise statement just to see if it works, and instead of my message, I get "Unidentified Errors. Please notify..." Here's my (simple) test: class Con...
Unidentified Errors.Please notify... error instead of my simple forms.ValidationError
OK, trying to add a clean method to a ModelForm in Django. I'm adding a simple raise statement just to see if it works, and instead of my message, I get "Unidentified Errors. Please notify..." Here's my (simple) test: class ConfigurationForm(forms.ModelForm): ... def clean(self): cleaned_data = self....
[ "Is your clean method returning the cleaned_data? If you look at the docs here:\nhttps://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other\nyou'll notice you have to make sure to return self.cleaned_data. Furthermore, don't raise validation errors; instead ...
[ 0, 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0007613306_django_django_forms_python.txt
Q: Maximum Python object which can be passed to write() I am looking around the net (so far I have found pickle ) for an explanation for what I am doing wrong I am trying to write a very large data structure (nested dictionary/list) to file. Using the below code I discovered that the problem might be because the pass...
Maximum Python object which can be passed to write()
I am looking around the net (so far I have found pickle ) for an explanation for what I am doing wrong I am trying to write a very large data structure (nested dictionary/list) to file. Using the below code I discovered that the problem might be because the passed string is too large: f = open('/path/to/file' , 'w') t...
[ "I'm gonna guess that your problem is that the string you create is too large to exist in memory. For something that big you should write it out piece by piece to the disk. \nYou could use pickle, json, xml or something which should handle this correctly.\n" ]
[ 4 ]
[]
[]
[ "file", "python", "size" ]
stackoverflow_0007626848_file_python_size.txt
Q: How do you use a variable as an index when slicing strings in Python? I've been trying to slice two characters out of a string using a loop, but instead of grabbing two characters, it only grabs one. I've tried: input[i:i+1] and input[i:(i+1)] but neither seems to work. How do I use a variable for slicing? The f...
How do you use a variable as an index when slicing strings in Python?
I've been trying to slice two characters out of a string using a loop, but instead of grabbing two characters, it only grabs one. I've tried: input[i:i+1] and input[i:(i+1)] but neither seems to work. How do I use a variable for slicing? The full routine: def StringTo2ByteList(input): # converts data string to a ...
[ "The slice values aren't the start and end characters of the slice, they're the start and end points. If you want to slice two elements then your stop must be 2 greater than your start.\ninput[i:i+2]\n\n", "A nice way to remember slice indexing is to think of the numbers as labeling the positions between the elem...
[ 9, 6, 1 ]
[]
[]
[ "python", "slice", "string" ]
stackoverflow_0007625326_python_slice_string.txt
Q: python: get google adsense earnings report I need a python script that gets the google adsense earnings and I found adsense scraper: http://pypi.python.org/pypi/adsense_scraper/0.5 It uses Twill and html5lib to scrape google adsense earnings data. When I use it I get this error message: Traceback (most recent call...
python: get google adsense earnings report
I need a python script that gets the google adsense earnings and I found adsense scraper: http://pypi.python.org/pypi/adsense_scraper/0.5 It uses Twill and html5lib to scrape google adsense earnings data. When I use it I get this error message: Traceback (most recent call last): File "adsense_scraper.py", line 163, i...
[ "there are several errors with the package, you mentioned only the first one\n1) twill package does not handle google's redirects correctly, adding\n newurl = newurl.strip( \"'\" )\n\nto twill/other_packages/_mechanize_dist/_http.py:108 before \n newurl = _rfc3986.clean_url(newurl, \"latin-1\")\n\nfixes that\...
[ 1 ]
[]
[]
[ "html5lib", "python", "twill" ]
stackoverflow_0005441989_html5lib_python_twill.txt
Q: Python's logging module misses "captureWarnings" function Python's standard logging module is supposed to contain a useful captureWarnings function that allows integration between the logging and the warnings modules. However, it seems that my installation misses this function: Python 2.6.5 (r265:79096, Mar 19 201...
Python's logging module misses "captureWarnings" function
Python's standard logging module is supposed to contain a useful captureWarnings function that allows integration between the logging and the warnings modules. However, it seems that my installation misses this function: Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", ...
[ "Unfortunately, there is no such method in Python 2.6.5's logging module. You need Python 2.7.\n" ]
[ 8 ]
[]
[]
[ "logging", "python", "warnings" ]
stackoverflow_0007627075_logging_python_warnings.txt
Q: fetching data from celery's backend(redis) How do I get data(all I really need is the state of the task) from a Celery backend? I am using Redis. A: Assuming that you configured the CELERY_RESULT_BACKEND to use redis ( see here ), then you can monitor your application using a variety of methods. I believe that c...
fetching data from celery's backend(redis)
How do I get data(all I really need is the state of the task) from a Celery backend? I am using Redis.
[ "Assuming that you configured the CELERY_RESULT_BACKEND to use redis ( see here ), then you can monitor your application using a variety of methods.\nI believe that celeryctl should suffice..\n" ]
[ 3 ]
[]
[]
[ "celery", "python", "redis" ]
stackoverflow_0007626846_celery_python_redis.txt
Q: How do I limit the number of digits in a list? This is a small piece of code that I am writing for an chemistry ab initio program. I am having issues making the C1pos list a number with exactly 6 digits after the decimal place. I have tried several methods such as the decimal function, but so far I am having no lu...
How do I limit the number of digits in a list?
This is a small piece of code that I am writing for an chemistry ab initio program. I am having issues making the C1pos list a number with exactly 6 digits after the decimal place. I have tried several methods such as the decimal function, but so far I am having no luck. Position is a definition that will take a matrix...
[ "','.join(\"%.6f\" % f for f in C1pos)\n\nExample\nC1pos = [2.123, 300.123456, 4.123456789]\nprint ','.join(\"%.6f\" % f for f in C1pos)\n\nOutput\n2.123000,300.123456,4.123457\n\n", "you can use the decimal class to round all your numbers to 6 decimal places.\nfrom decimal import Decimal, ROUND_UP\n\nDecimal(n)....
[ 2, 0 ]
[]
[]
[ "formatting", "list", "python" ]
stackoverflow_0007627116_formatting_list_python.txt
Q: setup.py install location? I'm running Mac OS X Lion 10.7.1 that has both python 2.6 and 2.7 installed. I've made 2.6 my default version. I am trying to install a package and it installs to 2.7. My setup looks like this: ~:hi› which python /usr/bin/python ~:hi› python -V Python 2.6.6 ~:hi› python Python 2.6.6 (r...
setup.py install location?
I'm running Mac OS X Lion 10.7.1 that has both python 2.6 and 2.7 installed. I've made 2.6 my default version. I am trying to install a package and it installs to 2.7. My setup looks like this: ~:hi› which python /usr/bin/python ~:hi› python -V Python 2.6.6 ~:hi› python Python 2.6.6 (r266:84292, Jun 16 2011, 16:59:16...
[ "When setup.py installs a Python package, it pays no attention to the Apple system settings. The only thing it knows is what version of Python you use to invoke it. If you say:\npython2.6 setup.py …\n\nthen that version gets used, and the same with\npython2.7 setup.py …\n\nIf you use the first of these two commands...
[ 3 ]
[]
[]
[ "distutils", "macos", "python", "setuptools" ]
stackoverflow_0007626682_distutils_macos_python_setuptools.txt
Q: Google Analytics Data Feed API Error 414 URI Too Large When using the google analytics data API with the python gdata library, we are assembling a GET request per the instructions in the documentation here: http://code.google.com/apis/analytics/docs/gdata/gdataReferenceDataFeed.html We are running into problems ho...
Google Analytics Data Feed API Error 414 URI Too Large
When using the google analytics data API with the python gdata library, we are assembling a GET request per the instructions in the documentation here: http://code.google.com/apis/analytics/docs/gdata/gdataReferenceDataFeed.html We are running into problems however. As our requests get longer, we're occasionally gettin...
[ "There is a 128 character limit on filters regardless of whether you're using GET or POST. Anything longer than that will result in a 400 error. The only way around that length limit is to use AND/OR boolean logic.\nHere's the full explanation from Google:\nRules for Filter Expressions\n" ]
[ 1 ]
[]
[]
[ "gdata", "google_analytics_api", "http", "python" ]
stackoverflow_0007575263_gdata_google_analytics_api_http_python.txt
Q: Running Scilab from pexpect I am trying to run scilab using the pexpect module with the following code: import pexpect c=pexpect.spawn('scilab-adv-cli -nb') c.expect('-->') When I do c.sendline('plot[1,2]') the plot shows up. But when I do ...
Running Scilab from pexpect
I am trying to run scilab using the pexpect module with the following code: import pexpect c=pexpect.spawn('scilab-adv-cli -nb') c.expect('-->') When I do c.sendline('plot[1,2]') the plot shows up. But when I do c.sendline('[1 2]*[3]') ...
[ "If all the output you want to read is that simple, then you can do:\nlargenum = 1000\n# flush any remaining output\nc.read_nonblocking(largenum)\nc.sendline('[1 2]*[3]')\n# discard unwanted lines until relevant line\nfor i in range(3): next(c)\n# get answer (in this case, a single line)\nans = next(c).strip()\n# d...
[ 1, 1 ]
[]
[]
[ "pexpect", "python", "scilab" ]
stackoverflow_0007618601_pexpect_python_scilab.txt
Q: Use of java image in pythonic OpenCV I'm fetching some images via HTTP: val ostream = new ByteArrayOutputStream() ImageIO.write(imageurl, imageType, ostream) val istream = new ByteArrayInputStream(ostream.toByteArray) (it is actually scala, but this code itself using Java libs, so there is no scala specific magi...
Use of java image in pythonic OpenCV
I'm fetching some images via HTTP: val ostream = new ByteArrayOutputStream() ImageIO.write(imageurl, imageType, ostream) val istream = new ByteArrayInputStream(ostream.toByteArray) (it is actually scala, but this code itself using Java libs, so there is no scala specific magic). Then I'm pushing istream to database (...
[ "Probably you need imdecode function.\n" ]
[ 1 ]
[]
[]
[ "java", "opencv", "python", "scala" ]
stackoverflow_0007627460_java_opencv_python_scala.txt
Q: python tweet parsing I'm trying to parse tweets data. My data shape is as follows: 59593936 3061025991 null null <d>2009-08-01 00:00:37</d> <s>&lt;a href="http://help.twitter.com/index.php?pg=kb.page&amp;id=75" rel="nofollow"&gt;txt&lt;/a&gt;</s> <t>honda just recalled 440k accords...traffic around here is gonna b...
python tweet parsing
I'm trying to parse tweets data. My data shape is as follows: 59593936 3061025991 null null <d>2009-08-01 00:00:37</d> <s>&lt;a href="http://help.twitter.com/index.php?pg=kb.page&amp;id=75" rel="nofollow"&gt;txt&lt;/a&gt;</s> <t>honda just recalled 440k accords...traffic around here is gonna be light...win!!</t> ajc858...
[ "The issue is self explanatory in the error, you have specified two parameters in your call to get_keywords() but your implementation only has one parameter. You should change your get_keywords implementation to something like:\ndef get_keywords(filepath, mode):\n with open(filepath, mode) as f:\n for line ...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007626643_python.txt
Q: Products catalogue: filter by parameters I need to make the filter products by features. So, products model: <pre style='color:#000000;background:#ffffff;'><span style='color:#800000; font-weight:bold; '>class</span> Product<span style='color:#808030; '>(</span>models<span style='color:#808030; '>.</span>Model<spa...
Products catalogue: filter by parameters
I need to make the filter products by features. So, products model: <pre style='color:#000000;background:#ffffff;'><span style='color:#800000; font-weight:bold; '>class</span> Product<span style='color:#808030; '>(</span>models<span style='color:#808030; '>.</span>Model<span style='color:#808030; '>)</span><span style=...
[ "Start with listing all Features for given product:\nproduct = Product.objects.get(pk=given_pk)\nfeatures = product.feature_set.all().select_related()\n\nNow group your features directly in Python.\nfeatures_dict = {}\nfor feature in features:\n values = features_dict.get(feature.name.name, [])\n features_dic...
[ 2 ]
[]
[]
[ "catalog", "django", "filter", "python" ]
stackoverflow_0007627621_catalog_django_filter_python.txt
Q: TypeError: 'in ' requires string as left operand, not generator in Python I'm trying to parse tweets data. My data shape is as follows: 59593936 3061025991 null null <d>2009-08-01 00:00:37</d> <s>&lt;a href="http://help.twitter.com/index.php?pg=kb.page&amp;id=75" rel="nofollow"&gt;txt&lt;/a&gt;</s> <t>honda just r...
TypeError: 'in ' requires string as left operand, not generator in Python
I'm trying to parse tweets data. My data shape is as follows: 59593936 3061025991 null null <d>2009-08-01 00:00:37</d> <s>&lt;a href="http://help.twitter.com/index.php?pg=kb.page&amp;id=75" rel="nofollow"&gt;txt&lt;/a&gt;</s> <t>honda just recalled 440k accords...traffic around here is gonna be light...win!!</t> ajc858...
[ "The reason is that keywords = get_keywords(...) returns a generator. Logically thinking about it, keywords should be a list of all the keywords. And for each keyword in this list, you want to check if it's in the tweet/line or not.\nSample code:\nkeywords = get_keywords('./related_keywords.txt', 'r')\nhas_keyword ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007627803_python.txt
Q: How much days left from today to given date I have a date - 2015.05.20 What is the best way to calculate using python how much days left from today till this date? from datetime import * today = date.today() future = date(2015,05,20) ??? A: import datetime today = datetime.date.today() future = datetime.date(20...
How much days left from today to given date
I have a date - 2015.05.20 What is the best way to calculate using python how much days left from today till this date? from datetime import * today = date.today() future = date(2015,05,20) ???
[ "import datetime\n\ntoday = datetime.date.today()\nfuture = datetime.date(2019,9,20)\ndiff = future - today\nprint (diff.days)\n\ndiff is a timedelta object.\n", "subtract them.\n>>> from datetime import *\n>>> today = date.today()\n>>> future = date(2015,05,20)\n>>> str(future - today)\n'1326 days, 0:00:00'\n>>>...
[ 27, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007628036_python.txt
Q: Is Python ever supposed to crash? I am running a stand-alone Python v3.2.2/Tkinter program on Windows, not calling any external libraries. Idle has been very helpful in reporting exceptions, and the program has been debugged to the point where none are reported. However, the python interpreter does occasionally...
Is Python ever supposed to crash?
I am running a stand-alone Python v3.2.2/Tkinter program on Windows, not calling any external libraries. Idle has been very helpful in reporting exceptions, and the program has been debugged to the point where none are reported. However, the python interpreter does occasionally crash at non-deterministic times - ope...
[ "Of course, the goal is for something like Python to never crash. Alas, we live in an imperfect world. A more useful question to ask, I think, is \"What should I do if Python crashes?\". If you want to help make a more perfect world, first make a quick search at the Python issue tracker to see if a similar probl...
[ 6, 4 ]
[]
[]
[ "crash", "python", "stripchart", "tkinter" ]
stackoverflow_0007627903_crash_python_stripchart_tkinter.txt
Q: Error, Retrieving a web page with data in Python 3 I have written a very basic Python 3 function to retrieve a web page with some data but I am getting an error message: import urllib.parse import urllib.request def fetch_web (url, par1,par2="",par3=""): values = {"s":"stor","l":"SVEENG"} data = urllib....
Error, Retrieving a web page with data in Python 3
I have written a very basic Python 3 function to retrieve a web page with some data but I am getting an error message: import urllib.parse import urllib.request def fetch_web (url, par1,par2="",par3=""): values = {"s":"stor","l":"SVEENG"} data = urllib.parse.urlencode(values) req = urllib.request.Request...
[ "You should learn about Bytes vs Characters in Python 3.\nAnd them use byte strings like: b'...' for data you post to a website.\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007627967_python_python_3.x.txt
Q: get all lines of a continuation line in traceback Is it possible to get all lines of a continuation line in a traceback? Example: #! /usr/bin/env python def function_with_long_name(foo, bar): raise Exception('problem?') function_with_long_name('very_important_value', 'meaningless_value') Output: $ ./test.py ...
get all lines of a continuation line in traceback
Is it possible to get all lines of a continuation line in a traceback? Example: #! /usr/bin/env python def function_with_long_name(foo, bar): raise Exception('problem?') function_with_long_name('very_important_value', 'meaningless_value') Output: $ ./test.py Traceback (most recent call last): File "./test.py", ...
[ "Someone appears to have just opened Python issue 12458 about this. Suggest you follow along there.\n" ]
[ 1 ]
[]
[]
[ "python", "traceback" ]
stackoverflow_0007628124_python_traceback.txt
Q: Lightweight notification technique I need to develop a realtime recent activity feed in django (with AJAX long-polling), and I'm wondering what's the best strategy for the server-side. Pseudocode: def recent_activity_post_save(): notify_view() [in the view] while not new_activity(): sleep(1) return HttpRe...
Lightweight notification technique
I need to develop a realtime recent activity feed in django (with AJAX long-polling), and I'm wondering what's the best strategy for the server-side. Pseudocode: def recent_activity_post_save(): notify_view() [in the view] while not new_activity(): sleep(1) return HttpResponse(new_activity()) The first thing ...
[ "I would suggest keeping it simple...\nCreate a database table to store your events, insert into that table when appropriate, then just implement a simple ajax polling technique to hit the server every x seconds on the client side.\nI have concerns with other solutions considering using a push-notification approach...
[ 5, 2, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "celery", "django", "greenlets", "python", "rabbitmq" ]
stackoverflow_0007460149_celery_django_greenlets_python_rabbitmq.txt
Q: "Message Must be multiple of 16" Encrypted Audio over the Network with Python I am sending encrypted audio through the network in Python. This app works momentarily then breaks saying it must be a multiple of 16. Not sure what I am doing wrong. Or where to look in the code to solve this. I would appreciate any hel...
"Message Must be multiple of 16" Encrypted Audio over the Network with Python
I am sending encrypted audio through the network in Python. This app works momentarily then breaks saying it must be a multiple of 16. Not sure what I am doing wrong. Or where to look in the code to solve this. I would appreciate any help you have to offer EDIT * I believe I have it working now if anyone is interested ...
[ "msg = conn.recv(2024)\nif msg: \n cmd, msg = ord(msg[0]),msg[1:]\n if cmd == CMD_MSG:\n listb1.insert(END, decrypt_my_message(msg.strip()) + \"\\n\")\n\nThe snippet above from your code reads 2024 bytes of data (which isn't a multiple of 16) and then (if the \"if\" statements are True) ...
[ 3, 1 ]
[]
[]
[ "pyaudio", "python" ]
stackoverflow_0007628548_pyaudio_python.txt
Q: seek in http connection when downloading with python I have actually two questions in one. Firstly, does http protocol allows seeking. If the wording is incorrect, what I mean is this: for example, there is file accessible through http request in some server. File's size is 2 gb. Can I retrieve only last 1 gb of t...
seek in http connection when downloading with python
I have actually two questions in one. Firstly, does http protocol allows seeking. If the wording is incorrect, what I mean is this: for example, there is file accessible through http request in some server. File's size is 2 gb. Can I retrieve only last 1 gb of this file using http. If this can be done, how to do it in ...
[ "The http protocol defines a way for a client to request part of the resource see http://www.w3.org/Protocols/rfc2616/\n\nSince all HTTP entities are represented in HTTP messages as sequences\n of bytes, the concept of a byte range is meaningful for any HTTP\n entity. (However, not all clients and servers need to...
[ 1, 0 ]
[]
[]
[ "http", "python" ]
stackoverflow_0007628711_http_python.txt
Q: Trouble running scripts installed by virtualenv-commands on Windows There's a problem with running installed scripts on Windows which can be seen below C:\Users\Piotr>where python C:\program files\Python\2.7\python.exe C:\Users\Piotr>python c:\program files\Python\2.7\scripts\ve init [Errno 2] No such file or dire...
Trouble running scripts installed by virtualenv-commands on Windows
There's a problem with running installed scripts on Windows which can be seen below C:\Users\Piotr>where python C:\program files\Python\2.7\python.exe C:\Users\Piotr>python c:\program files\Python\2.7\scripts\ve init [Errno 2] No such file or directory Is "ve-init" executable in the current path? C:\Users\Piotr> I tri...
[ "The solution is to add .py extension to PATHEXT environment variable so that Python scripts could be run without specifying extension (as long as they are on the PATH).\nNevertheless this is not enough to get virtualenv-commands working on Windows because this package uses Unix specific tools which are not availab...
[ 0 ]
[]
[]
[ "exec", "python", "virtualenv", "virtualenv_commands", "windows" ]
stackoverflow_0007131188_exec_python_virtualenv_virtualenv_commands_windows.txt
Q: Coloring compiler diagnostics with SCons I am currently using the colorama package to color messages generated by my build scripts. I have also used scolorizer, which replaces the build commands with custom, colored messages using strfunction() in SCons. This sure makes build output less verbose and warnings easie...
Coloring compiler diagnostics with SCons
I am currently using the colorama package to color messages generated by my build scripts. I have also used scolorizer, which replaces the build commands with custom, colored messages using strfunction() in SCons. This sure makes build output less verbose and warnings easier to spot. However, I often prefer to see the ...
[ "You can do this by setting CC and CXX in the environment to a suitable wrapper around your compiler, for example colorgcc. \n" ]
[ 2 ]
[]
[]
[ "build", "gcc", "python", "scons", "terminal_color" ]
stackoverflow_0007628881_build_gcc_python_scons_terminal_color.txt
Q: Python: getting finding a variable in a string I currently have some code that goes to a URL, fetches the source code, and I'm trying to get it to return a variable from the string. So I created: changetime = refreshsource.find('VARIABLE pm NST') But it wouldn't find the area in the string because the word is not ...
Python: getting finding a variable in a string
I currently have some code that goes to a URL, fetches the source code, and I'm trying to get it to return a variable from the string. So I created: changetime = refreshsource.find('VARIABLE pm NST') But it wouldn't find the area in the string because the word is not VARIABLE, it is something else. How would I retrieve...
[ "A regular expression will be able to achieve this for you. I'd you give some examples of what variable will be the we could come up with a strict expression. To match what you have above something like the following will do:\nimport re\n# this will match 01:23, 11:34, 12:00, etc.\ntimex = re.compile('.*(\\d{2}:\\d...
[ 2, 1 ]
[]
[]
[ "python", "string", "url", "urllib", "variables" ]
stackoverflow_0007628933_python_string_url_urllib_variables.txt
Q: BLAST Database allocation error I asked this question on the bioinformatics version of stackexchange, but since I think it is a computer problem I thought I should try my luck here. When running local BLAST (v2.2.24+) on a big database (all human proteins) I get the following error: proteinsApplicationError: Comm...
BLAST Database allocation error
I asked this question on the bioinformatics version of stackexchange, but since I think it is a computer problem I thought I should try my luck here. When running local BLAST (v2.2.24+) on a big database (all human proteins) I get the following error: proteinsApplicationError: Command 'blast-2.2.24+/bin/blastp.exe -qu...
[ "Fixed it by breaking the query file up in two and using blast 2.2.25 instead of 2.2.24\n" ]
[ 1 ]
[]
[]
[ "allocation", "blast", "mapping", "memory", "python" ]
stackoverflow_0007513818_allocation_blast_mapping_memory_python.txt
Q: Importing code from file into Python and adding file dialog box I have a python script signalgen.py that plays audio using equations but I would like to be able to hard code the file where the equation is stored in eq1.txt or choose a file and import the equation. The problems I'm having are: 1) How can I hard co...
Importing code from file into Python and adding file dialog box
I have a python script signalgen.py that plays audio using equations but I would like to be able to hard code the file where the equation is stored in eq1.txt or choose a file and import the equation. The problems I'm having are: 1) How can I hard code a file and it's path correctly so it will play the equation as aud...
[ "The imp module will help you to cleanly load Python code chunks from arbitrary files.\n#!/usr/bin/env python\n# equation in equation-one.py\ndef eqn(arg):\n return arg * 3 + 2\n\n#!/usr/bin/env python\n# your code\n\nimport imp\npath = \"equation-one.py\"\neq_mod = imp.load_source(\"equation\", path, open(path)...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007628523_python.txt
Q: Unable to understand TypeError Can someone please explain why I'm getting this error? My code: def x(n): if n == 1: n = 4 elif n == 2: n = 3 elif n == 3: n = 2 elif n == 4: n = 1 return n def y(n): if n == 1: n = 2 elif n == 2: n = 1 elif n == 3: n = 4 elif n == 4: n = 3 re...
Unable to understand TypeError
Can someone please explain why I'm getting this error? My code: def x(n): if n == 1: n = 4 elif n == 2: n = 3 elif n == 3: n = 2 elif n == 4: n = 1 return n def y(n): if n == 1: n = 2 elif n == 2: n = 1 elif n == 3: n = 4 elif n == 4: n = 3 return n def query_x(i, j, quadrants)...
[ "pair = map(int, raw_input().split())\nx, y = pair\n\nOn line 39 you are redefining the x and y objects to be integers. x and y no longer reference the functions that you defined at the top. Your \"main\" block of code is not a separate function scope you are still at the global namespace.\nhttp://docs.python.org/t...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007229531_python.txt
Q: How to clear all data in MIMEBase (email module) so i have this code: import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders import os def sendMail(to, subject, t...
How to clear all data in MIMEBase (email module)
so i have this code: import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders import os def sendMail(to, subject, text, files=[],server="smtp.gmail.com:587"): assert...
[ "It looks like your problem is that you:\n\nCreate a msg.\nAppend 21 files to msg.\nSend it.\nAppend 21 more files, so that it has 42 files now attached.\nSend it again; this second message is twice as large as the first.\nAppend 21 more files, bringing the total to 63.\nSend it again; it's getting pretty huge now....
[ 2 ]
[]
[]
[ "email", "python" ]
stackoverflow_0007624841_email_python.txt
Q: Cannot write text as UTF-8 to file using python I am working on a program that reads a downloaded webpage (stored as 'something'.html) and parses it accordingly. I am having some trouble getting the encoding and decoding correct for this program. It's my understanding most webpages are encoded in ISO-8859-1 and ...
Cannot write text as UTF-8 to file using python
I am working on a program that reads a downloaded webpage (stored as 'something'.html) and parses it accordingly. I am having some trouble getting the encoding and decoding correct for this program. It's my understanding most webpages are encoded in ISO-8859-1 and I checked the response from this page and that is the...
[ "I followed your instructions. The displayed page is NOT encoded in UTF-8; decoding using UTF-8 fails. According to an experimental character set detector that I muck about with occasionally, it is encoded in a Latin-based encoding ... one of ISO-8859-1, cp1252, and ISO-8859-15, and the language appears to be 'es' ...
[ 2, 1 ]
[]
[]
[ "encoding", "file_io", "parsing", "python", "utf_8" ]
stackoverflow_0007626044_encoding_file_io_parsing_python_utf_8.txt
Q: Python reading file in binary, binary data to string? I'm trying to learn Python and currently doing some exercises online. One of them involves reading zip files. When I do: import zipfile zp=zipfile.ZipFile('MyZip.zip') print(zp.read('MyText.txt')) it prints: b'Hello World' I just want a string with "Hello Wor...
Python reading file in binary, binary data to string?
I'm trying to learn Python and currently doing some exercises online. One of them involves reading zip files. When I do: import zipfile zp=zipfile.ZipFile('MyZip.zip') print(zp.read('MyText.txt')) it prints: b'Hello World' I just want a string with "Hello World". I know it's stupid, but the only way I could think of ...
[ "You need to decode the raw bytes in the string into real characters. Try running .decode('utf-8') on the value you are getting back from zp.read() before printing it.\n", "You need to decode the bytes to text first.\nprint(zp.read('MyText.txt').decode('utf-8'))\n\n", "Just decode the bytes:\nprint(zp.read('MyT...
[ 6, 5, 5 ]
[]
[]
[ "binary", "python", "string" ]
stackoverflow_0007629512_binary_python_string.txt
Q: Creating python subclass issue I'm having some trouble with class inheritance in Python 3.1x that I am hoping to get some help with. I have a class called ClassA and I am trying to create another class called ClassB that inherits from ClassA. Here is the code I've written: from myfile import ClassA class ClassB(...
Creating python subclass issue
I'm having some trouble with class inheritance in Python 3.1x that I am hoping to get some help with. I have a class called ClassA and I am trying to create another class called ClassB that inherits from ClassA. Here is the code I've written: from myfile import ClassA class ClassB(ClassA): def __init__(self): ...
[ "The problem is that you're not referring to what you've imported.\n>>> import SomeModule\n>>> x = SomeModule.ClassB()\n\n" ]
[ 3 ]
[]
[]
[ "class", "python", "subclass" ]
stackoverflow_0007629541_class_python_subclass.txt