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: Help me with my backprop implementation in Python EDIT2: New training set... Inputs: [ [0.0, 0.0], [0.0, 1.0], [0.0, 2.0], [0.0, 3.0], [0.0, 4.0], [1.0, 0.0], [1.0, 1.0], [1.0, 2.0], [1.0, 3.0], [1.0, 4.0], [2.0, 0.0], [2.0, 1.0], [2.0, 2.0], [2.0, 3.0], [2.0, 4.0], [3.0, 0.0], [3....
Help me with my backprop implementation in Python
EDIT2: New training set... Inputs: [ [0.0, 0.0], [0.0, 1.0], [0.0, 2.0], [0.0, 3.0], [0.0, 4.0], [1.0, 0.0], [1.0, 1.0], [1.0, 2.0], [1.0, 3.0], [1.0, 4.0], [2.0, 0.0], [2.0, 1.0], [2.0, 2.0], [2.0, 3.0], [2.0, 4.0], [3.0, 0.0], [3.0, 1.0], [3.0, 2.0], [3.0, 3.0], [3.0, 4.0], [4....
[ "Looks like what you get is nearly the initial state of Neuron (nearly self.idealValue). Maybe you should not initialize this Neuron before having actual data to provide ?\nEDIT: OK, I looked a bit deeper in the code and simplified it a bit (will post simplified version below). Basically your code has two minor err...
[ 7 ]
[]
[]
[ "algorithm", "math", "neural_network", "python" ]
stackoverflow_0003988238_algorithm_math_neural_network_python.txt
Q: Matplotlib: Curve touches axis boudary. How to solve this? I drew this graph using matplotlib using the following code. import matplotlib import matplotlib.pyplot as plt x = [450.0, 450.0, 438.0, 450.0, 420.0, 432.0, 416.0, 406.0, 432.0, 400.0] y = [328.90000000000003, 327.60000000000031, 305.90000000000146, 285....
Matplotlib: Curve touches axis boudary. How to solve this?
I drew this graph using matplotlib using the following code. import matplotlib import matplotlib.pyplot as plt x = [450.0, 450.0, 438.0, 450.0, 420.0, 432.0, 416.0, 406.0, 432.0, 400.0] y = [328.90000000000003, 327.60000000000031, 305.90000000000146, 285.2000000000013, 276.0, 264.0, 244.0, 236.0, 233.5, 236.0] z = [2...
[ "Use axis:\nplt.plot(z,x,'-',lw=3)\nplt.plot(z,y,'--',lw=3)\nplt.axis([2,20,100,500])\nplt.show()\n\nOr, use ylim:\nplt.ylim([100,500])\n\n", "I tried your code and the graph did not overlap. Anyway, try to add small margins to the plot:\nplt.margins(0,0.02)\nAlso you may try to add argument clip_on=True to plot ...
[ 1, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003988183_matplotlib_python.txt
Q: django template "file name too long" I'm very new to Python and Django so maybe someone can point me in the right direction. I have the following url.py line url(r'^$', direct_to_template, {'template':'index.html', 'extra_context':{'featured_actors': lambda: User.objects ...
django template "file name too long"
I'm very new to Python and Django so maybe someone can point me in the right direction. I have the following url.py line url(r'^$', direct_to_template, {'template':'index.html', 'extra_context':{'featured_actors': lambda: User.objects .annot...
[ "It's possible that the image path {% avatar_itself_url actor.avatar_set.all.0 200 %} is too long. Can you delete the line with <img ... and see if the template renders?\nIf the above renders, from the python manage.py shell, can you verify the length of your image path? Is the length greater than 255 chars?\nANS...
[ 2 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0003988165_django_django_urls_python.txt
Q: weird range value in the colorbar, matplotlib I am a new user to the python & matplotlib, this might be a simple question but I searched the internet for hours and couldn't find a solution for this. I am plotting precipitation data from which is in the NetCDF format. What I find weird is that, the data doesn't hav...
weird range value in the colorbar, matplotlib
I am a new user to the python & matplotlib, this might be a simple question but I searched the internet for hours and couldn't find a solution for this. I am plotting precipitation data from which is in the NetCDF format. What I find weird is that, the data doesn't have any negative values in it.(I checked that many ti...
[ "Yes, you can manually format everything about the colorbar. See this:\nimport matplotlib.colors as mc\nimport matplotlib.pyplot as plt\nplt.imshow(X, norm=mc.Normalize(vmin=0))\nplt.colorbar(ticks=[0,2,4,6], format='%0.2f')\n\n\nMany plotting functions including imshow, contourf, and others include a norm argument...
[ 2 ]
[]
[]
[ "colorbar", "matplotlib", "netcdf", "python" ]
stackoverflow_0003970072_colorbar_matplotlib_netcdf_python.txt
Q: Registering a Python program as a Windows Server 2003 R2 Service I wrote a Python script that I need to have installed on Windows Server 2003 R2, that will run when a specific directory is changed in any way (new files, deleted files, etc). I believe I need to register this as a system service, in order to listen ...
Registering a Python program as a Windows Server 2003 R2 Service
I wrote a Python script that I need to have installed on Windows Server 2003 R2, that will run when a specific directory is changed in any way (new files, deleted files, etc). I believe I need to register this as a system service, in order to listen for that, but I'm really not sure. So, my question is this: does such ...
[ "I believe your program will have to watch the directory for changes and act according. Alternatively, you could have a separate program watch the directory and then invoke your script, but this is essentially the same.\nTim Golden has an article here which discusses directory watching using python and the win32 a...
[ 1 ]
[]
[]
[ "python", "windows_server_2003", "windows_services" ]
stackoverflow_0003988599_python_windows_server_2003_windows_services.txt
Q: Python: Regular expression to change image filename I've got a string looks like this String a is ACdA(a = %b, ccc= 2r2) String b is \ewfsd\ss.jpg Expected outputs: ACdA(a = %b, ccc= 2r2, b_holder = \ewfsd\ss.jpg) It adds the string b to the end of string a, that's it! But be careful of the ")" "b_holder " is har...
Python: Regular expression to change image filename
I've got a string looks like this String a is ACdA(a = %b, ccc= 2r2) String b is \ewfsd\ss.jpg Expected outputs: ACdA(a = %b, ccc= 2r2, b_holder = \ewfsd\ss.jpg) It adds the string b to the end of string a, that's it! But be careful of the ")" "b_holder " is hard coded string, it's absolutly same in all cases, won't b...
[ "Is\na = \"ACdA(a = %b, ccc= 2r2)\"\nb = \"\\ewfsd\\ss.jpg\"\nprint a[:-1] + ', b_holder = ' + b + ')'\n\nwhat you had in mind?\nMost days of the week, I personally prefer\nprint '%s, b_holder = %s)' % (a[:-1], b)\n\nI recognize I'm likely in the minority in this particular regard.\nThere certainly are other implem...
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003988920_python_regex.txt
Q: Python set and the "in" keyword usage issue I'm trying to work with a set of django models in an external script. I'm querying the database at a preset interval to get the items that meet the query. When my external script is processing them, it takes a while and I may get the same results in the query if the pr...
Python set and the "in" keyword usage issue
I'm trying to work with a set of django models in an external script. I'm querying the database at a preset interval to get the items that meet the query. When my external script is processing them, it takes a while and I may get the same results in the query if the processing hasn't updated the model yet. I figured...
[ "Python sets require that objects implement __eq__ and __hash__ appropriately.\nI looked at django.db.models.base.Model (link) and saw that it defines these methods in terms of the model's PK:\n def __eq__(self, other):\n return isinstance(other, self.__class__) and self._get_pk_val() == other._get_pk_val...
[ 2 ]
[]
[]
[ "django", "python", "set" ]
stackoverflow_0003988204_django_python_set.txt
Q: Copy from a file until a certain marker string is found I am trying to write some code which will open List1.txt and copy the contents up until it sees the string 'John smith' to List2.txt. This is what I have so far: F=open('C:\T\list.txt','r').readlines() B=open('C:\T\list2.txt','w') BB=open('C:\T\list2.txt','r'...
Copy from a file until a certain marker string is found
I am trying to write some code which will open List1.txt and copy the contents up until it sees the string 'John smith' to List2.txt. This is what I have so far: F=open('C:\T\list.txt','r').readlines() B=open('C:\T\list2.txt','w') BB=open('C:\T\list2.txt','r').readlines() while BB.readlines() == 'John smith': B.wri...
[ "from itertools import takewhile\n\nwith open('List1.txt') as fin, open('List2.txt', 'w') as fout:\n lines = takewhile(lambda x : x != 'John smith\\n', fin)\n fout.writelines(lines)\n\n", "F=open('C:\\T\\list1.txt','r')\nB=open('C:\\T\\list2.txt','w')\nfor l in F: #for each line in list1.txt\n if l.strip...
[ 3, 1 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003989302_file_io_python.txt
Q: Terminate a sockert.recv in a thread in Python To implement a simple protocol in python, I've used a thread to monitor acknowledgements send by the receiver. To do this, I use a thread in a function def ackListener(self): while self.waitingforack: ack = self.socket_agent.recv(4) ... exit()...
Terminate a sockert.recv in a thread in Python
To implement a simple protocol in python, I've used a thread to monitor acknowledgements send by the receiver. To do this, I use a thread in a function def ackListener(self): while self.waitingforack: ack = self.socket_agent.recv(4) ... exit() where self.waitingforack is a boolean I set to Fal...
[ "Remember that these operations like recv are blocking operations in your case.\nSo calling this function blocks unless you have received the data.\nThere are two ways to go about it:\nMake socket non blocking\nsocket.setblocking(0)\n\nSet a timeout value\nsee : http://docs.python.org/library/socket.html#socket.soc...
[ 4 ]
[]
[]
[ "multithreading", "python", "sockets" ]
stackoverflow_0003990101_multithreading_python_sockets.txt
Q: XML "not well-formed (invalid token)" error from FlickrApi First of all : I'm using the well known (and tested I suppose) flickrapi. I was testing synchronization of flickr photos with my project and everything worked fine till I reached some specific files. Then python's xml parser failed to parse xml to string (...
XML "not well-formed (invalid token)" error from FlickrApi
First of all : I'm using the well known (and tested I suppose) flickrapi. I was testing synchronization of flickr photos with my project and everything worked fine till I reached some specific files. Then python's xml parser failed to parse xml to string (and error from topic). Debug gave me line and column in the xml,...
[ "Unsolvable: http://bitbucket.org/sybren/flickrapi/issue/11/encoding-issues . Looks like this is a flickr's side issue and they're not going to solve it quickly.\n", "I suppose that you have to encode everthing in UTF-8, so make sure it is so. \n" ]
[ 1, 0 ]
[]
[]
[ "flickr", "python", "xml", "xml_parsing" ]
stackoverflow_0003987032_flickr_python_xml_xml_parsing.txt
Q: Insert data into texctrl To insert data into a textctrl i do this : num_items = self.lc_sources.GetItemCount() self.lc_sources.SetStringItem(num_items, 1, data) But the problem is the insertion is done after the treatment of data, well and i need to do insertion in real time. Please how can i do this A: I usu...
Insert data into texctrl
To insert data into a textctrl i do this : num_items = self.lc_sources.GetItemCount() self.lc_sources.SetStringItem(num_items, 1, data) But the problem is the insertion is done after the treatment of data, well and i need to do insertion in real time. Please how can i do this
[ "I usually do something like this when I need to update a ListCtrl:\nself.list_ctrl.InsertStringItem(index, data)\nself.list_ctrl.SetStringItem(index, 1, moreData)\nLately, I've been using ObjectListView instead of the ListCtrl because I think it's just easier to use and more flexible too: http://objectlistview.sou...
[ 1 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0003989989_python_wxpython_wxwidgets.txt
Q: How to pass object to a function in this scenario I have the following piece of code: NameX.functionA(functionB(Dictionary["___"])) Instead of _ I would like to make a reference to NameX in the form of a string, so that the program interprets it as NameX.functionA(functionB(Dictionary["NameX"])) How can I do ...
How to pass object to a function in this scenario
I have the following piece of code: NameX.functionA(functionB(Dictionary["___"])) Instead of _ I would like to make a reference to NameX in the form of a string, so that the program interprets it as NameX.functionA(functionB(Dictionary["NameX"])) How can I do this? I tried to use str(self), but it is clearly wrong...
[ "Is NameX.__name__ perhaps what you want?\n", "You can use\nName.__name__\n\non an uninitialized object and\nName.__class__.__name__\n\non an initialized object.\n", "Abusive but it works:\n>>> def getvarname(var):\n d = globals()\n for n in d:\n if d[n] is var:\n return n\n return No...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003990562_python.txt
Q: python sqlite question - Insert method In the code below row is a tuple of 200 elements (numbers) and listOfVars is a tuple of 200 strings that are variable names in the testTable. tupleForm is a list of tuples, 200 elements in each tuple. The following code does not work. It returns a syntax error: for row in tu...
python sqlite question - Insert method
In the code below row is a tuple of 200 elements (numbers) and listOfVars is a tuple of 200 strings that are variable names in the testTable. tupleForm is a list of tuples, 200 elements in each tuple. The following code does not work. It returns a syntax error: for row in tupleForm: cmd = '''INSERT INTO testTable ...
[ "insert_query = '''INSERT INTO testTable ({0}) VALUES ({1})'''.format(\n (','.join(listOfVars)), ','.join('?'*len(listOfVars)))\ncur.executemany(insert_query, tupleForm)\n\nPlease do not use normal string interpolation for database queries.\nWe are fortunate to have the DB-API which explains in detail...
[ 7, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0003990769_python_sqlite.txt
Q: How two merge several .csv files horizontally with python? I've several .csv files (~10) and need to merge them together into a single file horizontally. Each file has the same number of rows (~300) and 4 header lines which are not necessarily identical, but should not be merged (only take the header lines from th...
How two merge several .csv files horizontally with python?
I've several .csv files (~10) and need to merge them together into a single file horizontally. Each file has the same number of rows (~300) and 4 header lines which are not necessarily identical, but should not be merged (only take the header lines from the first .csv file). The tokens in the lines are comma separated ...
[ "You can load the CSV files using the csv module in Python. Please refer to the documentation of this module for the loading code, I cannot remember it but it is really easy. Something like:\nimport csv\nreader = csv.reader(open(\"some.csv\", \"rb\"))\ncsvContent = list(reader)\n\nAfter that, when you have the CSV ...
[ 6, 2, 1, 1, 0, 0 ]
[]
[]
[ "csv", "file", "python" ]
stackoverflow_0003986353_csv_file_python.txt
Q: Is python time module reliable enough to use to measure response time? My question was not specific enough last time, and so this is second question about this topic. I'm running some experiments and I need to precisely measure participants' response time to questions in millisecond unit. I know how to do this w...
Is python time module reliable enough to use to measure response time?
My question was not specific enough last time, and so this is second question about this topic. I'm running some experiments and I need to precisely measure participants' response time to questions in millisecond unit. I know how to do this with the time module, but I was wondering if this is reliable enough or I sho...
[ "CPU load will affect timing. If your application is startved of a slice of CPU time, then timing would get affected. You can not help that much. You can be as precise and no more. Ensure that your program gets a health slice of cpu time and the result will be accurate. In most cases, the results should be accurate...
[ 2, 1 ]
[]
[]
[ "python", "time" ]
stackoverflow_0003989952_python_time.txt
Q: Numpy.array indexing question I am trying to create a 'mask' of a numpy.array by specifying certain criteria. Python even has nice syntax for something like this: >> A = numpy.array([1,2,3,4,5]) >> A > 3 array([False, False, False, True, True]) But if I have a list of criteria instead of a range: >> A = numpy.arr...
Numpy.array indexing question
I am trying to create a 'mask' of a numpy.array by specifying certain criteria. Python even has nice syntax for something like this: >> A = numpy.array([1,2,3,4,5]) >> A > 3 array([False, False, False, True, True]) But if I have a list of criteria instead of a range: >> A = numpy.array([1,2,3,4,5]) >> crit = [1,3,5] ...
[ "I think that the numpy function in1d is what you are looking for:\n>>> A = numpy.array([1,2,3,4,5])\n>>> B = [1,3,5]\n>>> numpy.in1d(A,crit)\narray([ True, False, True, False, True], dtype=bool)\n\nas stated in its docstring, \"in1d(a, b) is roughly equivalent to np.array([item in b for item in a])\"\nAdmittedly...
[ 6, 3, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0003989990_arrays_numpy_python.txt
Q: Maximum recursion depth exceeded when providing unique id I wanted to provide unique ID for different categories of models in my db. So I've introduced a dummy model : class GUUID(models.Model): guuid = models.PositiveSmallIntegerField(_(u"Dummy GUUID"), default=1) and in model that I want to have unique ID: ...
Maximum recursion depth exceeded when providing unique id
I wanted to provide unique ID for different categories of models in my db. So I've introduced a dummy model : class GUUID(models.Model): guuid = models.PositiveSmallIntegerField(_(u"Dummy GUUID"), default=1) and in model that I want to have unique ID: class Event(models.Model): unique = models.IntegerField(bl...
[ "I think you want to replace self.save() with super(Event, self).save(). Also might not be a bad idea to grab the parameters from the Event save method and pass them up:\ndef save(self, *args, **kwargs):\n #... other code here\n super(Event, self).save(*args, **kwargs)\n\n" ]
[ 6 ]
[]
[]
[ "django", "django_models", "python", "recursion", "uniqueidentifier" ]
stackoverflow_0003991008_django_django_models_python_recursion_uniqueidentifier.txt
Q: why python nose unittest teardown fixture failed I'm using nose test framework. When running a test module, the teardown function defined in it failed. the error raised says the fixture is locked by another process. here is my test module, test_my_module.py: ... ... def teardown(): if os.path.exists(test_o...
why python nose unittest teardown fixture failed
I'm using nose test framework. When running a test module, the teardown function defined in it failed. the error raised says the fixture is locked by another process. here is my test module, test_my_module.py: ... ... def teardown(): if os.path.exists(test_output_dir): shutil.rmtree(test_output_dir) ......
[ "You could try explicitly closing the sqlite connection in the teardown before removing test_output_dir.\n", "I believe I did have the same issue in my c# unit tests. \nI solved it by using calling SqliteConnection.ClearAllPools() before deleting the database file, so it is related to connection pooling. \nMaybe ...
[ 0, 0 ]
[]
[]
[ "fixture", "nose", "python", "unit_testing" ]
stackoverflow_0003915850_fixture_nose_python_unit_testing.txt
Q: python to uncomment the right line I have a file as follows: line 1: _____ ... # for AAA #export CONFIG = AAA_defconfig # for BBB, BbB, Bbb, BBb3 #export CONFIG = BBB_defconfig # for CCC, CcC, Ccc, Ccc1 #export CONFIG = CCC_defconfig ... other lines I want manipulate the file, so that based on the given s...
python to uncomment the right line
I have a file as follows: line 1: _____ ... # for AAA #export CONFIG = AAA_defconfig # for BBB, BbB, Bbb, BBb3 #export CONFIG = BBB_defconfig # for CCC, CcC, Ccc, Ccc1 #export CONFIG = CCC_defconfig ... other lines I want manipulate the file, so that based on the given string, I could export the right "CONFIG"...
[ "Then why not make it as\nline = 'xxxx'\nCONFIG = default_deconfig\n\nif line == 'AAA':\n CONFIG = AAA_defconfig\nelif line == 'CCC':\n CONFIG = CCC_defconfig\n...\n\nunless this is not a python file and you want to manipulate it. It looks like that.\nIn that case create a config generator which will create...
[ 1, 1, 1, 1 ]
[]
[]
[ "file_manipulation", "python", "string" ]
stackoverflow_0003989967_file_manipulation_python_string.txt
Q: Django - AutoField with regards to a foreign key I have a model with a unique integer that needs to increment with regards to a foreign key, and the following code is how I currently handle it: class MyModel(models.Model): business = models.ForeignKey(Business) number = models.PositiveIntegerField() sp...
Django - AutoField with regards to a foreign key
I have a model with a unique integer that needs to increment with regards to a foreign key, and the following code is how I currently handle it: class MyModel(models.Model): business = models.ForeignKey(Business) number = models.PositiveIntegerField() spam = models.CharField(max_length=255) class Meta:...
[ "You want that constraint at the database level. Otherwise you're going to eventually run into the concurrency problem you discussed. The solution is to wrap the entire operation (read, increment, write) in a transaction.\nWhy can't you use an AutoField for instead of a PositiveIntegerField?\nnumber = models.AutoFi...
[ 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003991437_django_django_models_python.txt
Q: Best way to integrate Erlang and python What's the best way to integrate Erlang and python? We need to call python functions in Erlang and call Erlang functions in python. At this moment we are trying to use SOAP as a intermediate layer between these two languages, but we have a lot of "not compatible" troubles. C...
Best way to integrate Erlang and python
What's the best way to integrate Erlang and python? We need to call python functions in Erlang and call Erlang functions in python. At this moment we are trying to use SOAP as a intermediate layer between these two languages, but we have a lot of "not compatible" troubles. Could you advise the best way to perform integ...
[ "As already mentioned with erlport you can use Erlang port protocol and term_to_binary/binary_to_term functions on Erlang side. On Python side there are low level port driver Port which can send and receive messages from Erlang and more high level protocol handler Protocol which simplified situation when you want t...
[ 26, 11 ]
[]
[]
[ "erlang", "python" ]
stackoverflow_0003990344_erlang_python.txt
Q: CherryPy combine file and dictionary based configuration I'm setting up a CherryPy application and would like to have the majority of my configuration settings in a .conf file like this: [global] server.socketPort = 8080 server.threadPool = 10 server.environment = "production" However I would also like to setup a...
CherryPy combine file and dictionary based configuration
I'm setting up a CherryPy application and would like to have the majority of my configuration settings in a .conf file like this: [global] server.socketPort = 8080 server.threadPool = 10 server.environment = "production" However I would also like to setup a few with a dictionary in code like this: conf = {'/': {'tools...
[ "quickstart is for quick sites. If you're doing anything as complex as having multiple configs, it's time to graduate. Look at the source code for the quickstart function (it's not scary!): you're going to unpack that into your startup script. So instead of quickstart, write this:\ncherrypy.config.update(conffile)\...
[ 11, 3 ]
[]
[]
[ "cherrypy", "configuration", "python" ]
stackoverflow_0003989763_cherrypy_configuration_python.txt
Q: how to create file names from a number plus a suffix in python how to create file names from a number plus a suffix??. for example I am using two programs in python script for work in a server, the first creates a file x and the second uses the x file, the problem is that this file can not overwrite. no matter wha...
how to create file names from a number plus a suffix in python
how to create file names from a number plus a suffix??. for example I am using two programs in python script for work in a server, the first creates a file x and the second uses the x file, the problem is that this file can not overwrite. no matter what name is generated from the first program. the second program of be...
[ "As far as I can understand you, you want to create a file with a unique name in one program and pass the name of that file to another program. I think you should take a look at the tempfile module, http://docs.python.org/library/tempfile.html#module-tempfile.\nHere is an example that makes use of NamedTemporaryFil...
[ 3 ]
[]
[]
[ "filenames", "python" ]
stackoverflow_0003991330_filenames_python.txt
Q: Options for handling javascript heavy pages while screen scraping Disclaimer here: I'm really not a programmer. I'm eager to learn, but my experience is pretty much basic on c64 20 years ago and a couple of days of learning Python. I'm just starting out on a fairly large (for me as a beginner) screen scraping proj...
Options for handling javascript heavy pages while screen scraping
Disclaimer here: I'm really not a programmer. I'm eager to learn, but my experience is pretty much basic on c64 20 years ago and a couple of days of learning Python. I'm just starting out on a fairly large (for me as a beginner) screen scraping project. So far I have been using python with mechanize+lxml for my browsin...
[ "You might be able to find the data you are looking for elsewhere. Try using the web-developer toolbar in firefox to see what is being loaded by javascript. It might be that you can find the data in the js files.\nOtherwise, you probably do need to use Mechanize. There are two tutorials that you might find useful h...
[ 1, 0, 0, 0 ]
[]
[]
[ "python", "screen_scraping" ]
stackoverflow_0003929005_python_screen_scraping.txt
Q: What exactly does distutils do? I have read the documentation but I don't understand. Why do I have to use distutils to install python modules ? Why do I just can't save the modules in python path ? A: You don't have to use distutils. You can install modules manually, just like you can compile a C++ library manu...
What exactly does distutils do?
I have read the documentation but I don't understand. Why do I have to use distutils to install python modules ? Why do I just can't save the modules in python path ?
[ "You don't have to use distutils. You can install modules manually, just like you can compile a C++ library manually (compile every implementation file, then link the .obj files) or install an application manually (compile, put into its own directory, add a shortcut for launching). It just gets tedious and error-pr...
[ 5, 4, 2 ]
[]
[]
[ "distutils", "python" ]
stackoverflow_0003991335_distutils_python.txt
Q: How to draw this window? Can I create a window without this topbar? : I want a window like this: A: Here they say you could try: gtk.Window.set_decorated(False) A: You could also do window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_SPLASHSCREEN) but that doesn't have rounded corners either, at least on my theme....
How to draw this window?
Can I create a window without this topbar? : I want a window like this:
[ "Here they say you could try:\ngtk.Window.set_decorated(False)\n\n", "You could also do\nwindow.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_SPLASHSCREEN)\n\nbut that doesn't have rounded corners either, at least on my theme. As eumiro says, that depends on the theme settings.\n" ]
[ 2, 1 ]
[]
[]
[ "gtk", "pygtk", "python", "ubuntu" ]
stackoverflow_0003991706_gtk_pygtk_python_ubuntu.txt
Q: ImportError: No module named ***** in python I am very new to python, about one month, and am trying to figure out how the importing works in python. I was told that I can import any 'module' that has Python code in it. So I am trying to import a module just to try it out, but I keep getting an 'ImportError: No mo...
ImportError: No module named ***** in python
I am very new to python, about one month, and am trying to figure out how the importing works in python. I was told that I can import any 'module' that has Python code in it. So I am trying to import a module just to try it out, but I keep getting an 'ImportError: No module named redue'. This is an example of the pytho...
[ "These files are not on sys.path. It should have been though.\nIf you want to access them from the interpreter, you will need to add the location to sys.path\n>>> import sys\n>>> print sys.path\n>>> sys.path.append('C:\\\\Users\\\\Cube\\\\Documents\\\\Python')\n>>> import reduc\n\nYou could also include the path in...
[ 16 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0003992952_python_python_import.txt
Q: passing text through a dictionary in Python I currently have python code that compares two texts using the cosine similarity measure. I got the code here. What I want to do is take the two texts and pass them through a dictionary (not a python dictionary, just a dictionary of words) first before calculating the s...
passing text through a dictionary in Python
I currently have python code that compares two texts using the cosine similarity measure. I got the code here. What I want to do is take the two texts and pass them through a dictionary (not a python dictionary, just a dictionary of words) first before calculating the similarity measure. The dictionary will just be a ...
[ "If the dictionary fites in memory, use a Python set:\nok_words = set([\"a\", \"b\", \"c\", \"e\"])\n\ndef filter_words(words):\n return [word for word in words if word in ok_words]\n\nIf it doesn't fit in memory, you can use shelve\n", "The structure you try to create is known as Inverted Index. Here you can ...
[ 1, 0 ]
[]
[]
[ "python", "similarity", "text" ]
stackoverflow_0003992769_python_similarity_text.txt
Q: Why does this Python service stop by itself in spite of an infinite loop? I managed to install a Python script as a service using this recipe at ActiveState: win-services-helper. In order to get much use out of it, I included the business end of my program by replacing lines 99 - 100: 95 class Test(Service): 9...
Why does this Python service stop by itself in spite of an infinite loop?
I managed to install a Python script as a service using this recipe at ActiveState: win-services-helper. In order to get much use out of it, I included the business end of my program by replacing lines 99 - 100: 95 class Test(Service): 96 def start(self): 97 self.runflag=True 98 while se...
[ "I believe that this message appears too when an error is encountered. It's not unlikely that the user running the service hasn't got the rights to write in the log file. You might try to create that csv file and set up the access rights so that \"Everyone\" can write to it.\n", "It works now. Thanks everyone for...
[ 2, 1, 0 ]
[]
[]
[ "python", "service", "windows", "windows_services" ]
stackoverflow_0003938746_python_service_windows_windows_services.txt
Q: multicpu bzip2 using a python script I want to quickly bzip2 compress several hundred gigabytes of data using my 8 core , 16 GB ram workstation. Currently I am using a simple python script to compress a whole directory tree using bzip2 and an os.system call coupled to an os.walk call. I see that the bzip2 only use...
multicpu bzip2 using a python script
I want to quickly bzip2 compress several hundred gigabytes of data using my 8 core , 16 GB ram workstation. Currently I am using a simple python script to compress a whole directory tree using bzip2 and an os.system call coupled to an os.walk call. I see that the bzip2 only uses a single cpu while the other cpus remain...
[ "Use the subprocess module to spawn several processes at once. If N of them are running (N should a bit bigger than the number of CPUs you have, say 3 for 2 cores, 10 for 8), wait for one to terminate and then start another one.\nNote that this might not help much since there will be a lot of disk activity which yo...
[ 1, 1 ]
[]
[]
[ "bzip2", "os.walk", "python" ]
stackoverflow_0003345199_bzip2_os.walk_python.txt
Q: What does ... mean in numpy code? And what is it called? I don't know how to search for it; I tried calling it ellipsis with the Google. I don't mean in interactive output when dots are used to indicate that the full array is not being shown, but as in the code I'm looking at, xTensor0[...] = xVTensor[..., 0] Fr...
What does ... mean in numpy code?
And what is it called? I don't know how to search for it; I tried calling it ellipsis with the Google. I don't mean in interactive output when dots are used to indicate that the full array is not being shown, but as in the code I'm looking at, xTensor0[...] = xVTensor[..., 0] From my experimentation, it appears to fu...
[ "Yes, you're right. It fills in as many : as required. The only difference occurs when you use multiple ellipses. In that case, the first ellipsis acts in the same way, but each remaining one is converted to a single :.\n", "Although this feature exists mainly to support numpy and other, similar modules, it's ...
[ 7, 3, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003993125_numpy_python.txt
Q: Facebook Permission request form for Crawling? I have been Googling for sometime but I guess I am using the wrong set of keywords. Does anyone know this URI that lets me request permission from Facebook to let me crawl their network? Last time I was using Python to do this, someone suggested that I look at it but ...
Facebook Permission request form for Crawling?
I have been Googling for sometime but I guess I am using the wrong set of keywords. Does anyone know this URI that lets me request permission from Facebook to let me crawl their network? Last time I was using Python to do this, someone suggested that I look at it but I couldn't find that post either.
[ "Amazingly enough, that's given in their robots.txt.\nThe link you're looking for is this one:\nhttp://www.facebook.com/apps/site_scraping_tos.php\nIf you're not a huge organization already, don't expect to be explicitly whitelisted there. If you're not explicitly whitelisted, you're not allowed to crawl at all, ac...
[ 5, 0 ]
[]
[]
[ "facebook", "mechanize", "python", "web_crawler" ]
stackoverflow_0003993474_facebook_mechanize_python_web_crawler.txt
Q: Python regular expression problem I need to do something in regex but I'm really not good at it, long time didn't do that . /a/c/a.doc I need to change it to \\a\\c\\a.doc Please trying to do it by using regular expression in Python. A: I'm entirely in favor of helping user483144 distinguish "solution" from "...
Python regular expression problem
I need to do something in regex but I'm really not good at it, long time didn't do that . /a/c/a.doc I need to change it to \\a\\c\\a.doc Please trying to do it by using regular expression in Python.
[ "I'm entirely in favor of helping user483144 distinguish \"solution\" from \"regular expression\", as the previous two answerers have already done. It occurs to me, moreover, that os.path.normpath() http://docs.python.org/library/os.path.html might be what he's really after.\n", "why do you think you every solut...
[ 5, 2, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003993385_python_regex.txt
Q: GAE CGI: how to response http status code I am using google appening, it's CGI environment. I want block some request, I want response nothing even no http status code. Alternative, I want just close the connection. Can I do this? update: I have decide to use what pyfunc said, use 204 status, but how can I do thi...
GAE CGI: how to response http status code
I am using google appening, it's CGI environment. I want block some request, I want response nothing even no http status code. Alternative, I want just close the connection. Can I do this? update: I have decide to use what pyfunc said, use 204 status, but how can I do this at GAE CGI environment without any webframewo...
[ "\nThe HTTP status code is important in response\n\n\nYou can use HTTP NO CONTENT 204 to responde with empty content.\nYou could use 403 Forbidden but I prefer 204 to make a silent drop of request \nYou could loose connection but that would be rude and can result in server being pounded with connections as user may...
[ 4 ]
[]
[]
[ "cgi", "google_app_engine", "python" ]
stackoverflow_0003993827_cgi_google_app_engine_python.txt
Q: how to round to higher 10's place in python I have a bunch of floats and I want to round them up to the next highest multiple of 10. For example: 10.2 should be 20 10.0 should be 10 16.7 should be 20 94.9 should be 100 I only need it to go from the range 0-100. I tried math.ceil() but that only rounds up to the ...
how to round to higher 10's place in python
I have a bunch of floats and I want to round them up to the next highest multiple of 10. For example: 10.2 should be 20 10.0 should be 10 16.7 should be 20 94.9 should be 100 I only need it to go from the range 0-100. I tried math.ceil() but that only rounds up to the nearest integer. Thanks in advance.
[ "from math import ceil\n\ndef ceil_to_tens(x):\n return int(ceil(x / 10.0)) * 10\n\nEdit: okay, now that I have an undeserved \"Nice answer\" badge for this answer, I think owe the community with a proper solution using the decimal module that does not suffer from these problems :) Thanks to Jeff for pointing th...
[ 15, 4, 1, 0 ]
[]
[]
[ "math", "python" ]
stackoverflow_0003986996_math_python.txt
Q: Python unicode: how to test against unicode string I have a script like this: #!/Python26/ # -*- coding: utf-8 -*- import sys import xlrd import xlwt argset = set(sys.argv[1:]) #----------- import ---------------- wb = xlrd.open_workbook("excelfile.xls") #----------- script ---------------- #Get the first shee...
Python unicode: how to test against unicode string
I have a script like this: #!/Python26/ # -*- coding: utf-8 -*- import sys import xlrd import xlwt argset = set(sys.argv[1:]) #----------- import ---------------- wb = xlrd.open_workbook("excelfile.xls") #----------- script ---------------- #Get the first sheet either by name sh = wb.sheet_by_name(u'Data') hlo = [...
[ "Python has a sequence type called unicode which will be useful here. These links contain more information to help you regarding this:\n\nPython Unicode HOWTO\nPython built-in types (See section 6.6).\nUnicode In Python, Completely Demystified\n\n", "Try encoding the Excel unicode to string using cp1252 (windows ...
[ 4, 1 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0001818263_python_unicode.txt
Q: How do I check for if an exact string exists in another string? I'm currently running into a bit of a problem. I'm trying to write a program that will highlight occurrences of a word or phrase inside of another string, but only if the string it's being matched to is exactly the same. The part I'm running into trou...
How do I check for if an exact string exists in another string?
I'm currently running into a bit of a problem. I'm trying to write a program that will highlight occurrences of a word or phrase inside of another string, but only if the string it's being matched to is exactly the same. The part I'm running into troubles with is identifying whether or not the subphrase I'm matching th...
[ "There are ways to do it without a regex, but most of those ways are so convoluted that you'll wish you had spent the time learning the simple regex sequence that you need for it.\n", "It is one line with regex...\nimport re\n\nindicators = [\"therefore\", \"for\", \"since\"]\nphrase = \"... therefore, I conclude...
[ 5, 2, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "pattern_matching", "python", "string" ]
stackoverflow_0003994010_pattern_matching_python_string.txt
Q: How do I update a single field, using a variable as a field name? I want to do something like for field in field_list: my_table.field = new_value Couldn't find any documentation on how to do the above with a variable. A: setattr(mytable, field, new_value)
How do I update a single field, using a variable as a field name?
I want to do something like for field in field_list: my_table.field = new_value Couldn't find any documentation on how to do the above with a variable.
[ "setattr(mytable, field, new_value)\n" ]
[ 5 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003994222_django_django_models_python.txt
Q: Python : One regular expression help In python, I've got a string like ABC(a =2,bc=2, asdf_3 = None) By using regular expression, I want to make it like ABC(a =2,bc=2) I want to remove the parameter that named 'asdf_3', that's it! Update: The parameters can be a lot, only the asdf_3 is same in all cases, the ord...
Python : One regular expression help
In python, I've got a string like ABC(a =2,bc=2, asdf_3 = None) By using regular expression, I want to make it like ABC(a =2,bc=2) I want to remove the parameter that named 'asdf_3', that's it! Update: The parameters can be a lot, only the asdf_3 is same in all cases, the order is usually the last one.
[ "import re\n\nfoo = 'ABC(a =2,bc=2, asdf_3 = None)'\nbar = re.sub(r',?\\s+asdf_3\\s+=\\s+[^,)]+', '', foo)\n\n# bar is now 'ABC(a =2,bc=2,)'\n\nThe \\s+ portions let you match any amount of whitespace, and the [^,)]+ part lets it basically anything on the right-hand side that doesn't start another argument.\n", "...
[ 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003993793_python_regex.txt
Q: Python Regular Expression Matching: ## ## Im new to python and regular expressions. Im searching a file line by line for the occurrence of ##random_string##, and i want to be able to capture the random_string in-between the ##s. Ive tried both patterns but no luck =/ pattern1=r'[##]()[##]' pattern2=r'\#{2}()\#{2}'...
Python Regular Expression Matching: ## ##
Im new to python and regular expressions. Im searching a file line by line for the occurrence of ##random_string##, and i want to be able to capture the random_string in-between the ##s. Ive tried both patterns but no luck =/ pattern1=r'[##]()[##]' pattern2=r'\#{2}()\#{2}' prog=re.compile(pattern1) result=prog1.search...
[ "Try using:\n'##(.*?)##'\n\nThe problem with your regex is that you are trying to match an empty string between the ## using a (), you should be using .*? to match anything or a .+? to match any non-empty thing.\nYour first regex [##]()[##] has an additional bug. A character class matches a single character, exampl...
[ 6, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003994024_python_regex.txt
Q: Python: Create associative array in a loop I want to create an associative array with values read from a file. My code looks something like this, but its giving me an error saying i can't the indicies must be ints. Thanks =] for line in open(file): x=prog.match(line) myarray[x.group(1)]=[x.group(2)] A: myarr...
Python: Create associative array in a loop
I want to create an associative array with values read from a file. My code looks something like this, but its giving me an error saying i can't the indicies must be ints. Thanks =] for line in open(file): x=prog.match(line) myarray[x.group(1)]=[x.group(2)]
[ "myarray = {} # Declares myarray as a dict\nfor line in open(file, 'r'):\n x = prog.match(line)\n myarray[x.group(1)] = [x.group(2)] # Adds a key-value pair to the dict\n\n", "Associative arrays in Python are called mappings. The most common type is the dictionary.\n", "Because array indices should be an ...
[ 17, 5, 1 ]
[]
[]
[ "associative_array", "python" ]
stackoverflow_0003994345_associative_array_python.txt
Q: Reading files in GAE using python I created a simple python project that serves up a couple of pages. I'm using the 'webapp' framework and django. What I'm trying to do is use one template file, and load 'content files' that contain the actual page text. When I try to read the content files using os.open, I get t...
Reading files in GAE using python
I created a simple python project that serves up a couple of pages. I'm using the 'webapp' framework and django. What I'm trying to do is use one template file, and load 'content files' that contain the actual page text. When I try to read the content files using os.open, I get the following error: pageContent = os.op...
[ "os.path.normpath() on \"content_includes\" is a no-op - normpath just removes double slashes and other denormalizations. What you probably want is to build a path relative to the script, in which case you should do something like os.path.join(os.path.dirname(__file__), 'content_includes', pageName + '.inc').\n", ...
[ 2, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0003955361_django_google_app_engine_python.txt
Q: Why wouldn't GAE store my logging.debug? It seems logging.debug() doesn't appear in GAE logs, but logging.error() does. Does anyone have an idea how can I make logging.debug() appear in the GAE logs? A: Logging in Python can be set to a different level, so that only a specified level of information appears in th...
Why wouldn't GAE store my logging.debug?
It seems logging.debug() doesn't appear in GAE logs, but logging.error() does. Does anyone have an idea how can I make logging.debug() appear in the GAE logs?
[ "Logging in Python can be set to a different level, so that only a specified level of information appears in the log file. Try to change the logging level:\nlogging.setLevel(logging.DEBUG)\n\n", "I observed that on the SDK-Server debug logging really disappears. In production I get full debug logs. This may be be...
[ 1, 0 ]
[]
[]
[ "debugging", "google_app_engine", "logging", "python" ]
stackoverflow_0003962423_debugging_google_app_engine_logging_python.txt
Q: Can't set full range on QSpinBox I'm trying to create a QSpinBox that accepts all numbers, but I'm having some trouble with hte maximums sbox = QSpinBox(self) sbox.setRange(-sys.maxint/88-1, sys.maxint/86) sbox.setValue(int(setting.value)) I wanted to just use sbox.setRange(-sys.maxint-1, sys.maxint) but then ...
Can't set full range on QSpinBox
I'm trying to create a QSpinBox that accepts all numbers, but I'm having some trouble with hte maximums sbox = QSpinBox(self) sbox.setRange(-sys.maxint/88-1, sys.maxint/86) sbox.setValue(int(setting.value)) I wanted to just use sbox.setRange(-sys.maxint-1, sys.maxint) but then I couldn't enter anything, if I increa...
[ "\nthat accepts all numbers\n\nI assume you mean all integers rather than all numbers?\nRemember that although PyQt is written in Python, the underlying Qt library is written in C++ so it most likely is limited to fixed-size integers of a certain width (for example 32-bit or 64-bit). If you try to use numbers close...
[ 1 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0003994717_pyqt4_python.txt
Q: Online job-searching is tedious. Help me automate it Many job sites have broken searches that don't let you narrow down jobs by experience level. Even when they do, it's usually wrong. This requires you to wade through hundreds of postings that you can't apply for before finding a relevant one, quite tedious. Sinc...
Online job-searching is tedious. Help me automate it
Many job sites have broken searches that don't let you narrow down jobs by experience level. Even when they do, it's usually wrong. This requires you to wade through hundreds of postings that you can't apply for before finding a relevant one, quite tedious. Since I'd rather focus on writing cover letters etc., I want t...
[ "Ok, this answer is probably not going to be helpful -- I will say that up front. But, in my opinion, merely thinking about the problem in this way is enough to get you hired at most places I've worked. My suggestion? Contact the hiring manager at any of the postings in which you have interest, tell them this is...
[ 1, 1, 0 ]
[]
[]
[ "nlp", "perl", "python", "regex", "ruby" ]
stackoverflow_0003048268_nlp_perl_python_regex_ruby.txt
Q: Python - Stripping timestamps and username from line in file I'm writing a script that will print a random line of text from a file into an XCHAT channel. So far it works fine, but I want to add one last bit of functionality. I have logs with, for example, "Oct 23 12:07:59 (nickname> " appearing before every li...
Python - Stripping timestamps and username from line in file
I'm writing a script that will print a random line of text from a file into an XCHAT channel. So far it works fine, but I want to add one last bit of functionality. I have logs with, for example, "Oct 23 12:07:59 (nickname> " appearing before every line of text. I just want to print the parts of the lines that foll...
[ "If the first > character is exactly the place to split, then try:\ntoBeIgnored, toBeUsed = line.split('>', 1)\n\n", "I think > can be used as separator, so:\n_, message = message.split('>', 1)\n\nwill split line into 2 part, first part (underscore while it is not important) with \"Oct 23 12:07:59 (nickname\" and...
[ 1, 0, 0 ]
[]
[]
[ "irc", "python", "string", "text_files" ]
stackoverflow_0003994825_irc_python_string_text_files.txt
Q: Python: Adding elements to an dict list or associative array Im trying to add elements to a dict list (associative array), but every time it loops, the array overwrites the previous element. So i just end up with an array of size 1 with the last element read. I verified that the keys ARE changing every time. array...
Python: Adding elements to an dict list or associative array
Im trying to add elements to a dict list (associative array), but every time it loops, the array overwrites the previous element. So i just end up with an array of size 1 with the last element read. I verified that the keys ARE changing every time. array=[] for line in open(file): result=prog.match(line) array={res...
[ "Your solution is incorrect; the correct version is:\narray={}\nfor line in open(file):\n result=prog.match(line)\n array[result.group(1)] = result.group(2)\n\nIssues with your version:\n\nassociative arrays are dicts and empty dicts = {}\narrays are list , empty list = []\nYou are pointing the array to new dicti...
[ 6, 0, 0 ]
[]
[]
[ "associative_array", "list", "python" ]
stackoverflow_0003994874_associative_array_list_python.txt
Q: Is there a way to resist unnecessary joins that are only checking id existence when using Django's orm? In example. If I have a model Person who's got a mother field, which is a foreign key.. The following is getting to me: p = Person.object.get(id=1) if p.mother_id: print "I have a mother!" In the above exam...
Is there a way to resist unnecessary joins that are only checking id existence when using Django's orm?
In example. If I have a model Person who's got a mother field, which is a foreign key.. The following is getting to me: p = Person.object.get(id=1) if p.mother_id: print "I have a mother!" In the above example, we've issued one query. I've tricked Django into not fetching the mother by using the _id field instead ...
[ "I was surprised by this - I thought Person.object.filter(mother=None) would work without an extra join - but on checking it turns out you're right. In fact this has been logged as a bug in Django's ticket tracker.\nUnfortunately, the person who logged it - and who (re)wrote most of the Django query code - is no lo...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003992576_django_python.txt
Q: Embedding Python thread safe I'm trying to use Python in a module for an analysis software of vehicle bus systems. For this I have to embed Python in a thread safe manner, since there can be multiple instances of the module witch work independently. I could use a mutex to guard all access to Python and create an ...
Embedding Python thread safe
I'm trying to use Python in a module for an analysis software of vehicle bus systems. For this I have to embed Python in a thread safe manner, since there can be multiple instances of the module witch work independently. I could use a mutex to guard all access to Python and create an unique (python) module for every t...
[ "If you're CPU bound, Python can only scale to multiple core using the multiprocessing library. However, if you're I/O bound, then threading is usually sufficient.\nIf you want easy thread safety, then use Queue for all message passing. \n", "To follow-up on my question: I went ahead in implemented it using Proce...
[ 3, 0 ]
[]
[]
[ "embedded_language", "embedding", "multicore", "python", "thread_safety" ]
stackoverflow_0003943106_embedded_language_embedding_multicore_python_thread_safety.txt
Q: Solving the unicode output in Python I have written some code which sends queries to google and returns the query results. Apparently the contents which are retrieved are in unicode format, so when I put them in a list for example and print this list (the whole list together and not member by member) an annoying e...
Solving the unicode output in Python
I have written some code which sends queries to google and returns the query results. Apparently the contents which are retrieved are in unicode format, so when I put them in a list for example and print this list (the whole list together and not member by member) an annoying extra 'u' is always behind all of the membe...
[ "Instead of:\n>>> print your_list\n[u'foo', u'bar']\n\nUse:\n>>> print '\\n'.join(your_list)\nfoo\nbar\n\nYou can use ', ' instead of '\\n' as the separator if you prefer to keep it all on one line.\nYou may also have problems if you are trying to display Unicode characters in the Windows console. If so, you could ...
[ 5, 1 ]
[]
[]
[ "encoding", "python", "unicode", "unicode_string" ]
stackoverflow_0003994930_encoding_python_unicode_unicode_string.txt
Q: For user-based and certificate-based authentication, do I want to use urllib, urllib2, or curl? A few months ago, I hastily put together a Python program that hit my company's web services API. It worked in three different modes: 1) HTTP with no authentication 2) HTTP with user-name and password authentication 3)...
For user-based and certificate-based authentication, do I want to use urllib, urllib2, or curl?
A few months ago, I hastily put together a Python program that hit my company's web services API. It worked in three different modes: 1) HTTP with no authentication 2) HTTP with user-name and password authentication 3) HTTPS with client certificate authentication I got 1) to work with urllib, but ran into problems wit...
[]
[]
[ "I believe that mechanize is the module you need.\nEDIT: mechanize objects have this method for authentication: add_password(self, url, user, password, realm=None)\n" ]
[ -1 ]
[ "python", "urllib", "urllib2" ]
stackoverflow_0003982291_python_urllib_urllib2.txt
Q: Python easy_install gives [errno13] I'm tring to install Hookbox but without success, when I call easy_install or python setup.py install it gives me [Errno 13] Permission denied: '/usr/local/lib/python2.6/site-packages/test-easy-install-68779.write-test' When I try to grant write permissions to this derectory ...
Python easy_install gives [errno13]
I'm tring to install Hookbox but without success, when I call easy_install or python setup.py install it gives me [Errno 13] Permission denied: '/usr/local/lib/python2.6/site-packages/test-easy-install-68779.write-test' When I try to grant write permissions to this derectory it gives chmod: /usr/local/lib/python2.6/...
[ "You should have used appropriate privilege to install\nsudo python setup.py install\n\nAnother option is to use virtualenv to create a isolated environment where you could install\n\nhttp://pypi.python.org/pypi/virtualenv\n\nAnother way is too install some where, where you have permission.\npython setup.py install...
[ 7 ]
[]
[]
[ "easy_install", "python", "ssh" ]
stackoverflow_0003995339_easy_install_python_ssh.txt
Q: C Lexical analyzer in python I'm creating a C Lexical analyzer using python as part of developing a parser.Here in my code i have written some methods for identifying keywords,numbers,operators etc. No error is shown after compiling. While executing i could input a .c file.My output should list all the keywords,id...
C Lexical analyzer in python
I'm creating a C Lexical analyzer using python as part of developing a parser.Here in my code i have written some methods for identifying keywords,numbers,operators etc. No error is shown after compiling. While executing i could input a .c file.My output should list all the keywords,identifiers etc in the input file. B...
[ "Your code is bad. Try splitting it up into smaller functions that you can test individually. Have you tried debugging the program? Once you find the place that causes the problem, you can come back here and ask a more specific question.\nSome more hints. You can implement isdelim much simpler like this:\ndef isdel...
[ 1, 1, 0 ]
[]
[]
[ "lexical_analysis", "parsing", "python" ]
stackoverflow_0003995439_lexical_analysis_parsing_python.txt
Q: Pylons: accidentally typed 'setup.py install', how can I fix? While working on a Pylons app, I accidentally typed python setup.py install in the home directory of a project, instead of what I meant to type, namely python setup.py egg_info Oops. It looks like the Pylons app has now been installed as a Python pac...
Pylons: accidentally typed 'setup.py install', how can I fix?
While working on a Pylons app, I accidentally typed python setup.py install in the home directory of a project, instead of what I meant to type, namely python setup.py egg_info Oops. It looks like the Pylons app has now been installed as a Python package. Whenever I make changes to the project, they don't get propag...
[ "delete the related content from the dist-packages/site-packages and .egg info files manually\n" ]
[ 2 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0003995837_pylons_python.txt
Q: Stateless pagination in CouchDB? Most of the research I've seen on pagination with CouchDB suggests that what you need to do is take the first ten (or however many) items from your view, then record the last document's docid and pass it on to the next page. Unfortunately, I can see a few glaring issues with that m...
Stateless pagination in CouchDB?
Most of the research I've seen on pagination with CouchDB suggests that what you need to do is take the first ten (or however many) items from your view, then record the last document's docid and pass it on to the next page. Unfortunately, I can see a few glaring issues with that method. It apparently makes it impossi...
[ "I'm new to CouchDB, but I think I might be able to help. I read the following from CouchDB: The Definitive Guide:\n\nOne drawback of the linked list style pagination is that... jumping to a specific page doesn’t really work... If you really do need jump to page over the full range of documents... you can still mai...
[ 3, 1 ]
[]
[]
[ "couchdb", "pagination", "python" ]
stackoverflow_0003081721_couchdb_pagination_python.txt
Q: How can I call a function with delay in python? I have a slider and I want to call a specific function only when the interaction is complete. The idea is to call a function after 500ms (and not before). If the slider continues to move then the call is canceled. In other words, if the slider "rests" for more than 5...
How can I call a function with delay in python?
I have a slider and I want to call a specific function only when the interaction is complete. The idea is to call a function after 500ms (and not before). If the slider continues to move then the call is canceled. In other words, if the slider "rests" for more than 500ms than the function is call. Thanks Update #sl...
[ "Patrick: See this thread - How to create a timer using tkinter?\nYou can use Threading.Timer to do this. It has a cancel method that you can use to cancel it before it runs.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003996083_python.txt
Q: How can I trigger and listen for events in python? How can I trigger and listen for events in python ? I need a practical example.. thanks Update #add Isosurface button def addIso(): #trigger event self.addButton = tk.Button(self.leftFrame, text="Add", command=addIso) #.grid(column=3, row=1) self.addButton.pa...
How can I trigger and listen for events in python?
How can I trigger and listen for events in python ? I need a practical example.. thanks Update #add Isosurface button def addIso(): #trigger event self.addButton = tk.Button(self.leftFrame, text="Add", command=addIso) #.grid(column=3, row=1) self.addButton.pack(in_=self.leftFrame, side="right", pady=2)
[ "There's a bind function for TKinter objects that takes two parameters: the first is a string representing the name of the event you want to listen for (probably \"\" in this case), and the second is a method which takes the triggering event as a parameter.\nExample:\ndef addButton_click(event):\n print 'button ...
[ 1, 1, 1, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003969947_python_tkinter.txt
Q: Python Mechanize + GAEpython code I am aware of previous questions regarding mechanize + Google App Engine, What pure Python library should I use to scrape a website? and Mechanize and Google App Engine. Also there is some code here, which I cannot get to work on app engine, throwing File “D:\data\eclipse-php\te...
Python Mechanize + GAEpython code
I am aware of previous questions regarding mechanize + Google App Engine, What pure Python library should I use to scrape a website? and Mechanize and Google App Engine. Also there is some code here, which I cannot get to work on app engine, throwing File “D:\data\eclipse-php\testpy4\src\mechanize\_http.py”, line 43,...
[ "I have solved this problem, just change the code of mechanize._http.py, about line 43, \nfrom:\ntry:\n socket._fileobject(\"fake socket\", close=True)\nexcept TypeError:\n # python <= 2.4\n create_readline_wrapper = socket._fileobject\nelse:\n def create_readline_wrapper(fh):\n return socket._fi...
[ 10, 1, 0 ]
[]
[]
[ "google_app_engine", "mechanize_python", "python" ]
stackoverflow_0001902079_google_app_engine_mechanize_python_python.txt
Q: else clause in try statement... what is it good for Possible Duplicate: Python try-else Comming from a Java background, I don't quite get what the else clause is good for. According to the docs It is useful for code that must be executed if the try clause does not raise an exception. But why not put the co...
else clause in try statement... what is it good for
Possible Duplicate: Python try-else Comming from a Java background, I don't quite get what the else clause is good for. According to the docs It is useful for code that must be executed if the try clause does not raise an exception. But why not put the code after the try block? It seems im missing something im...
[ "The else clause is useful specifically because you then know that the code in the try suite was successful. For instance:\nfor arg in sys.argv[1:]:\n try:\n f = open(arg, 'r')\n except IOError:\n print 'cannot open', arg\n else:\n print arg, 'has', len(f.readlines()), 'lines'\n ...
[ 19, 3, 3 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0003996329_exception_handling_python.txt
Q: Python with statement - is there a need for old-style file handling any more? With having the with statement, is there ever a need to open a file/check for exceptions/do manual closing of resources, like in try: f = open('myfile.txt') for line in f: print line except IOError: print 'Could not open/read...
Python with statement - is there a need for old-style file handling any more?
With having the with statement, is there ever a need to open a file/check for exceptions/do manual closing of resources, like in try: f = open('myfile.txt') for line in f: print line except IOError: print 'Could not open/read file' finally: f.close()
[ "Your current code tries to handle the exception of the file not being found, or of insufficient access permissions etc., which a with open(file) as f: block wouldn't have done.\nAlso, in this case, the finally: block would have raised a NameError since f wouldn't have been defined.\nIn a with block, any exception ...
[ 5 ]
[]
[]
[ "exception_handling", "python", "with_statement" ]
stackoverflow_0003996358_exception_handling_python_with_statement.txt
Q: Python - Non-matching regex I have the following regex: regex = compile("((?P<lastyear>[\dBFUPR]+)/)*((?P<lastseason>[\dBFUPR]+))*(^|-(?P<thisseason>[\dBFUPR]*))") Which I am using to process horce racing form strings. Sometimes a horses' form will look like this "1234-" meaning that it has not raced yet this sea...
Python - Non-matching regex
I have the following regex: regex = compile("((?P<lastyear>[\dBFUPR]+)/)*((?P<lastseason>[\dBFUPR]+))*(^|-(?P<thisseason>[\dBFUPR]*))") Which I am using to process horce racing form strings. Sometimes a horses' form will look like this "1234-" meaning that it has not raced yet this season (there are no numbers to the ...
[ "This works:\n>>> regex = re.compile(r'(?:(?P<lastyear>[\\dBFUPR]+)/)?(?:(?P<lastseason>[\\dBFUPR]+)-)?(?P<thisseason>[\\dBFUPR]+)?')\n>>> regex.match(\"1234/123-12\").groupdict()\n{'thisseason': '12', 'lastyear': '1234', 'lastseason': '123'}\n>>> regex.match(\"00999F\").groupdict()\n{'thisseason': '00999F', 'lasty...
[ 0 ]
[]
[]
[ "match", "python", "regex" ]
stackoverflow_0003996391_match_python_regex.txt
Q: Is it possible to modify the return value of a function without defining new function in python? def foo(a, b, c = 0): return a+b I have dozens of functions like 'foo', which all have different argument numbers and names. Is there a common way that I can get the return values of these functions and do just a ...
Is it possible to modify the return value of a function without defining new function in python?
def foo(a, b, c = 0): return a+b I have dozens of functions like 'foo', which all have different argument numbers and names. Is there a common way that I can get the return values of these functions and do just a single extra operation like pformat to them? Yes I can just generate a new function like the following...
[ "About your problem :\n\n\n\"But then the new function 'wrapper' is different to the old one 'func', for example, >> in argument number, 'wrapper' has only 2 args--'arg' and 'kw', but 'func' may have many >> args, like 'a', 'b', 'c'.\" \n\n\nyou can use the decorator module which enable you to create a signature-pr...
[ 4, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003995815_python.txt
Q: Updating Feedparser Feeds in Django So I'm writing a basic feed aggregator/popurls clone site in Django and having trouble getting the feeds to update. For each feed source, I have a separate app to parse and return the requested info, for the sake of simplicity let's say it's just getting the feed title. eg: #fee...
Updating Feedparser Feeds in Django
So I'm writing a basic feed aggregator/popurls clone site in Django and having trouble getting the feeds to update. For each feed source, I have a separate app to parse and return the requested info, for the sake of simplicity let's say it's just getting the feed title. eg: #feed source xyz views.py from django.http im...
[ "aggregate is a global variable, so the function get_feed_xyz() is only called when the module loads. You will need to update it inside index().\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003994437_django_python.txt
Q: Python urllib urlencode problem with æøå How can I urlencode a string with special chars æøå? ex. urllib.urlencode('http://www.test.com/q=testæøå') I get this error :(.. not a valid non-string sequence or mapping object A: urlencode is intended to take a dictionary, for example: >>> q= u'\xe6\xf8\xe5' # u'æø...
Python urllib urlencode problem with æøå
How can I urlencode a string with special chars æøå? ex. urllib.urlencode('http://www.test.com/q=testæøå') I get this error :(.. not a valid non-string sequence or mapping object
[ "urlencode is intended to take a dictionary, for example:\n>>> q= u'\\xe6\\xf8\\xe5' # u'æøå'\n>>> params= {'q': q.encode('utf-8')}\n>>> 'http://www.test.com/?'+urllib.urlencode(params)\n'http://www.test.com/?q=%C3%A6%C3%B8%C3%A5'\n\nIf you just want to URL-encode a single string, the function you're looking for is...
[ 26, 9 ]
[]
[]
[ "python", "urlencode", "urllib" ]
stackoverflow_0003996974_python_urlencode_urllib.txt
Q: Why is PyQt application startup so slow? C++ is fast. Qt is fast. Python interpreter startup is relatively fast (2-3 seconds on my computer). PyQt is thin wrapper around Qt. Why then PyQt app startup (about 80 lines, even in .pyc form) is so slow (6-12 seconds)? I'm interested in reasons for this and, most importa...
Why is PyQt application startup so slow?
C++ is fast. Qt is fast. Python interpreter startup is relatively fast (2-3 seconds on my computer). PyQt is thin wrapper around Qt. Why then PyQt app startup (about 80 lines, even in .pyc form) is so slow (6-12 seconds)? I'm interested in reasons for this and, most importantly, ways to improve this situation.
[ "There is a known bug in Qt 4.6.3 that cripples application start times. Maybe 4.4.3 is also affected. Try to upgrade to 4.7.0, which fixes that bug.\nYour problem might also come from dynamic library relocation. If you compile either Qt or Python yourself, try to give them a base address different from the default...
[ 5 ]
[]
[]
[ "performance", "pyqt", "python", "startup" ]
stackoverflow_0003994443_performance_pyqt_python_startup.txt
Q: Exception when running a Python method from another class Here is my code. import urllib2 import urllib import json from BeautifulSoup import BeautifulSoup class parser: """ This class uses the Beautiful Soup library to scrape the information from the HTML source code from Google Translate. It al...
Exception when running a Python method from another class
Here is my code. import urllib2 import urllib import json from BeautifulSoup import BeautifulSoup class parser: """ This class uses the Beautiful Soup library to scrape the information from the HTML source code from Google Translate. It also offers a way to consume the AJAX result of the translation, ...
[ "You have to have an instance of the parser class, not call the method on the class itself.\nfrom Parser import parser\n\nprint parser().fromHTML(\"Hello my lady!\", \"English\", \"Italian\")\n\nor\nfrom Parser import parser\n\np = parser()\np.fromHTML(...)\n\nAlternatively, you could make fromHTML a staticmethod:\...
[ 1, 0 ]
[]
[]
[ "class", "methods", "module", "python" ]
stackoverflow_0003997071_class_methods_module_python.txt
Q: How can I make contents of a txt file be used as subject for mail in linux? I have a crontab file which executes a shell script as shown below 27 11 * * * /usr/python/bi_python/launcher/launch_script_leds.sh The shell script does a number of things: 1)executes python script launcher.py which runs tests and output...
How can I make contents of a txt file be used as subject for mail in linux?
I have a crontab file which executes a shell script as shown below 27 11 * * * /usr/python/bi_python/launcher/launch_script_leds.sh The shell script does a number of things: 1)executes python script launcher.py which runs tests and outputs to log files 2)sends mail notification when tests have completed with test outp...
[ "Try\nsubject=$(</path/subject.txt)\nmailx -s \"$subject\" me@sample.com < /usr/python/bi_python/launcher/test_output.txt\n\n", "Well, just pass the parameter -s to the mail command, with a suitable subject.\nTo use the contents of a file as the subject, just read the file. In Bash,\nfilecontents=$(cat /my/file)\...
[ 3, 0 ]
[]
[]
[ "cron", "email", "linux", "python" ]
stackoverflow_0003997444_cron_email_linux_python.txt
Q: Python generator, non-swallowing exception in 'coroutine' I recently came across some surprising behaviour in Python generators: class YieldOne: def __iter__(self): try: yield 1 except: print '*Excepted Successfully*' # raise for i in YieldOne(): raise Exception('test exception') Wh...
Python generator, non-swallowing exception in 'coroutine'
I recently came across some surprising behaviour in Python generators: class YieldOne: def __iter__(self): try: yield 1 except: print '*Excepted Successfully*' # raise for i in YieldOne(): raise Exception('test exception') Which gives the output: *Excepted Successfully* Traceback (most r...
[ "Your code does not do what you think it does. You cannot raise Exceptions in a coroutine like this. What you do instead is catching the GeneratorExit exception. See what happens when you use a different Exception:\nclass YieldOne:\n def __iter__(self):\n try:\n yield 1\n except RuntimeError:\n p...
[ 14, 6 ]
[]
[]
[ "exception", "generator", "python" ]
stackoverflow_0003997496_exception_generator_python.txt
Q: Replacing Words in TextField In Django In django, in TextField, how to we replace, [vimeo 123456] with <iframe src="http://player.vimeo.com/video/123456" width="400" height="225" frameborder="0"></iframe> Thank you. A: I don't think it's a good idea to have the HTML in the TextField. First, it would make edit...
Replacing Words in TextField In Django
In django, in TextField, how to we replace, [vimeo 123456] with <iframe src="http://player.vimeo.com/video/123456" width="400" height="225" frameborder="0"></iframe> Thank you.
[ "I don't think it's a good idea to have the HTML in the TextField. First, it would make editing a pain (you'd have to write code to translate back, which will be more difficult than forward); second, it would waste disk on storing a lot of HTML in the database; and finally, it would make it harder to fix bugs late...
[ 1, 0 ]
[]
[]
[ "django", "python", "replace" ]
stackoverflow_0003995248_django_python_replace.txt
Q: Class has method that shows in intellisense, but gives an error when running it I'm tring to set the default encoding of my console to UTF-8 so it can display cyrillic letters and accented letters. Here is my code: from Parser import parser import sys print sys.getdefaultencoding() sys.setdefaultencoding('utf-8'...
Class has method that shows in intellisense, but gives an error when running it
I'm tring to set the default encoding of my console to UTF-8 so it can display cyrillic letters and accented letters. Here is my code: from Parser import parser import sys print sys.getdefaultencoding() sys.setdefaultencoding('utf-8') Output: ascii Traceback (most recent call last): File "C:\Users\Sergio.Tapia\Doc...
[ "The function sys.setdefaultencoding() does exist but is removed from sys' dictionary by site.py itself.\nOn my machine, site.py contains the following comment:\n# Remove sys.setdefaultencoding() so that users cannot change the\n# encoding after initialization. The test for presence is needed when\n# this module i...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003997430_python.txt
Q: Can Cython speed up array of object iteration? I want to speed up the following code using cython: class A(object): cdef fun(self): return 3 class B(object): cdef fun(self): return 2 def test(): cdef int x, y, i, s = 0 a = [ [A(), B()], [B(), A()]] for i in xrange(1000): ...
Can Cython speed up array of object iteration?
I want to speed up the following code using cython: class A(object): cdef fun(self): return 3 class B(object): cdef fun(self): return 2 def test(): cdef int x, y, i, s = 0 a = [ [A(), B()], [B(), A()]] for i in xrange(1000): for x in xrange(2): for y in xrange...
[ "Looks like code like this gives about 20x speedup:\nimport numpy as np\ncimport numpy as np\ncdef class Base(object):\n cdef int fun(self):\n return -1\n\ncdef class A(Base):\n cdef int fun(self):\n return 3\n\n\ncdef class B(Base):\n cdef int fun(self):\n return 2\n\ndef test():\n ...
[ 7 ]
[]
[]
[ "cython", "python" ]
stackoverflow_0003988233_cython_python.txt
Q: Can some explain this strange behavior of the hypergeometric distribution in scipy? I am running Python 2.6.5 on Mac OS X 10.6.4 (this is not the native version, I installed it myself) with Scipy 0.8.0. If I do the following: >>> from scipy.stats import hypergeom >>> hypergeom.sf(5,10,2,5) I get an IndexError. Th...
Can some explain this strange behavior of the hypergeometric distribution in scipy?
I am running Python 2.6.5 on Mac OS X 10.6.4 (this is not the native version, I installed it myself) with Scipy 0.8.0. If I do the following: >>> from scipy.stats import hypergeom >>> hypergeom.sf(5,10,2,5) I get an IndexError. Then I do: >>> hypergeom.sf(2,10,2,2) -4.44.... I suspect the negative value is due to bad...
[ "The problem seems to arise based if the first call to the survival function is in the range that should obviously be zero (see my comment to the previous answer). E.g., for calls to hypergeom.sf(x,M,n,N) it fails if the first call to a hypergeometric function to the function is a situation where x > n, where the ...
[ 3, 0 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0003812896_python_scipy.txt
Q: Specific Quote Issue Here is my problem. I have a model Project, that has a quote field in it. When a new instance of project is created I need to append the last 2 digits of the year plus a hyphen onto the start of the "quote" field. Ex. 2010 = "10-". Im just not quite sure how to start it? As of right now I ...
Specific Quote Issue
Here is my problem. I have a model Project, that has a quote field in it. When a new instance of project is created I need to append the last 2 digits of the year plus a hyphen onto the start of the "quote" field. Ex. 2010 = "10-". Im just not quite sure how to start it? As of right now I have hard coded in "10-" i...
[ "Try this:\ndef save(self):\n today = datetime.date.today()\n self.quote = \"%s-%s\" % (str(today.year)[2:4], self.quote)\n\nAssuming you imported datetime.\n", "Your existing quote field is set as an integer. You will need to set this as a text field. Once you do that, you can override the save() functio...
[ 1, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "django_views", "python" ]
stackoverflow_0003997887_django_django_forms_django_models_django_views_python.txt
Q: modelling the google datastore/python Hi I am trying to build an application which has models resembling something like the below ones:-(While it would be easy to merge the two models into one and use them , but that is not feasible in the actual app) class User(db.Model): username=db.StringProperty() em...
modelling the google datastore/python
Hi I am trying to build an application which has models resembling something like the below ones:-(While it would be easy to merge the two models into one and use them , but that is not feasible in the actual app) class User(db.Model): username=db.StringProperty() email=db.StringProperty() class UserLikes(db...
[ "Beside the relation model you have, you could handle this in two other ways depending on your exact use case. You have a good idea in your update, use a ListProperty. Check out Brett Slatkin's taslk on Relation Indexes for some background.\nYou could use a child entity (Relation Index) on user that contains a li...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003995851_google_app_engine_google_cloud_datastore_python.txt
Q: Python: variable is not correctly initialized? I wrote the following code in python self._job = None #slider def sliderCallback(self): if self._job: And I get this error message AttributeError: 'str' object has no attribute '_job' why ? I thought I have initialized the variable before... Update Same issue wi...
Python: variable is not correctly initialized?
I wrote the following code in python self._job = None #slider def sliderCallback(self): if self._job: And I get this error message AttributeError: 'str' object has no attribute '_job' why ? I thought I have initialized the variable before... Update Same issue with Timer variable import Tkinter as tk import vtk fr...
[ "try this:\n\nself.slider = tk.Scale(self.leftFrame, from_=0, to=256, orient=tk.HORIZONTAL, command=self.sliderCallback)\n\nthe difference is the self, when invoked sliderCallback has to be bound to its instance to be useful.\n", "if this is happening in class: try change self._job = None to _job = None - at that...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003996142_python.txt
Q: HTML code processing I want to process some HTML code and remove the tags as in the example: "<p><b>This</b> is a very interesting paragraph.</p>" results in "This is a very interesting paragraph." I'm using Python as technology; do you know any framework I may use to remove the HTML tags? Thanks! A: This questi...
HTML code processing
I want to process some HTML code and remove the tags as in the example: "<p><b>This</b> is a very interesting paragraph.</p>" results in "This is a very interesting paragraph." I'm using Python as technology; do you know any framework I may use to remove the HTML tags? Thanks!
[ "This question may help you: Strip HTML from strings in Python\nNo matter what solution you choose, I'd recommend avoiding regular expressions. They can be slow when processing large strings, they might not work due to invalid HTML, and stripping HTML with regex isn't always secure or reliable.\n", "BeautifulSou...
[ 5, 4, 1, 1, 1 ]
[]
[]
[ "html_parsing", "python" ]
stackoverflow_0003998165_html_parsing_python.txt
Q: Remove differences between two folders can anyone please suggest a method (ruby, python or dos preferable) to remove only the different files and sub-folders between two given folders? I need it to recurse through sub-directories and delete everything that is different. I don't wanna have to install anything, so a...
Remove differences between two folders
can anyone please suggest a method (ruby, python or dos preferable) to remove only the different files and sub-folders between two given folders? I need it to recurse through sub-directories and delete everything that is different. I don't wanna have to install anything, so a script would be great. Thanks in advance
[ "Wouldn't rsync be the better solution? It supports everything you want and does it fast.\n", "You can use Python's difflib to tell what files differ, then os.unlink them. Really, if all you need is to tell if the files differ at all, you can just compare their text with:\nfor file1, file2 in files:\n f1 = ope...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "dos", "python", "ruby" ]
stackoverflow_0003997445_dos_python_ruby.txt
Q: Python Facebook login How can I make a Python script which checks if I have logged in the Facebook? If I haven't, it should log me in. A: Being "logged in" to Facebook (or any system for that matter) is generally a contract between the server and the client - and not just a "flipped bit" on the server. As an exa...
Python Facebook login
How can I make a Python script which checks if I have logged in the Facebook? If I haven't, it should log me in.
[ "Being \"logged in\" to Facebook (or any system for that matter) is generally a contract between the server and the client - and not just a \"flipped bit\" on the server.\nAs an example, if you log into Facebook on you phone - you can't then pull up Facebook on your desktop machine and be logged in.\nIn short - no,...
[ 1 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0003998586_facebook_python.txt
Q: add rights to a folder using python I want to give anyone full access to a specific folder (+sub-folders +files in it). I tried that code: f = "c:\test" #... which is the folder #vars sidWorld = win32security.CreateWellKnownSid(win32security.WinWorldSid, None) worldRights = win32file.FILE_ALL_ACCESS #get DACL fi...
add rights to a folder using python
I want to give anyone full access to a specific folder (+sub-folders +files in it). I tried that code: f = "c:\test" #... which is the folder #vars sidWorld = win32security.CreateWellKnownSid(win32security.WinWorldSid, None) worldRights = win32file.FILE_ALL_ACCESS #get DACL fileSecDesc = win32security.GetNamedSecurit...
[ "Got it after a break: it's so easy:\n#vars\nsidWorld = win32security.CreateWellKnownSid(win32security.WinWorldSid, None)\nworldRights = win32file.FILE_ALL_ACCESS\nflags = win32security.OBJECT_INHERIT_ACE| \\\n win32security.CONTAINER_INHERIT_ACE\n\n#get DACL\nfileSecDesc = win32security.GetNamedSecurityInfo( \\...
[ 4 ]
[]
[]
[ "python", "pywin32" ]
stackoverflow_0003996863_python_pywin32.txt
Q: Why my code doesn't work? Why doesn't this work? for i in [a, b, c]: i.SetBitmap(wx.Bitmap(VarFiles[str(i)])) I get: Traceback (most recent call last): File "<string>", line 11, in ? File "codecc.py", line 724, in ? app = MyApp(0) # stdio to console; nothing = stdio to its own window File "C:\Prog...
Why my code doesn't work?
Why doesn't this work? for i in [a, b, c]: i.SetBitmap(wx.Bitmap(VarFiles[str(i)])) I get: Traceback (most recent call last): File "<string>", line 11, in ? File "codecc.py", line 724, in ? app = MyApp(0) # stdio to console; nothing = stdio to its own window File "C:\Program Files (x86)\WorldViz\Vizard...
[ "As the traceback says you have a KeyError. Since i is an object when you do str(i) you get \"<wx._core.MenuItem; proxy of <Swig Object of type 'wxMenuItem *' at 0x165aeab0> >\", such key doesn't exist in a VarFiles container.\nIt has nothing whatsoever to do with the for loop or the way you write your list.\n", ...
[ 1, 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003998561_python_wxpython.txt
Q: How to convert colors into strings with the same size? I'm converting color values to string values, however when I get 0, the string is too short and I have to manually add "00" after it. Whats the most elegant way to solve this issue in Python ? print "#" + str(self.R) + str(self.G) + str(self.B) if self.R is 0...
How to convert colors into strings with the same size?
I'm converting color values to string values, however when I get 0, the string is too short and I have to manually add "00" after it. Whats the most elegant way to solve this issue in Python ? print "#" + str(self.R) + str(self.G) + str(self.B) if self.R is 0 then I get a too short string.
[ "Use formatting strings:\n\"#%02X%02X%02X\" % (self.r, self.g, self.b)\nwill give you what you probably want. If you actually want your values to be in decimal like in your example, use \"%03d\" instead.\n", "Assuming you are using Python 2.6 or newer you can use str.format:\nprint \"#{0:02}{1:02}{2:02}\".format(...
[ 4, 4, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003999145_python.txt
Q: Detect when column in gtk.treeview is resized What signal can I catch to detect when a column changes size in a gtk.TreeView? I can't seem to find it in the docs. A: gtk.TreeViewColumns aren't widgets so they unfortunately don't have a dedicated signal for size changes. But you can register a callback function t...
Detect when column in gtk.treeview is resized
What signal can I catch to detect when a column changes size in a gtk.TreeView? I can't seem to find it in the docs.
[ "gtk.TreeViewColumns aren't widgets so they unfortunately don't have a dedicated signal for size changes. But you can register a callback function that receives \"width\" change notifications:\ndef onColWidthChange(col, width):\n # Note that \"width\" is a GParamInt object, not an integer\n ...\n\ncol.connect...
[ 7 ]
[]
[]
[ "gtk", "gtktreeview", "pygtk", "python", "signals" ]
stackoverflow_0003999146_gtk_gtktreeview_pygtk_python_signals.txt
Q: What does process exit status 3 mean? I've seen the usage of exit status 3 in several python scripts that restart processes. As far as I know the convention is only about 0 and "not 0" on Unix/Linux. Is there a convention defining other values like 3. A: At least in the old days, a return value of 1 generally m...
What does process exit status 3 mean?
I've seen the usage of exit status 3 in several python scripts that restart processes. As far as I know the convention is only about 0 and "not 0" on Unix/Linux. Is there a convention defining other values like 3.
[ "At least in the old days, a return value of 1 generally meant a hard error and value 2 was usually reserved for problems with the command line arguments — it meant that the user had made an error, not the program. But beyond that: no, no convention; and even that slight convention was not universal. Like dashes in...
[ 10, 4, 0, 0 ]
[]
[]
[ "linux", "process", "python", "status", "unix" ]
stackoverflow_0003996061_linux_process_python_status_unix.txt
Q: Raise child_exception Errno 2 I'm attempting to convert a C header into a Python library using ctypes and ctypeslib. I'm running Python 2.7, on OSX 10.6.4 (Snow Leopard). The header-file I am converting is mcbcio32.h, located in /header/mcbcio32.h I wish to create an xml output in the same folder, named mcbcio32.x...
Raise child_exception Errno 2
I'm attempting to convert a C header into a Python library using ctypes and ctypeslib. I'm running Python 2.7, on OSX 10.6.4 (Snow Leopard). The header-file I am converting is mcbcio32.h, located in /header/mcbcio32.h I wish to create an xml output in the same folder, named mcbcio32.xml. I run h2xml.py (which converts ...
[ "The problem was with the installation of gcc-xml. Make sure when installing gcc-xml to also install the cmake function (cmake.org). Properly using cmake on the gcc install folder solved all the directory problems I was experiencing. \n" ]
[ 1 ]
[]
[]
[ "ctypes", "header_files", "python" ]
stackoverflow_0003833627_ctypes_header_files_python.txt
Q: Help me understand my mod_wsgi Django config file I was wondering why this works: sys.path.append('/home/user/django') sys.path.append('/home/user/django/mysite') os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' but this doesn't? sys.path.append('/home/user/django') os.environ['DJANGO_SETTINGS_MODULE'] ...
Help me understand my mod_wsgi Django config file
I was wondering why this works: sys.path.append('/home/user/django') sys.path.append('/home/user/django/mysite') os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' but this doesn't? sys.path.append('/home/user/django') os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' I thought that adding the django f...
[ "Maybe if in your settings.py you have an import to a module that's inside the mysite directory, this import fails and that's why you get the ImportError.\n", "Have a look at http://codespatter.com/2009/04/10/how-to-add-locations-to-python-path-for-reusable-django-apps/\n" ]
[ 0, 0 ]
[]
[]
[ "django", "mod_wsgi", "python" ]
stackoverflow_0003995830_django_mod_wsgi_python.txt
Q: Can't get argspec for Python callables? I'm playing with Python callable. Basically you can define a python class and implement __call__ method to make the instance of this class callable. e.g., class AwesomeFunction(object): def __call__(self, a, b): return a+b Module inspect has a function getargspe...
Can't get argspec for Python callables?
I'm playing with Python callable. Basically you can define a python class and implement __call__ method to make the instance of this class callable. e.g., class AwesomeFunction(object): def __call__(self, a, b): return a+b Module inspect has a function getargspec, which gives you the argument specification...
[ "If you need this functionality, it is absolutely trivial to write a wrapper function that will check to see if fn has an attribute __call__ and if it does, pass its __call__ function to getargspec.\n", "If you look at the definition of getargspec in the inspect module code on svn.python.org. You will see that it...
[ 10, 7, 0 ]
[]
[]
[ "inspection", "python", "reflection" ]
stackoverflow_0003999463_inspection_python_reflection.txt
Q: Suggestions for writing this small piece of code more elegantly Although it looks terrible, I am not finding a nicer/more efficient way of doing this: ae = np.arange(0.0,1,0.05) aee = np.arange(0.3,1.01,0.345) aef = np.arange(0.3,1.01,0.345) random.shuffle(ae) random.shuffle(aee) random.shuffle(aef) for ite...
Suggestions for writing this small piece of code more elegantly
Although it looks terrible, I am not finding a nicer/more efficient way of doing this: ae = np.arange(0.0,1,0.05) aee = np.arange(0.3,1.01,0.345) aef = np.arange(0.3,1.01,0.345) random.shuffle(ae) random.shuffle(aee) random.shuffle(aef) for item_a in aee: for item_b in ae: for item_c in aef: ...
[ "If you do not want to shuffle the rlist, but the initial lists, then you can try to put the last four lines into a list comprehension:\nrlist = [ colorsys.hsv_to_rgb(b, a, c) for c in aef for b in ae for a in aee ] \n\n", "import numpy as np\nimport random\nimport itertools\nimport colorsys\nhue, saturation, val...
[ 4, 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003971916_python.txt
Q: How can I write a python script equivalent of mdfind using PyObjC bindings and NSMetadataQuery? I want to write the python equivalent of mdfind. I want to use the .Spotlight-V100 metadata and I cannot find a description for the metadata db format used, but NSMetadataQuery seems to be what I need. I'd like to do th...
How can I write a python script equivalent of mdfind using PyObjC bindings and NSMetadataQuery?
I want to write the python equivalent of mdfind. I want to use the .Spotlight-V100 metadata and I cannot find a description for the metadata db format used, but NSMetadataQuery seems to be what I need. I'd like to do this in python using the built in Obj-C bindings, but have not been able to figure out the correct inca...
[ "I got a very simple version working. I don't quite have the predicate correct, as the equivalent mdfind call has additional results. Also, it requires two args, the first is the base pathname to work from with the second being the search term.\nHere is the code:\nfrom Cocoa import *\n\nimport sys\n\nquery = NSMeta...
[ 1 ]
[]
[]
[ "macos", "pyobjc", "python", "spotlight" ]
stackoverflow_0003992003_macos_pyobjc_python_spotlight.txt
Q: Non-critical unittest failures I'm using Python's built-in unittest module and I want to write a few tests that are not critical. I mean, if my program passes such tests, that's great! However, if it doesn't pass, it's not really a problem, the program will still work. For example, my program is designed to work w...
Non-critical unittest failures
I'm using Python's built-in unittest module and I want to write a few tests that are not critical. I mean, if my program passes such tests, that's great! However, if it doesn't pass, it's not really a problem, the program will still work. For example, my program is designed to work with a custom type "A". If it fails t...
[ "As a practical matter, I'd probably use print statements to indicate failure in that case. A more correct solution is to use warnings:\nhttp://docs.python.org/library/warnings.html\nYou could, however, use the logging facility to generate a more detailed record of your test results (i.e. set your \"B\" class failu...
[ 8, 4, 4, 3, 3, 3, 1, 0, 0 ]
[ "You could write your test so that they count success rate. \nWith OCR you could throw at code 1000 images and require that 95% is successful. \nIf your program must work with type A then if this fails the test fails. If it's not required to work with B, what is the value of doing such a test ?\n" ]
[ -1 ]
[ "python", "python_unittest" ]
stackoverflow_0001406552_python_python_unittest.txt
Q: What's more resource intensive? PHP or Python? My current web host allows for up to 25 processes running at once. From what I can figure, Python scripts take up a spot in processes, but PHP doesn't? I get a 500 error if more than 25 processes are running at once (unlikely, but still a hassle), so I was wondering ...
What's more resource intensive? PHP or Python?
My current web host allows for up to 25 processes running at once. From what I can figure, Python scripts take up a spot in processes, but PHP doesn't? I get a 500 error if more than 25 processes are running at once (unlikely, but still a hassle), so I was wondering if it would be easier on the server if I were to por...
[ "It depends on how you have PHP/Python set up. If you have, say, Apache loading PHP via mod_php, then it doesn't actually spawn a new process. Likewise, if you were using, say, Tornado to handle web requests, then the webserver itself is already running the Python process, and thus there's no additional Python proc...
[ 2, 2 ]
[]
[]
[ "php", "python", "resources" ]
stackoverflow_0003999679_php_python_resources.txt
Q: python style: inline function that needs no inlining? I'mm writing gtk code. I often have short callbacks that don't need to be closures, as they are passed all the parameters they need. For example, I have this in a loop when creating some gtk.TreeViewColumns: def widthChanged(MAINCOL, SPEC, SUBCOL, expandable): ...
python style: inline function that needs no inlining?
I'mm writing gtk code. I often have short callbacks that don't need to be closures, as they are passed all the parameters they need. For example, I have this in a loop when creating some gtk.TreeViewColumns: def widthChanged(MAINCOL, SPEC, SUBCOL, expandable): if expandable: return w = MAINCOL.get_width() S...
[ "Go with whatever style is most readable. Don't worry about speed unless your code profiling tools have told you that the area is a hotspot.\n" ]
[ 4 ]
[]
[]
[ "closures", "coding_style", "performance", "python" ]
stackoverflow_0003999989_closures_coding_style_performance_python.txt
Q: Profile python program that forks itself as a daemon Is it possible to run cprofile on a mult-threaded python program that forks itself into a daemon process? I know you can make it work on multi thread, but I haven't seen anything on profiling a daemon. A: Well you can always profile it for a single process or ...
Profile python program that forks itself as a daemon
Is it possible to run cprofile on a mult-threaded python program that forks itself into a daemon process? I know you can make it work on multi thread, but I haven't seen anything on profiling a daemon.
[ "Well you can always profile it for a single process or single thread & optimize. After which make it multi-thread. Am I missing something here?\n" ]
[ 0 ]
[]
[]
[ "cprofile", "daemon", "profiling", "python" ]
stackoverflow_0003999938_cprofile_daemon_profiling_python.txt
Q: Suitable kind of database to track a high volume of changes I am trying to implement a python script which writes and reads to a database to track changes within a 3d game (Minecraft) These changes are done by various clients and can be represented by player name, coordinates (x,y,z), and a description. I am stori...
Suitable kind of database to track a high volume of changes
I am trying to implement a python script which writes and reads to a database to track changes within a 3d game (Minecraft) These changes are done by various clients and can be represented by player name, coordinates (x,y,z), and a description. I am storing a high volume of changes and would like to know what would be ...
[ "Any kind. A NoSQL option like MongoDB might be especially interesting.\n", "PostgreSQL has a cube module that supports simple storage, indexing and spatial operations on 3D points and cubes.\n" ]
[ 0, 0 ]
[]
[]
[ "change_tracking", "database", "python" ]
stackoverflow_0004000072_change_tracking_database_python.txt
Q: Python list help simple Python question: Example list: A = [1,2,3,4,5] I need to generate another list B which is a shallow copy of list A such that B is a new list containing the same elements in the same order (so that I can substitute one of B's elements w/o affecting A). How can I do this? clarification: I wa...
Python list help
simple Python question: Example list: A = [1,2,3,4,5] I need to generate another list B which is a shallow copy of list A such that B is a new list containing the same elements in the same order (so that I can substitute one of B's elements w/o affecting A). How can I do this? clarification: I want to do something lik...
[ "That would be a deep copy, not a shallow one.\nLists copy shallow by default. That's why there's a deepcopy command in the copy module.\nB = copy.deepcopy(A)\nOptionally, B = A[:] will do. But keep deepcopy in mind for future. More complex data types can benefit from it.\n\nAdded Info about copy:\nA shallow copy:\...
[ 8, 5, 3, 3, 3, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004000345_list_python.txt
Q: Most efficient way to remove duplicates from Python list while preserving order and removing the oldest element I've seen a bunch of solutions on the site to remove duplicates while preserving the oldest element. I'm interested in the opposite: removing duplicates while preserving the newest element, for example:...
Most efficient way to remove duplicates from Python list while preserving order and removing the oldest element
I've seen a bunch of solutions on the site to remove duplicates while preserving the oldest element. I'm interested in the opposite: removing duplicates while preserving the newest element, for example: list = ['1234','2345','3456','1234'] list.append('1234') >>> ['1234','2345','3456','1234','1234'] list = unique(list...
[ "Requires the items (or keys) to be hashable, works in-place on list-likes:\ndef inplace_unique_latest(L, key=None):\n if key is None:\n def key(x):\n return x\n seen = set()\n n = iter(xrange(len(L) - 1, -2, -1))\n for x in xrange(len(L) - 1, -1, -1):\n item = L[x]\n k = key(item)\n if k not i...
[ 3 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004000621_list_python.txt
Q: Linux: Pipe into Python (ncurses) script, stdin and termios Apparently this is almost a duplicate of "Bad pipe filedescriptor when reading from stdin in python - Stack Overflow"; however, I believe this case is slightly more complicated (and it is not Windows specific, as the conclusion of that thread was). I'm c...
Linux: Pipe into Python (ncurses) script, stdin and termios
Apparently this is almost a duplicate of "Bad pipe filedescriptor when reading from stdin in python - Stack Overflow"; however, I believe this case is slightly more complicated (and it is not Windows specific, as the conclusion of that thread was). I'm currently trying to experiment with a simple script in Python: I'd...
[ " The problem is that whenever I try the actual piping, that seems to mess up stdin, and the curses window never shows. \n\n[...snip...]\n\n\nAs far as I can see, the issue is: - whenever we pipe strings into the Python script, the Python script loses the reference to the terminal as stdin, and notices that the rep...
[ 12, 1 ]
[]
[]
[ "linux", "ncurses", "pipe", "python", "termios" ]
stackoverflow_0003999114_linux_ncurses_pipe_python_termios.txt
Q: Sum one row of a NumPy array I'd like to sum one particular row of a large NumPy array. I know the function array.max() will give the maximum across the whole array, and array.max(1) will give me the maximum across each of the rows as an array. However, I'd like to get the maximum in a certain row (for example, ro...
Sum one row of a NumPy array
I'd like to sum one particular row of a large NumPy array. I know the function array.max() will give the maximum across the whole array, and array.max(1) will give me the maximum across each of the rows as an array. However, I'd like to get the maximum in a certain row (for example, row 7, or row 29). I have a large ar...
[ "You can easily access a row of a two-dimensional array using the indexing operator. The row itself is an array, a view of a part of the original array, and exposes all array methods, including sum() and max(). Therefore you can easily get the maximum per row like this:\nx = arr[7].max() # Maximum in row 7\ny =...
[ 23 ]
[]
[]
[ "arrays", "numpy", "performance", "python" ]
stackoverflow_0004001067_arrays_numpy_performance_python.txt
Q: How to get a gtkDialog's default response to trigger of the space bar as well I have a messageDialog set up so that its default response is gtk.RESPONSE_OK so the okay button is clicked when the user hits enter even if the okay button does not have focus. I would like to also have the space bar trigget the default...
How to get a gtkDialog's default response to trigger of the space bar as well
I have a messageDialog set up so that its default response is gtk.RESPONSE_OK so the okay button is clicked when the user hits enter even if the okay button does not have focus. I would like to also have the space bar trigget the default_response. What is the best way to do this? This is with python 2.4 in a linux envi...
[ "Connect to the key-press-event signal on the message dialog:\ndef on_dialog_key_press(dialog, event):\n if event.string == ' ':\n dialog.response(gtk.RESPONSE_OK)\n return True\n return False\n\ndialog = gtk.MessageDialog(message_format='Some message', buttons=gtk.BUTTONS_OK_CANCEL)\ndialog.add...
[ 2, 0 ]
[]
[]
[ "dialog", "gtk", "key", "key_bindings", "python" ]
stackoverflow_0004000097_dialog_gtk_key_key_bindings_python.txt
Q: what's the max range for colors in this format: #AABBCC? How can I convert colors from (N, N, N) format to #AABBCC (and #AAABBBCCC) ? thanks A: #FFFFFF, so simple every single char has 0..F range. That is 0..15. So two chars is 0..(16*16-1) -> 0-255 To convert between formats just think about: #AABBCC are three ...
what's the max range for colors in this format: #AABBCC?
How can I convert colors from (N, N, N) format to #AABBCC (and #AAABBBCCC) ? thanks
[ "#FFFFFF, so simple\nevery single char has 0..F range. That is 0..15. So two chars is 0..(16*16-1) -> 0-255\nTo convert between formats just think about:\n#AABBCC are three values AA BB CC. Every single value represents a channel (red, green, blue) that can span from 0 to 255 or from 0 to FF or from 0.0 to 1.0\nif ...
[ 2, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "colors", "python" ]
stackoverflow_0004000137_colors_python.txt
Q: can't 'import time' in python, get 'AttributeError: struct_time' How to solve? Running python on Snow Leopard, and I can't import the 'time' module. Works in ipython. Don't have any .pythonrc files being loaded. Scripts that 'import time' using the same interpreter run fine. Have no idea how to troubleshoot this. ...
can't 'import time' in python, get 'AttributeError: struct_time' How to solve?
Running python on Snow Leopard, and I can't import the 'time' module. Works in ipython. Don't have any .pythonrc files being loaded. Scripts that 'import time' using the same interpreter run fine. Have no idea how to troubleshoot this. Anyone have an idea? [wiggles@bananas ~]$ python2.6 Python 2.6.6 (r266:84292, Sep 1...
[ "Look for a file called time.py. It looks like Python is importing that, instead of the one from the standard library:\n File \"time.py\", line 4, in <module>\n\nThe solution is to rename the file something other than \"time.py\".\nBy the way, you can find the path to the offending file by opening a Python REPL an...
[ 8 ]
[]
[]
[ "import", "python", "time" ]
stackoverflow_0004001211_import_python_time.txt