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: Find value within a range in lookup table I have the simplest problem to implement, but so far I have not been able to get my head around a solution in Python. I have built a table that looks similar to this one: 501 - ASIA 1262 - EUROPE 3389 - LATAM 5409 - US I will test a certain value to see if it falls within...
Find value within a range in lookup table
I have the simplest problem to implement, but so far I have not been able to get my head around a solution in Python. I have built a table that looks similar to this one: 501 - ASIA 1262 - EUROPE 3389 - LATAM 5409 - US I will test a certain value to see if it falls within these ranges, 389 -> ASIA, 1300 -> LATAM, 5400...
[ "You could use the bisect module. Instead of linear search, that would use binary search, which would hopefully be faster:\nimport bisect\n\nplaces = [\n (501, 'ASIA'),\n (1262, 'EUROPE'),\n (3389, 'LATAM'),\n (5409, 'US'),\n]\nplaces.sort() # list must be sorted\n\nfor to_find in (389, 1300, 5400):\n ...
[ 20, 4, 2, 2 ]
[]
[]
[ "lookup", "python" ]
stackoverflow_0002899129_lookup_python.txt
Q: How do I find out how many objects are in a list basically what the title says. I want to be able to find out how many objects a list contains. Maybe my Google-fu is failing me or my terminology is wrong. A: len(s) Return the length (the number of items) of an object. The argument may be a sequence (string, tup...
How do I find out how many objects are in a list
basically what the title says. I want to be able to find out how many objects a list contains. Maybe my Google-fu is failing me or my terminology is wrong.
[ "len(s)\n\nReturn the length (the number of items) of an object. The argument may be a sequence (string, tuple or list) or a mapping (dictionary).\n\n>>> l = [1, 2, 3]\n>>> len(l)\n3\n\n", "Check out the len built-in function:\nlen(someList)\n\nhttp://docs.python.org/library/functions.html#len\n", " a = ['1', '...
[ 6, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007524439_python.txt
Q: Why is this cursor not working? Do you know why this cursor is not working? When I click on "More Results" no other results are displayed. Thanks. if n==1: query = Main.all() query.filter("tag_list", s[0]) query.order("-date") cursor = self.request.get("cursor") if cursor: query.with_cursor(cur...
Why is this cursor not working?
Do you know why this cursor is not working? When I click on "More Results" no other results are displayed. Thanks. if n==1: query = Main.all() query.filter("tag_list", s[0]) query.order("-date") cursor = self.request.get("cursor") if cursor: query.with_cursor(cursor) items = query.fetch(2) c...
[ "Assuming that code is in a handler, is s[0] the same on each invocation? Cursors only work on identically declared queries. If s[0] changes, the query changes, and the previously-saved cursor won't work with it.\n" ]
[ 2 ]
[]
[]
[ "cursor", "google_app_engine", "python" ]
stackoverflow_0007522811_cursor_google_app_engine_python.txt
Q: Installing pymake? There dont seem to be any instructions on how to build this sucker. Downloaded from http://benjamin.smedbergs.us/pymake/ The usual files are not in the top directory - make.py and mkparse.py. neither of them seem to do much.. seems like it needs a makefile, but there isn't one in any part of ...
Installing pymake?
There dont seem to be any instructions on how to build this sucker. Downloaded from http://benjamin.smedbergs.us/pymake/ The usual files are not in the top directory - make.py and mkparse.py. neither of them seem to do much.. seems like it needs a makefile, but there isn't one in any part of the distro.. > python m...
[ "pymake is a make utility, and running make.py looks for a Makefile (that you've created, for your own project). There's no build step specifically required for pymake itself.\n" ]
[ 3 ]
[]
[]
[ "building", "python" ]
stackoverflow_0007524219_building_python.txt
Q: Python binary tree serializing problem I have a binary tree class as below: class BTree: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def __unicode__(self): return "%s" % self.data and I have another tree serializing...
Python binary tree serializing problem
I have a binary tree class as below: class BTree: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def __unicode__(self): return "%s" % self.data and I have another tree serializing method listed as below: class JTree(object)...
[ "It seems to me that you want a simple recursive function like:\ndef convert_to_jtree(bt):\n return JTree(bt.data, [convert_to_jtree(bt.left) if bt.left else None,\n convert_to_jtree(bt.right) if bt.right else None])\n\nor something very similar.\n", "The json module can only serialize...
[ 2, 0 ]
[]
[]
[ "python", "serialization", "tree" ]
stackoverflow_0007524467_python_serialization_tree.txt
Q: Using Declarative syntax, how do I define a relationship representing the latest object in a many-to-one collection? I'm using SQLAlchemy's declarative syntax and I'd like to specify a relationship that provides the latest (max primary id) element in a collection. I've found this post: How do I define a SQLAlchemy...
Using Declarative syntax, how do I define a relationship representing the latest object in a many-to-one collection?
I'm using SQLAlchemy's declarative syntax and I'd like to specify a relationship that provides the latest (max primary id) element in a collection. I've found this post: How do I define a SQLAlchemy relation representing the latest object in a collection? but I'm having a tough time using this pattern, creating a subqu...
[ "The easiest way is to define the relationship outside the class once all classes are defined.\nRemove your definition of latest_article from NewsPaper and add following code after the class Article definition (taken directly from Mike's answer you linked to):\n# define the relationship\nt_article = Article.__table...
[ 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0007521715_python_sqlalchemy.txt
Q: python unmanaged dll call, fails on win32 FindWindow api with Access Violation I have the following bare minimum function in a DLL #define INTELHOOK_API extern "C" __declspec(dllexport) INTELHOOK_API BOOL testFunc(void) { BOOL success = false; HWND parent = NULL; parent = FindWindow("Arium.SourceP...
python unmanaged dll call, fails on win32 FindWindow api with Access Violation
I have the following bare minimum function in a DLL #define INTELHOOK_API extern "C" __declspec(dllexport) INTELHOOK_API BOOL testFunc(void) { BOOL success = false; HWND parent = NULL; parent = FindWindow("Arium.SourcePont", NULL); if (parent != NULL) { success = true; } return succ...
[ "For what it's worth, this works fine for me in 32-bit Windows XP with Python 3.2.1 and 2.7.2, compiled with i686-w64-mingw32-g++.exe version 4.5.3:\nc/test.cpp:\n#include <windows.h>\n\n#define INTELHOOK_API extern \"C\" __declspec(dllexport)\nINTELHOOK_API BOOL test(void) {\n BOOL success = FALSE;\n HWND pa...
[ 2, 1 ]
[]
[]
[ "access_violation", "dll", "python", "unmanaged" ]
stackoverflow_0007521245_access_violation_dll_python_unmanaged.txt
Q: Opening another file from Python and terminate script I am trying to figure out the best solution to accomplish this. Basically, I want to open another program from Python (doesn't matter, could be an image, executable, etc). I have tried os.system and subprocess.call however both will not terminate the script aft...
Opening another file from Python and terminate script
I am trying to figure out the best solution to accomplish this. Basically, I want to open another program from Python (doesn't matter, could be an image, executable, etc). I have tried os.system and subprocess.call however both will not terminate the script after, and will instead wait for a return. I have looked at os...
[ "Use subprocess.Popen[docs]\nJust don't call communicate on the resulting object.\n", "os.execlp(\"start\", r\"B:\\test.txt\")\n\n(That's for Windows. On a Unix system running X11, you'd do this:)\nos.execlp(\"xdg-open\", r\"B:\\test.txt\")\n\n" ]
[ 1, 1 ]
[]
[]
[ "file", "io", "operating_system", "python" ]
stackoverflow_0007523967_file_io_operating_system_python.txt
Q: what's the overhead of passing python callback functions to Fortran subroutines? I just wrapped a Fortran 90 subroutine to python using F2PY. The subtlety here is that the Fortran subroutine aslo takes a python call-back function as one of its arguments: SUBROUTINE f90foo(pyfunc, a) real(kind=8),intent(in) :: a !f...
what's the overhead of passing python callback functions to Fortran subroutines?
I just wrapped a Fortran 90 subroutine to python using F2PY. The subtlety here is that the Fortran subroutine aslo takes a python call-back function as one of its arguments: SUBROUTINE f90foo(pyfunc, a) real(kind=8),intent(in) :: a !f2py intent(callback) pyfunc external pyfunc !f2py real*8 y,x !f2py y = pyfunc(x) !***...
[ "In the code you posted, a is double precision float. Passing it from Fortran to Python means wrapping the Fortran double to a PyFloat object, which does have a cost. In the pure Python version, k is a PyFloat and you don't pay the price for wrapping it 1000 times. \nAnother issue is the function call itself. Calli...
[ 9 ]
[]
[]
[ "f2py", "fortran", "optimization", "python", "wrapper" ]
stackoverflow_0007524941_f2py_fortran_optimization_python_wrapper.txt
Q: if/elif/else statement help with money Updated my new code at the bottom of the page as an answer. So for my CS 170 class, we have to make a program that has user input for less than $10 and change is returned in the least amount of coins, no bills or 50 cent pieces. For the most part the program does well except ...
if/elif/else statement help with money
Updated my new code at the bottom of the page as an answer. So for my CS 170 class, we have to make a program that has user input for less than $10 and change is returned in the least amount of coins, no bills or 50 cent pieces. For the most part the program does well except when you run into a x.x0 e.g.: Python 2.7.2 ...
[ "There are a few changes you could make to clean up this code, and one of them might fix your problem. First, pass does absolutely nothing. It is usually used as a placeholder for a loop or function that will be filled in later. Also, the conditions of your elif statements are mutually exclusive with the if stateme...
[ 3, 2, 1 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0007479985_if_statement_python.txt
Q: Python passing dictionary to process in multiprocessing I have a class that contains a (large) number of different properties, including a few dictionaries. When I pass an instance of the class through to a new process, all of the numeric values seem to get passed in correctly, but any dictionaries that were in t...
Python passing dictionary to process in multiprocessing
I have a class that contains a (large) number of different properties, including a few dictionaries. When I pass an instance of the class through to a new process, all of the numeric values seem to get passed in correctly, but any dictionaries that were in the class object get emptied. Here's a simple test I cooked up...
[ "the problem is clearly described in the documentation for the multiprocessing module: windows lacks a fork() system call, so on windows, the module source code gets reevaluated at the start of each process, thus the current state is not preserved. (on un*x based system, including OSX, Process is implemented using ...
[ 3, 0 ]
[]
[]
[ "arguments", "dictionary", "multiprocessing", "python" ]
stackoverflow_0007353973_arguments_dictionary_multiprocessing_python.txt
Q: Git and packaging: common pattern to keep packaging-files out of the way? For the last python project I developed, I used git as versioning system. Now it's that time of the development cycle in which I should begin to ship out packages to the beta testers (in my case they would be .deb packages). In order to buil...
Git and packaging: common pattern to keep packaging-files out of the way?
For the last python project I developed, I used git as versioning system. Now it's that time of the development cycle in which I should begin to ship out packages to the beta testers (in my case they would be .deb packages). In order to build my packages I need a number of extra files (copyright, icon.xpm. setup.py, se...
[ "why would you want to keep those out of the source control? They are part of the inputs to generate the final, built output! You definately don't want to lose track of them, and you probably want to keep track of how they change over time, as you continue to develop your application.\nWhat you most likely want t...
[ 4, 2, 0 ]
[]
[]
[ "debian", "git", "packaging", "python", "setuptools" ]
stackoverflow_0007409720_debian_git_packaging_python_setuptools.txt
Q: pymongo error operation failure I'm currently using celery with django, i have pymongo ver 1.11 mongodb ver 1.8 I'm getting following error, i'm not able to figure out what is the error. [2011-09-23 02:06:59,544: WARNING/MainProcess] File "/usr/local/lib/python2.6/dist-packages/pymongo/database.py", line 293, in ...
pymongo error operation failure
I'm currently using celery with django, i have pymongo ver 1.11 mongodb ver 1.8 I'm getting following error, i'm not able to figure out what is the error. [2011-09-23 02:06:59,544: WARNING/MainProcess] File "/usr/local/lib/python2.6/dist-packages/pymongo/database.py", line 293, in command [2011-09-23 02:06:59,560: WAR...
[ "I think its to do with MongoDB indexes are using version 1 which relates to mongodb >= 2.0\nsee: http://www.mongodb.org/display/DOCS/Index+Versions\n" ]
[ 0 ]
[]
[]
[ "celery", "mongodb", "pymongo", "python" ]
stackoverflow_0007525534_celery_mongodb_pymongo_python.txt
Q: Binary string comparison I'm just learning python and the best way to learn a language is to use it, so I thought I'd make a script that compares binary words to determine which ones are grey. If there is one bit that is different then it should flag record which number binary code it is. So by means of example, ...
Binary string comparison
I'm just learning python and the best way to learn a language is to use it, so I thought I'd make a script that compares binary words to determine which ones are grey. If there is one bit that is different then it should flag record which number binary code it is. So by means of example, if N=3 then the binary code is...
[ "Since this is a binary calculation problem (with a weird input), it's not really the area where you can apply pythonic tools like generators, list comprehensions and itertools.\ndef neighbors(code, N=3):\n num = int(code, 2)\n return [num ^ (1 << (N-i-1)) for i in range(N)]\n\nIf you want the output to be sorted...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007511476_python.txt
Q: django model polymorphism with proxy inheritance My Discount model describes common fields for all types of discounts in the system. I have some proxy models which describe concrete algorithm for culculating total. Base Discount class has a member field named type, which is a string identifing its type and its rel...
django model polymorphism with proxy inheritance
My Discount model describes common fields for all types of discounts in the system. I have some proxy models which describe concrete algorithm for culculating total. Base Discount class has a member field named type, which is a string identifing its type and its related class. class Discount(models.Model): TYPE_CHOI...
[ "Your init method needs to look like this instead:\ndef __init__(self, *args, **kwargs):\n super(Discount, self).__init__(*args, **kwargs)\n if self.type:\n self.__class__ = getattr(sys.modules[__name__], self.type + 'Discount')\n\nYou need to call super's __init__ before you will be able to access sel...
[ 12, 0 ]
[]
[]
[ "django", "django_models", "proxy_classes", "python" ]
stackoverflow_0007526088_django_django_models_proxy_classes_python.txt
Q: Wait for the result of an external webservice inside a task I need to write a bunch of tasks where every task needs to query an external web service. The web service always replies with a 202 ACCEPTED status and points in the Location header to the URI where the result can be polled. The time it takes for this web...
Wait for the result of an external webservice inside a task
I need to write a bunch of tasks where every task needs to query an external web service. The web service always replies with a 202 ACCEPTED status and points in the Location header to the URI where the result can be polled. The time it takes for this web service to deliver the result can vary from 2 seconds to a minut...
[ "You' re surely killing your resources. Just query your external web service and save the URI to be polled (use a cache or a db).Then you can have a periodic task that collects the results, if ready...\n", "I'd be thinking about a celery task that polls the Location provided by the 202 response. If it is complete...
[ 1, 0, 0 ]
[]
[]
[ "celery", "python" ]
stackoverflow_0007514588_celery_python.txt
Q: Is it necessary to explicitly free memory in Google App Engine's Python environment? Is there a way to free memory in google's app engine? Is there a garbage collector in python? A: Python has it's own garbage collection so there's no need to release memory manually. A: Python itself managing the garbage coll...
Is it necessary to explicitly free memory in Google App Engine's Python environment?
Is there a way to free memory in google's app engine? Is there a garbage collector in python?
[ "Python has it's own garbage collection so there's no need to release memory manually.\n", "Python itself managing the garbage collection. Normally, no need for manual memory release.\nalthough, you can check Python GC lib, if you want to do it manually.\n" ]
[ 6, 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007526746_google_app_engine_python.txt
Q: Python - List of dictionary to list of list of dictionary I have this kind of list of dictionary [ {'word': u'live', 'sequence': 1L, 'part': 1L}, {'word': u'school', 'sequence': 2L, 'part': 1L}, {'word': u'job', 'sequence': 1L, 'part': 2L}, {'word': u'house', 'sequence': 2L, 'part': 2L}, ] That I'd like t...
Python - List of dictionary to list of list of dictionary
I have this kind of list of dictionary [ {'word': u'live', 'sequence': 1L, 'part': 1L}, {'word': u'school', 'sequence': 2L, 'part': 1L}, {'word': u'job', 'sequence': 1L, 'part': 2L}, {'word': u'house', 'sequence': 2L, 'part': 2L}, ] That I'd like to transform into this kind of list of list of dictionary [ [ ...
[ "Since itertools can be confusing, here's how you can do it:\n>>> import pprint\n>>> import itertools\n>>> l = [\n... {'word': u'live', 'sequence': 1L, 'part': 1L},\n... {'word': u'school', 'sequence': 2L, 'part': 1L},\n... {'word': u'job', 'sequence': 1L, 'part': 2L},\n... {'word': u'house', 'sequence': 2L...
[ 3, 1, 1 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0007527523_dictionary_list_python.txt
Q: How to extract parameters from a list and pass them to a function call What is a good, brief way to extract items from a list and pass them as parameters to a function call, such as in the example below? Example: def add(a,b,c,d,e): print(a,b,c,d,e) x=(1,2,3,4,5) add(magic_function(x)) A: You can unpack a ...
How to extract parameters from a list and pass them to a function call
What is a good, brief way to extract items from a list and pass them as parameters to a function call, such as in the example below? Example: def add(a,b,c,d,e): print(a,b,c,d,e) x=(1,2,3,4,5) add(magic_function(x))
[ "You can unpack a tuple or a list into positional arguments using a star.\ndef add(a, b, c):\n print(a, b, c)\n\nx = (1, 2, 3)\nadd(*x)\n\nSimilarly, you can use double star to unpack a dict into keyword arguments.\nx = { 'a': 3, 'b': 1, 'c': 2 }\nadd(**x) \n\n", "I think you mean the * unpacking operator:\n>>...
[ 96, 15, 6 ]
[]
[]
[ "argument_unpacking", "list", "python" ]
stackoverflow_0007527849_argument_unpacking_list_python.txt
Q: Is it possible to set the python -O (optimize) flag within a script? I'd like to set the optimize flag (python -O myscript.py) at runtime within a python script based on a command line argument to the script like myscript.py --optimize or myscript --no-debug. I'd like to skip assert statements without iffing all o...
Is it possible to set the python -O (optimize) flag within a script?
I'd like to set the optimize flag (python -O myscript.py) at runtime within a python script based on a command line argument to the script like myscript.py --optimize or myscript --no-debug. I'd like to skip assert statements without iffing all of them away. Or is there a better way to efficiently ignore sections of py...
[ "-O is a compiler flag, you can't set it at runtime because the script already has been compiled by then.\nPython has nothing comparable to compiler macros like #if.\nSimply write a start_my_project.sh script that sets these flags.\n", "#!/usr/bin/env python\ndef main():\n assert 0\n print(\"tada\")\n\nif _...
[ 13, 8 ]
[]
[]
[ "assert", "conditional_compilation", "optimization", "python", "runtime" ]
stackoverflow_0007527055_assert_conditional_compilation_optimization_python_runtime.txt
Q: Python, GIS and Fortran: Trying to create multiple polygons from xy point data I've been working on this problem for awhile and have found no joy on the ESRI forum page or with some FORTRAN triangulation script I wrote. I have two .csv files with hundreds of xy point data in. These points represent the high and lo...
Python, GIS and Fortran: Trying to create multiple polygons from xy point data
I've been working on this problem for awhile and have found no joy on the ESRI forum page or with some FORTRAN triangulation script I wrote. I have two .csv files with hundreds of xy point data in. These points represent the high and low end of an intertidal range. The high and low points run parallel to each other and...
[ "This should work for the interpolation (say the tide line is x, y distance from some control point on shore):\nimport math\n\nexample_triangle = [[0,0], [5,5], [0,5], [0,0]]\nhigh_tide_line = [[0, 0], [5., 1.5], [10., 3.2], [20., 1.], [30., 4.5], [80.,2.], [80,0]]\nlow_tide_line = [[0, 10.], [5., 11.5], [10., 13.2...
[ 0 ]
[]
[]
[ "fortran", "gis", "points", "python", "triangulation" ]
stackoverflow_0007519162_fortran_gis_points_python_triangulation.txt
Q: posting pickle dumps string with urllib I need to post data to a Django server. I'd like to use pickle. (There're no security requirements -> small intranet app.) First, I pickle the data on the client and sending it with urllib2 def dispatch(self, func_name, *args, **kwargs): dispatch_url = urljoin(self.base_...
posting pickle dumps string with urllib
I need to post data to a Django server. I'd like to use pickle. (There're no security requirements -> small intranet app.) First, I pickle the data on the client and sending it with urllib2 def dispatch(self, func_name, *args, **kwargs): dispatch_url = urljoin(self.base_url, "api/dispatch") pickled_args = cPick...
[ "\nObviously the urllib.urlencode has created a unicode string.\n\nurllib.urlencode doesn't return Unicode string.\nIt might be a feature of the web framework you use that request.POST contains Unicode strings.\nDon't use pickle to communicate between services it is not secure, brittle, not portable, hard to debug ...
[ 2 ]
[]
[]
[ "django", "encoding", "pickle", "python", "urllib" ]
stackoverflow_0007527302_django_encoding_pickle_python_urllib.txt
Q: Sorting algorithm in OpenOffice calc I'm having a really long day, the culmination of which is a dumb moment trying to sort a list of strings. Calc sorts them like this: 0DCv6UlY6T0 0ITZEBZrwMk 1062VEX2EfI 2jk7hilGMs0 2lZVu3haI6A 3f8s3KbFQ0Q 3hB09daYLmk 43Erj3qFxxo 6lj33w3YoOw 7jiNQnkfx0k 7TSMj6g3UoE 7Wba8IUk6v8 ...
Sorting algorithm in OpenOffice calc
I'm having a really long day, the culmination of which is a dumb moment trying to sort a list of strings. Calc sorts them like this: 0DCv6UlY6T0 0ITZEBZrwMk 1062VEX2EfI 2jk7hilGMs0 2lZVu3haI6A 3f8s3KbFQ0Q 3hB09daYLmk 43Erj3qFxxo 6lj33w3YoOw 7jiNQnkfx0k 7TSMj6g3UoE 7Wba8IUk6v8 9hbG9dS7zl0 ALThJiGFBSc by_VzOiPhZM Ce250P...
[ "It's because of locale. See the difference between:\nsort inputfile\n\nand with (what you probably want):\nLANG=\"C\" sort inputfile\n\noutput of second command:\n0DCv6UlY6T0\n0ITZEBZrwMk\n1062VEX2EfI\n2jk7hilGMs0\n2lZVu3haI6A\n3f8s3KbFQ0Q\n3hB09daYLmk\n43Erj3qFxxo\n6lj33w3YoOw\n7TSMj6g3UoE\n7Wba8IUk6v8\n7jiNQnkfx...
[ 4, 2, 1 ]
[]
[]
[ "algorithm", "python", "sorting" ]
stackoverflow_0007528246_algorithm_python_sorting.txt
Q: how to access cell values faster with openpyxl? for rownum in range(0, len(self.sheet.rows) ): for cell in self.sheet.rows[rownum]: print cell.value I want to access all cell values in a sheet row by row with openpyxl. Above code works but too slow. How can I access all cell values faster? A: If you're...
how to access cell values faster with openpyxl?
for rownum in range(0, len(self.sheet.rows) ): for cell in self.sheet.rows[rownum]: print cell.value I want to access all cell values in a sheet row by row with openpyxl. Above code works but too slow. How can I access all cell values faster?
[ "If you're only reading cells from top to bottom and from left to right (like most of us) you can use the \"optimized reader\" http://openpyxl.readthedocs.org/en/latest/optimized.html. It works quite fast (CPU bound) and has smaller memory footprint than regular reader.\nDisclaimer: I'm the author of openpyxl.\n", ...
[ 17, 4 ]
[]
[]
[ "excel", "openpyxl", "python", "xlsx" ]
stackoverflow_0006870231_excel_openpyxl_python_xlsx.txt
Q: Building zxing's cpp/lib Fails under Fedora14 even when Following instructions Exactly That is, following the instructions in zxing/cpp/README, which say 'To build the library only: - Run "scons lib" in this folder (cpp)' Well, that is exactly what I did. But I get: scons lib scons: Reading SConscript files ... s...
Building zxing's cpp/lib Fails under Fedora14 even when Following instructions Exactly
That is, following the instructions in zxing/cpp/README, which say 'To build the library only: - Run "scons lib" in this folder (cpp)' Well, that is exactly what I did. But I get: scons lib scons: Reading SConscript files ... scons: done reading SConscript files. scons: Building targets ... o build/core/src/zxing/Barc...
[ "It is likely that you are correct, and that SCons isn't finding GCC. Your best bet is to add a call to display the contents of some (or all) of the environment. As shown below, you can either pull out specific variable, or show the whole environment. The best place would probably near a call to the builder (Shared...
[ 0 ]
[]
[]
[ "build", "python", "scons", "zxing" ]
stackoverflow_0007524599_build_python_scons_zxing.txt
Q: Is there a Python API for drawing diagrams (that use lines to connect corresponding values between two lists) Given two lists, which contain same elements of string but in different orders, is there any API that can draw diagrams like The diagram consists of two stacks of string. Between these two stacks, lines a...
Is there a Python API for drawing diagrams (that use lines to connect corresponding values between two lists)
Given two lists, which contain same elements of string but in different orders, is there any API that can draw diagrams like The diagram consists of two stacks of string. Between these two stacks, lines are used to link same elements between these two stacks. Its outlook is similar as the visualization of sonar (an E...
[ "The general graph description format DOT seems the most appropriate to me: it is easy to describe a huge variety of graphs, with this (text) format, and you can plot them with one of the many tools available (Graphviz comes to mind, for example).\nYou also have the specialized python-graph module at your disposal ...
[ 4, 0 ]
[]
[]
[ "api", "diff", "graphics", "python" ]
stackoverflow_0007528224_api_diff_graphics_python.txt
Q: Py2exe bundling files into a single exe I'm having some trouble getting Py2exe to bundle all the files into a single .exe. It works fine for me when I don't bundle them together. So this is the setup.py script I use when I'm not bundling them together, and it always works: from distutils.core import setup import p...
Py2exe bundling files into a single exe
I'm having some trouble getting Py2exe to bundle all the files into a single .exe. It works fine for me when I don't bundle them together. So this is the setup.py script I use when I'm not bundling them together, and it always works: from distutils.core import setup import py2exe setup(console=['test.py']) So I wanted...
[ "just from the errorlog message, could you try again after assuring the last line of test.py ends with a carriage return? (press enter after the last line in test.py and save again) \n" ]
[ 0 ]
[]
[]
[ "exe", "py2exe", "python", "windows" ]
stackoverflow_0007528904_exe_py2exe_python_windows.txt
Q: Efficiently generating a document index for a large number of small documents in a large file Goal I have a very large corpus of the following format: <entry id=1> Some text ... Some more text </entry> ... <entry id=k> Some text ... Some more text </entry> There are tens of millions of entries for this corpus, ...
Efficiently generating a document index for a large number of small documents in a large file
Goal I have a very large corpus of the following format: <entry id=1> Some text ... Some more text </entry> ... <entry id=k> Some text ... Some more text </entry> There are tens of millions of entries for this corpus, and more for other corpora I want to deal with. I want to treat each entry as a separate document a...
[ "Well, keeping all entries in a single file is not a good idea. You can process your big file using generators, so as to avoid memory issues, entry by entry, and then I'd recommend storing each one in a database. While on the process, you can dynamically construct all the relevant stuff, such as term frequencies, d...
[ 2 ]
[]
[]
[ "io", "lucene", "python" ]
stackoverflow_0007528835_io_lucene_python.txt
Q: How fast is Python? I'm a Java programmer and if there's one thing that I dislike about it, it would be speed. Java seems really slow, but a lot of the Python scriptsprograms I have written so far seem really fast. So I was just wondering if Python is faster than Java, or C# and how that compares to C/C++ (which ...
How fast is Python?
I'm a Java programmer and if there's one thing that I dislike about it, it would be speed. Java seems really slow, but a lot of the Python scriptsprograms I have written so far seem really fast. So I was just wondering if Python is faster than Java, or C# and how that compares to C/C++ (which I figure it'll be slower ...
[ "In terms of raw performance, Python is definitely slower than Java, C# and C/C++. However, there are other things that matter for the user/observer such as total memory usage, initial startup time, etc. For most things, Python is fast enough ;)\nThis site lets you compare different programming languages to each ot...
[ 31, 24, 4, 4, 2, 1, 0, 0 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0001686192_performance_python.txt
Q: Python - Access protected network resource I need to open a file on my local network from a Python script. In the basic case is very simple: fh = open('\\servername\path\resource.txt', 'r') ... The problem is that the access to this network resource is protected. I tried something like: fh = open('\\servername\pa...
Python - Access protected network resource
I need to open a file on my local network from a Python script. In the basic case is very simple: fh = open('\\servername\path\resource.txt', 'r') ... The problem is that the access to this network resource is protected. I tried something like: fh = open('\\servername\path\resource.txt@username:pass', 'r') but it doe...
[ "First of all, backslashes in Python need to be escaped, so your path string is\n'\\\\\\\\servername\\\\path\\\\resource.txt'\n# or ..\nr'\\\\servername\\path\\resource.txt'\n\nPython's open function has no support for passwords. You'll need to use windows functions to specify passwords. Here's an example program d...
[ 5 ]
[]
[]
[ "file", "networking", "python", "windows" ]
stackoverflow_0007529439_file_networking_python_windows.txt
Q: Copying an instance of a model and updating fields I'm trying to copy an instance of my Page model and set the new page's status to "draft." This code works perfectly in the Django shell, but in the admin action where it lives, a new instance is created but the status is not updated. for page in pages: pag...
Copying an instance of a model and updating fields
I'm trying to copy an instance of my Page model and set the new page's status to "draft." This code works perfectly in the Django shell, but in the admin action where it lives, a new instance is created but the status is not updated. for page in pages: page.pk, page.id = None, None page.save() p...
[ "Don't.\nfor page in pages:\n new_page= Page.objects.create(\n this= page.this, that=page.that, ...\n status= Page.DRAFT )\n\nMuch simpler. Much clearer. And it actually works.\n", "It turns out that the proxy models subclassing Page had custom save method overriding my updates.\n" ]
[ 1, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007520460_django_django_models_python.txt
Q: Appending a Counter() list to a pygtk treestore (Python) I'm currently attempting to append a sorted list of items to a pygtk treestore. The list is a count of the times the number occurs in the original list, eg. 2 lots of 24 Generating the list from collections import Counter c = Counter(aSeries) l = c.items() l...
Appending a Counter() list to a pygtk treestore (Python)
I'm currently attempting to append a sorted list of items to a pygtk treestore. The list is a count of the times the number occurs in the original list, eg. 2 lots of 24 Generating the list from collections import Counter c = Counter(aSeries) l = c.items() l.sort(key = lambda item: item[0]) print l Example of list pri...
[ "This might depend a bit on your model, but how about something like this (i.e. append every single element of the list seperately to the treestore, which I assume to have only one column based on your picture):\nl = c.items()\n…\nfor (char, count) in l:\n treestore.append(parent, (\"%d: %s\" % (count, char),))\...
[ 1 ]
[]
[]
[ "arrays", "list", "pygtk", "python" ]
stackoverflow_0007529691_arrays_list_pygtk_python.txt
Q: sqlite and python... fast and furious I implemented in python a program that builds some db from protein fasta file. A fasta file is a text file that contains some macromolecular sequences. You can read more about here. From each protein my program generate a list of peptides, they are pieces of proteins. For my...
sqlite and python... fast and furious
I implemented in python a program that builds some db from protein fasta file. A fasta file is a text file that contains some macromolecular sequences. You can read more about here. From each protein my program generate a list of peptides, they are pieces of proteins. For my goals the program builds and interrogates...
[ "You won't improve performance, the ORM layer will add a bit of overhead, but you'll probably be able to experiment easier. Given the size of your data you might be able to create the database in memory which would be faster. Or you might want to look at a different type of database, like redis for example.\n" ]
[ 4 ]
[]
[]
[ "performance", "python", "sqlite" ]
stackoverflow_0007529750_performance_python_sqlite.txt
Q: ggplot2 not present in rpy2 for python? I am working with rpy2 v2.1.9 in Python3.2, I don't understand why I can't use the library ggplot2 import rpy2 from rpy2.robjects import r r.library("ggplot2") Here is the error message I got Error in function (package, help, pos = 2, lib.loc = NULL, character.only = FALSE,...
ggplot2 not present in rpy2 for python?
I am working with rpy2 v2.1.9 in Python3.2, I don't understand why I can't use the library ggplot2 import rpy2 from rpy2.robjects import r r.library("ggplot2") Here is the error message I got Error in function (package, help, pos = 2, lib.loc = NULL, character.only = FALSE, : there is no package called 'ggplot2' T...
[ "See the tail of the first error message:\n\nthere is no package called 'ggplot2'\n\nYou need to install the ggplot2 package first. Fire up R itself, and say\n install.packages(\"ggplot2\")\n\n" ]
[ 7 ]
[]
[]
[ "ggplot2", "python", "python_3.x", "r", "rpy2" ]
stackoverflow_0007529862_ggplot2_python_python_3.x_r_rpy2.txt
Q: Matplotlib Backend Differences between Agg and Cairo Hej, I'd like to produce high quality PDFs from matplotlib plots. Using other code, I have produced a large array of numbers, which I plot in a figure using plt.imshow. If I now produce a PDF using plt.savefig, I notice strong differences depending on which back...
Matplotlib Backend Differences between Agg and Cairo
Hej, I'd like to produce high quality PDFs from matplotlib plots. Using other code, I have produced a large array of numbers, which I plot in a figure using plt.imshow. If I now produce a PDF using plt.savefig, I notice strong differences depending on which backend I use. Most importantly, the produced files get huge w...
[ "As suggested by steabert in the comments above, a workaround is exporting the graphics in a different format and then convert it to PDF afterwards. Adjusting my example from above, the workflow could look something like this:\nimport os\nimport matplotlib as mpl\nmpl.use(\"Agg\")\n\nimport numpy as np\nimport matp...
[ 6 ]
[]
[]
[ "backend", "matplotlib", "pdf", "python" ]
stackoverflow_0007346254_backend_matplotlib_pdf_python.txt
Q: how to get unique values set from a repeating values list I need to parse a large log file (flat file), which contains two column of values (column-A , column-B). Values in both columns are repeating. I need to find for each unique value in column-A , I need to find a set of column-B values. Is this can be done...
how to get unique values set from a repeating values list
I need to parse a large log file (flat file), which contains two column of values (column-A , column-B). Values in both columns are repeating. I need to find for each unique value in column-A , I need to find a set of column-B values. Is this can be done using unix shell command or need to write any perl or python s...
[ "Perl 'one-liner' intended/expanded out so that everything fits in the window:\n$ perl -F -lane '\n\n $hash{ $F[0] }{ $F[1] }++;\n } END {\n\n for my $columnA ( keys %hash ) {\n\n print $columnA, \" - \", join( \",\", keys %$hash{$columnA} ), \"\\n\";\n }\n '\n\nExplanation will follow if ...
[ 5, 3, 1, 1, 0, 0, 0 ]
[]
[]
[ "parsing", "perl", "python" ]
stackoverflow_0004976964_parsing_perl_python.txt
Q: Require BeautifulSoup in a Python Package - What's needed in setup.py? I'm writing a setup script for a python distribution, foo. My code requires BeautifulSoup, so currently my directory is structured like so: <root>/ setup.py __init__.py foo.py BeautifulSoup/ __init__....
Require BeautifulSoup in a Python Package - What's needed in setup.py?
I'm writing a setup script for a python distribution, foo. My code requires BeautifulSoup, so currently my directory is structured like so: <root>/ setup.py __init__.py foo.py BeautifulSoup/ __init__.py BeautifulSoup.py etc. And setup.py currently loo...
[ "Directory structure:\n<root>/\n setup.py\n foo.py\n\nNote: there is no __init__.py file.\nYou could use distribute to specify dependencies, setup.py:\nfrom setuptools import setup\n\nsetup(name='foo',\n version='0.9.0',\n py_modules=['foo'],\n install_requires=['BeautifulSoup >= X.X.X'...
[ 4 ]
[]
[]
[ "distutils", "module", "python", "python_2.7", "setup.py" ]
stackoverflow_0007530026_distutils_module_python_python_2.7_setup.py.txt
Q: I have an Oracle Stack trace file Python cx_Oracle My python application is dying, this oracle trace file is being generated. I am using cx_Oracle, how do I go about using this trace file to resolve this crash? ora_18225_139690296567552.trc kpedbg_dmp_stack()+360<-kpeDbgCrash()+192<-kpureq2()+3194<-OCIStmtPrepare2...
I have an Oracle Stack trace file Python cx_Oracle
My python application is dying, this oracle trace file is being generated. I am using cx_Oracle, how do I go about using this trace file to resolve this crash? ora_18225_139690296567552.trc kpedbg_dmp_stack()+360<-kpeDbgCrash()+192<-kpureq2()+3194<-OCIStmtPrepare2()+157<-Cursor_InternalPrepare()+298<-0000000000EA3010<-...
[ "Do you have an Oracle support contract? If I would file an SR and upload the trace to Oracle and have them tell you what it is complaining about. Those code calls are deep in their codebase from the looks of it.\n" ]
[ 0 ]
[]
[]
[ "cx_oracle", "python" ]
stackoverflow_0007285135_cx_oracle_python.txt
Q: How to automate Windows authentication in Python with selenium-rc? I am using python to write selenium-rc test code for my server code. The server application is written with ASP.NET and is configured with "Windows authentication". The execution steps of my python code look like the following: Start python main()...
How to automate Windows authentication in Python with selenium-rc?
I am using python to write selenium-rc test code for my server code. The server application is written with ASP.NET and is configured with "Windows authentication". The execution steps of my python code look like the following: Start python main() Create the selenium instance (say sel) Start the selenium by calling s...
[ "Selenium has issues recognizing that window (try to search HTTP Basic Authentification for more details about it)\nBasically, only thing which kinda works is to put username and password into URL request itself. Assuming your application runs on http://example.com the new url should look like this:\n http://userna...
[ 1, 0 ]
[]
[]
[ "python", "selenium", "windows_authentication" ]
stackoverflow_0007517441_python_selenium_windows_authentication.txt
Q: Python decode text to ascii How to decode unicode string like this: what%2527s%2bthe%2btime%252c%2bnow%253f into ascii like this: what's+the+time+now A: in your case, the string was decoded twice, so we need unquote twice to get it back In [1]: import urllib In [2]: urllib.unquote(urllib.unquote("what%252...
Python decode text to ascii
How to decode unicode string like this: what%2527s%2bthe%2btime%252c%2bnow%253f into ascii like this: what's+the+time+now
[ "in your case, the string was decoded twice, so we need unquote twice to get it back\nIn [1]: import urllib\nIn [2]: urllib.unquote(urllib.unquote(\"what%2527s%2bthe%2btime%252c%2bnow%253f\") )\nOut[3]: \"what's+the+time,+now?\"\n\n", "Something like this?\ntitle = u\"what%2527s%2bthe%2btime%252c%2bnow%253f\"\npr...
[ 6, 0, 0 ]
[]
[]
[ "decode", "python", "unicode" ]
stackoverflow_0007530561_decode_python_unicode.txt
Q: Python command to create no-arch rpm's I am creating rpm's for my project which is in pure python. I am running the command python setup.py bdist_rpm to build the rpm. This is creating architechture specific rpm's (x86 or x86-64). What I would like is to have a no-arch rpm. Can any of python guru's help me with ...
Python command to create no-arch rpm's
I am creating rpm's for my project which is in pure python. I am running the command python setup.py bdist_rpm to build the rpm. This is creating architechture specific rpm's (x86 or x86-64). What I would like is to have a no-arch rpm. Can any of python guru's help me with creating a no-arch rpm. Any help would be ap...
[ "If your software does not contain extension modules (modules written in C/C++), distutils will make the RPM noarch. I don’t think there’s a way to explicitly control it.\n" ]
[ 1 ]
[]
[]
[ "distutils", "python", "rpm" ]
stackoverflow_0007400099_distutils_python_rpm.txt
Q: Which lightweight python web framework has applications and hot-deployed code I am used to PHP having applications. For example, c:\xampp\htdocs\app1 c:\xampp\htdocs\app2 can be accessed as localhost://app1/page.php localhost://app2/page.php Things to be noticed: a directory placed inside the www-root directory...
Which lightweight python web framework has applications and hot-deployed code
I am used to PHP having applications. For example, c:\xampp\htdocs\app1 c:\xampp\htdocs\app2 can be accessed as localhost://app1/page.php localhost://app2/page.php Things to be noticed: a directory placed inside the www-root directory maps directly with the URL when a file/directory is added/removed/changed, the wor...
[ "No mature python framework that I'm aware of allows you to map urls to python modules, and frankly, for good reason. You can do this with CGI, but it's definitely not the recommended way to deploy python apps. Setting that requirement aside, flask and bottle are both lightweight micro web-frameworks with similar a...
[ 4, 2, 1 ]
[ "If you are used to PHP, you might want to take a look at the Apache modules mod_python or mod_wsgi (and WSGI in general if you do web development -- which is the Pythonic way).\nWith those two modules, the Python interpreter gets started every time a request comes in (similar to PHP). Needless to say, this slows t...
[ -1 ]
[ "python" ]
stackoverflow_0007529229_python.txt
Q: Parsing Django Queryset JSON I want to parse a query set to output json data. However I need to make it so that the new jquery ui autocomplete can use it too, and the autocomplete needs the keys label, id and value to be able to read it. Currently I use: emp_list = Employees.objects.filter(eng_name__icontains=...
Parsing Django Queryset JSON
I want to parse a query set to output json data. However I need to make it so that the new jquery ui autocomplete can use it too, and the autocomplete needs the keys label, id and value to be able to read it. Currently I use: emp_list = Employees.objects.filter(eng_name__icontains=q_term) json_serializer = ser...
[ "build it in your view then json dump it \nemployees_output_list = []\nfor emp in emp_list:\n name_rank_str = \"%s (%s)\" % (emp.first_name, emp.rank)\n emp_dict = {\n \"id\": emp.pk,\n \"label\": name_rank_str,\n \"value\": name_rank_str,\n }\n employees_output_list.append(emp_dict)\nreturn HttpRespon...
[ 2 ]
[]
[]
[ "django", "jquery", "python" ]
stackoverflow_0007531310_django_jquery_python.txt
Q: Parallel execution in cx-oracle I have recently joined a new company and am new to python (their preferred scripting language) and have been working with cx_oracle to create some ETL processes. The scripts I have built so far have been single-threaded jobs that select the subset of columns I need from an Oracle s...
Parallel execution in cx-oracle
I have recently joined a new company and am new to python (their preferred scripting language) and have been working with cx_oracle to create some ETL processes. The scripts I have built so far have been single-threaded jobs that select the subset of columns I need from an Oracle source DB and write the output to a na...
[ "First of all, you need to make sure that *cx_Oracle* is thread-safe. Since it implements the Python DB API Spec v2.0, all you need to do is check the threadsafety module global. \nValues 2 or 3 mean that you can open multiple connections to the DB and run multiple queries at the same time. The best way to do this ...
[ 1 ]
[]
[]
[ "cx_oracle", "python" ]
stackoverflow_0007530319_cx_oracle_python.txt
Q: ctypes and passing a by reference to a function I'm trying to use libpcap in python3 using ctypes. given the following function in C pcap_lookupnet(dev, &net, &mask, errbuf) in python I have the following pcap_lookupnet = pcap.pcap_lookupnet mask = ctypes.c_uint32 net = ctypes.c_int32 if(pcap_lookupnet(dev,net...
ctypes and passing a by reference to a function
I'm trying to use libpcap in python3 using ctypes. given the following function in C pcap_lookupnet(dev, &net, &mask, errbuf) in python I have the following pcap_lookupnet = pcap.pcap_lookupnet mask = ctypes.c_uint32 net = ctypes.c_int32 if(pcap_lookupnet(dev,net,mask,errbuf) == -1): print("Error could not get netm...
[ "You need to create instances for net and mask, and use byref to pass them.\nmask = ctypes.c_uint32()\nnet = ctypes.c_int32()\npcap_lookupnet(dev, ctypes.byref(net), ctypes.byref(mask), errbuf)\n\n", "You probably need to use ctypes.pointer, like this:\npcap_lookupnet(dev, ctypes.pointer(net), ctypes.pointer(mask...
[ 24, 2, 2 ]
[]
[]
[ "ctypes", "libpcap", "python" ]
stackoverflow_0007530473_ctypes_libpcap_python.txt
Q: Need help using python 2.7.1 to select and run various batch files based on user input all. I am trying to use python 2.7.1 to run batch files based on what a user enters at the input prompt. The problem I'm having is the batch files do not run. I have been able to get a specific batch file to run from python i...
Need help using python 2.7.1 to select and run various batch files based on user input
all. I am trying to use python 2.7.1 to run batch files based on what a user enters at the input prompt. The problem I'm having is the batch files do not run. I have been able to get a specific batch file to run from python if it is called from main() but cannot get python to select the file based on the input value...
[ "Use raw_input istead of input. input converts numeric input to from string to integer.\n>>> input()\n001\n1\n>>> raw_input()\n001\n'001'\n\n" ]
[ 0 ]
[]
[]
[ "batch_file", "python" ]
stackoverflow_0007531514_batch_file_python.txt
Q: regexp matching slug Please help with slug regexp. I would appreciate if the code will be given in python. Conditions: 1 #valid 1-1 #valid 1-1-1 #valid (infinite \d-\d) 1- #invalid -1 #invalid -1- #invalid *NOTE 1 = \d A: I would write it this way: compiled = re.compile(r'\d(?:-\d)*$') result = compiled.mat...
regexp matching slug
Please help with slug regexp. I would appreciate if the code will be given in python. Conditions: 1 #valid 1-1 #valid 1-1-1 #valid (infinite \d-\d) 1- #invalid -1 #invalid -1- #invalid *NOTE 1 = \d
[ "I would write it this way:\ncompiled = re.compile(r'\\d(?:-\\d)*$')\nresult = compiled.match(string_to_parse)\n\n", "How about:\nre.match(r'\\d(?:-\\d)*$', s)\n\n" ]
[ 5, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007531689_python_regex.txt
Q: Sqlite3 / Webpy: "no such column" with double left join I am trying to do Sqlite3 query via webpy framework.The query works in SQLiteManager. But with web.db i get "sqlite3.OperationalError no such column a.id". Is this a webpy bug? import web db = web.database(dbn='sqlite', db='data/feed.db') account = 1 query='...
Sqlite3 / Webpy: "no such column" with double left join
I am trying to do Sqlite3 query via webpy framework.The query works in SQLiteManager. But with web.db i get "sqlite3.OperationalError no such column a.id". Is this a webpy bug? import web db = web.database(dbn='sqlite', db='data/feed.db') account = 1 query=''' SELECT a.id, a.url, a.title, a.description, a.account_...
[ "Not sure why you are getting the error \"no such column a.id\", but \nit may help to \n\nuse a multiline string (easier to read),\nuse a parametrized argument for account (Was $account a Perl-hangover?)\n\n\nquery = '''\n SELECT a.id, a.url, a.title, a.description, a.account_count, b.id subscribed \n ...
[ 0 ]
[]
[]
[ "left_join", "python", "sqlite", "web", "web.py" ]
stackoverflow_0007531835_left_join_python_sqlite_web_web.py.txt
Q: Python regex catch two kind of comment Exemple : a = "bzzzzzz <!-- blabla --> blibli * bloblo * blublu" I want to catch the first comment. A comment may be (<!-- .* -->) or (\* .* \*) That is ok : re.search("<!--(?P<comment> .* )-->",a).group(1) Also that : re.search("\*(?P<comment> .* )\*",a).group(1) But if...
Python regex catch two kind of comment
Exemple : a = "bzzzzzz <!-- blabla --> blibli * bloblo * blublu" I want to catch the first comment. A comment may be (<!-- .* -->) or (\* .* \*) That is ok : re.search("<!--(?P<comment> .* )-->",a).group(1) Also that : re.search("\*(?P<comment> .* )\*",a).group(1) But if i want one or the other in comment, i have ...
[ "Try conditional expression:\n>>> for m in re.finditer(r\"(?:(<!--)|(\\*))(?P<comment> .*? )(?(1)-->)(?(2)\\*)\", a):\n... print m.group('comment')\n...\n blabla\n bloblo\n\n", "As Gurney pointed out, you have two captures with the same name. Since you're not actually using the name, just leave that out.\nAlso,...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007531253_python_regex.txt
Q: How to install pymorph on windows? I am very new to python so sorry if this is a trivial question. I am developing on windows and I want to install the following library pymorph I know it can be installed on linux but how to install it on windows enviroment ? Thanks A: Download the package. Extract the package, ...
How to install pymorph on windows?
I am very new to python so sorry if this is a trivial question. I am developing on windows and I want to install the following library pymorph I know it can be installed on linux but how to install it on windows enviroment ? Thanks
[ "Download the package. Extract the package, cd to the folder (make sure setup.py is in the folder) and run python setup.py install from your cmd while in said folder.\n", "There are 2 main ways to install a python dependency.\nFirst method\nYou can install pymorph (and almost all python dependencies) with the eas...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007532091_python.txt
Q: Python range function Say I want to loop from 0 to 100 but with a step of 1/2. If you try for i in range(0, 100, 0.5): whatever Error: the step must not be 0 Question: Is there any built-in way in Python 2.x to do something like this? A: Python2.x: for idx in range(0, int(100 / 0.5)): print 0.5 * id...
Python range function
Say I want to loop from 0 to 100 but with a step of 1/2. If you try for i in range(0, 100, 0.5): whatever Error: the step must not be 0 Question: Is there any built-in way in Python 2.x to do something like this?
[ "Python2.x:\nfor idx in range(0, int(100 / 0.5)):\n\n print 0.5 * idx \n\noutputs: \n\n0.0\n0.5\n1.0\n1.5\n..\n99.0\n99.5\n\n\nNumpy:\nnumpy.arange would also do the trick.\nnumpy.arange(0, 100, 0.5)\n\n", "If you have numpy, here are two ways to do it:\nnumpy.arange(0, 100, 0.5)\n\nnumpy.linspace(0, 100,...
[ 26, 10, 4, 3, 0, 0 ]
[]
[]
[ "python", "python_2.7", "range" ]
stackoverflow_0007531945_python_python_2.7_range.txt
Q: django + javascript Application framework (not Jquery)? Step up from the Django + jQuery / Prototype question... Can anyone tell me about their experience with a UI application framework like YUI or spoutcore, but that works best with django? A: I've found that jQuery (or jQuery UI if you like) is always a soli...
django + javascript Application framework (not Jquery)?
Step up from the Django + jQuery / Prototype question... Can anyone tell me about their experience with a UI application framework like YUI or spoutcore, but that works best with django?
[ "I've found that jQuery (or jQuery UI if you like) is always a solid choice no matter what you're building, and I always end up using it with Django (or any other language/framework for that matter). Users almost always have it cached in their browsers, it's easy to use/learn, tons of examples on the net, and othe...
[ 3 ]
[]
[]
[ "ajax", "django", "frameworks", "python" ]
stackoverflow_0007532294_ajax_django_frameworks_python.txt
Q: how to redirect python's subprocess.Call methods output to a file and not console? I am using python's Call method in subprocess module to execute a sqlldr command from subprocess import call retcode = call([self.COMMAND, self.CONNECTION_STRING, "control=" +self.CONTROL_FILE, "log="+self.TEMP_LOG_FIL...
how to redirect python's subprocess.Call methods output to a file and not console?
I am using python's Call method in subprocess module to execute a sqlldr command from subprocess import call retcode = call([self.COMMAND, self.CONNECTION_STRING, "control=" +self.CONTROL_FILE, "log="+self.TEMP_LOG_FILE, self.MODE , "data="+loadfile]) When i run the above script the output of the sqlldr ...
[ "Open a file for writing and pass that as the stdout keyword argument of subprocess.call:\nwith open('stdout.txt', 'wb') as out:\n subprocess.call(['ls', '-l'], stdout=out)\n\n(subprocess.call accepts the same arguments as the subprocess.Popen constructor.)\n" ]
[ 2 ]
[]
[]
[ "python", "sql_loader", "subprocess" ]
stackoverflow_0007532455_python_sql_loader_subprocess.txt
Q: How can I use XPATH to add data of subtree to main tree in Python/Django I'm using etree to parse an external xml file and trying to get the listing data from a tree from the below external xml file and add the subtree agancy data to it. I am able to pull the data for isting and agancy just fine seperately, but ...
How can I use XPATH to add data of subtree to main tree in Python/Django
I'm using etree to parse an external xml file and trying to get the listing data from a tree from the below external xml file and add the subtree agancy data to it. I am able to pull the data for isting and agancy just fine seperately, but don't know how to merge them so that the listing gets the correct agency info. ...
[ "You can use listing.xpath('agency/name/text()')[0] as you iterate through your list to get the agency's name for just that listing.\nfor listing in listings:\n this_value = {\n 'bedrooms': listing.findtext('bedrooms'),\n 'bathrooms': listing.findtext('bathrooms'),\n 'agency': listing.xpath(...
[ 1 ]
[]
[]
[ "django", "dom", "python", "xml", "xpath" ]
stackoverflow_0007532200_django_dom_python_xml_xpath.txt
Q: Python pull back plain text body from message from IMAP account I have been working on this and am missing the mark. I am able to connect and get the mail via imaplib. msrv = imaplib.IMAP4(server) msrv.login(username,password) # Get mail msrv.select() #msrv.search(None, 'ALL') typ, data = msrv.search(None, 'AL...
Python pull back plain text body from message from IMAP account
I have been working on this and am missing the mark. I am able to connect and get the mail via imaplib. msrv = imaplib.IMAP4(server) msrv.login(username,password) # Get mail msrv.select() #msrv.search(None, 'ALL') typ, data = msrv.search(None, 'ALL') # iterate through messages for num in data[0].split(): typ, ...
[ "To get the plain text version of the body of the email I did something like this....\nxxx= data[0][1] #puts message from list into string\n\n\nxyz=email.message_from_string(xxx)# converts string to instance of message xyz is an email message so multipart and walk work on it.\n\n#Finds the plain text version of the...
[ 9, 1 ]
[]
[]
[ "email", "imap", "parsing", "plaintext", "python" ]
stackoverflow_0007519964_email_imap_parsing_plaintext_python.txt
Q: arguments in functions python This is a subtle question about notation. I want to call a function with specific arguments, but without having to redefine it. For example, min() with a key function on the second argument key = itemgetter(1) would look like: min_arg2 = lambda p,q = min(p,q, key = itemgetter(1)) ...
arguments in functions python
This is a subtle question about notation. I want to call a function with specific arguments, but without having to redefine it. For example, min() with a key function on the second argument key = itemgetter(1) would look like: min_arg2 = lambda p,q = min(p,q, key = itemgetter(1)) I'm hoping to just call it as somet...
[ "You want to use functools.partial():\nmin_arg2 = functools.partial(min, key=itemgetter(1))\n\nSee http://docs.python.org/library/functools.html for the docs.\nExample:\n>>> import functools\n>>> from operator import itemgetter\n>>> min_arg2 = functools.partial(min, key=itemgetter(1))\n>>> min_arg2(vals)\n('b', 0)\...
[ 10, 2 ]
[]
[]
[ "arguments", "python" ]
stackoverflow_0007532583_arguments_python.txt
Q: Python Script, args not transferred to Script I have got a Python Script called "gcc_opt.pyw" and I included its directory to the Windows PATH environment variable. But not a single commandline argument is passed to the script. Printing out sys.argv tells me there is only the filename in the argv-list. This comman...
Python Script, args not transferred to Script
I have got a Python Script called "gcc_opt.pyw" and I included its directory to the Windows PATH environment variable. But not a single commandline argument is passed to the script. Printing out sys.argv tells me there is only the filename in the argv-list. This command: gcc_opt HelloWorld.c -o HelloWorld.exe -shared ...
[ "The reason why you're not getting parameters is because you broke the .py\nassociation so you could double-click those files to open them in NotePad++, \nand subsequently broke the .pyw association to do what .py is supposed to do.\nIn short, you forgot to include the %* at the end of your Python.exe command \nlin...
[ 5, 2 ]
[]
[]
[ "cmd", "python" ]
stackoverflow_0007530303_cmd_python.txt
Q: Python style: should I avoid commenting my import statements? I'll try to make this as closed-ended of a question as possible: I often find that I have a group of imports that go together, like a bunch of mathy imports; but later on I might delete or move the section of code which uses those imported items to anot...
Python style: should I avoid commenting my import statements?
I'll try to make this as closed-ended of a question as possible: I often find that I have a group of imports that go together, like a bunch of mathy imports; but later on I might delete or move the section of code which uses those imported items to another file. The problem is that I often forget why I was using a part...
[ "Well, the beautiful thing about python is that it is (or should be) explicit. In this case, so long as you're not doing * imports, (which is considered bad practice), you'll KNOW whether an import is referenced simply by doing a grep for the namespace. And then you'll know whether you can delete it.\nAllow me to a...
[ 11, 5, 3, 1, 1 ]
[]
[]
[ "coding_style", "comments", "import", "python" ]
stackoverflow_0007533050_coding_style_comments_import_python.txt
Q: eclipse: Run/Debug current file In search of a Python debugger I stumbled upon Aptana, which is based on eclipse. Often, I want to debug a single python script. However, Aptana won't let me run/debug the currently opened file directly. Instead, it requires me to create a debug/run configuration for each file I wou...
eclipse: Run/Debug current file
In search of a Python debugger I stumbled upon Aptana, which is based on eclipse. Often, I want to debug a single python script. However, Aptana won't let me run/debug the currently opened file directly. Instead, it requires me to create a debug/run configuration for each file I would like to run/debug. Alternatively I...
[ "This is because Aptana/Eclipse doesn't \"realize\" that the file you opened should be debugged using the Python debugger as it's not associated with a Python project/perspective (there's a lot of environment setup when a project is created in Aptana/Eclipse). \nThe simplest solution, IMO, would be to create a simp...
[ 4, 1 ]
[]
[]
[ "aptana", "debugging", "eclipse", "python" ]
stackoverflow_0007335185_aptana_debugging_eclipse_python.txt
Q: Which python web framework has hassle-free development and deployment? I have written a web API in BaseHTTPServer. It is meant to be used only on localhost. It returns JSON objects on GET/POST operations. http://localhost:8888/operation?param and code is like def do_GET(self): if self.path=="operation": ...
Which python web framework has hassle-free development and deployment?
I have written a web API in BaseHTTPServer. It is meant to be used only on localhost. It returns JSON objects on GET/POST operations. http://localhost:8888/operation?param and code is like def do_GET(self): if self.path=="operation": self.wfile.write("output") But I am worried about keep-alive mechanisms (r...
[ "The recommended way of deploying wsgi is as a long-running-process, either embedded or daeomonized, and not as a cgi script. Either way, its going to be a little different than just uploading files like in php, restarting the server/process by touching the config file is normally the closest you get to \"hot-deplo...
[ 6, 0, 0 ]
[]
[]
[ "cherrypy", "flask", "python" ]
stackoverflow_0007525130_cherrypy_flask_python.txt
Q: random string in python I am trying to make a script that will generate a random string of text when i run it. I have got far but im having a problem with formatting. Here is the code im using import random alphabet = 'abcdefghijklmnopqrstuvwxyz' min = 5 max = 15 name = random.sample(alphabet,random.randint(...
random string in python
I am trying to make a script that will generate a random string of text when i run it. I have got far but im having a problem with formatting. Here is the code im using import random alphabet = 'abcdefghijklmnopqrstuvwxyz' min = 5 max = 15 name = random.sample(alphabet,random.randint(min,max)) print name And wh...
[ "join() it:\n>>> name = ['i', 'c', 'x', 'n', 'y', 'b', 'g', 'r', 'h', 'p', 'w', 'o']\n>>> ''.join(name)\n'icxnybgrhpwo'\n\n", "import string\nimport random\n\ndef create_random(length=8):\n \"\"\" Create a random string of {length} length \"\"\"\n chars = string.letters + string.digits\n return ''.join(r...
[ 12, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007524500_python.txt
Q: how to get a word count on word document in python? I am trying to get the word counts of .doc .docx .odt and .pdf type files. This is pretty simple for .txt files but how can I go about doing a word count on the mentioned types? I'm using python django on Ubuntu and trying to word count the documents words when a...
how to get a word count on word document in python?
I am trying to get the word counts of .doc .docx .odt and .pdf type files. This is pretty simple for .txt files but how can I go about doing a word count on the mentioned types? I'm using python django on Ubuntu and trying to word count the documents words when a user uploads a file through the system.
[ "First you need to read your .doc .docx .odt and .pdf.\nSecond, count the words (<2.7 version).\n", "Given that you can do this for .txt files I'll assume that you know how to count the words, and that you just need to know how to read the various file types. Take a look at these libraries:\nPDF: pypdf\ndoc/docx...
[ 4, 0 ]
[]
[]
[ "django", "python", "word_count" ]
stackoverflow_0007529287_django_python_word_count.txt
Q: Why is __init__.py not being called? I'm using Python 2.7 and have the following files: ./__init__.py ./aoeu.py __init__.py has the following contents: aoeu aoeuaoeu aoeuaoeuaoeu so I would expect running aoeu.py to error when Python tries to load __init__.py, but it doesn't. The behavior is the same whether PY...
Why is __init__.py not being called?
I'm using Python 2.7 and have the following files: ./__init__.py ./aoeu.py __init__.py has the following contents: aoeu aoeuaoeu aoeuaoeuaoeu so I would expect running aoeu.py to error when Python tries to load __init__.py, but it doesn't. The behavior is the same whether PYTHONPATH is set to '.' or unset. What's go...
[ "__init__.py makes the enclosing directory a package. It won't be executed unless you actually try to import the package directly.\n" ]
[ 16 ]
[]
[]
[ "python" ]
stackoverflow_0007533480_python.txt
Q: Django sub queries I have a basic database that I want to pull out sub data (related) in the same view: models.py: class InvoiceHeader(models.Model): customer = models.CharField(max_length = 255) number = models.IntegerField(unique = True) class InvoiceLine(models.Model): description = models.CharFiel...
Django sub queries
I have a basic database that I want to pull out sub data (related) in the same view: models.py: class InvoiceHeader(models.Model): customer = models.CharField(max_length = 255) number = models.IntegerField(unique = True) class InvoiceLine(models.Model): description = models.CharField(max_length = 255) ...
[ "You want to use aggregation:\nfrom django.db.models import Sum\n\ndef list_invoices(request):\n invoices = Item.objects.all().annotate(subtotal=Sum('invoiceline__price'))\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007533309_django_django_models_python.txt
Q: python: in parent class's method, call classmethod of that class, but bound to a child class Say I have the following code: class Parent(object): classattr1 = 'parent' def __init__(self): Parent.foo() @classmethod def foo(cls): print cls.classattr1 class Child(Parent): classat...
python: in parent class's method, call classmethod of that class, but bound to a child class
Say I have the following code: class Parent(object): classattr1 = 'parent' def __init__(self): Parent.foo() @classmethod def foo(cls): print cls.classattr1 class Child(Parent): classattr1 = 'child' def foo(cls): raise Exception("I shouldn't be here") Child() In Paren...
[ "Here is an option:\nclass Parent(object):\n classattr1 = 'parent'\n def __init__(self):\n Parent.foo(self)\n\n def foo(self):\n print self.classattr1 # or self.__class__.classattr1\n\nclass Child(Parent):\n classattr1 = 'child'\n def foo(cls):\n raise Exception(\"I shouldn't...
[ 1, 0, 0 ]
[]
[]
[ "attributes", "class_method", "inheritance", "python" ]
stackoverflow_0007533120_attributes_class_method_inheritance_python.txt
Q: PyDev: @DynamicAttrs for modules In the program I am writing, I created a module called settings that declares a few constants but loads other from a configuration file, placing them in the module namespace (for example: the value of π might be in the code of the module, but the weight of the user in a configurati...
PyDev: @DynamicAttrs for modules
In the program I am writing, I created a module called settings that declares a few constants but loads other from a configuration file, placing them in the module namespace (for example: the value of π might be in the code of the module, but the weight of the user in a configuration file). This is such that in other m...
[ "Actually you'd probably have the same error even if it wasn't a wild import (i.e.: import settings / settings.MY_VARIABLE would still show an error because the code-analysis can't find it).\nAside from the @UndefinedVariable in each place that references it (CTRL+1 will show that option), I think that a better pat...
[ 3, 0 ]
[]
[]
[ "aptana", "code_analysis", "pydev", "python" ]
stackoverflow_0007521485_aptana_code_analysis_pydev_python.txt
Q: How can I tell what class in the polymorphic hierarchy contains the method I'm about to call? If I have: class A(): def f(self): print("running function, f from class A") class B(A): def __init__(self): A.__init__(self) def f(self): print("running function, f from class B") and...
How can I tell what class in the polymorphic hierarchy contains the method I'm about to call?
If I have: class A(): def f(self): print("running function, f from class A") class B(A): def __init__(self): A.__init__(self) def f(self): print("running function, f from class B") and I make an instance of class B and call f on it, we all know we'll see the message about "from clas...
[ "class A():\n def f(self):\n print(\"running function, f from class A\")\nclass B(A):\n def f(self):\n print(\"running function, f from class B\")\nclass C(A):\n pass\n\nThis shows that B.f does not equal A.f. So B must override f:\nobj = B()\nprint(obj.__class__.f == A.f)\n# False\n\nThis sh...
[ 3, 1 ]
[]
[]
[ "introspection", "polymorphism", "python" ]
stackoverflow_0007533464_introspection_polymorphism_python.txt
Q: How to process zip file with Python a.zip--- -- b.txt -- c.txt -- d.txt Methods to process the zip files with Python, I could expand the zip file to a temporary directory, then process each txt file one bye one Here, I am more interested to know whether or not python provides such a way so that ...
How to process zip file with Python
a.zip--- -- b.txt -- c.txt -- d.txt Methods to process the zip files with Python, I could expand the zip file to a temporary directory, then process each txt file one bye one Here, I am more interested to know whether or not python provides such a way so that I don't have to manually expand the zip f...
[ "The Python standard library helps you.\nDoug Hellman writes very informative posts about selected modules: https://pymotw.com/3/zipfile/\nTo comment on Davids post: From Python 2.7 on the Zipfile object provides a context manager, so the recommended way would be:\nimport zipfile\nwith zipfile.ZipFile(\"zipfile.zip...
[ 28, 7 ]
[]
[]
[ "python" ]
stackoverflow_0007533677_python.txt
Q: Encrypting passwords on POST Django aside from using SSL, is there any way to encrypt a password in the Django framework on the first POST to the server? For example, if I have a form that accepts a username and password, then send it to another view, aren't the passwords sent to the backend unencrypted? If so, is...
Encrypting passwords on POST Django
aside from using SSL, is there any way to encrypt a password in the Django framework on the first POST to the server? For example, if I have a form that accepts a username and password, then send it to another view, aren't the passwords sent to the backend unencrypted? If so, is there a way to encrypt the passwords bef...
[ "SSL is a de facto solution, but if for some reason you can't have it, then you'll find shelter in some javascript libraries that encrypt post data. And there are plenty of them if you search.. But I don't believe that any of them can achieve maximum security.\n" ]
[ 5 ]
[]
[]
[ "django", "encryption", "python" ]
stackoverflow_0007532972_django_encryption_python.txt
Q: Which one to learn Python 3.x or Python 2.x? I wanted to learn the python programming but I don't know which one to learn, I mean I think there are some difference between the two languages and I wanted to know which one is going to be used in the future. It does make sense if I learn Python 2.x and it is stopped ...
Which one to learn Python 3.x or Python 2.x?
I wanted to learn the python programming but I don't know which one to learn, I mean I think there are some difference between the two languages and I wanted to know which one is going to be used in the future. It does make sense if I learn Python 2.x and it is stopped being used by anyone. Any info please?
[ "Most useful modules still aren't ported to Python3. So if you need to call such things you are better off learning Python 2.x until they are ported. Even today the standard version of Python that OSes call is 2.x. (For instance OSX Lion has 2.7.1) Unless there's a compelling reason to use 3.x (such as just lea...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007532339_python.txt
Q: How to keep a variable value across requests in web.py I want to update logfile as soon as a request comes. I have a class variable event_logging_enabled which is initialised to TRUE. and in the POST() function I check the value of event_logging_enabled. Now at run time, I modify the value of this flag to FALSE f...
How to keep a variable value across requests in web.py
I want to update logfile as soon as a request comes. I have a class variable event_logging_enabled which is initialised to TRUE. and in the POST() function I check the value of event_logging_enabled. Now at run time, I modify the value of this flag to FALSE for subsequent requests. But It remains TRUE. During debuggin...
[ "What I've done in the past and it seems to work alright is if I need to have a variable that's persistent throughout all requests, I jam it onto the web object right before the app.run()\nFor example, if I want to have a variable called 'foo' that's shared throughout all requests and is persistent between requests...
[ 12, 3 ]
[]
[]
[ "python", "python_requests", "variables", "web.py" ]
stackoverflow_0007512681_python_python_requests_variables_web.py.txt
Q: Python - how to avoid exec for batching? I have an existing python application (limited deployment) that requires the ability to run batches/macros (ie do foo 3 times, change x, do y). Currently I have this implemented as exec running through a text file which contains simple python code to do all the required ba...
Python - how to avoid exec for batching?
I have an existing python application (limited deployment) that requires the ability to run batches/macros (ie do foo 3 times, change x, do y). Currently I have this implemented as exec running through a text file which contains simple python code to do all the required batching. However exec is messy (ie security i...
[ "Have you considered using a serialized data format like JSON? It's lightweight, can easily translate to Python dictionaries, and all the cool kids are using it. \nYou could construct the data in a way that is meaningful, but doesn't require containing actual code. You could then read in that construct, grab the pa...
[ 0 ]
[]
[]
[ "exec", "python" ]
stackoverflow_0007534078_exec_python.txt
Q: What is the best way to handle SOAP type Exceptions in python In case the user enters data that is NOT on the web server being accessed by a WSDL, i get an error: <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:ns3="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/e...
What is the best way to handle SOAP type Exceptions in python
In case the user enters data that is NOT on the web server being accessed by a WSDL, i get an error: <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:ns3="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns0="http://schemas.xmlsoap.org/soap/encoding/" xml...
[ "it was fixed in jira.py :\nchange he decode function to:\n\ndef decode(e):\n \"\"\"Process an exception for useful feedback\"\"\"\n # TODO how to log the fact it is an error, but allow info to be unchanged?\n # TODO now fault not faultstring?\n # The faultType class has faultcode, faultstring and detai...
[ 1 ]
[]
[]
[ "python", "soap", "xml" ]
stackoverflow_0007529703_python_soap_xml.txt
Q: django save data in database only when certain conditions are met I have a python function that scrapes some data from a few different websites and I want to save that data into my database only if a certain condition is met. Namely, the scraped data should only be saved if the combination of the location and dat...
django save data in database only when certain conditions are met
I have a python function that scrapes some data from a few different websites and I want to save that data into my database only if a certain condition is met. Namely, the scraped data should only be saved if the combination of the location and date field is unique So in my view I have a new location variable and and ...
[ "You want a combination of two things. First, you want a inner Meta class to enforce the uniqueness in the database:\nclass Speech(models.Model):\n location = models.ForeignKey(Location)\n speaker = models.CharField(max_length=100)\n date = models.DateField()\n\n class Meta:\n unique_together = (...
[ 1 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0007534047_django_django_models_django_views_python.txt
Q: calling functions returned as pointers from other functions in ctypes I'm trying to use ctypes to call a c function that was returned as a pointer from another function. It seems from the documentation that I can do this by declaring the function with CFUNCTYPE, and then creating an instance using the pointer. T...
calling functions returned as pointers from other functions in ctypes
I'm trying to use ctypes to call a c function that was returned as a pointer from another function. It seems from the documentation that I can do this by declaring the function with CFUNCTYPE, and then creating an instance using the pointer. This, however seems to give me a segfault. Here is some sample code. sample...
[ "You are not defining any return type for _foo, try adding:\n_foo.restype = c_void_p\n\nctypes defaults to int returntype, and it looks (from the cast done in you pdb session) like you are on a 64-bit system meaning that you pointer will be truncated when converted to int. On my system the code seems to work - but ...
[ 2 ]
[]
[]
[ "ctypes", "function_pointers", "python" ]
stackoverflow_0007533898_ctypes_function_pointers_python.txt
Q: pygtk OSError: [Errno 2] No such file or directory. subprocess.Popen PIPE command I'm new to python and I'm trying to make a search bar that searches only 2 directories using two find commands and output the results into an ordered list []. def search_entry(self, widget,): s1 = subprocess.Popen(['find...
pygtk OSError: [Errno 2] No such file or directory. subprocess.Popen PIPE command
I'm new to python and I'm trying to make a search bar that searches only 2 directories using two find commands and output the results into an ordered list []. def search_entry(self, widget,): s1 = subprocess.Popen(['find /home/bludiescript/tv-shows', '-type f'], shell=False, stdout=subprocess.PIPE) ...
[ "Separate all the arguments in the args list:\ns1 = subprocess.Popen(['find','/home/bludiescript/tv-shows', '-type','f'], shell=False, stdout=subprocess.PIPE)\ns2 = subprocess.Popen(['find','/media/FreeAgent\\ GoFlex\\ Drive/tobins-media', '-type', 'f'], stdin=s1.stdout, shell=False, stdout=subprocess.PIPE)\n\nOUT...
[ 2, 0 ]
[]
[]
[ "pipe", "pygtk", "python", "subprocess" ]
stackoverflow_0007532023_pipe_pygtk_python_subprocess.txt
Q: Altering numpy function output array in place I'm trying to write a function that performs a mathematical operation on an array and returns the result. A simplified example could be: def original_func(A): return A[1:] + A[:-1] For speed-up and to avoid allocating a new output array for each function call, I w...
Altering numpy function output array in place
I'm trying to write a function that performs a mathematical operation on an array and returns the result. A simplified example could be: def original_func(A): return A[1:] + A[:-1] For speed-up and to avoid allocating a new output array for each function call, I would like to have the output array as an argument, ...
[ "If you want to perform the operation in-place, do\n\ndef inplace_func(A, out):\n np.add(A[1:], A[:-1], out)\n\nThis does not create any temporaries (which A[1:] + A[:-1]) does.\nAll Numpy binary operations have corresponding functions, check the list here: http://docs.scipy.org/doc/numpy/reference/ufuncs.html#a...
[ 12, 5 ]
[ "I agree with Olivers explanation. If you want to perform the operation inplace, you have to loop over your array manually. This will be much slower, but if you need speed you can resort to Cython which gives you the speed of a pure C implementation.\n" ]
[ -1 ]
[ "arrays", "function", "in_place", "numpy", "python" ]
stackoverflow_0007529786_arrays_function_in_place_numpy_python.txt
Q: importing modules in python i am having some trouble in understanding how to distribute a tornado application into multiple files.i need to have one file which creates the application instance another file which handles login/logout functionality ,another which handles profile page view and so on.but what i dont g...
importing modules in python
i am having some trouble in understanding how to distribute a tornado application into multiple files.i need to have one file which creates the application instance another file which handles login/logout functionality ,another which handles profile page view and so on.but what i dont get is how to do this . lets say f...
[ "What happens if you drop the \"import app\" in both auth.py and profile.py? it seems you are creating circular imports.\n" ]
[ 1 ]
[]
[]
[ "import", "module", "python", "tornado" ]
stackoverflow_0007533756_import_module_python_tornado.txt
Q: Scipy's fmin sticks only on inf only sometimes I'm using Scipy's fmin search to compute the log of the likelihood of a distribution's fit to some data. I'm using fmin to search for the parameters that maximize the log likelihood, like so: j = fmin(lambda p:-sum(log(likelihood_calculator(data, p))), array([1.5]), f...
Scipy's fmin sticks only on inf only sometimes
I'm using Scipy's fmin search to compute the log of the likelihood of a distribution's fit to some data. I'm using fmin to search for the parameters that maximize the log likelihood, like so: j = fmin(lambda p:-sum(log(likelihood_calculator(data, p))), array([1.5]), full_output=True) (likelihood_calculator takes data ...
[ "Maybe your update answers the question. Since fmin uses a downhill gradient algorithm, it searches in a neighborhood of the initial guess for the direction of steepest descent. If you are deep enough into a parameter-region where the function always returns inf then the algorithm can not see which direction to go....
[ 3 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0007534653_python_scipy.txt
Q: Using strings as incomplete bits of code in Python (please help me clarify the title) This is what I'd like to do: s = "'arg1', 'arg2', foo='bar', baz='qux'" def m(*args, **kwargs): return args, kwargs args, kwargs = m(magic(s)) # args = ['arg1', 'arg2'] # kwargs = {'foo': 'bar', 'baz'='qux'} What is the defin...
Using strings as incomplete bits of code in Python
(please help me clarify the title) This is what I'd like to do: s = "'arg1', 'arg2', foo='bar', baz='qux'" def m(*args, **kwargs): return args, kwargs args, kwargs = m(magic(s)) # args = ['arg1', 'arg2'] # kwargs = {'foo': 'bar', 'baz'='qux'} What is the definition of magic()? Parsing the string myself is a last re...
[ "With s and m defined as you have them:\n>>> args, kwargs = eval('m(%s)' % s)\n>>> args\n('arg1', 'arg2')\n>>> kwargs\n{'foo': 'bar', 'baz': 'qux'}\n\n", "Take a look at eval, but be aware that bad things can happen if you're not careful.\n" ]
[ 3, 0 ]
[]
[]
[ "eval", "metaprogramming", "python" ]
stackoverflow_0007534891_eval_metaprogramming_python.txt
Q: What is a pythonic webserver equivalent to IIS and ASP? For very simple, internal web-apps using ASP I was able to just switch IIS 'on' and then write some ASP scripts in the www directory that would start working immediately. Is there an equivalent webserver app for Python scripts that I can run that will automat...
What is a pythonic webserver equivalent to IIS and ASP?
For very simple, internal web-apps using ASP I was able to just switch IIS 'on' and then write some ASP scripts in the www directory that would start working immediately. Is there an equivalent webserver app for Python scripts that I can run that will automatically start serving dynamic pages (python scripts) in a cert...
[ "There's always CGI. Add a script mapping of .py to \"C:\\Python27\\python.exe\" -u \"%s\" then drop .py files in a folder and IIS will execute them.\nI'd not generally recommend it for real work—in the longer term you would definitely want to write apps to WSGI, and then deploy them through any number of interface...
[ 4, 1, 0, 0 ]
[]
[]
[ "python", "webserver" ]
stackoverflow_0007534244_python_webserver.txt
Q: python shelve ... bsddb deprecated ... how to get shelve to use another database? I have an app developed in python 2.7.2 on OS X. I use the module shelve and seems to default to bsddb on the mac. The program won't run on a Windows 7 machine with ActiveState python 2.7 because the module bsddb is not present and i...
python shelve ... bsddb deprecated ... how to get shelve to use another database?
I have an app developed in python 2.7.2 on OS X. I use the module shelve and seems to default to bsddb on the mac. The program won't run on a Windows 7 machine with ActiveState python 2.7 because the module bsddb is not present and is not in ActiveState's package manager (pypm). ActiveState's documentation says depreca...
[ "You can set the type of db created by setting anydbm._defaultmod before calling shelve.open. \nThis works for Python 2.6 (and maybe for 2.7?), but since anydbm._defaultmod is a private variable, be aware that this is a hack.\nanydbm._defaultmod=__import__('gdbm')\n\nFor example:\nimport anydbm\nimport whichdb\nimp...
[ 3, 2 ]
[]
[]
[ "python", "shelve" ]
stackoverflow_0007523205_python_shelve.txt
Q: Converting dynamic, nicely formatted tabular data in Python to str.format() I have the following Python 2.x code, which generates a header row for tabular data: headers = ['Name', 'Date', 'Age'] maxColumnWidth = 20 # this is just a placeholder headerRow = "|".join( ["%s" % k.center(maxColumnWidth) for k in headers...
Converting dynamic, nicely formatted tabular data in Python to str.format()
I have the following Python 2.x code, which generates a header row for tabular data: headers = ['Name', 'Date', 'Age'] maxColumnWidth = 20 # this is just a placeholder headerRow = "|".join( ["%s" % k.center(maxColumnWidth) for k in headers] ) print(headerRow) This code outputs the following: Name | ...
[ "headers = ['Name', 'Date', 'Age']\nmaxColumnWidth=21\nheaderRow = \"|\".join( \"{k:^{m}}\".format(k=k,m=maxColumnWidth) for k in headers )\nprint(headerRow)\n\nyields\n Name | Date | Age \n\n\nYou can represent the width maxColumnWidth as {m}, and then\nsubstitute the val...
[ 4, 3 ]
[]
[]
[ "migration", "python", "python_3.x" ]
stackoverflow_0007535236_migration_python_python_3.x.txt
Q: Ignore minimum size when resizing QWidget Is there a way to make a QWidget (and any subclass of it) completely ignore its minimum size? What I want is for a QPushButton to cut off when it is sized too small, rather than prevent the window from resizing (the default behavior). A: You can use: button.setSizePolicy...
Ignore minimum size when resizing QWidget
Is there a way to make a QWidget (and any subclass of it) completely ignore its minimum size? What I want is for a QPushButton to cut off when it is sized too small, rather than prevent the window from resizing (the default behavior).
[ "You can use:\nbutton.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)\n\nbut you'll have to set the initial size yourself.\nOr you can just set the minimum size to a small non-zero value:\nbutton.setMinimumSize(1,1)\n\nTo apply that to all buttons within a widget, you could try to use a style sheet, but the...
[ 1 ]
[]
[]
[ "pyqt", "python", "qt", "qwidget" ]
stackoverflow_0007534644_pyqt_python_qt_qwidget.txt
Q: auto-Writing/auto-Inputting application for a lousy routine web-based submitions? I've started learning python for a week, as always love to learn as much languages as I can ; as python is one of the easiest languages, but still there's lots of things teachers won't tell. Interacting with web pages is an obvious e...
auto-Writing/auto-Inputting application for a lousy routine web-based submitions?
I've started learning python for a week, as always love to learn as much languages as I can ; as python is one of the easiest languages, but still there's lots of things teachers won't tell. Interacting with web pages is an obvious example; registration in forums and other websites gives a headache, so building a simpl...
[ "For a simply contacting the website, consider the requests or twill libraries. For screen-scraping, BeautifulSoup is your friend.\nIf third-party libraries really aren't an option, though, you'll need to delve into the htmllib, httplib, urllib, and urllib2 Python modules.\n" ]
[ 1 ]
[]
[]
[ "autocomplete", "python", "web" ]
stackoverflow_0007535669_autocomplete_python_web.txt
Q: Should these expressions evaluate differently? I was somewhat confused until I found the bug in my code. I had to change a.matched_images.count #True when variable is 0 to a.matched_images.count > 0 #False when variable is 0 Since I quickly wanted to know whether an object had any images, the first code will ap...
Should these expressions evaluate differently?
I was somewhat confused until I found the bug in my code. I had to change a.matched_images.count #True when variable is 0 to a.matched_images.count > 0 #False when variable is 0 Since I quickly wanted to know whether an object had any images, the first code will appear like the photo has images since the expression ...
[ "What is the nature of count? If it's a basic Python number, then if count is the same as if count != 0. On the other hand, if count is a custom class then it needs to implement either __nonzero__ or __len__ for Python 2.x, or __bool__ or __len__ for Python 3.x. If those methods are not defined, then every instan...
[ 3, 2, 1 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0007535765_if_statement_python.txt
Q: Python sys.exit() help? I am working in Python and am trying to have a line of code execute and after it executes I am calling sys.exit() to have the script itself "exit." However, it seems that sys.exit() is executing before the line of code above it executes. Below is the code I am trying to implement: if someth...
Python sys.exit() help?
I am working in Python and am trying to have a line of code execute and after it executes I am calling sys.exit() to have the script itself "exit." However, it seems that sys.exit() is executing before the line of code above it executes. Below is the code I am trying to implement: if something == True: self.redirec...
[ "There is probably some buffering or asynchrony in self.redirect(). People often run into a similar problem when they do a print, followed by sys.exit(): the print output gets buffered, and then the process exits before the in-process output buffer is flushed).\nYou can work around this by flushing buffers and/or ...
[ 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007535735_python.txt
Q: What do I put for a ParameterType value in an ITK function call in Python? I'm trying to do this using the ITK Python bindings: mi_metric = itk.MutualInformationImageToImageMetric[itk.Image.F3, itk.Image.F3].New() mi_metric.SetFixedImage(i1) mi_metric.SetMovingImage(i2) v = mi_metric.GetValue( ? ) The GetValue fu...
What do I put for a ParameterType value in an ITK function call in Python?
I'm trying to do this using the ITK Python bindings: mi_metric = itk.MutualInformationImageToImageMetric[itk.Image.F3, itk.Image.F3].New() mi_metric.SetFixedImage(i1) mi_metric.SetMovingImage(i2) v = mi_metric.GetValue( ? ) The GetValue function requires a ParameterType value to be passed to it, but I can't find any i...
[ "It appears to be an Array of double, so I'd assume that you need to create an itk.Array of type double.\nBut this class is meant to be used with an optimizer, and not really meant to be used alone. So, I'd normally create an Optimizer, and use it with that.\n", "This behavior is very well defined new application...
[ 0, 0 ]
[]
[]
[ "itk", "python", "vtk" ]
stackoverflow_0005186201_itk_python_vtk.txt
Q: Python sort unique list of lists' items I can't seem to find a question on SO about my particular problem, so forgive me if this has been asked before! Anyway, I'm writing a script to loop through a set of URL's and give me a list of unique urls with unique parameters. The trouble I'm having is actually comparing ...
Python sort unique list of lists' items
I can't seem to find a question on SO about my particular problem, so forgive me if this has been asked before! Anyway, I'm writing a script to loop through a set of URL's and give me a list of unique urls with unique parameters. The trouble I'm having is actually comparing the parameters to eliminate multiple duplicat...
[ "I'll assume that subsets are considered \"duplicates\" (non-commutatively, of course)...\nStart by converting each query into a set and ordering them all from largest to smallest. Then add each query to a new list if it isn't a subset of an already-added query. Since any set is a subset of itself, this logic cover...
[ 5 ]
[]
[]
[ "list", "python", "sorting", "unique" ]
stackoverflow_0007535889_list_python_sorting_unique.txt
Q: Why doesn't this closure modify the variable in the enclosing scope? This bit of Python does not work: def make_incrementer(start): def closure(): # I know I could write 'x = start' and use x - that's not my point though (: while True: yield start start += 1 return c...
Why doesn't this closure modify the variable in the enclosing scope?
This bit of Python does not work: def make_incrementer(start): def closure(): # I know I could write 'x = start' and use x - that's not my point though (: while True: yield start start += 1 return closure x = make_incrementer(100) iter = x() print iter.next() # Except...
[ "Whenever you assign a variable inside of a function it will be a local variable for that function. The line start += 1 is assigning a new value to start, so start is a local variable. Since a local variable start exists the function will not attempt to look in the global scope for start when you first try to acc...
[ 36, 11, 4, 3 ]
[]
[]
[ "closures", "generator", "python" ]
stackoverflow_0007535857_closures_generator_python.txt
Q: Problem having SQL statements that contain " or ' I am storing HTML in an SQLite3 database using python. When I go to insert some HTML into an SQL table I get an error/problem when I have '"' characters. The following example of my problem creates the incorrect SQL statement: INSERT INTO mytable(id, html, othe...
Problem having SQL statements that contain " or '
I am storing HTML in an SQLite3 database using python. When I go to insert some HTML into an SQL table I get an error/problem when I have '"' characters. The following example of my problem creates the incorrect SQL statement: INSERT INTO mytable(id, html, other) VALUE(1, " <img src="images/1.png" alt=""/> ", "some...
[ "Use a parameterized query:\nquery = \"\"\" INSERT INTO mytable(id, html, other) VALUES(?, ?, ?) \"\"\"\n\n# ...\n\ncur.execute(query, (1, HTML, \"some other info\"))\n\n" ]
[ 3 ]
[]
[]
[ "python", "sql", "sqlite", "syntax" ]
stackoverflow_0007536003_python_sql_sqlite_syntax.txt
Q: Data type conversion of column in numpy record array I have a numpy recarray with several integer columns and some string columns. The data in the string columns is composed 99% of integers, but numpy things it's a string because "NA" is in the column. So I have two questions: How do I remove the NA's and change ...
Data type conversion of column in numpy record array
I have a numpy recarray with several integer columns and some string columns. The data in the string columns is composed 99% of integers, but numpy things it's a string because "NA" is in the column. So I have two questions: How do I remove the NA's and change them to 0s? How can I convert the string columns to intege...
[ "Use where and astype:\n>>> x = np.array([123, 456, \"789\", \"NA\", \"0\", 0])\n>>> x \narray(['123', '456', '789', 'NA', '0', '0'], dtype='|S8')\n>>> np.where(x != 'NA', x, 0).astype(int)\narray([123, 456, 789, 0, 0, 0])\n\n" ]
[ 3 ]
[]
[]
[ "arrays", "matplotlib", "numpy", "python", "record" ]
stackoverflow_0007536120_arrays_matplotlib_numpy_python_record.txt
Q: Why doesn't PostgreSQL increase the last_value on the id_sequence when merging an instance? In a previous question, I was wondering why I was getting an Integrity Error from SA when merging an instance with an ID for the first time into the database (injecting fixture data). However, I learned to account for the p...
Why doesn't PostgreSQL increase the last_value on the id_sequence when merging an instance?
In a previous question, I was wondering why I was getting an Integrity Error from SA when merging an instance with an ID for the first time into the database (injecting fixture data). However, I learned to account for the problem by calling with the highest index I'm injecting: select setval('my_items_id_seq', {id}); ...
[ "If your object already has its PK attribute set, then the ID sequence will not be used and therefore not incremented because there is no reason for the database to perform an implicit insert into mytable (id, ...) values ((select nextval from mytable_id_seq), ...).\nAre you sure you need to be doing a merge instea...
[ 3, 0 ]
[]
[]
[ "postgresql", "python", "sqlalchemy" ]
stackoverflow_0007044980_postgresql_python_sqlalchemy.txt
Q: pyQt signals/slots with QtDesigner I'm trying to write a program that will interact with QGraphicsView. I want to gather mouse and keyboard events when the happen in the QGraphicsView. For example, if the user clicks on the QGraphicsView widget I will get the mouse position, something like that. I can hard code ...
pyQt signals/slots with QtDesigner
I'm trying to write a program that will interact with QGraphicsView. I want to gather mouse and keyboard events when the happen in the QGraphicsView. For example, if the user clicks on the QGraphicsView widget I will get the mouse position, something like that. I can hard code it rather easily, but I want to use QtDe...
[ "The signal must come from the QGraphicsView object that was defined in the ui.\nYou can create a class derived from QGraphicsView like this\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\nclass MyView(QGraphicsView):\n moved = pyqtSignal(QMouseEvent)\n\n def __init__(self, parent = None):\n ...
[ 3 ]
[]
[]
[ "pyqt4", "python", "qt_designer", "signals", "slots" ]
stackoverflow_0007524307_pyqt4_python_qt_designer_signals_slots.txt
Q: I can't change the default Python version from Apple supplied 2.7.2 to 3.2.2 (OS10.7) in Lion, have installed python 3.2.2 from python.org. It comes with a terminal command that is supposed to move this version of python earlier by updating my shell profile. When i run it, and then check my default python in Termi...
I can't change the default Python version from Apple supplied 2.7.2 to 3.2.2 (OS10.7)
in Lion, have installed python 3.2.2 from python.org. It comes with a terminal command that is supposed to move this version of python earlier by updating my shell profile. When i run it, and then check my default python in Terminal, it still says 2.7.2 which is the Apple supplied one. Do I need to run the command with...
[ "For Python 3 interpreters, you must enter python3 not python.\n$ python -V\nPython 2.7.2\n$ python3 -V\nPython 3.2.2\n\nFor more background on the current recommendation that python refer to a version of Python 2 and python3 refer to a version of Python 3, see the draft PEP 394 - The \"python\" Command on Unix-Lik...
[ 2, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0007536250_macos_python.txt
Q: python subprocess.Popen vs shlex question my sub process command to search first off it only searches one directory that i wrote (s2) omits the first (s1). second i was doing some reading on python docs and got confused. my code def search_entry(self, widget): s1 = subprocess.Popen(['find', '/home/bl...
python subprocess.Popen vs shlex question
my sub process command to search first off it only searches one directory that i wrote (s2) omits the first (s1). second i was doing some reading on python docs and got confused. my code def search_entry(self, widget): s1 = subprocess.Popen(['find', '/home/bludiescript/tv-shows', '-type', 'f'], shell=Fals...
[ "It sounds like you want to run a pair of commands and join the output from them:\ncmds = [\n 'find /media/FreeAgent\\ GoFlex\\ Drive/tobins-media -type f',\n 'find /home/bludiescript/tv-shows -type f'\n]\n\nouput = '\\n'.join(subprocess.check_output(shlex.split(cmd)) for cmd in cmds)\n\n", "Try os.walk ins...
[ 2, 0 ]
[]
[]
[ "list", "pipe", "python", "subprocess" ]
stackoverflow_0007535940_list_pipe_python_subprocess.txt
Q: Create a 2D array with a nested loop The following code n = 3 matrix = [[0] * n] * n for i in range(n): for j in range(n): matrix[i][j] = i * n + j print(matrix) prints [[6, 7, 8], [6, 7, 8], [6, 7, 8]] but what I expect is [[0, 1, 2], [3, 4, 5], [6, 7, 8]] Why? A: Note this: >>> matrix = [[0] ...
Create a 2D array with a nested loop
The following code n = 3 matrix = [[0] * n] * n for i in range(n): for j in range(n): matrix[i][j] = i * n + j print(matrix) prints [[6, 7, 8], [6, 7, 8], [6, 7, 8]] but what I expect is [[0, 1, 2], [3, 4, 5], [6, 7, 8]] Why?
[ "Note this:\n>>> matrix = [[0] * 3] * 3\n>>> [x for x in matrix]\n[[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n>>> [id(x) for x in matrix]\n[32484168, 32484168, 32484168]\n>>>\n\nThree rows but only one object.\nSee the docs especially Note 2 about the s * n operation.\nFix:\n>>> m2= [[0] * 3 for i in xrange(5)]\n>>> [id(x) ...
[ 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007536465_python.txt
Q: Flask app that routes based on subdomain I want to have my top-level domain as a portal for various subdomains that correspond to different sections of my site. example.com should route to a welcome.html template. eggs.example.com should route to an "eggs" subsection or application of the site. How would I achieve...
Flask app that routes based on subdomain
I want to have my top-level domain as a portal for various subdomains that correspond to different sections of my site. example.com should route to a welcome.html template. eggs.example.com should route to an "eggs" subsection or application of the site. How would I achieve this in Flask?
[ "@app.route() takes a subdomain argument to specify what subdomain the route is matched on. Blueprint also takes a subdomain argument to set subdomain matching for all routes in a blueprint.\nYou must set app.config['SERVER_NAME'] to the base domain so Flask knows what to match against. You will also need to specif...
[ 37 ]
[]
[]
[ "flask", "google_app_engine", "python", "url_routing", "werkzeug" ]
stackoverflow_0007512698_flask_google_app_engine_python_url_routing_werkzeug.txt
Q: How to alter these functions so that they recursively find the solution This is a question about Project Euler problem #67. (Find the maximum path down a triangle) I know it may be in bad taste to ask for help on these. I have these functions: def chooseBest(rowOfTriangle): if len(rowOfTriangle) == 1: ...
How to alter these functions so that they recursively find the solution
This is a question about Project Euler problem #67. (Find the maximum path down a triangle) I know it may be in bad taste to ask for help on these. I have these functions: def chooseBest(rowOfTriangle): if len(rowOfTriangle) == 1: return rowOfTriangle return list(max(element) for element in zip(rowOfTri...
[ "Something like this?\ndef max_path(triangle, idx=0, total=0):\n if triangle:\n row = triangle[0]\n next = max(row[idx:idx+2])\n return max_path(triangle[1:], row.index(next), total+next)\n return total\n\n" ]
[ 1 ]
[]
[]
[ "functional_programming", "python" ]
stackoverflow_0007536583_functional_programming_python.txt
Q: Python - Converting a Number to a Letter without an if statement I am making a program for my own purposes (a naming program) that completely generates a random name. The problem is I cannot assign a number to a letter, so as a being 1 and z being 26, or a being 0 and z being 25. It gives me a SyntaxError. I need ...
Python - Converting a Number to a Letter without an if statement
I am making a program for my own purposes (a naming program) that completely generates a random name. The problem is I cannot assign a number to a letter, so as a being 1 and z being 26, or a being 0 and z being 25. It gives me a SyntaxError. I need to assign this because the random integer (1,26) triggers a letter (if...
[ "chr (see here) and ord (see here) are the two functions you're looking for (though you already seem to know about the latter). Follow those links for a more detailed explanation.\nThe first gives you a one-character string based on the integer, the second does the reverse operaion (technically, it handles Unicode ...
[ 2, 2, 0 ]
[]
[]
[ "integer", "python", "string", "variables" ]
stackoverflow_0007535769_integer_python_string_variables.txt