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: Count how many reads in a data file are in an interval from reference file. Python I am trying to count the number of hits a value in one file(column) falls between an interval from another file (two columns). I am completely stuck on how to map it. I tried something like this: for line in file1: if line[0]=l...
Count how many reads in a data file are in an interval from reference file. Python
I am trying to count the number of hits a value in one file(column) falls between an interval from another file (two columns). I am completely stuck on how to map it. I tried something like this: for line in file1: if line[0]=line2[0] and line2[1]<line[1]<line2[2]: print line I'm not sure if this is correct. ...
[ "Assuming your lines match up one-to-one (so you want to test whether the value on the first line of one file lies between the values on the first line of the other, second line to second line, etc), you can zip the two files to iterate over them in step:\nwith open(...) as interval_file, open(...) as value_file:\n...
[ 0, 0 ]
[]
[]
[ "intervals", "mapping", "python" ]
stackoverflow_0007259086_intervals_mapping_python.txt
Q: Scons Glob and Builder - Only building first file in Glob I have a Builder that looks like this: baseEnv['COMPILEPROPERCOM'] = '$CXX -S -o ${TARGET.file} -c $CPPFLAGS -fPIC $COMPILE_PROPER_PATH $COMPILE_PROPER_DEFINES ${SOURCE.file}' compileProperAction = Action('$COMPILEPROPERCOM') compileProper_bld = Bui...
Scons Glob and Builder - Only building first file in Glob
I have a Builder that looks like this: baseEnv['COMPILEPROPERCOM'] = '$CXX -S -o ${TARGET.file} -c $CPPFLAGS -fPIC $COMPILE_PROPER_PATH $COMPILE_PROPER_DEFINES ${SOURCE.file}' compileProperAction = Action('$COMPILEPROPERCOM') compileProper_bld = Builder(action=compileProperAction, suffix = '.s_', chdir=1) And ...
[ "I would write it like this :\nimport os, glob\nfor filename in glob('*.c'):\n asm = libEnv.cp(filename, os.path.split(filename)[0] + \".cpp\")\n\nHope it helps.\n", "After attacking it a different way thanks to Louis's answer, what ended up working for me was to call the builders like so.\ninstrAsm = []\nfor ...
[ 1, 1 ]
[]
[]
[ "python", "scons" ]
stackoverflow_0007231257_python_scons.txt
Q: Automatically call common initialization code without creating __init__.py file I have two directories in my project: project/ src/ scripts/ "src" contains my polished code, and "scripts" contains one-off Python scripts. I would like all the scripts to have "../src" added to their sys.path, so that they can ...
Automatically call common initialization code without creating __init__.py file
I have two directories in my project: project/ src/ scripts/ "src" contains my polished code, and "scripts" contains one-off Python scripts. I would like all the scripts to have "../src" added to their sys.path, so that they can access the modules under the "src" tree. One way to do this is to write a scripts/__i...
[ "Even if you have other plans for distribution, it might be worth putting together a basic setup.py in your src folder. That way, you can run setup.py develop to have distutils put a link to your code onto your default path (meaning any changes you make will be reflected in-place without having to \"reinstall\", an...
[ 4, 1, 1 ]
[]
[]
[ "python", "python_module", "pythonpath", "scripting" ]
stackoverflow_0007250632_python_python_module_pythonpath_scripting.txt
Q: modified a given list inside a function i would like to assign new values to the list i pass to my functions. At the case of get_p_values it works fine, but at `read_occupation' not (I get as an output: [[0], [0], [0], [0]] instead of [[1,2,3], [1,2,3], [1,2,3], [1,2,3]]). Remark, the reason i pass to function rea...
modified a given list inside a function
i would like to assign new values to the list i pass to my functions. At the case of get_p_values it works fine, but at `read_occupation' not (I get as an output: [[0], [0], [0], [0]] instead of [[1,2,3], [1,2,3], [1,2,3], [1,2,3]]). Remark, the reason i pass to function read_occupation the list matrix[ index ] is that...
[ "Except for what Sylvain said, of course it still didn't work because a process can't modify the variables of its parent process. The variables are copied when a new process is created.\nYou can try the following example.\nfrom multiprocessing import Process\n\ndef modify(idx, li):\n li[idx] = 'hello'\n\na = [0]...
[ 3, 2, 1, 0 ]
[]
[]
[ "function", "multiprocessing", "python" ]
stackoverflow_0007259695_function_multiprocessing_python.txt
Q: How to Create a python Dll file that should be used in C#.net? I have to create a win32 python dll file which can used in C#.Net code. And access the classes & functions present in the dll file through C#. Is there any way to create a win32 python dll? Please help me out.... A: You can compile your Python source...
How to Create a python Dll file that should be used in C#.net?
I have to create a win32 python dll file which can used in C#.Net code. And access the classes & functions present in the dll file through C#. Is there any way to create a win32 python dll? Please help me out....
[ "You can compile your Python sources to a DLL with pyc.py, in the Samples directory of IronPython. However, you can't load this DLL from C# directly - you'll still need to host IronPython, but then you can reference the DLL with the IronPython engine and import from it.\n", "Try do some investigation about Pyrex....
[ 1, 0, 0 ]
[]
[]
[ ".net", "c#", "ironpython", "python" ]
stackoverflow_0007201899_.net_c#_ironpython_python.txt
Q: Python Reference to Member Variable Which is Immutable I'm having a problem with not being able to reference a member variable indirectly. I have a class with a function which does one thing. This function uses a member variable during its execution, and which member variable it uses is dependent on the input par...
Python Reference to Member Variable Which is Immutable
I'm having a problem with not being able to reference a member variable indirectly. I have a class with a function which does one thing. This function uses a member variable during its execution, and which member variable it uses is dependent on the input parameter cmd. Here's some code: class Foo(object): def __i...
[ "In this particular case, I would simply keep track of the string name of the attribute you're interested in. something like: \nclass Foo(object):\n def __init__(self):\n self.a = 0\n self.b = 0\n\n def bar(self, cmd):\n if cmd == \"do_this\":\n index_name = 'a'\n elif ...
[ 3, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007259613_python.txt
Q: Python exception KeyError question This is really a rookie question, but I couldn't figure out how to debug so here I am. The Python official document says: "exception KeyError: Raised when a mapping (dictionary) key is not found in the set of existing keys." Simple enough. I'm writing Python code to generate a n...
Python exception KeyError question
This is really a rookie question, but I couldn't figure out how to debug so here I am. The Python official document says: "exception KeyError: Raised when a mapping (dictionary) key is not found in the set of existing keys." Simple enough. I'm writing Python code to generate a nested dictionary, starting with the oute...
[ "Try the following:\nfor line in avr:\n try:\n print (dict1[arg[0]], dict1[newTyp], dict1[dev], arg)\n except KeyError:\n import sys, pdb\n pdb.post_mortem(sys.exc_info()[2])\n\nThen run it with the process still at a console and you can inspect the stack at the point of your error and se...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0007260205_python.txt
Q: toward iPython: easy_install can't find my Python(s) on Mac OS 10.5.8 Installed setuptools-0.6c11-py2.7.egg on my Mac OS 10.5.8 but then sudo easy_install readline ipython yields a possible script problem? Processing readline-6.2.0.tar.gz Running readline-6.2.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-...
toward iPython: easy_install can't find my Python(s) on Mac OS 10.5.8
Installed setuptools-0.6c11-py2.7.egg on my Mac OS 10.5.8 but then sudo easy_install readline ipython yields a possible script problem? Processing readline-6.2.0.tar.gz Running readline-6.2.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-N_JiZD/readline- 6.2.0/egg-dist-tmp-9IRgCS No eggs found in /tmp/easy_inst...
[ "Which version of python is easy_install for? Look at the top of the file listed by which easy_install. I'll bet it's Python 2.6. See if you have an easy_install-2.7 or somesuch and use that instead if you do. If not, then make sure you reinstall setuptools with the right python version.\nFinally, I don't think...
[ 3 ]
[]
[]
[ "easy_install", "ipython", "macos", "python", "setuptools" ]
stackoverflow_0007259672_easy_install_ipython_macos_python_setuptools.txt
Q: Converting a list of strings in a numpy array in a faster way br is the name of a list of strings that goes like this: ['14 0.000000 -- (long term 0.000000)\n', '19 0.000000 -- (long term 0.000000)\n', '22 0.000000 -- (long term 0.000000)\n', ... I am interested in the first two columns, which I would like to c...
Converting a list of strings in a numpy array in a faster way
br is the name of a list of strings that goes like this: ['14 0.000000 -- (long term 0.000000)\n', '19 0.000000 -- (long term 0.000000)\n', '22 0.000000 -- (long term 0.000000)\n', ... I am interested in the first two columns, which I would like to convert to a numpy array. So far, I've come up with the following so...
[ "This is dramatically faster for me:\nimport numpy as N\n\nbr = ['14 0.000000 -- (long term 0.000000)\\n']*50000\naa = N.zeros((len(br), 2))\n\nfor i,line in enumerate(br):\n al, strs = aa[i], line.split(None, 2)[:2]\n al[0], al[1] = float(strs[0]), float(strs[1])\n\nChanges:\n\nPreallocate the numpy array (t...
[ 4, 2, 1 ]
[]
[]
[ "list", "numpy", "python", "string" ]
stackoverflow_0007260010_list_numpy_python_string.txt
Q: Python tracing and conditional jumps I'm writing a concolic engine for Python using the sys.settrace() functionality. The main task during such kind of execution is to record the constraints on the input variables. The constraints are nothing else than the conditions of the if statements, that create two branches ...
Python tracing and conditional jumps
I'm writing a concolic engine for Python using the sys.settrace() functionality. The main task during such kind of execution is to record the constraints on the input variables. The constraints are nothing else than the conditions of the if statements, that create two branches (the 'then' and the 'else' branch). When a...
[ "There is no information in the trace facility about the last branch taken.\nWhat I did to implement branch coverage measurement in coverage.py is to keep a record for each stack frame of the last line executed, then the next time the trace function is called, I can record a pair of line numbers which form a from-t...
[ 6, 4 ]
[]
[]
[ "branch", "python", "testing", "trace" ]
stackoverflow_0006943852_branch_python_testing_trace.txt
Q: Python source code recovery from exe I had a python program written which I converted to an exe binary using py2exe. I have all of the files generated in the dist folder but due to a system crash, I lost the source code. Is there a way to get the .py source code file back from .exe or other supporting files genera...
Python source code recovery from exe
I had a python program written which I converted to an exe binary using py2exe. I have all of the files generated in the dist folder but due to a system crash, I lost the source code. Is there a way to get the .py source code file back from .exe or other supporting files generated by py2exe?
[ "According to the following links, you can extract your .pyc files from library.zip and then use decompyle to obtain .py files similar to what you started with.\nhttp://bytes.com/topic/python/answers/101743-py2exe-there-way-go-backwards-exe2py\nhttp://sourceforge.net/projects/decompyle/\nHope it works, and I hope y...
[ 5 ]
[]
[]
[ "python", "recovery" ]
stackoverflow_0007260602_python_recovery.txt
Q: New to Pylons and Trying to Understand Routes I am new to pylon and trying to understand this piece of code: map.connect(':controller/:action/:id') Any help would be much appreciated, thanks in advance! A: That's a generic route that tells pylons approximately to "Split up an incoming request url into three par...
New to Pylons and Trying to Understand Routes
I am new to pylon and trying to understand this piece of code: map.connect(':controller/:action/:id') Any help would be much appreciated, thanks in advance!
[ "That's a generic route that tells pylons approximately to \"Split up an incoming request url into three parts, try to find a controller classed named after the first path item, with a method named after the second. If that exists call it with the third path item as argument.\" These kinds of paths are common for...
[ 2 ]
[]
[]
[ "pylons", "python", "routes" ]
stackoverflow_0007259254_pylons_python_routes.txt
Q: Proper way of avoiding to store the same attachment twice I'm using the project.task model where delegation creates a parent/child link between both. When delegating I would like the person who gets the delegated task to also have access to the attachments on the original task, how could I avoid to have to really ...
Proper way of avoiding to store the same attachment twice
I'm using the project.task model where delegation creates a parent/child link between both. When delegating I would like the person who gets the delegated task to also have access to the attachments on the original task, how could I avoid to have to really copy it? I've thought about using an <act_window> or a wizard w...
[ "I think building a wizard is the only way that will work, because there isn't a real link between attachment and project.task. If I were you, I would build a wizard that walks the parent relation to build a list of all ancestor task ids, plus the current task id. Then have the wizard open the attachment window usi...
[ 1 ]
[]
[]
[ "openerp", "project", "python", "task" ]
stackoverflow_0006151975_openerp_project_python_task.txt
Q: Python install python-ntlm-1.0 I downloaded the python-ntlm-1.0.tar.gz and am trying to install. I extracted the .tar file to its own directory (C:\python-ntlm-1.0) and executed the following command in the command prompt from that directory: C:\python27\python.exe C:\Python27\Tools\Scripts\setup.py install I ge...
Python install python-ntlm-1.0
I downloaded the python-ntlm-1.0.tar.gz and am trying to install. I extracted the .tar file to its own directory (C:\python-ntlm-1.0) and executed the following command in the command prompt from that directory: C:\python27\python.exe C:\Python27\Tools\Scripts\setup.py install I get the following output: running inst...
[ "You need to read up on handling archives. See the tar.gz section of that linked doc. You've only uncompressed the tar file, not extracted the contained files.\n" ]
[ 4 ]
[]
[]
[ "ntlm", "python" ]
stackoverflow_0007260810_ntlm_python.txt
Q: Adding REST behavior to a class with flask, case for blueprints? I am dealing with a python application that consists of multiple distributed lightweight components that communicate using RabbitMQ & Kombu. A component listens on two queues and can receive multiple message types on each queue. Subclasses can overr...
Adding REST behavior to a class with flask, case for blueprints?
I am dealing with a python application that consists of multiple distributed lightweight components that communicate using RabbitMQ & Kombu. A component listens on two queues and can receive multiple message types on each queue. Subclasses can override how each message type is processed by registering custom handlers....
[ "Something else was quietly introduced in Flask 0.7 that might be of interest to you - Pluggable Views. These are class based rather than function based endpoints - so you can use the dispatch_request method to manage your state transitions (only overriding it when needed). \nThe benefit of doing it this way, as ...
[ 11 ]
[]
[]
[ "amqp", "design_patterns", "flask", "python", "rest" ]
stackoverflow_0007256889_amqp_design_patterns_flask_python_rest.txt
Q: Saving appengine db Key value into memcache After fetching an entity from the datastore, I'd like to save its key into memcache and also pass it as part of a url parameter for a task for referencing it later. However, since Key is a composite item, you can't forward it as is and when I try to re-construct the key,...
Saving appengine db Key value into memcache
After fetching an entity from the datastore, I'd like to save its key into memcache and also pass it as part of a url parameter for a task for referencing it later. However, since Key is a composite item, you can't forward it as is and when I try to re-construct the key, the values aren't identical. What's the best ap...
[ "See http://code.google.com/appengine/docs/python/datastore/keyclass.html#Key\nA key can be encoded to a string by passing the Key object to str() (or calling the object's __str__() method). A string-encoded key is an opaque value using characters safe for including in URLs. The string-encoded key can be converted ...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007260854_google_app_engine_python.txt
Q: python pyramid mongo and wsgi : "Cannot connect to the database" in production I trying to run a pyramid+mongodb at dotcloud with this wsgi.py import os, sys from paste.deploy import loadapp current_dir = os.path.dirname(__file__) application = loadapp('config:production.ini', relative_to=current_dir) production....
python pyramid mongo and wsgi : "Cannot connect to the database" in production
I trying to run a pyramid+mongodb at dotcloud with this wsgi.py import os, sys from paste.deploy import loadapp current_dir = os.path.dirname(__file__) application = loadapp('config:production.ini', relative_to=current_dir) production.ini mongodb.url = mongodb://root:PASSWORD@sarasa.dotcloud.com:18145 mongodb.db_name ...
[ "Your URI should look like this:\nmongodb://root:PASSWORD@sarasa.dotcloud.com:18145/my_data_base\n" ]
[ 1 ]
[]
[]
[ "configuration", "dotcloud", "mongodb", "pyramid", "python" ]
stackoverflow_0007260735_configuration_dotcloud_mongodb_pyramid_python.txt
Q: CORBA IIOPNet and OmniORBpy, remote method call with valuetype param issue My scope: I'm trying to create a CORBA solution for two apps one at .NET side (server) and the other on python (client). I'm using IIOPNet for server and IDLs generation and OmniORBpy for Stubs generations and client calls. In general is wo...
CORBA IIOPNet and OmniORBpy, remote method call with valuetype param issue
My scope: I'm trying to create a CORBA solution for two apps one at .NET side (server) and the other on python (client). I'm using IIOPNet for server and IDLs generation and OmniORBpy for Stubs generations and client calls. In general is working for simple calls like the typical example: Adder. But when a i try to call...
[ "I think that you forgot to add the interface stub, generated by IDLCompiler.\npublic class MyRemoteObject : MarshalByRefObject, module1.module2.module3.MyRemoteObject\n{\n public override object InitializeLifetimeService()\n {\n return null;\n }\n\n public bool DoSomething(InterfaceRequest reque...
[ 1 ]
[]
[]
[ ".net", "corba", "iiop", "python" ]
stackoverflow_0007239257_.net_corba_iiop_python.txt
Q: Recursively traverse directory and replace function calls I would like to traverse a directory recursively and find all files that have at least one of the function calls of the following set: A(a) B(a,b) C(a,b,c) now, disregarding the arguments I can get a list of such files with grep -r -l '[A-C](' . although ...
Recursively traverse directory and replace function calls
I would like to traverse a directory recursively and find all files that have at least one of the function calls of the following set: A(a) B(a,b) C(a,b,c) now, disregarding the arguments I can get a list of such files with grep -r -l '[A-C](' . although I am sure I can also match the arguments somehow. On these file...
[ "find -type f -exec perl -i.bak -pe'\n if (my ($orig, $pre, $func, $args, $post) =\n /^((.*)\\b(A|B|C)\\((.*?)\\)(.*?))\\n/s\n ) {\n $args = join ', ', map { \"f($_)\" } split /,\\s*/, $args;\n $_ = \"#ifdef LOL\\n\";\n $_ .= $pre${func}_new($args)$post\\n\";\n $_ .= \"#else\\n\";\...
[ 1, 1 ]
[]
[]
[ "bash", "grep", "perl", "python", "sed" ]
stackoverflow_0007260802_bash_grep_perl_python_sed.txt
Q: Running a Python script saved on a Windows 7 server... on a Mac? We have a server running Windows 7 Pro. I have several Python script I'd like to save to the server and have it so that client computers can run them by simply double-clicking. The client computers are all running OSX. This is proving to be... proble...
Running a Python script saved on a Windows 7 server... on a Mac?
We have a server running Windows 7 Pro. I have several Python script I'd like to save to the server and have it so that client computers can run them by simply double-clicking. The client computers are all running OSX. This is proving to be... problematic. First I tried to simply make the Python scripts executable, but...
[ "This is probably what you're looking for: http://oreilly.com/catalog/samba/chapter/book/ch05_03.html says that Samba clients (that OS X uses to connect to Windows shares) can map archive/hidden/system file attributes to owner/group/world executable bits respectively.\nTry setting those attributes on the script fil...
[ 1, 0 ]
[]
[]
[ "macos", "python", "windows_7" ]
stackoverflow_0007261242_macos_python_windows_7.txt
Q: Way to allow for duplicate many-to-many entries in Python/Django I have the following Django model: class Icon(models.Model): name = models.CharField(max_length=200,null=False,blank=False) class Post(models.Model): icons = models.ManyToManyField(Icon) When I write the following code: post = Post() icons ...
Way to allow for duplicate many-to-many entries in Python/Django
I have the following Django model: class Icon(models.Model): name = models.CharField(max_length=200,null=False,blank=False) class Post(models.Model): icons = models.ManyToManyField(Icon) When I write the following code: post = Post() icons = [] icon_id = form.cleaned_data['icon_1'] if (icon_id): i = Icon....
[ "Define the model yourself, to have such non-unique many-to-many relations\nclass PostIcon(models.Model):\n post = models.ForeignKey(Post)\n icon = models.ForeignKey(Icon)\n\nand than add them one by one\nfor icon in icons:\n PostIcon(post=post, icon=icon).save()\n\nor pass that model as through argument o...
[ 13 ]
[]
[]
[ "django", "many_to_many", "manytomanyfield", "python" ]
stackoverflow_0007260716_django_many_to_many_manytomanyfield_python.txt
Q: Iterating through a python list of list and creating a new list Basically, I have a dictionary of the form: 'the trip':('The Trip','www.SearchHero.com',"See sponsored listings for 'The Trip.' Click here!",0.1,'The Trip','3809466'), 'post office':('Post Office','www.SearchHero.com',"See sponsored listings for 'Pos...
Iterating through a python list of list and creating a new list
Basically, I have a dictionary of the form: 'the trip':('The Trip','www.SearchHero.com',"See sponsored listings for 'The Trip.' Click here!",0.1,'The Trip','3809466'), 'post office':('Post Office','www.SearchHero.com',"See sponsored listings for 'Post Office.' Click here!",0.1,'Post Office','5803938'), 'balanced diet...
[ "A basic example:\n['%f, %s' % (x,y) for _,_,_,x,_,y in d.values()]\n\nyou can adapt the format string to have more control over the output.\nThe underlying syntax construct is called a list comprehension\n", "[', '.join((value[3], value[5])) for value in my_dict.iteritems()]\n\n" ]
[ 3, 1 ]
[]
[]
[ "enumeration", "python", "ruby" ]
stackoverflow_0007261489_enumeration_python_ruby.txt
Q: os.walk and read file, having some problems with walking the path Here is the entirety of my code, I am trying to debug it, but it seems like I can't do any reading of files while using os.walk. The problem is that without changing directories, I am hit with a error that 'out.csv' cannot be found, so i put in a c...
os.walk and read file, having some problems with walking the path
Here is the entirety of my code, I am trying to debug it, but it seems like I can't do any reading of files while using os.walk. The problem is that without changing directories, I am hit with a error that 'out.csv' cannot be found, so i put in a chdir(), to move to that directory to read that file, but now it will on...
[ "Remove chdir and do f = csv.reader(open(os.path.join(root, 'out.csv'),'rb'))\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007261545_python.txt
Q: How to structure this OpenCL brute-force code I'm just starting to play about with OpenCL, and I'm stuck with how to structure the program in a reasonably efficient manner (mainly avoiding lots of transferring of data to/from the GPU or wherever the work is being done) What I'm trying to do is, given: v = r*i + b*...
How to structure this OpenCL brute-force code
I'm just starting to play about with OpenCL, and I'm stuck with how to structure the program in a reasonably efficient manner (mainly avoiding lots of transferring of data to/from the GPU or wherever the work is being done) What I'm trying to do is, given: v = r*i + b*j + g*k ..I know v for various values of r, g and ...
[ "Are i,j,k sets independent? I assumed that yes. Few things hurts your performance:\n\nrunning too many small kernels\nusing global memory for communication between score_matrix and rm_to_rms\n\nYou could rewrite both kernels into one with following changes:\n\nmake that one OpenCL work-group would work on differen...
[ 1, 1 ]
[]
[]
[ "algorithm", "brute_force", "opencl", "python" ]
stackoverflow_0007258931_algorithm_brute_force_opencl_python.txt
Q: How to find and split a string by repeated characters? I am trying to split a string into a list, separated by a change in character, in python. I am finding this very difficult, but am sure that I am over thinking it and missing a probably simple solution. Example: 'abgg22ffeeekkkk1zzabbb' would become: ['a', 'b...
How to find and split a string by repeated characters?
I am trying to split a string into a list, separated by a change in character, in python. I am finding this very difficult, but am sure that I am over thinking it and missing a probably simple solution. Example: 'abgg22ffeeekkkk1zzabbb' would become: ['a', 'b', 'gg', '22', 'ff', 'eee', 'kkkk', '1', 'zz', 'a', 'bbb']
[ "import itertools\n[''.join(value) for key, value in itertools.groupby(my_str)]\n\n", ">>> import re\n>>> my_str = 'abgg22ffeekkkk1zzabbb'\n>>> [m.group() for m in re.finditer(r'(.)\\1*', my_str)]\n['a', 'b', 'gg', '22', 'ff', 'ee', 'kkkk', '1', 'zz', 'a', 'bbb']\n\n" ]
[ 7, 3 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007261523_python_string.txt
Q: Can I use file.readline in a blocking manner? Am I doing this right? I'm trying to write a something that monitors a log file and adds a timestamp when it sees a complete line: import sys f = open(sys.argv[1]) if not f: print 'Failed to open %s' % sys.argv[1] print sys.argv[1] import time try: while T...
Can I use file.readline in a blocking manner? Am I doing this right?
I'm trying to write a something that monitors a log file and adds a timestamp when it sees a complete line: import sys f = open(sys.argv[1]) if not f: print 'Failed to open %s' % sys.argv[1] print sys.argv[1] import time try: while True: line = f.readline().replace('\n', '') if not line: ...
[ "\nTest file size with os.path.getsize to see if there is a difference in the file\nf.readline only if there is a difference in size\nEvery time you read call seek first to make sure you are actually reading the last line.\nUse f.readline()[0:-1] to get rid of the trailing \\n (thanks to rm for pointing out that rs...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007260542_python.txt
Q: Memory allocated to Python is not released back in Linux even after gc.collect() I have written code within Python that doesn't release memory the way it should. The memory is taken by Python but never gets released even after not being used anymore. Even if you break the running program with ctrl+c. Delete the va...
Memory allocated to Python is not released back in Linux even after gc.collect()
I have written code within Python that doesn't release memory the way it should. The memory is taken by Python but never gets released even after not being used anymore. Even if you break the running program with ctrl+c. Delete the variable and run gc.collect() it doesn't seem to collect. Or the same as in Ipython and ...
[ "Virtual memory is not a scarce resource. There is no need to return it to the system since each process has its own address space. What is your actual problem? What issue is this behavior causing you?\n", "I had installed the latest svn of numpy and the issue had vanished. I assume it was inside one of the numpy...
[ 2, 0 ]
[]
[]
[ "garbage_collection", "malloc", "memory_management", "numpy", "python" ]
stackoverflow_0005975255_garbage_collection_malloc_memory_management_numpy_python.txt
Q: SQLAlchemy configuring many-to-many relationship to self using Association I am having problems configuring a many to many relationship to a model itself. I can configure a self-many-to-many relation when I use anormal relationship configuration i.e. one not using an Association object. In this scenario I have to ...
SQLAlchemy configuring many-to-many relationship to self using Association
I am having problems configuring a many to many relationship to a model itself. I can configure a self-many-to-many relation when I use anormal relationship configuration i.e. one not using an Association object. In this scenario I have to record some extra information in the many-to-many table itself so I'm trying to ...
[ "The association object pattern is not a sepecialization of the many-to-many relationship, but rather a special case of one-to-many relationships where you have a left_table - Many-To-One - association_table - One-To-Many - right_table set up. In short, you need two relationships, neither of which should have a se...
[ 5 ]
[]
[]
[ "flask_sqlalchemy", "orm", "python", "sqlalchemy" ]
stackoverflow_0007261383_flask_sqlalchemy_orm_python_sqlalchemy.txt
Q: extracing data from websites using python I'm pretty new to web development and I have an idea for something that I would like to explore and I'd like some advice on what tools I should use. I know python and have been learning django recently so I would ideally like to incorporate them. What I want to do is rela...
extracing data from websites using python
I'm pretty new to web development and I have an idea for something that I would like to explore and I'd like some advice on what tools I should use. I know python and have been learning django recently so I would ideally like to incorporate them. What I want to do is related to some basic html parsing and use of regul...
[ "For the extraction part I think your best bet would be Beautiful soup mostly beacause it's easy to use and would try to parse anything even broken xml/html.\n", "Check out BeautifulSoup\nUpdate:\nIf you want to fill forms you can use mechanize\n" ]
[ 3, 1 ]
[]
[]
[ "django", "python", "regex" ]
stackoverflow_0007262218_django_python_regex.txt
Q: how to random a list using python this is my code : import random a = [12,2,3,4,5,33,14,124,55,233,565] b=[] for i in a: b.append(random.choice(a)) print a,b but i think maybe has a method like sort named randomList has this method in python . thanks A: import random a = [12,2,3,4,5,33,14,124,55,233,565]...
how to random a list using python
this is my code : import random a = [12,2,3,4,5,33,14,124,55,233,565] b=[] for i in a: b.append(random.choice(a)) print a,b but i think maybe has a method like sort named randomList has this method in python . thanks
[ "import random\n\na = [12,2,3,4,5,33,14,124,55,233,565]\n\nb = a[:]\nrandom.shuffle(b)\n\n# b: [55, 12, 33, 5, 565, 3, 233, 2, 124, 4, 14]\n\nThis will not modify a.\nTo modify a inplace, just do random.shuffle(a).\n", "I think you are looking for random.shuffle.\n", "you could use random.shuffle \nrandom.shuff...
[ 5, 3, 2, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006120818_list_python.txt
Q: LXML itertree parsing tag information I have been searching around for answers, but I can't seem to find anything. Using lxml to iterparse through xml, I have been trying to get data from within a tag. For example, I have the xml: <line number="0">Line 1</line> <line number="1">Line 2</line> <line number="2">Line...
LXML itertree parsing tag information
I have been searching around for answers, but I can't seem to find anything. Using lxml to iterparse through xml, I have been trying to get data from within a tag. For example, I have the xml: <line number="0">Line 1</line> <line number="1">Line 2</line> <line number="2">Line 3</line> I need to be able to read < lin...
[ "To get information from an etree element you can do:\n>>> elem.tag\n'line'\n>>> elem.get('number')\n'2'\n>>> elem.text\n'Line 3'`\n\n" ]
[ 3 ]
[]
[]
[ "lxml", "parsing", "python", "xml" ]
stackoverflow_0007261995_lxml_parsing_python_xml.txt
Q: How do I get a reference for the current class object? In Python, how do I get a reference to the current class object within a class statement? Example: def setup_class_members(cls, prefix): setattr(cls, prefix+"_var1", "hello") setattr(cls, prefix+"_var2", "goodbye") class myclass(object): setup_c...
How do I get a reference for the current class object?
In Python, how do I get a reference to the current class object within a class statement? Example: def setup_class_members(cls, prefix): setattr(cls, prefix+"_var1", "hello") setattr(cls, prefix+"_var2", "goodbye") class myclass(object): setup_class_members(cls, "coffee") # How to get "cls"? def my...
[ "For Python 3, the class must be declared as\nclass myclass(object, metaclass = Meta):\n prefix = \"coffee\"\n ...\n\n\nA few other points:\n\nThe metaclass may be a callable, not just a class (Python 2&3)\nIf the base class of your class already has a non-standard metaclass, you have to make sure you call it's...
[ 4, 3, 2, 1 ]
[]
[]
[ "pyqt", "python", "python_3.x" ]
stackoverflow_0007260370_pyqt_python_python_3.x.txt
Q: Django url include module showing the urls separated by an space This is my problem now, have a Django project named 'personal' with an urls.py file like this: # file personal/urls.py from django.conf.urls.defaults import * ### SAB urlpatterns = patterns('', (r'^sab/', include('personal.sab.s...
Django url include module showing the urls separated by an space
This is my problem now, have a Django project named 'personal' with an urls.py file like this: # file personal/urls.py from django.conf.urls.defaults import * ### SAB urlpatterns = patterns('', (r'^sab/', include('personal.sab.sab_urls')), ) ### STK urlpatterns += patterns('', ...
[ "It doesn't appear that you have a url defined for http://localhost/test_app/ only for http://localhost/test_app/view_1\nSomething along the lines of the following should work (in test_app/urls.py):\nurlpatterns = patterns('personal.test_app',\n (r'^$', 'test_app_index'),\n (r'^view_1/$', 'view_1'),\n)\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_urls", "module", "python" ]
stackoverflow_0007262384_django_django_urls_module_python.txt
Q: Find the default application name for a given file In Linux, is there a way to ask any xdg services, or gtk services, which application is the default application for a given file? I realize that xdg-open will in fact, launch the correct application. However, I want to be able to display the application's name in...
Find the default application name for a given file
In Linux, is there a way to ask any xdg services, or gtk services, which application is the default application for a given file? I realize that xdg-open will in fact, launch the correct application. However, I want to be able to display the application's name in a context menu. So that when the user clicks on the me...
[ "Use the xdg-mime command. It allows you to query for a mimetype, and then get the program associated, without executing it.\nNote that this returns the name of the associated .desktop file. Then you have to locate the actual file and further parse it to get the real name of the program, even localized in any langu...
[ 9, 4, 1 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0005440050_linux_python.txt
Q: How can I draw a log-normalized imshow plot with a colorbar representing the raw data in matplotlib I'm using matplotlib to plot log-normalized images but I would like the original raw image data to be represented in the colorbar rather than the [0-1] interval. I get the feeling there's a more matplotlib'y way of...
How can I draw a log-normalized imshow plot with a colorbar representing the raw data in matplotlib
I'm using matplotlib to plot log-normalized images but I would like the original raw image data to be represented in the colorbar rather than the [0-1] interval. I get the feeling there's a more matplotlib'y way of doing this by using some sort of normalization object and not transforming the data beforehand... in any...
[ "Yes, there is! Use LogNorm. Here is a code excerpt from a utility that I wrote to display confusion matrices on a log scale.\nfrom pylab import figure, cm\nfrom matplotlib.colors import LogNorm\n\n# C = some matrix\nf = figure(figsize=(6.2, 5.6))\nax = f.add_axes([0.17, 0.02, 0.72, 0.79])\naxcolor = f.add_axes([0....
[ 65, 8 ]
[]
[]
[ "matplotlib", "normalize", "python" ]
stackoverflow_0002546475_matplotlib_normalize_python.txt
Q: Embedding a python code to a GUI I have created some Python code which is really complicated but it basically asks for an input and then outputs a huge DNA sequence depending on the input given, along with some graphs and many equations. I would like to embed this code into the user interface that I will most like...
Embedding a python code to a GUI
I have created some Python code which is really complicated but it basically asks for an input and then outputs a huge DNA sequence depending on the input given, along with some graphs and many equations. I would like to embed this code into the user interface that I will most likely make with wxPython or Tkinter. I do...
[ "A good place to start would be the wxPython tutorial.\n", "The best advice for you is not to start trying to build the actual GUI. Learning GUI programming is not trivial and you should start slowly and work up to the real thing.\nPick a framework (Tkinter, wxPython, Qt) and start with the simplest tutorial you ...
[ 1, 1, 0, 0 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0007259001_python_user_interface_wxpython.txt
Q: How to run a Python script from another Python script in the cross-platform way? Here is the problem... I'm writing very small plugin for Blender, I have 10 python scripts, they parsing different file formats by using command-line, and I have a Main Python script to run all other scripts with proper commands... fo...
How to run a Python script from another Python script in the cross-platform way?
Here is the problem... I'm writing very small plugin for Blender, I have 10 python scripts, they parsing different file formats by using command-line, and I have a Main Python script to run all other scripts with proper commands... for example, "Main.py" include: txt2cfg.py -inFile -outFile... ma2lxo.py -inFile -outFil...
[ "If you really need to execute a python script in a new process and you don't know where the interpreter you want is located then use the sys module to help out. \nimport sys\nimport subprocess\n\nsubprocess.Popen((sys.executable, \"script.py\"))\n\nThough importing the module (dynamically if need be) and then runn...
[ 4, 3, 1 ]
[]
[]
[ "blender", "python" ]
stackoverflow_0007262604_blender_python.txt
Q: Please help to justify the code redundancy In the book I'm reading now, Practical Programming - An Introduction to Computer Science Using Python, I've come across an example of code. I can's see what is the reason for the first cycle and the conditional check. As I see it, the second cycle alone is enough to do th...
Please help to justify the code redundancy
In the book I'm reading now, Practical Programming - An Introduction to Computer Science Using Python, I've come across an example of code. I can's see what is the reason for the first cycle and the conditional check. As I see it, the second cycle alone is enough to do the same work. I've put the code through the debug...
[ "The reason for having both is that you must first establish the existence of some suitable element, in the general case, before you can ask whether a best one exists. In this code, the first loop establishes the existence of a suitable element, and the second loop can then assume this and simply look for a best on...
[ 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007262876_python.txt
Q: In python extending the string.Template class for easy regular expressions I like everything about python mostly thanks to its simplicity. I feel regular expressions have taken me away from my love for python far too many times. As such I wanted to extend the already existing string.Template class which lets me se...
In python extending the string.Template class for easy regular expressions
I like everything about python mostly thanks to its simplicity. I feel regular expressions have taken me away from my love for python far too many times. As such I wanted to extend the already existing string.Template class which lets me set variables in a string so that I can get values of an already existing string. ...
[ "You're pretty much trying to turn a template into a regex reading that template, right? That's not always doable, for example if you have a template \"$x$y\" and a string \"abc\", you can't know whether it's (\"ab\", \"c\"), (\"abc\", \"\") or some other case. And it's not just the case with template variables sit...
[ 3, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007262813_python_regex.txt
Q: Auto register a class when it's defined (but without importing it anywhere) I would like to register a class (not an instance) when it's created... but without importing it. Basically, I want to do what's described here: How to auto register a class when it's defined ... but without having to import the registered...
Auto register a class when it's defined (but without importing it anywhere)
I would like to register a class (not an instance) when it's created... but without importing it. Basically, I want to do what's described here: How to auto register a class when it's defined ... but without having to import the registered class anywhere. Here's the issue: At a certain point of my application, I need t...
[ "I feel that your approach is a bit complicated to implement the functionality you want. My suggestion is to you use a strategy like this:\n\nName your modules so that the command classes are defined in files named after the commands they implement. For example, the RebootCommand class goes into the file commands/r...
[ 2 ]
[]
[]
[ "class", "metaclass", "oop", "python" ]
stackoverflow_0007263101_class_metaclass_oop_python.txt
Q: How should I rethink objects/object orientation here? I'm (mostly trying to learn python and json, but also) trying to periodically pull and format a list of trending topics off of twitter. I cobbled this together skimming a lot of different tutorials. It serves my purposes -- prints the HTML I need to stdout, but...
How should I rethink objects/object orientation here?
I'm (mostly trying to learn python and json, but also) trying to periodically pull and format a list of trending topics off of twitter. I cobbled this together skimming a lot of different tutorials. It serves my purposes -- prints the HTML I need to stdout, but I'm wondering if I could have thought about objects differ...
[ "In your example, I don't see why trending needs to be a clas at all, since it only has one function. This could be written with get_trending as a standalone function, which takes the api_url and title as arguments.\n" ]
[ 1 ]
[]
[]
[ "json", "python", "simplejson", "twitter" ]
stackoverflow_0007263091_json_python_simplejson_twitter.txt
Q: 'No module named' error in Python while importing outside /home directory Probably this is a silly issue, but I haven't been able to figure it out. I'm getting ImportError: No module named etree.ElementTree when I write: #!/usr/bin/python3.2 import xml.etree.ElementTree as etree tree = etree.parse('feed.xml') root...
'No module named' error in Python while importing outside /home directory
Probably this is a silly issue, but I haven't been able to figure it out. I'm getting ImportError: No module named etree.ElementTree when I write: #!/usr/bin/python3.2 import xml.etree.ElementTree as etree tree = etree.parse('feed.xml') root = tree.getroot() If I run this same script in /home/ or /home/<user>/, it wor...
[ "Try running Python in the place where it works and the place where it doesn't work, and compare the values of sys.path when running Python in those two locations.\nMy first guess would be that you have $PYTHONSTARTUP set to something that depends on the working directory.\n" ]
[ 1 ]
[]
[]
[ "import", "importerror", "python" ]
stackoverflow_0007263290_import_importerror_python.txt
Q: Loading scripting languages files at modules in Python I need some libraries to run code written in JavaScript, Ruby and other scrinting languages inside my application written in Python. I don't want to use converters or local webservice as solution. A: Try running interpritator in shell (node.js for JS i guess...
Loading scripting languages files at modules in Python
I need some libraries to run code written in JavaScript, Ruby and other scrinting languages inside my application written in Python. I don't want to use converters or local webservice as solution.
[ "Try running interpritator in shell (node.js for JS i guess) from python and parsing results.\nIt's impossible to create bindings to modules and functions of other interpetative language as far as I know.\n" ]
[ 0 ]
[]
[]
[ "interpreter", "python", "ruby", "scripting" ]
stackoverflow_0007263289_interpreter_python_ruby_scripting.txt
Q: Problem parsing with beautifulsoup I'm trying to parse the following web page link. Code below: import urllib2 import sys from BeautifulSoup import BeautifulSoup url = 'http://www.etsy.com/teams/list' source = urllib2.urlopen(url) soup = BeautifulSoup(source) print soup.prettify() print len(soup('h3')) #to pri...
Problem parsing with beautifulsoup
I'm trying to parse the following web page link. Code below: import urllib2 import sys from BeautifulSoup import BeautifulSoup url = 'http://www.etsy.com/teams/list' source = urllib2.urlopen(url) soup = BeautifulSoup(source) print soup.prettify() print len(soup('h3')) #to print the no of occurances of h3 h3s = sou...
[ "I'd recommend using lxml instead:\n>>> import lxml.html\n>>> doc = lxml.html.parse('http://www.etsy.com/teams/list')\n>>> len(doc.xpath('//h3'))\n<<< 10\n\n" ]
[ 2 ]
[]
[]
[ "beautifulsoup", "parsing", "python" ]
stackoverflow_0007263422_beautifulsoup_parsing_python.txt
Q: Trouble inserting data into Postgresql db via Python/psycopg2 Using a method (see bottom), I build an insert command to insert an item (stored as a dictionary) into my postgresql database. Although, when I pass that command to cur.execute I get a syntax error. I'm really at a loss as to why this error is occurri...
Trouble inserting data into Postgresql db via Python/psycopg2
Using a method (see bottom), I build an insert command to insert an item (stored as a dictionary) into my postgresql database. Although, when I pass that command to cur.execute I get a syntax error. I'm really at a loss as to why this error is occurring. >>> print insert_string """INSERT INTO db_test (album, dj, date...
[ "Your string is not a valid SQL statement, it contains lots of python cruft.\nI think I've fixed the method:\ndef build_insert(self, table_name, item):\n if len(item) == 0:\n log.msg('Build_insert failed. Delivered item was empty.', level=log.ERROR)\n return ''\n\n keys = item.keys()\n values = ...
[ 2 ]
[ "You're missing '%' (before passing on parameters for the query ).\nBasically you have to make sure that '%s' gets replaced by actual values .\nFor example :\n msg = 'world'\n Test = 'hello %s' % msg \n'%' will replace the place holder with whatever is stored in the variable msg.\nYou can see in the error msg...
[ -2 ]
[ "insert", "postgresql", "python" ]
stackoverflow_0007263362_insert_postgresql_python.txt
Q: Disable Appstats logging I'm using Appstats as documented here: http://code.google.com/appengine/docs/python/tools/appstats.html It works fine, but every request now logs an info message like this: Saved; key: appstats:039300, part: 65 bytes, full: 12926 bytes, overhead: 0.000 + 0.004; link: http://example.com/st...
Disable Appstats logging
I'm using Appstats as documented here: http://code.google.com/appengine/docs/python/tools/appstats.html It works fine, but every request now logs an info message like this: Saved; key: appstats:039300, part: 65 bytes, full: 12926 bytes, overhead: 0.000 + 0.004; link: http://example.com/stats/details?time=1290733239309...
[ "You might want to take a look at the sample appstats config file. You could configure appstats to only run for a percentage of your requests; that should reduce the number of logging messages but you'll still have the information.\nIf you want to patch appstats, you should take a look at line 303 in /google/appe...
[ 6, 6, 2 ]
[]
[]
[ "appstats", "google_app_engine", "python" ]
stackoverflow_0004305243_appstats_google_app_engine_python.txt
Q: Finding out an Objects class in Python I am trying to find out the class of an object in python and struggling. object.class returns an error. What is the best way to inquire as to an objects class? Thanks in advance! A: obj.__class__ Example: >>> class foo: ... pass ... >>> bar = foo() >>> bar.__class__ ...
Finding out an Objects class in Python
I am trying to find out the class of an object in python and struggling. object.class returns an error. What is the best way to inquire as to an objects class? Thanks in advance!
[ " obj.__class__\n\nExample:\n>>> class foo:\n... pass\n... \n>>> bar = foo()\n>>> bar.__class__ == foo\nTrue\n\n" ]
[ 4 ]
[]
[]
[ "class", "python", "python_2.7" ]
stackoverflow_0007263956_class_python_python_2.7.txt
Q: Thread-safe warnings in Python I am trying to find a good way to log a warning message but appending to it information that is only known by the caller of the function. I think it will be clear with an example. # log method as parameter class Runner1(object): def __init__(self, log): self.log = log ...
Thread-safe warnings in Python
I am trying to find a good way to log a warning message but appending to it information that is only known by the caller of the function. I think it will be clear with an example. # log method as parameter class Runner1(object): def __init__(self, log): self.log = log def run(self): self.log(...
[ "import Queue\n\nlog = Queue.Queue()\nclass Runner1(object):\n\n def run(self):\n log.put('First Warning')\n log.put('Second Warning')\n return 42\n\nclass Main1(object):\n\n def __init__(self):\n self._runner = Runner1()\n\n def log(self, message):\n print('Some object s...
[ 2 ]
[]
[]
[ "logging", "python", "python_3.x", "warnings" ]
stackoverflow_0007264002_logging_python_python_3.x_warnings.txt
Q: Syntax error iterating over tuple in python I am new to Python and am unsure of the best way to iterate over a tuple. The syntax for i in tuple print i causes an error. Any help will be much appreciated! I am a ruby programmer new to python. A: That is an error because the syntax is invalid, add a colon: ...
Syntax error iterating over tuple in python
I am new to Python and am unsure of the best way to iterate over a tuple. The syntax for i in tuple print i causes an error. Any help will be much appreciated! I am a ruby programmer new to python.
[ "That is an error because the syntax is invalid, add a colon:\nfor i in tup:\n print i\n\nAlso, you should not use tuple as the name for a variable, as it is the name of a built-in function.\n", "for i in my_tuples_name:\n print i\n\nYou don't iterate over the keyword tuple, you iterate over your variable.\...
[ 37, 5, 4 ]
[]
[]
[ "python", "python_2.7", "tuples" ]
stackoverflow_0007264073_python_python_2.7_tuples.txt
Q: python list substring I am trying to read the variables from newreg.py (e.g. state, district, dcode, etc, a long list which in turn picking up data from a web form) into insertNew.py. I have currently read the whole file into a list named 'lines'. Now, how do I filter each variable (like- state, district, etc. app...
python list substring
I am trying to read the variables from newreg.py (e.g. state, district, dcode, etc, a long list which in turn picking up data from a web form) into insertNew.py. I have currently read the whole file into a list named 'lines'. Now, how do I filter each variable (like- state, district, etc. approx 50-55 variables. This '...
[ "I am assuming you want to copy the variables from one Python module to another at runtime. \nimport newreg\nnewreg_vars = dir(newreg)\nprint newreg_vars\n\nwill print all of the attributes of the module \"newreg\".\nTo read the variables from the module:\nprint getattr(newreg, 'state')\nprint getattr(newreg, 'dist...
[ 1 ]
[]
[]
[ "list", "python", "substring" ]
stackoverflow_0007262616_list_python_substring.txt
Q: Convert sslsocket python code to ruby I have such code on python connect to some software by socket: import socket, ssl host = '127.0.0.1' port = 8963 sert_key = '../keys/key.pem' sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True) sock.setsockop...
Convert sslsocket python code to ruby
I have such code on python connect to some software by socket: import socket, ssl host = '127.0.0.1' port = 8963 sert_key = '../keys/key.pem' sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True) sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, True)...
[ "Seems like you should use something like this:\nrequire 'socket'\nrequire 'openssl'\n\nhost = '127.0.0.1'\nport = 8963\nsert_key = '../keys/key.pem'\n\nsocket = TCPSocket.new(host, port) # not help also\n\nssl_context = OpenSSL::SSL::SSLContext.new(:TLSv1)\nssl_context.cert = OpenSSL::X509::Certificate.new(File.op...
[ 1 ]
[]
[]
[ "python", "ruby", "sockets", "ssl" ]
stackoverflow_0007263960_python_ruby_sockets_ssl.txt
Q: How to use python curses module to create a key event? I'm trying to make a key event in python. I think that with curses module i can do that but i don't know how to. Please help me. How can i call a function with a press of a keyboard key. Like, if "space" key is pressed do something, if "c" key is pressed show...
How to use python curses module to create a key event?
I'm trying to make a key event in python. I think that with curses module i can do that but i don't know how to. Please help me. How can i call a function with a press of a keyboard key. Like, if "space" key is pressed do something, if "c" key is pressed show image, if "s" key is pressed save image. My problem is only...
[ "Generating a keypress:\nOn Windows it is quite easy to generate keypresses. On Linux a bit more difficult:\n\nThe crude way: os.system('xvkbd -text \"\\\\\\\\CP\" ')\nAlternatives:\nSimulate keystroke in Linux with Python\nSimulating Key Press event using Python for Linux\nThis module is interesting, uses a kern...
[ 2, 0 ]
[]
[]
[ "curses", "python" ]
stackoverflow_0007264208_curses_python.txt
Q: MySQL in Python, MATCH and injection attack Is MATCH from MySQL also vulnerable to injection attack? For example: """SELECT * FROM myTable WHERE MATCH(myColumnName) AGAINST(%s) ORDER BY id LIMIT 20""" % query seems to allow arbitrary strings, which looks bad. If so, I've instead tried - fo...
MySQL in Python, MATCH and injection attack
Is MATCH from MySQL also vulnerable to injection attack? For example: """SELECT * FROM myTable WHERE MATCH(myColumnName) AGAINST(%s) ORDER BY id LIMIT 20""" % query seems to allow arbitrary strings, which looks bad. If so, I've instead tried - following examples in the Python docs - t = (query...
[ "It doesn't much matter what operators, functions, clauses or any other host-language terms you're using when it comes to injection. Injection is a matter of mixing data and language statements, which happens when you interpolate data into a statement. Prepared statement parameters keep data and statements separate...
[ 4, 1, 1, 0 ]
[]
[]
[ "match", "mysql", "python", "sql_injection" ]
stackoverflow_0007254506_match_mysql_python_sql_injection.txt
Q: Convert int to ascii [chr()] in django template I am writing a django application, and in a loop, {% for item in list %} {{ forloop.counter0 }} {% endfor %} this will printout the number in the loop starting from 0. But I want to printout alphabet starting from 'A', so the python way to do it is chr(f...
Convert int to ascii [chr()] in django template
I am writing a django application, and in a loop, {% for item in list %} {{ forloop.counter0 }} {% endfor %} this will printout the number in the loop starting from 0. But I want to printout alphabet starting from 'A', so the python way to do it is chr(forloop.counter0+65), but this is inside the template,...
[ "You can write a simple custom template tag, for example a filter:\n@register.filter(name='chr')\ndef chr_(value):\n return chr(value + 65)\n\nThen load it in your template and you can do:\n{{ forloop.counter0|chr }}\n\n" ]
[ 9 ]
[]
[]
[ "ascii", "chr", "django", "django_templates", "python" ]
stackoverflow_0007264634_ascii_chr_django_django_templates_python.txt
Q: Python everything in try block I am writing a large batch-type script in Python, and need to do some cleanup in the end, regardless of whether an exception occurred. To do this I'm simply putting the main program in a try block and the cleanup in a finally block. This seems to work well, but my question is how to ...
Python everything in try block
I am writing a large batch-type script in Python, and need to do some cleanup in the end, regardless of whether an exception occurred. To do this I'm simply putting the main program in a try block and the cleanup in a finally block. This seems to work well, but my question is how to print any exceptions that might occu...
[ "You should just be able to use a try/finally block with no exception handler. It won't catch the exception or suppress the traceback, just ensure your cleanup code is run whether or not there is an exception. That's the entire point of finally.\nHere's an example:\nPython 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)...
[ 4, 3 ]
[]
[]
[ "exception_handling", "python", "try_catch_finally" ]
stackoverflow_0007264661_exception_handling_python_try_catch_finally.txt
Q: How do I include 3rd party modules with my python scripts? I've started using Python to automate repetitive tasks I have at work, and often need to integrate references to third party modules into my scripts. How can I include these files with my scripts directly? I know there are ways to install the libraries cen...
How do I include 3rd party modules with my python scripts?
I've started using Python to automate repetitive tasks I have at work, and often need to integrate references to third party modules into my scripts. How can I include these files with my scripts directly? I know there are ways to install the libraries centrally in my python installation folder (C:\Python27). Many thi...
[ "Update:\nYes, you can copy third party modules to your application folder. While using the site-packages folder allows for centralized per-machine updates, if you change the libraries infrequently it might be easier for you to just include them in your application folder as you describe.\nIf possible, putting you...
[ 1 ]
[ "Well you can use a py2exe or pyinstaller or you can reference your modules on start of scripts pack them into a archive and have your program portable over different os-es !\nBut well as much heh I see you only use windows ! What make idea of portability last in your back thought ...\n" ]
[ -1 ]
[ "python", "python_import" ]
stackoverflow_0007263696_python_python_import.txt
Q: List of guesses Python I am just learning python and I wrote this, but I want to show all the guesses and maybe whether they are too high or low. The "responseList" part is where I need help. Thanks! import random, easygui secret = random.randint (1, 100) guess = 0 tries = 0 easygui.msgbox ...
List of guesses Python
I am just learning python and I wrote this, but I want to show all the guesses and maybe whether they are too high or low. The "responseList" part is where I need help. Thanks! import random, easygui secret = random.randint (1, 100) guess = 0 tries = 0 easygui.msgbox ("""Guess the secret number....
[ "I'm guessing you want responseList to contain a list of all user's responses. You didn't write it. :)\nYou'll need to set responseList to empty list on the start and than append each new response to it.\nresponseList = [user_response] just sets it to one-element list every time. Obviously you'll end up with a one-...
[ 3, 1, 1 ]
[]
[]
[ "arrays", "easygui", "list", "python", "random" ]
stackoverflow_0007264924_arrays_easygui_list_python_random.txt
Q: Coffeescript equivalent to Python's getattr In python I can put a function into a variable at runtime, then call it using the getattr function method = getattr(self,self.name) method() Is there a similar way to do this in Coffeescript? Thanks! Using zeekay suggestion but using classes would be: class Test foo...
Coffeescript equivalent to Python's getattr
In python I can put a function into a variable at runtime, then call it using the getattr function method = getattr(self,self.name) method() Is there a similar way to do this in Coffeescript? Thanks! Using zeekay suggestion but using classes would be: class Test foo: -> alert 'foo' foo2: methodName -> this[meth...
[ "In Javascript objects are associative arrays, and you can access property/methods using the name of the property as the key:\nobj =\n method: -> 'xxx'\nmethod = obj['method']\nmethod() # 'xxx'\n\nYour updated example doesn't work because foo2 is merely returning foo. You might want to try this:\nclass Test\n fo...
[ 11, 2, 1, 1, 1 ]
[]
[]
[ "coffeescript", "javascript", "python" ]
stackoverflow_0007264676_coffeescript_javascript_python.txt
Q: Python ArgParse Subparsers and linking to the correct function I'm creating a small Python script to manage different classes of servers (FTP, HTTP, SSH, etc.) On each type of server, we can perform different types of actions (deploy, configure, check, etc.) I have a base Server class, then a separate class for ea...
Python ArgParse Subparsers and linking to the correct function
I'm creating a small Python script to manage different classes of servers (FTP, HTTP, SSH, etc.) On each type of server, we can perform different types of actions (deploy, configure, check, etc.) I have a base Server class, then a separate class for each type of server that inherits from this: class Server: ... ...
[ "If you are set on using a subparser for each command I would do something like this. Use argparse's type support to call a function that lookups the class you want to instantiate and returns it.\nThen call the method on that instance dynamically with getattr()\nimport argparse\n\nclass Server:\n def check(self...
[ 2, 0, 0 ]
[]
[]
[ "argparse", "command_line_arguments", "parameters", "python" ]
stackoverflow_0006262788_argparse_command_line_arguments_parameters_python.txt
Q: Sphinx floating point formatting I'm using Sphinx to generate documentation from code. Does anyone know if there is a way to control the formatting of floating point numbers generated from default arguments. For example if I have the following function: def f(x = 0.97): return x+1 The generated documentation...
Sphinx floating point formatting
I'm using Sphinx to generate documentation from code. Does anyone know if there is a way to control the formatting of floating point numbers generated from default arguments. For example if I have the following function: def f(x = 0.97): return x+1 The generated documentation ends up looking like: foo(x = 0.96999...
[ "You can override a function signature with the .. autofunction:: directive. So to address your example, a function defined as foo(x=0.97) in module bar:\n.. automodule:: bar\n\n .. autofunction:: foo(x=0.97)\n\nAnd the resulting doc will use the signature provided instead of the interpreted version with the real...
[ 1, 0 ]
[]
[]
[ "formatting", "python", "python_sphinx" ]
stackoverflow_0007259971_formatting_python_python_sphinx.txt
Q: Python Parsing - Multiple Emails in One Text File I receive similar emails from multiple senders and use regular expressions m and n below to pull out needed strings. That part is working fine. Regular expression o however is what has me confused. The text file I am reading is a combination of 9 email messages sa...
Python Parsing - Multiple Emails in One Text File
I receive similar emails from multiple senders and use regular expressions m and n below to pull out needed strings. That part is working fine. Regular expression o however is what has me confused. The text file I am reading is a combination of 9 email messages saved to one text file and opened in Python as a string. ...
[ "Your question isn't completely clear since you didn't show an output sample, but here's an educated guess:\ncount_cusip = 0\ncount_name = 0\ncount_sender = 0 \ncur_sender = ''\nfor line in lines:\n\n m = re.search('[0-9]{3}[a-zA-Z0-9]{6}', line)\n if m:\n count_cusip += 1\n ws.write(count_cusip...
[ 1, 1 ]
[]
[]
[ "python", "regex", "xlwt" ]
stackoverflow_0007263042_python_regex_xlwt.txt
Q: How to send a form request (method = POST) to a page using the initial addres? I need to solve this problem. I have to send a form using post request, but I have to send it to the page where the form is, and in all the solutions that I find to send the request you have to send it to the page where the results come...
How to send a form request (method = POST) to a page using the initial addres?
I need to solve this problem. I have to send a form using post request, but I have to send it to the page where the form is, and in all the solutions that I find to send the request you have to send it to the page where the results come, and to me this doesn't work because the page that I need to send the request to ha...
[ "If the request needs to send to same page where the request comes, why just call the response method directly since they are in the same page, the method can be accessed.\n" ]
[ 2 ]
[]
[]
[ "http", "post", "python", "request" ]
stackoverflow_0007265553_http_post_python_request.txt
Q: Best site for posting Python code? Which sites are the best for posting Python code that actually works? To show/share, and get input? I would like to post my code. A: Check out ActiveState's Python Recipes site. It reminds me a bit of StackOverflow. A: I think Github (Git) or Bitbucket/Kiln (Mercurial) would...
Best site for posting Python code?
Which sites are the best for posting Python code that actually works? To show/share, and get input? I would like to post my code.
[ "Check out ActiveState's Python Recipes site. It reminds me a bit of StackOverflow.\n", "I think Github (Git) or Bitbucket/Kiln (Mercurial) would be the best places to host any code. That way you can keep it in version control + get comments, suggestions, and even features or additional code for free via the pull...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007265548_python.txt
Q: Adding data to a CSV file through Python I've got a function that adds new data to a csv file. I've got it somewhat working. However, I'm having a few problems. When I add the new values (name, phone, address, birthday), it adds them all in one column, rather than separate columns in the same row. (Not really muc...
Adding data to a CSV file through Python
I've got a function that adds new data to a csv file. I've got it somewhat working. However, I'm having a few problems. When I add the new values (name, phone, address, birthday), it adds them all in one column, rather than separate columns in the same row. (Not really much idea on how to split them up in various colu...
[ "Based on your requirements, and what you appear to be trying to do, I've written the following. It should be verbose enough to be understandable.\nYou need to be consistent with your delimiters and other properties when reading the CSV files.\nAlso, try and move \"friends.csv\" to a global, or at least in some non...
[ 4, 1, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0007257763_csv_python.txt
Q: What is the fastest way to get multiple copies of a tree in python? In my python program I need multiple copies of a tree. Initially, I use deepcopy from the copy module, which turns out to be very slow. Then I write my own code to copy a tree, the code traverses the tree being copied and create a new node at each...
What is the fastest way to get multiple copies of a tree in python?
In my python program I need multiple copies of a tree. Initially, I use deepcopy from the copy module, which turns out to be very slow. Then I write my own code to copy a tree, the code traverses the tree being copied and create a new node at each node being visited. Then I call this subroutines multiple times to get m...
[ "When trying to improve performance you should almost always start with profiling data and then optimize based on what you see there. Start by using cProfile.run to run your top-level tree copy code, then use pstats.Stats class to inspect the profiling data and see where you should really focus your optimization. ...
[ 1 ]
[]
[]
[ "copy", "python", "tree" ]
stackoverflow_0007266009_copy_python_tree.txt
Q: Excel Combobox in Python xlwt module Is this possible? Generation of Excel combobox in a cell using xlwt or similar module? When I load the xls using xlrd, then copy and save it using xlwt, the combobox from original xls is lost. A: No, it's not possible. xlrd doesn't pick up the combo box and suchlike.
Excel Combobox in Python xlwt module
Is this possible? Generation of Excel combobox in a cell using xlwt or similar module? When I load the xls using xlrd, then copy and save it using xlwt, the combobox from original xls is lost.
[ "No, it's not possible. xlrd doesn't pick up the combo box and suchlike.\n" ]
[ 1 ]
[]
[]
[ "combobox", "excel", "python", "xlrd", "xlwt" ]
stackoverflow_0007094771_combobox_excel_python_xlrd_xlwt.txt
Q: How can i store excel file created using pyExcelerator as input for db.BlobProperty() How can i store excel file created using pyExcelerator as input for db.BlobProperty() ? Actally what i need is that Using taskqueue program will create a excel file and store it in the datastore. And will send a link to the user...
How can i store excel file created using pyExcelerator as input for db.BlobProperty()
How can i store excel file created using pyExcelerator as input for db.BlobProperty() ? Actally what i need is that Using taskqueue program will create a excel file and store it in the datastore. And will send a link to the users to download the file. How do i do this ? Please help me Datamodel: class filestore(db.Mode...
[ "If your goal is to create an Excel file and save it as a blob for later use you need to first save it as a StringIO object, not construct a response, as you are doing currently.\nHere is a sample using xlwt (a fork of pyExcelerator):\nimport xlwt\n\nfile_type = 'application/ms-excel'\nfile_name = 'sample.xls'\n\nw...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "pyexcelerator", "python", "xlwt" ]
stackoverflow_0007254317_google_app_engine_pyexcelerator_python_xlwt.txt
Q: How to add a to the absolute value of b without call abs I'm having a little problem defining a function. I'm trying to add a to the absolute value of b without calling abs from operator import add, sub def a_plus_absolute_b(a, b): """Return a+abs(b), but without calling abs.""" if b < 0: op = add(...
How to add a to the absolute value of b without call abs
I'm having a little problem defining a function. I'm trying to add a to the absolute value of b without calling abs from operator import add, sub def a_plus_absolute_b(a, b): """Return a+abs(b), but without calling abs.""" if b < 0: op = add(a, (b * -1)) else: op = add(a, b) return op(a,...
[ "You don't need to import add() for this.\nWhy don't you simply do\ndef a_plus_absolute_b(a, b):\n \"\"\"Return a+abs(b), but without calling abs.\"\"\"\n if b < 0:\n result = a - b\n else:\n result = a + b\n return result\n\n", "The solution you're looking for, which you're overlooking ...
[ 7, 4 ]
[]
[]
[ "function", "python" ]
stackoverflow_0007266385_function_python.txt
Q: Python 2.7.1 and Python 2.7.1+ on Ubuntu 11.04 I am having two different machines running Ubuntu 11.04 with Python 2.7.1 installed. However, on one machine with Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 I am able to press the up arrow to load the previous commands, left and right to...
Python 2.7.1 and Python 2.7.1+ on Ubuntu 11.04
I am having two different machines running Ubuntu 11.04 with Python 2.7.1 installed. However, on one machine with Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 I am able to press the up arrow to load the previous commands, left and right to move toward the left and right and such during inte...
[ "The second installation of Python 2.7.1 seems to have been compiled later. I'm guessing it was compiled from source. The libreadline-dev(*) package must be installed so support for readline can be included when Python is compiled.\n(*) The actual package name for your particular version of Linux will vary.\n" ]
[ 2 ]
[]
[]
[ "interpreter", "python" ]
stackoverflow_0007266507_interpreter_python.txt
Q: Python - Split String Containing '\x' I want only the number here which is in scientific notation. The output below is the Python interpreter output from Terminal. How would one go about this. Added info: the string isn't always the same length so no char. length shortcuts... The suffix is also not always the same...
Python - Split String Containing '\x'
I want only the number here which is in scientific notation. The output below is the Python interpreter output from Terminal. How would one go about this. Added info: the string isn't always the same length so no char. length shortcuts... The suffix is also not always the same. >>> x [' 1.9580000000000002E-05\xef\xbb\x...
[ ">>> import re\n>>> x = [' 1.9580000000000002E-05\\xef\\xbb\\xbf\\r\\n']\n>>> float(re.search(r'\\d\\.\\d*E[+-]\\d+',x[0]).group())\n1.9580000000000002e-05\n\nBut, depending on the encoding of your text and where you get that data from, this is possibly more \"correct\":\n>>> float(x[0].decode('utf8').encode('ascii...
[ 6, 2, 2, 2, 1 ]
[]
[]
[ "python", "split" ]
stackoverflow_0007266646_python_split.txt
Q: How to do os.execv() in Python in Windows without detaching from the console? I'm using Python 2.6 on Windows 7. I have Windows .cmd file which invokes Python to run the CherryPy Web server (version 3.1.2). I start this .cmd file by executing it at the prompt in a Windows CMD shell. When CherryPy notices that one ...
How to do os.execv() in Python in Windows without detaching from the console?
I'm using Python 2.6 on Windows 7. I have Windows .cmd file which invokes Python to run the CherryPy Web server (version 3.1.2). I start this .cmd file by executing it at the prompt in a Windows CMD shell. When CherryPy notices that one of its dependent files has changed, it restarts. There are a couple problems that a...
[]
[]
[ "you can use subprocess.call method like this example\nimport subprocess\n\nretcode = subprocess.call([\"ls\", \"-l\"])\n\nsee this link for more information about subprocess class:\nsubprocess — Subprocess management\n" ]
[ -3 ]
[ "cmd", "exec", "python", "windows" ]
stackoverflow_0007264571_cmd_exec_python_windows.txt
Q: Twisted, Deferred full traceback I'm just learning to write applications on Twisted and so do a lot of mistakes. Suppose there is a code: d = defer.Deferred() d.addCallback(self.start_app) #d.addErrback(self.command_die) d.callback(0) def start_app(self, d): #import os return os.startfile(self.path) def ...
Twisted, Deferred full traceback
I'm just learning to write applications on Twisted and so do a lot of mistakes. Suppose there is a code: d = defer.Deferred() d.addCallback(self.start_app) #d.addErrback(self.command_die) d.callback(0) def start_app(self, d): #import os return os.startfile(self.path) def command_die(self, d): print ('com_...
[ "Twisted Failure object has everything you need.\nFor getting nice traceback try using printTraceback() method:\n>>> from twisted.internet.defer import Deferred as D\n>>> def start_app(_):\n... #import os\n... return os.startfile('sasa')\n... \n... def command_die(err):\n... err.printTraceback()\n... \n...
[ 6 ]
[]
[]
[ "deferred", "python", "twisted" ]
stackoverflow_0007266398_deferred_python_twisted.txt
Q: Character \u260e During web scraping, I got character \u260e in unicode. My output is "The Last Resort, ☎ +977 1 4700525". So instead of ☎, there should be ☎. How can I get it back to telephone sign (☎)? So output will be "The Last Resort, ☎ +977 1 4700525". Krish A: When you scraped a site, Python recogniz...
Character \u260e
During web scraping, I got character \u260e in unicode. My output is "The Last Resort, ☎ +977 1 4700525". So instead of ☎, there should be ☎. How can I get it back to telephone sign (☎)? So output will be "The Last Resort, ☎ +977 1 4700525". Krish
[ "When you scraped a site, Python recognized a \"☎\" character and stored it in a string.\nThis character has codepoint 260e. When characters are stored, however, they are stored as sequences of one or more bytes. What those bytes are depends on the encoding being used. In your case UTF-8 was probably used.\nThe ...
[ 8, 1 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0007266842_python_unicode.txt
Q: OpenCV crashing on cv.Resize When running OpenCV on Windows 7, using the standard python shell, I get the following behavior. import cv im = cv.LoadImageM("data/somefile.jpg") thumb = cv.CreateMat(im.rows/6, im.cols/6, im.type) print "Before" cv.Resize(im, thumb) print "After" Gives: >>> Before =============...
OpenCV crashing on cv.Resize
When running OpenCV on Windows 7, using the standard python shell, I get the following behavior. import cv im = cv.LoadImageM("data/somefile.jpg") thumb = cv.CreateMat(im.rows/6, im.cols/6, im.type) print "Before" cv.Resize(im, thumb) print "After" Gives: >>> Before ========================= RESTART =============...
[ "Most memory allocation in OpenCV is unchecked and can result in crashes. OpenCV also attempts to throw exceptions through C code, which may cause anything to happen (usually a crash) depending on how it was compiled.\nCheck whether the values of im.rows/6, etc. are what you expect and that the image sizes should b...
[ 2, 1, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0004596315_opencv_python.txt
Q: (Python) What is the proper nomenclature for this so I can search for and learn about it? Sorry for the poor title. I really have no idea how to describe this to a search engine to find out how it works. class MyClass(object): def __init__(self, contents=None): self.contents = contents Specifically, ...
(Python) What is the proper nomenclature for this so I can search for and learn about it?
Sorry for the poor title. I really have no idea how to describe this to a search engine to find out how it works. class MyClass(object): def __init__(self, contents=None): self.contents = contents Specifically, the contents=None parameter. I've been studying Python for about 2 months now, and that part se...
[ "That's a Default Argument Value for a Keyword Argument.\nThey're pretty straightforward, as long as they're not a mutable object like a list or dictionary.\nJust in case it was the __init__ method throwing you off -- it's the instance method of a class that gets automatically called when the instance is created. A...
[ 8, 3, 1, 1 ]
[]
[]
[ "class", "parameters", "python", "python_2.x" ]
stackoverflow_0007267687_class_parameters_python_python_2.x.txt
Q: Producer/Consumer Multi producers and a single Consumer writing to File Python My requirement is similar to Multiple producers, single consumer except i need it in python I have created an application that spawns 5 concurrent processes (I am using multiprocessing library).These 5 process are independently produci...
Producer/Consumer Multi producers and a single Consumer writing to File Python
My requirement is similar to Multiple producers, single consumer except i need it in python I have created an application that spawns 5 concurrent processes (I am using multiprocessing library).These 5 process are independently producing output in dict format. Earlier I was printing the output to console, but now woul...
[ "I've implemented this pattern in Python where a supervisor process spawns a bunch of processes and then consumes log messages from all of them and writes those log messages into a single log file.\nBasically, I used execve to spawan the processes an specified that stderr for each process was connected to a PTY. Th...
[ 1, 0 ]
[]
[]
[ "file_io", "message_queue", "multiprocessing", "producer_consumer", "python" ]
stackoverflow_0007266210_file_io_message_queue_multiprocessing_producer_consumer_python.txt
Q: How to use whois in google app engine I know there is pywhois but it can't used in gae, see this question. But i really need this function to verify whether a domain is registered, is there other way to implement whois by pure python? Thanks. A: You need to find a HTTP Api to get whois like http://www.whoisxmlap...
How to use whois in google app engine
I know there is pywhois but it can't used in gae, see this question. But i really need this function to verify whether a domain is registered, is there other way to implement whois by pure python? Thanks.
[ "You need to find a HTTP Api to get whois like http://www.whoisxmlapi.com/ and with urlfetch you can fetch informations.\nAn another solution is to create this webservice with a micro instance from AWS and install the module pywhois, you need to just create the interface in HTTP.\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "python", "whois" ]
stackoverflow_0007266588_google_app_engine_python_whois.txt
Q: Using Selenium webdriver with a custom firefox profile - how to get rid of addins popup When I use selenium webdriver with a custom firefox profile I get the firefox Add-ons pop up showing 2 extensions: Firefx WebDriver 2.5.0 and Ubuntu Firefox Modifications 0.9rc2. How can I get rid of this popup? I looked in the...
Using Selenium webdriver with a custom firefox profile - how to get rid of addins popup
When I use selenium webdriver with a custom firefox profile I get the firefox Add-ons pop up showing 2 extensions: Firefx WebDriver 2.5.0 and Ubuntu Firefox Modifications 0.9rc2. How can I get rid of this popup? I looked in the server jar to see if I could find the extensions, no luck. Looked online for the extensions,...
[ "You need to add an entry called extensions.newAddons to the profile's preferences and set the value to false.\nStart firefox with the custom profile\nfirefox -profile <path to profile directory>\n\nType about:config in the address bar and press the enter key. Right-click the preference pane to open the context men...
[ 2, 0 ]
[]
[]
[ "firefox", "python", "selenium" ]
stackoverflow_0007233631_firefox_python_selenium.txt
Q: Beautifulsoup web scraper issue I'm using BeautifulSoup and mechanise to find some content from a web page. The thing is that SOMETIMES the string I'm looking for is not found. I don't know what could be a problem It worked fine for many months for many web pages but suddenly it stopped working. Then I have to res...
Beautifulsoup web scraper issue
I'm using BeautifulSoup and mechanise to find some content from a web page. The thing is that SOMETIMES the string I'm looking for is not found. I don't know what could be a problem It worked fine for many months for many web pages but suddenly it stopped working. Then I have to restart my program and hope for the righ...
[ "I helped someone out with a similar problem and it turned out to be the encoding of the string. This link (from their docs) might help you on the way - Beautiful Soup Gives You Unicode, Dammit\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "mechanize", "python", "web_scraping" ]
stackoverflow_0007267846_beautifulsoup_mechanize_python_web_scraping.txt
Q: Django: setup.py install - access denied? I have recently asked this question and this one Now i think I know the answer to my questions....it's all because i installed django using pypm... and something else is wrong! I did as they said, the first answer: start over, the 2nd answer: pydev do not detect detect dja...
Django: setup.py install - access denied?
I have recently asked this question and this one Now i think I know the answer to my questions....it's all because i installed django using pypm... and something else is wrong! I did as they said, the first answer: start over, the 2nd answer: pydev do not detect detect django if installed from pypm so i decided to star...
[ "I would try runnig the following command from the Django source code directory on the windows command line: \nC:\\Python26\\python.exe setup.py install\n\nI do this all the time since I have several versions of Python installed on my system. Of course, replace Python26 with your Python installation dir. \n", "...
[ 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "activepython", "activestate", "django", "pypm", "python" ]
stackoverflow_0007233058_activepython_activestate_django_pypm_python.txt
Q: (Python) Issues with directories that have special characters OS: Windows server 03 Python ver: 2.7 For the code below, its runs fine when I substitute "fuchida@domain.com" with "fuchida". If I use the email format for directory name I get the following error "WindowsError: [Error 123] The filename, directory nam...
(Python) Issues with directories that have special characters
OS: Windows server 03 Python ver: 2.7 For the code below, its runs fine when I substitute "fuchida@domain.com" with "fuchida". If I use the email format for directory name I get the following error "WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:" . Please let me know what...
[ "I suspect problems with your \\ as escape characters. Try this:\nimport os\n\ndef dirListing():\n dirList = os.listdir(r\"C:\\\\Program Files\\home\\Server\\Logs\\fuchida@domain.com\")\n for fname in dirList:\n print fname\n return\n\ndef main():\n dirListing()\n\nif __name__ == '__main__':main(...
[ 8 ]
[]
[]
[ "directory", "python", "windows" ]
stackoverflow_0007268618_directory_python_windows.txt
Q: no error message in CMD after uninstalling python3.2 Hi I am running in windows XP. I have python2.6 and python 3.2 installed at the same time. My problem is when i uninstall python 3.2 and run a program with an error, the CMD does not return error message. But the program execute properly when it has no error. I...
no error message in CMD after uninstalling python3.2
Hi I am running in windows XP. I have python2.6 and python 3.2 installed at the same time. My problem is when i uninstall python 3.2 and run a program with an error, the CMD does not return error message. But the program execute properly when it has no error. I've tried re installing python2.6 but it is still the same...
[ "\nFrom the desktop, right-click My Computer and click Properties.\nIn the System Properties window, click on the Advanced tab.\nIn the Advanced section, click the Environment Variables button.\nIn the Environment Variables window highlight the Path variable in the Systems Variable section and click the Edit button...
[ 2, 0 ]
[]
[]
[ "python", "python_2.6", "python_3.x", "windows" ]
stackoverflow_0007054379_python_python_2.6_python_3.x_windows.txt
Q: New to Python and need some help Good day. I'm after some help and probably jumping in the deepend here. I'm trying to write a plugin that will check if services are on or of on a mac os x server. The plugin needs to be written in python and I have manage to create something that will give me result's, but I need ...
New to Python and need some help
Good day. I'm after some help and probably jumping in the deepend here. I'm trying to write a plugin that will check if services are on or of on a mac os x server. The plugin needs to be written in python and I have manage to create something that will give me result's, but I need some help in finishing it off. import ...
[ "It'll be something along these lines.\nclass someclass:\n def run(self):\n return dict((svc, os.popen('serveradmin status ' + svc, 'r').read().strip())\n for svc in ('afp', 'dhcp', 'dirserv', 'dns', 'ftp'))\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007268743_python.txt
Q: Package-specific import hooks in Python I'm working on creating a Python module that maps API provided by a different language/framework into Python. Ideally, I would like this to be presented as a single root package that exposes helper methods, and which maps all namespaces in that other framework to Python pack...
Package-specific import hooks in Python
I'm working on creating a Python module that maps API provided by a different language/framework into Python. Ideally, I would like this to be presented as a single root package that exposes helper methods, and which maps all namespaces in that other framework to Python packages/modules. For the sake of convenience, le...
[ "In general, I think your approach looks fine. I wouldn't worry about it being \"global\", since the whole point is to specify which paths should be handled by you. Moving this test inside the import logic would just needlessly complicate it, so it's left to the implementer of the hook to decide.\nJust one small co...
[ 5 ]
[]
[]
[ "import_hooks", "python" ]
stackoverflow_0007268643_import_hooks_python.txt
Q: convert a mixed list of strings to a list of integer I not familiar with python and need help to convert a list containing strings and numbers (all represented as strings!) to a new list that include only the numbers. input string : ['LOAD','0x00134','0','0','R','E','0x1df0','0x1df0'] result needed: [0x00134,0,0,...
convert a mixed list of strings to a list of integer
I not familiar with python and need help to convert a list containing strings and numbers (all represented as strings!) to a new list that include only the numbers. input string : ['LOAD','0x00134','0','0','R','E','0x1df0','0x1df0'] result needed: [0x00134,0,0,0x1df0,0x1df0] All non-numeric entries like 'LOAD' and 'R...
[ "input = ['LOAD','0x00134','0','0','R','E','0x1df0','0x1df0']\n\ndef tryInt(x):\n base = 10\n if x.startswith('0x'): base = 16\n try: return int(x, base)\n except ValueError: return None\n\nfilter(lambda x: x is not None, map(tryInt, input))\n\n", "You can use this function from: http://rosettacode.or...
[ 3, 1, 1, 0 ]
[]
[]
[ "integer", "list", "python", "string" ]
stackoverflow_0007266501_integer_list_python_string.txt
Q: Where is the most authoritative/complete source of documentation on rpm-python module? Trying to learn how to use the rpm-python module (i.e. "import rpm" on RHEL5). I can't find any tutorials that are complete or recent. Specifically regarding how to install and manage rpm's on a system. Anyone? A: There is som...
Where is the most authoritative/complete source of documentation on rpm-python module?
Trying to learn how to use the rpm-python module (i.e. "import rpm" on RHEL5). I can't find any tutorials that are complete or recent. Specifically regarding how to install and manage rpm's on a system. Anyone?
[ "There is some documentation on Fedora website.\n", "If you are on RHEL then you could seriously consider using the yum APIs instead of rpm-python directly ... the API is much easier to use.\n", "Centos 5.6 uses rpm 4.4.2.3. I'd go with the Developer Documentation\n" ]
[ 3, 0, 0 ]
[]
[]
[ "python", "rhel5", "rpm" ]
stackoverflow_0004880818_python_rhel5_rpm.txt
Q: Python magic detects images just as 'binary' In another question here I've read that python-magic should output the correct mime type of a file. I've added python-magic = 0.4.0 to my Django project, but here's what it detects: In [2]: import magic In [3]: m = magic.Magic(mime_encoding=True) In [4]: m.from_file('/h...
Python magic detects images just as 'binary'
In another question here I've read that python-magic should output the correct mime type of a file. I've added python-magic = 0.4.0 to my Django project, but here's what it detects: In [2]: import magic In [3]: m = magic.Magic(mime_encoding=True) In [4]: m.from_file('/home/culebron/Documents/chapter2.pdf') Out[4]: 'bin...
[ "Looking at the examples in the readme, it seems that you need to use mime=True instead of mime_encoding=True to get the mime type.\n" ]
[ 2 ]
[]
[]
[ "django", "mime_types", "python" ]
stackoverflow_0007268791_django_mime_types_python.txt
Q: Count subpatterns in PHP PCRE RegEx I want to implement something like "editor for regular expressions". It is for power users of my PHP application. The problem is, I need something like "reflection" for the regular expression (to be more precise, for any given regular expression) to find out how many subpatterns...
Count subpatterns in PHP PCRE RegEx
I want to implement something like "editor for regular expressions". It is for power users of my PHP application. The problem is, I need something like "reflection" for the regular expression (to be more precise, for any given regular expression) to find out how many subpatterns it contains. In Python, I simply type: r...
[ "I can see that being very hard. The maximum number of possible patterns is pretty complex to determine, because extended/POSIX/Perl regular expressions are just so complex. They nest, capturing some patterns means others won't be, and so on. I don't know of a way to determine the maximum number of patterns directl...
[ 1, 1 ]
[]
[]
[ "pcre", "php", "python", "regex" ]
stackoverflow_0007268863_pcre_php_python_regex.txt
Q: Python, mechanize - problem with finding form by name import urllib import cookielib import mechanize url = "http://hattrick.org/World/Transfers/" cookie = cookielib.CookieJar() browser = mechanize.Browser() browser.set_cookiejar(cookie) browser.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_tim...
Python, mechanize - problem with finding form by name
import urllib import cookielib import mechanize url = "http://hattrick.org/World/Transfers/" cookie = cookielib.CookieJar() browser = mechanize.Browser() browser.set_cookiejar(cookie) browser.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) browser.open(url) browser.select_form(name="aspnetFor...
[ "You can check what forms are available by using the browser.forms() iterator.\nTo find out what forms are available in a Python interpreter, just do:\n>>> print [form for form in browser.forms()][0]\n\n" ]
[ 7 ]
[]
[]
[ "forms", "mechanize", "python" ]
stackoverflow_0007268886_forms_mechanize_python.txt
Q: How common set up and clear down jobs are performed in py.test? Python's unittest has a handy way to perform common set up and clear down jobs by grouping the relevant functions into a class that inherits unittest.TestCase and providing setUp and tearDown functions for that class. However, I couldn't find similar ...
How common set up and clear down jobs are performed in py.test?
Python's unittest has a handy way to perform common set up and clear down jobs by grouping the relevant functions into a class that inherits unittest.TestCase and providing setUp and tearDown functions for that class. However, I couldn't find similar mechanism in py.test. What am I missing?
[ "OK, I have already found the answer: it's called \"Test fixture management: and is discussed here: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-3-pytest-tool.html\n" ]
[ 1 ]
[]
[]
[ "pytest", "python", "unit_testing" ]
stackoverflow_0007252852_pytest_python_unit_testing.txt
Q: Spawning a QThread containing a socket connection in python I am currently trying implement a QThread that contains a socket connection. The socket connection runs repeatedly (while 1:) checking for new data received. Once this data is received, it is supposed to fire off a SIGNAL calling a function and feeding it...
Spawning a QThread containing a socket connection in python
I am currently trying implement a QThread that contains a socket connection. The socket connection runs repeatedly (while 1:) checking for new data received. Once this data is received, it is supposed to fire off a SIGNAL calling a function and feeding it the received data. I got the socket connection working. When I r...
[ "The thread might be destroyed if there is no further reference to it. \nTry using self.thread instead of just thread.\n" ]
[ 4 ]
[]
[]
[ "multithreading", "pyqt", "python", "qt", "sockets" ]
stackoverflow_0007252681_multithreading_pyqt_python_qt_sockets.txt
Q: Python Script to sort and rename files - Removes duplicates I've written a small script that I needed to rename and sort files in the same folder where the script is. It renames the files into integers (1, 2, 3, 4, ...) based on the last modification of files: import os import sys def gtime(nam): return os.pat...
Python Script to sort and rename files - Removes duplicates
I've written a small script that I needed to rename and sort files in the same folder where the script is. It renames the files into integers (1, 2, 3, 4, ...) based on the last modification of files: import os import sys def gtime(nam): return os.path.getmtime('./'+nam) files = os.listdir('.') files.remove(str(sys...
[ "So here's an example that will copy to a subdirectory and avoid copying your script's .pyc file as well.\nimport os, sys\nfrom os.path import exists, isfile, getmtime, join as pjoin\nfrom shutil import copyfile\n\ntargetdir='process'\nstub='inputfile'\n\nif not exists(targetdir):\n os.mkdir(targetdir)\n\nfiles = ...
[ 2, 1, 0 ]
[]
[]
[ "file_rename", "python", "sorting" ]
stackoverflow_0007268329_file_rename_python_sorting.txt
Q: From a python embedded program, how do I get access to a an instance value? Assume that I have the following c-program with embedded python: const char *pyCode = "class Foo:\n" " def __init__(self):\n" " self.foo = 42\n" " def set_foo(foo):\n" " self.foo=foo\n" "\n" "foo=Foo()\n" ; Py_Init...
From a python embedded program, how do I get access to a an instance value?
Assume that I have the following c-program with embedded python: const char *pyCode = "class Foo:\n" " def __init__(self):\n" " self.foo = 42\n" " def set_foo(foo):\n" " self.foo=foo\n" "\n" "foo=Foo()\n" ; Py_Initialize(); PyObject* main_module = PyImport_AddModule("__main__"); PyObject* main_...
[ "Using the object protocol functions. PyObject_GetAttr family is an attribute access (e.g. PyObject_GetAttrString(FooObj, \"foo\"), PyObject_Call family is a function call (e.g. PyObject_CallMethod(FooObj, \"set_obj\", \"(O)\", some_other_object)).\n", "http://docs.python.org/c-api/ is your friend.\nAttributes ar...
[ 1, 1 ]
[]
[]
[ "embedded", "python" ]
stackoverflow_0007269563_embedded_python.txt
Q: What is the difference between django.conf.settings and global_settings? What is the difference between django.conf.settings and django.conf.global_settings ? A: settings is a proxy object that you use in your code to access the settings. global_settings is a module internal to Django, containing default settin...
What is the difference between django.conf.settings and global_settings?
What is the difference between django.conf.settings and django.conf.global_settings ?
[ "settings is a proxy object that you use in your code to access the settings.\nglobal_settings is a module internal to Django, containing default settings, used when you leave out a variable out of project's settings. I.e. you don't touch it, unless you're changing Django core.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007269669_django_python.txt
Q: Custom headers with pycurl Can I send a custom header like "yaddayadda" to the server with the pycurl request? A: I would code something like: pycurl_connect = pycurl.Curl() pycurl_connect.setopt(pycurl.URL, your_url) pycurl_connect.setopt(pycurl.HTTPHEADER, ['header_name1: header_value1', ...
Custom headers with pycurl
Can I send a custom header like "yaddayadda" to the server with the pycurl request?
[ "I would code something like:\npycurl_connect = pycurl.Curl()\npycurl_connect.setopt(pycurl.URL, your_url)\npycurl_connect.setopt(pycurl.HTTPHEADER, ['header_name1: header_value1',\n 'header_name2: header_value2'])\npycurl_connect.perform()\n\n", "you can, with HTTPHEADER....
[ 53, 5, 3 ]
[]
[]
[ "header", "pycurl", "python" ]
stackoverflow_0003044782_header_pycurl_python.txt
Q: Help with a chat python application I am currently making a chat application in python. I am having 2 separate codes: one for the server and one for the client. The server script is taking the login data of new clients that connects and in another thread manages the messages that he has to receive and send. The cl...
Help with a chat python application
I am currently making a chat application in python. I am having 2 separate codes: one for the server and one for the client. The server script is taking the login data of new clients that connects and in another thread manages the messages that he has to receive and send. The client application is made into a class and...
[ "Found myself the mistake after searching all the night through the code. Apparently if i use this line:\nself.theframe=self.tbox=self.entry=self.scrollbar=self.button=self.base=[0]*20\n\nAll the objects point to the same value.\n", "My guess is, the code that is creating the UI is throwing an error that you are ...
[ 0, 0 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0007263492_python_tkinter_user_interface.txt
Q: Comparing web.py's Templator and Jinja2: strengths and weaknesses I'm adding a simple web interface to an already existing piece of software; web.py fits the job just right and that's what I'm using. Now I'm researching what templating engine to use and came down to two alternatives: either using web.py's own Temp...
Comparing web.py's Templator and Jinja2: strengths and weaknesses
I'm adding a simple web interface to an already existing piece of software; web.py fits the job just right and that's what I'm using. Now I'm researching what templating engine to use and came down to two alternatives: either using web.py's own Templator or using Jinja2. I already have both working in the app and I'm w...
[ "Taking a quick look at Templator (which I have never used) and comparing it to Jinja2 (which I have used somewhat extensively), I'd say that the two are pretty similar ... but Templator is closer akin to Mako than to Jinja.\nMako and Jinja both support:\n\nTemplate Inheritance (You can have a layout that all your ...
[ 4, 1 ]
[]
[]
[ "jinja2", "python", "templates", "web.py" ]
stackoverflow_0007244683_jinja2_python_templates_web.py.txt
Q: Add a second ILogObserver to a service I try to write a small service with twisted. I created a simple Application, and try to add 2 ILogObservers to my service. But unfortunatly, it doesnt work. The last added Observer is always the observer that will be used. def log(eventDict): ... def mylog(eventDict): ... L...
Add a second ILogObserver to a service
I try to write a small service with twisted. I created a simple Application, and try to add 2 ILogObservers to my service. But unfortunatly, it doesnt work. The last added Observer is always the observer that will be used. def log(eventDict): ... def mylog(eventDict): ... LoopingCall(logSomething).start(1) applicati...
[ "kay, I found the solution, it was far easier then I suspected.\nI just have to add \nfrom twisted.python.log import addObserver \n\nif I have a secondary log observer\ndef mylogobserver(eventDict):\n # doSth\n\nI can add it VERY SIMPLE with\naddObserver(mylogobserver)\n\nBest regards\n" ]
[ 2 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0007255712_python_twisted.txt
Q: Translate module (app) name in django I am trying to translate the app names within my django project, I found this code on the web: init.py from django.utils.translation import gettext_noop gettext_noop("AppName") template {% trans app.name %} However in the current version of django this code is present, so I ...
Translate module (app) name in django
I am trying to translate the app names within my django project, I found this code on the web: init.py from django.utils.translation import gettext_noop gettext_noop("AppName") template {% trans app.name %} However in the current version of django this code is present, so I guess theres a way of doing this in django ...
[ "Concerning blocktrans, you're misunderstanding how it works with values being passed in. If you have something like this:\n{% blocktrans with foo=bar %}-- {{ foo }} --{% endblocktrans %}\n\nThis is roughly equivalent to either of the following in Python:\ngettext('-- %(foo)s --') % {'foo': bar}\ngettext('-- {foo} ...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007268626_django_python.txt
Q: python trying to remove single apostrophe I'm using a program called CityEngine which has a python element to it. The problem: I've just called a function on an object and returns me a list of numbers, xyz. I split the xyz into their own names. I also call a function to retrieve a different attribute related to ...
python trying to remove single apostrophe
I'm using a program called CityEngine which has a python element to it. The problem: I've just called a function on an object and returns me a list of numbers, xyz. I split the xyz into their own names. I also call a function to retrieve a different attribute related to this object to replace the previously retrieved...
[ "That looks more as if the function were not returning a number but a string. So, in order to deal with it, you’ll have to convert the string using either int() or float().\nIn general, if you do a print(l) on some list of items, each item will be printed with the output of it’s __repr__ method. Convention has it t...
[ 2, 0 ]
[]
[]
[ "apostrophe", "printing", "python" ]
stackoverflow_0007270356_apostrophe_printing_python.txt