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: What is the general way to implement operators precedence in Python Suppose I would like to write a fairly simple programming language, and I want to implement operators such like 2 + 3 * 2 = 8 What is the general way to implement things like this? A: I'm not sure how much detail you're interested in, but it s...
What is the general way to implement operators precedence in Python
Suppose I would like to write a fairly simple programming language, and I want to implement operators such like 2 + 3 * 2 = 8 What is the general way to implement things like this?
[ "I'm not sure how much detail you're interested in, but it sounds like you're looking to implement a parser. There's typically two steps:\nThe lexer reads over the text and converts it to tokens. For example, it might read \"2 + 3 * 2\" and convert it to INTEGER PLUS INTEGER STAR INTEGER\nThe parser reads in the to...
[ 11, 4 ]
[]
[]
[ "algorithm", "parsing", "programming_languages", "python" ]
stackoverflow_0008235666_algorithm_parsing_programming_languages_python.txt
Q: Searching images files with regular expressions I have a text file that looks like this: [22/Nov/2011 12:57:58] "GET /media/js/jquery-1.4.3.min.js HTTP/1.1" 304 0 [22/Nov/2011 12:57:58] "GET /media/js/fancybox/fancybox-x.png HTTP/1.1" 304 0 [22/Nov/2011 12:57:59] "GET /media/js/fancybox/fancybox-y.png HTTP/1.1" 30...
Searching images files with regular expressions
I have a text file that looks like this: [22/Nov/2011 12:57:58] "GET /media/js/jquery-1.4.3.min.js HTTP/1.1" 304 0 [22/Nov/2011 12:57:58] "GET /media/js/fancybox/fancybox-x.png HTTP/1.1" 304 0 [22/Nov/2011 12:57:59] "GET /media/js/fancybox/fancybox-y.png HTTP/1.1" 304 0 [22/Nov/2011 12:57:59] "GET /media/js/fancybox/bl...
[ "You're looking for non-capturing version of regular parentheses (?:...). The description is available in the re module docs.\ns ='''[22/Nov/2011 12:57:58] \"GET /media/js/jquery-1.4.3.min.js HTTP/1.1\" 304 0\n[22/Nov/2011 12:57:58] \"GET /media/js/fancybox/fancybox-x.png HTTP/1.1\" 304 0\n[22/Nov/2011 12:57:59] \"...
[ 3, 3, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008236020_python_regex.txt
Q: How to get the last four characters of a string whose length may change in Python My string coming in could be really any length i just need the last four characters: string = asdfPALD string = asddasdfBLCA A: Use string[-4:]: string = "asdfPALD" string[-4:] would equal 'PALD' A: Python has positive and (as b...
How to get the last four characters of a string whose length may change in Python
My string coming in could be really any length i just need the last four characters: string = asdfPALD string = asddasdfBLCA
[ "Use string[-4:]:\nstring = \"asdfPALD\"\n\nstring[-4:] would equal 'PALD'\n", "Python has positive and (as bizarre as it sounds) negative indexes. The negative indexes start at the end of the string (as you can see in the image). So if I want to get the last element of a string (regardless of the length of the s...
[ 9, 4, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008232934_python.txt
Q: Python directory structure on Windows vs Linux I am writing a Python script on Windows, that needs to work on a Red Hat Linux machine. On Windows, os.path.abspath(os.curdir) returns something like C:\Users\Me\...\CurrentDirectory without a trailing \ . I'm unable to run it on Linux, but to my knowledge it woul...
Python directory structure on Windows vs Linux
I am writing a Python script on Windows, that needs to work on a Red Hat Linux machine. On Windows, os.path.abspath(os.curdir) returns something like C:\Users\Me\...\CurrentDirectory without a trailing \ . I'm unable to run it on Linux, but to my knowledge it would be more like /home/Me/.../CurrentDirectory with ...
[ "It shouldn't matter if you use os.path.join()\nSee:\n\nPython os.path.join on Windows\nWhy doesn't os.path.join() work in this case?\n\n", "The behavior would be more or less the same across the OS. Instead of using \\ or / use \n os.sep\n\ninside your code. Do not try to hardcode anything\n" ]
[ 3, 2 ]
[]
[]
[ "compatibility", "directory", "linux", "python", "windows" ]
stackoverflow_0008236398_compatibility_directory_linux_python_windows.txt
Q: python matching on structures I have two related questions. First, i have a some information such as: (732, 2378) (233, 52172) 23 ['Mona'] 7 There are two tuples, two integers and one list. Let us index the five items as x[0] : x[4] My first question is what kind of data structure can I use to store these differ...
python matching on structures
I have two related questions. First, i have a some information such as: (732, 2378) (233, 52172) 23 ['Mona'] 7 There are two tuples, two integers and one list. Let us index the five items as x[0] : x[4] My first question is what kind of data structure can I use to store these different items (sorry, I'm new to python...
[ "It looks like the data structures in your question are already reasonable -- just put them in list form. If you use named tuples, the search code will tend to be more readable than otherwise. For the search/match code look at operator.attrgetter and operator.itemgetter.\nFor example, here is a convenient form to...
[ 2 ]
[]
[]
[ "data_structures", "matching", "python" ]
stackoverflow_0008236395_data_structures_matching_python.txt
Q: How to catch the stdio from a python subroutine? I have the following codes: def fsub(): print 'OK' def fmain(): a = fsub() fmain() Apparently fsub() won't return 'OK' and assign to a in fmain(). However, this is what I want. Is there anyway we can make it without changing fsub()? A: When you do a = fsub(...
How to catch the stdio from a python subroutine?
I have the following codes: def fsub(): print 'OK' def fmain(): a = fsub() fmain() Apparently fsub() won't return 'OK' and assign to a in fmain(). However, this is what I want. Is there anyway we can make it without changing fsub()?
[ "When you do a = fsub(), you're trying to assing a the return of fsub(), in this case None (because fsub() doesn't return anything).\nThe correct thing to do is to redirect the stdout to a file, then call the fsub() function, and the redirect back the stdout to the original stdout:\nimport sys\n\ndef fmain():\n ...
[ 3 ]
[]
[]
[ "io", "python" ]
stackoverflow_0008236556_io_python.txt
Q: Extracting links from HTML table using BeautifulSoup with unclean source code I am trying to scrape articles from a Chinese newspaper database. Here is some of the source code (pasting excerpt b/c keyed site): <base href="http://huylpd.twinbridge.com.ezp-prod1.hul.harvard.edu/web\" /><html> <! -- <%@ page content...
Extracting links from HTML table using BeautifulSoup with unclean source code
I am trying to scrape articles from a Chinese newspaper database. Here is some of the source code (pasting excerpt b/c keyed site): <base href="http://huylpd.twinbridge.com.ezp-prod1.hul.harvard.edu/web\" /><html> <! -- <%@ page contentType="text/html;charset=GBK" %> <head> <meta http-equiv="Content-Language" content=...
[ "Removing the second line made BS find all the tags. I didn't find a better way to parse this.\npage = br.open(url)\npage = page.read().replace('<! -- <%@ page contentType=\"text/html;charset=GBK\" %>', '')\nsoup = BeautifulSoup(page)\n\n", "When your html is very messed up, it's better to clean it up a little fi...
[ 1, 0, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0008235637_beautifulsoup_python.txt
Q: SCons: How to call a self defined python function in scons script and make right dependency I write a python function such as replace strings and called in scons script. def Replace(env, filename, old, new): with open(filename,"r+") as f: d = f.read() d = d.replace(old, new) f.truncate(0) f.se...
SCons: How to call a self defined python function in scons script and make right dependency
I write a python function such as replace strings and called in scons script. def Replace(env, filename, old, new): with open(filename,"r+") as f: d = f.read() d = d.replace(old, new) f.truncate(0) f.seek(0) f.write(d) f.close() env.AddMethod(Replace,'Replace') In SConscript lib = env.Shar...
[ "I believe that you're probably looking for builders that execute python functions.\nThe tricky bit is that SCons doesn't really want to work the way you're forcing it to. Build actions should be repeatable and non-destructive, in your code you're actually destroying the original contents of somefile. Instead, you ...
[ 4 ]
[]
[]
[ "python", "scons" ]
stackoverflow_0008226026_python_scons.txt
Q: sort list of floating-point numbers in groups I have an array of floating-point numbers, which is unordered. I know that the values always fall around a few points, which are not known. For illustration, this list [10.01,5.001,4.89,5.1,9.9,10.1,5.05,4.99] has values clustered around 5 and 10, so I would like [5,1...
sort list of floating-point numbers in groups
I have an array of floating-point numbers, which is unordered. I know that the values always fall around a few points, which are not known. For illustration, this list [10.01,5.001,4.89,5.1,9.9,10.1,5.05,4.99] has values clustered around 5 and 10, so I would like [5,10] as answer. I would like to find those clusters f...
[ "Check python-cluster. With this library you could do something like this :\nfrom cluster import *\n\ndata = [10.01,5.001,4.89,5.1,9.9,10.1,5.05,4.99]\ncl = HierarchicalClustering(data, lambda x,y: abs(x-y))\nprint [mean(cluster) for cluster in cl.getlevel(1.0)]\n\nAnd you would get:\n[5.0062, 10.003333333333332]\n...
[ 16, 8 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0008226923_numpy_python.txt
Q: Bugs in my login/logout with facebook I have a funny and strange bug in my facebook for websites. When I log a user in with facebook, as a user I must press reload to get the user data from the cookie. Otherwise the cookie doesn't find a user. If I press reload once after login and reload once after logout I can l...
Bugs in my login/logout with facebook
I have a funny and strange bug in my facebook for websites. When I log a user in with facebook, as a user I must press reload to get the user data from the cookie. Otherwise the cookie doesn't find a user. If I press reload once after login and reload once after logout I can login and logout but that indicates I've bee...
[ "Solution: Avoid javascript, avoid cookies and use serverside OAuth 2.0 and it is much easier to follow what is going on and this works:\nclass FBUser(db.Model):\n id = db.StringProperty(required=True)\n created = db.DateTimeProperty(auto_now_add=True)\n updated = db.DateTimeProperty(auto_now=True)\n na...
[ 0 ]
[]
[]
[ "debugging", "facebook", "facebook_graph_api", "google_app_engine", "python" ]
stackoverflow_0008224691_debugging_facebook_facebook_graph_api_google_app_engine_python.txt
Q: Groupby and list comprehension headache in python I've got this from a Hadoop tutorial. It is a reducer that basically takes in (word, count) pairs from stdin and sums them. def read_mapper_output(file, separator='\t'): for line in file: yield line.rstrip().split(separator, 1) def main(separator='\t')...
Groupby and list comprehension headache in python
I've got this from a Hadoop tutorial. It is a reducer that basically takes in (word, count) pairs from stdin and sums them. def read_mapper_output(file, separator='\t'): for line in file: yield line.rstrip().split(separator, 1) def main(separator='\t'): data = read_mapper_output(sys.stdin, separator=se...
[ "\ngroupby\n\nThat is the groupby function from the itertools module, documented here. The data is \"grouped by\" the results of applying itemgetter(0) (an instance of the itemgetter class from the operator module, documented here) to each element. It returns pairs of (key result, iterator-over-elements-with-that-k...
[ 3, 0 ]
[]
[]
[ "functional_programming", "list_comprehension", "python" ]
stackoverflow_0008236146_functional_programming_list_comprehension_python.txt
Q: Python Sorting Lists in Lists Given: lst = [['John',3],['Blake',4],['Ted',3]] Result: lst = [['John',3],['Ted',3],['Blake',4]] I'm looking for a way to sort lists in lists first numerically then alphabetically without the use of the "itemgetter" syntax. A: Since you insist: lst.sort(key=lambda x: x[::-1]) A: Y...
Python Sorting Lists in Lists
Given: lst = [['John',3],['Blake',4],['Ted',3]] Result: lst = [['John',3],['Ted',3],['Blake',4]] I'm looking for a way to sort lists in lists first numerically then alphabetically without the use of the "itemgetter" syntax.
[ "Since you insist:\nlst.sort(key=lambda x: x[::-1])\n\n", "You could use the argument key from the built-in sorted function.\nIn this key argument, you pass a function with one parameter, that returns something that will be sorted instead of sorting the list by its elements.\ndef my_func(elem):\n # return a tu...
[ 5, 2, 2, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0008236823_list_python.txt
Q: lxml parser eats all memory I'm writing some spider in python and use lxml library for parsing html and gevent library for async. I found that after sometime of work lxml parser starts eats memory up to 8GB(all server memory). But i have only 100 async threads each of them parse document max to 300kb. i'v tested a...
lxml parser eats all memory
I'm writing some spider in python and use lxml library for parsing html and gevent library for async. I found that after sometime of work lxml parser starts eats memory up to 8GB(all server memory). But i have only 100 async threads each of them parse document max to 300kb. i'v tested and get that problem starts in lxm...
[ "You might be keeping some references which keep the documents alive. Be careful with string results from xpath evaluation for example: by default they are \"smart\" strings, which provide access to the containing element, thus keeping the tree in memory if you keep a reference to them. See the docs on xpath return...
[ 7, 1, 0 ]
[]
[]
[ "lxml", "memory_leaks", "python" ]
stackoverflow_0005260261_lxml_memory_leaks_python.txt
Q: How to add OAuth 2.0 providers? I could reproduce my bug using servside OAuth2.0 only so it's not javascript and the issue is that I must reload to make login / logout take effect and I want it to work without javascript. I have an idea that making logout twice makes logout effective so I could use a custom reques...
How to add OAuth 2.0 providers?
I could reproduce my bug using servside OAuth2.0 only so it's not javascript and the issue is that I must reload to make login / logout take effect and I want it to work without javascript. I have an idea that making logout twice makes logout effective so I could use a custom request handler for /login and/or /logour o...
[ "How to add Facebook as OAuth 2.0 provider: Here's how I make \"Login with facebook\" for my website with OAuth instead of javascript / cookie this is python only for OAuth 2.0 with Facebook and as far as I can tell it's working:\nclass FBUser(db.Model):\n id = db.StringProperty(required=True)\n created = db....
[ 0 ]
[]
[]
[ "facebook", "google_app_engine", "oauth", "oauth_2.0", "python" ]
stackoverflow_0007799010_facebook_google_app_engine_oauth_oauth_2.0_python.txt
Q: Using psyco with py2exe? In my main script, lets call this MyScript.py, I have it like this: import psyco psyco.full() And then my setup.py looks like this: from distutils.core import setup import py2exe, sys, os, glob sys.argv.append('py2exe') import psyco #speed up compilation psyco.full() def find_data_file...
Using psyco with py2exe?
In my main script, lets call this MyScript.py, I have it like this: import psyco psyco.full() And then my setup.py looks like this: from distutils.core import setup import py2exe, sys, os, glob sys.argv.append('py2exe') import psyco #speed up compilation psyco.full() def find_data_files(source,target,patterns): ...
[ "Hunting down py2exe errors appears to be an art to me. \nThat said, I will at least offer something to try.\nI py2exe'ed a psyco enabled python script and tossed it in the includes part of the setup. \nThats the only part that looks different between your setup and my old one. \noptions = {'py2exe': {'packages': [...
[ 0 ]
[]
[]
[ "psyco", "py2exe", "python" ]
stackoverflow_0008236718_psyco_py2exe_python.txt
Q: MATLAB + Python Ideas? I have been noticing a lot of necessary functions that are present in MATLAB but seem to not exist in Python. I am planning to make a Package or Master Class containing all of these functions and was wondering on any specifics Y'all might have or would like in the Package. If this has alread...
MATLAB + Python Ideas?
I have been noticing a lot of necessary functions that are present in MATLAB but seem to not exist in Python. I am planning to make a Package or Master Class containing all of these functions and was wondering on any specifics Y'all might have or would like in the Package. If this has already been done, can I please ha...
[ "For Python-as-a-Matlab-replacement, the two must-have places to look at are:\n\npython(x,y) - http://code.google.com/p/pythonxy/ - \"is a free scientific and engineering development software for numerical computations, data analysis and data visualization based on Python programming language, Qt graphical user int...
[ 3, 2 ]
[]
[]
[ "matlab", "python" ]
stackoverflow_0008236969_matlab_python.txt
Q: How can I stop IDLE from printing giant lists? Sometimes I'll be working with, say, a list of thousands of items in IDLE, and accidently print it out to the shell. When this happens, it crashes or at least very significaly slows down IDLE. As you can imagine, this is extremely inconvenient. Is there a way to make ...
How can I stop IDLE from printing giant lists?
Sometimes I'll be working with, say, a list of thousands of items in IDLE, and accidently print it out to the shell. When this happens, it crashes or at least very significaly slows down IDLE. As you can imagine, this is extremely inconvenient. Is there a way to make it, rather than printing the entire thing, just give...
[ "As above, try a custom print function like:\ndef my_print(obj): \n if hasattr(obj, '__len__') and len(obj) > 100: \n print '... omitted object of %s with length %d ...' % (type(obj), len(obj)) \n else: print obj\n\n", "Use IPython as shell instead. \n", "You could use custom print function.\n",...
[ 2, 0, 0, 0, 0 ]
[]
[]
[ "editor", "ide", "python", "python_idle" ]
stackoverflow_0000609190_editor_ide_python_python_idle.txt
Q: print html tag programmatically on GAE Python is there any way to print html code on GAE webapp? for k, v in menubar.iteritems(): if(re.search(v, self.request.path)): menustring += '<li class="current"><a href="'+v+'">'+k+'</a></li>' else: menustring += '<li><a href="'+v+'">'+k+'</a></li>' print on template: ...
print html tag programmatically on GAE Python
is there any way to print html code on GAE webapp? for k, v in menubar.iteritems(): if(re.search(v, self.request.path)): menustring += '<li class="current"><a href="'+v+'">'+k+'</a></li>' else: menustring += '<li><a href="'+v+'">'+k+'</a></li>' print on template: <ul> {{ menustring }} </ul> it shows &lt &...
[ "HTML tags (or rather, <) are automatically escaped by Django templates to prevent cross site scripting vulnerabilities. You can use the safe filter (eg {{menustring|safe}}) to prevent escaping.\nYou almost certainly shouldn't be using this here, though - you should instead pass in the list of groups into the templ...
[ 4 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0008236863_django_google_app_engine_python.txt
Q: Python 3 - non-copying stream interface to bytearray? I read buffer of data from somewhere to bytearray. Now, I want to work with this data using stream-like interface (i.e. read, seek etc.) Can I just wrap my bytearray with io.BytesIO? mybytearray = bytearray(...) stream = io.BytesIO(mybytearray) My fear here is...
Python 3 - non-copying stream interface to bytearray?
I read buffer of data from somewhere to bytearray. Now, I want to work with this data using stream-like interface (i.e. read, seek etc.) Can I just wrap my bytearray with io.BytesIO? mybytearray = bytearray(...) stream = io.BytesIO(mybytearray) My fear here is BytesIO copies data of mybytearray, but I don't want it - ...
[ "BytesIO manages its own memory and will copy a buffer used to initialize it. You could encapsulate your bytearray in a file-like class. Or you can go the other way, letting the BytesIO object handle memory allocation. Then you can get a view of the buffer that can be modified by index and slice, but you can't re-s...
[ 12 ]
[]
[]
[ "bytearray", "python", "python_3.x", "stream" ]
stackoverflow_0008237122_bytearray_python_python_3.x_stream.txt
Q: Exception returning no exception I got a code something like this: try: do_something() except (urllib2.URLError, socket.timeout), er: print something except Exception, ex: print "The code failed because", ex, "Please review" Now, the problem is on executing the above code I am getting following ou...
Exception returning no exception
I got a code something like this: try: do_something() except (urllib2.URLError, socket.timeout), er: print something except Exception, ex: print "The code failed because", ex, "Please review" Now, the problem is on executing the above code I am getting following output: The code failed because Please r...
[ "Not necessarily - the expectation is not entirely true. The following code prints nothing:\ntry:\n raise BaseException()\nexcept BaseException, ex:\n print ex \n\nBut this prints \"abc\":\ntry:\n raise BaseException(\"abc\")\nexcept BaseException, ex:\n print ex\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0008237537_python.txt
Q: Trouble doing simple parse in pyparsing I'm having some basic problem using pyparsing. Below is the test program and the output of the run. aaron-mac:sql aaron$ more s.py from pyparsing import * n = Word(alphanums) a = Group( n | Group( n + OneOrMore( Suppress(",") + n ))) p = Group( a + Suppress(".") ) print a...
Trouble doing simple parse in pyparsing
I'm having some basic problem using pyparsing. Below is the test program and the output of the run. aaron-mac:sql aaron$ more s.py from pyparsing import * n = Word(alphanums) a = Group( n | Group( n + OneOrMore( Suppress(",") + n ))) p = Group( a + Suppress(".") ) print a.parseString("first") print a.parseString("fi...
[ "The '|' operator creates a MatchFirst expression, in which the alternatives are evaluated until there is a first match. \nPyparsing works purely left-to-right, applying parser expressions to the input string as it can. The only lookahead that pyparsing does is whatever you write into the parser.\nIn this express...
[ 6, 2 ]
[]
[]
[ "pyparsing", "python" ]
stackoverflow_0008234923_pyparsing_python.txt
Q: Python - read and write input from user I am having trouble writing this short program for my python class I was hoping someone could offer some assistance. What I would like to accomplish: 1. Write a program that uses a while loop to accept input from the user (if the user presses Enter, exit the program). 2. ...
Python - read and write input from user
I am having trouble writing this short program for my python class I was hoping someone could offer some assistance. What I would like to accomplish: 1. Write a program that uses a while loop to accept input from the user (if the user presses Enter, exit the program). 2. Save the input to a file, then print it. 3....
[ "To be honest, your program as you've shown it is kind of a mess. I say this not to be insulting, but because you do have a pretty clear list of the steps your program needs to take, and I think you will wind up with a better understanding by scrapping your existing code and starting from scratch.\nIn your question...
[ 5, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0008237862_file_io_python.txt
Q: Python Filtering 2 Lists I'm trying to find a way to use one list to filter out elements of another. Kinda like the intersect syntax but the exact opposite lst = [0,1,2,6] secondlst = [0,1,2,3,4,5,6] expected outcome [3,4,5] A: Simple way: r = [v for v in secondlst if v not in lst] or list(set(secondlst).diff...
Python Filtering 2 Lists
I'm trying to find a way to use one list to filter out elements of another. Kinda like the intersect syntax but the exact opposite lst = [0,1,2,6] secondlst = [0,1,2,3,4,5,6] expected outcome [3,4,5]
[ "Simple way:\nr = [v for v in secondlst if v not in lst]\n\nor\nlist(set(secondlst).difference(lst))\n\n", "You can use filter\nfilter(lambda x: x not in lst, secondlst)\n\n", "Look no further than Python's set()' type.\n>>> lst = [0,1,2,6]\n>>> secondlst = [0,1,2,3,4,5,6]\n>>> set(lst).symmetric_difference(set...
[ 12, 3, 2, 1 ]
[]
[]
[ "element", "filter", "list", "python" ]
stackoverflow_0008238005_element_filter_list_python.txt
Q: Unexpected Behavior of menu command link to function Following is a Python script to display a menu(file,option) where option is used to initiate a function conf. As I had assumed, the conf fun will only execute when i press the respective menu widget. That means 'haha' will only be printed when i press option/Edi...
Unexpected Behavior of menu command link to function
Following is a Python script to display a menu(file,option) where option is used to initiate a function conf. As I had assumed, the conf fun will only execute when i press the respective menu widget. That means 'haha' will only be printed when i press option/Edit comp list and similarly 'nana' will only be printed when...
[ "Your error is quite simple:\nmenu_option.add_command(label=\"Edit Comp List\",command=conf('comp'))\n\nWhen you pass this argument:\ncommand=conf('comp')\n\nYou aren't actually passing it. You are passing the result of conf('comp') as your function. The result of that function is a print statement, which is what y...
[ 3 ]
[]
[]
[ "function", "menu", "python", "tkinter" ]
stackoverflow_0008238085_function_menu_python_tkinter.txt
Q: Count the duplicates in list of dict in django python How can i find the count of duplicates in this list. >>> result = SiteTags.objects.values('content_type','object_id') >>> result [{'object_id': 1, 'content_type': 46}, {'object_id': 1, 'content_type': 46}, {'object_id': 2, 'content_type': 42}] Is there anyway ...
Count the duplicates in list of dict in django python
How can i find the count of duplicates in this list. >>> result = SiteTags.objects.values('content_type','object_id') >>> result [{'object_id': 1, 'content_type': 46}, {'object_id': 1, 'content_type': 46}, {'object_id': 2, 'content_type': 42}] Is there anyway to find in query? or through an other way? Thanks!
[ "If I'm understanding your request correctly, collections.Counter would be a useful way to count the duplicates. It works only with hashable inputs, so you dictionaries in your list need to be converted tuples of sorted items:\n>>> from collections import Counter\n>>> Counter([tuple(sorted(d.items())) for d in res...
[ 6, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008238319_django_python.txt
Q: Avoid duplicate data PostgreSQL How do i insert these artist into database only if does not exist in database. I have written following code. But it is wrong. Will you please help me ? thanks Artist List Lata Mangeshkar Lata Mangeshkar Lata Mangeshkar Asha Bhosle Lata Mangeshkar Mahendra Kapoor Lata Mangeshkar...
Avoid duplicate data PostgreSQL
How do i insert these artist into database only if does not exist in database. I have written following code. But it is wrong. Will you please help me ? thanks Artist List Lata Mangeshkar Lata Mangeshkar Lata Mangeshkar Asha Bhosle Lata Mangeshkar Mahendra Kapoor Lata Mangeshkar Kishore Kumar Lata Mangeshkar My co...
[ "\nEnforce that on the database side. Add constraint on the column name to enforce the column is unique. This should be enough:\nALTER TABLE song_artist ADD UNIQUE (name);\nThis way you can be sure that whatever you do, you won't have any duplicated values.\nYou could insert the data using queries like this:\nINSER...
[ 2, 0, 0 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0008227956_postgresql_python.txt
Q: django exception while using Filter (ImportError: No Module named ..) When I try using in Django the "filter" Method: dumpData.objects.filter(bid = True) I get the following Exception: ImportError: No module named Trades File "XXX\CacheUtil.py", line 141, in loadItems print DumpData.objects.filter(bid = True) ...
django exception while using Filter (ImportError: No Module named ..)
When I try using in Django the "filter" Method: dumpData.objects.filter(bid = True) I get the following Exception: ImportError: No module named Trades File "XXX\CacheUtil.py", line 141, in loadItems print DumpData.objects.filter(bid = True) File "XXX\site-packages\django\db\models\manager.py", line 141, in filter...
[ "I didn't found any documentation about it, but I would suggest to use lowercase names for apps.\nAlso, try :\ndumpData.objects.filter(bid = True).all()\n\n", "Ok i solved my Problem.\nThe reason because it didnt worked was in the Project Strukture, i had:\n\\src\n \\PackageNr1\n Main.py <-- File where ...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0008225803_django_django_models_python.txt
Q: Feedparser (and urllib2) issue: Connection timed out Starting with urllib2 and feedparser libraries in Python I'm getting the following error most of the time whenever try to connect and fetch content from particular URL: urllib2.URLError: <urlopen error [Errno 110] Connection timed out> The minimal reproducible ...
Feedparser (and urllib2) issue: Connection timed out
Starting with urllib2 and feedparser libraries in Python I'm getting the following error most of the time whenever try to connect and fetch content from particular URL: urllib2.URLError: <urlopen error [Errno 110] Connection timed out> The minimal reproducible examples (basic, using feedparser.parser directly and adva...
[ "As the error denotes, it is a connection problem. This may be a problem with your internet connection or with their servers/connection/bandwidth..\nA simple workaround is to do your feedparsing in a while loop, of course keeping a counter of MAX retries..\n", "How often does the timeout occur? If it's not freque...
[ 3, 3 ]
[]
[]
[ "feedparser", "python", "rss", "urllib", "urllib2" ]
stackoverflow_0008239098_feedparser_python_rss_urllib_urllib2.txt
Q: Use Python to load data into Mysql is it possible to set up tables for Mysql in Python? Here's my problem, I have bunch of .txt files which I want to load into Mysql database. Instead of creating tables in phpmyadmin manually, is it possible to do the following things all in Python? Create table, including data ...
Use Python to load data into Mysql
is it possible to set up tables for Mysql in Python? Here's my problem, I have bunch of .txt files which I want to load into Mysql database. Instead of creating tables in phpmyadmin manually, is it possible to do the following things all in Python? Create table, including data type definition. Load many files one by ...
[ "It is. Typically what you want to do is use an Object-Retlational Mapping library.\nProbably the most widely used in the python ecosystem is SQLAlchemy, but there is a lot of magic going on in it, so if you want to keep a tighter control on your DB schema, or if you are learning about relational DB's and want to f...
[ 1, 1 ]
[]
[]
[ "mysql", "phpmyadmin", "python" ]
stackoverflow_0008239554_mysql_phpmyadmin_python.txt
Q: Linkedin API for python I used this library to make API requests and got the access tokens successfully. But the documentation does not explain how _access_token and _access_token_secret should be used afterwards future. I suppose that there should be a method like: set_access_token(_access_token, _access_token_s...
Linkedin API for python
I used this library to make API requests and got the access tokens successfully. But the documentation does not explain how _access_token and _access_token_secret should be used afterwards future. I suppose that there should be a method like: set_access_token(_access_token, _access_token_secret) but I could't find a ...
[ "I have not used this particular library or API, but a common pattern in these cases is that you pass the token as an argument to subsequent calls. Looking at the source, I can see a function called get_user_profile in __init__.py:\ndef get_user_profile(self, access_token, selectors=None, headers=None, **kwargs):\n...
[ 1 ]
[]
[]
[ "api", "linkedin", "python" ]
stackoverflow_0008239605_api_linkedin_python.txt
Q: Python regex group() appends 'None' I have simple regex for parsing this string: rawresp0 = """<response> <comment>Привет.</comment> </response>""" I need to get: Привет. But the code below for some reason returns: Привет. None Whats wrong def pars_resp(text): reg = re.compile(ur'(?<=<comment>).+(?=</comme...
Python regex group() appends 'None'
I have simple regex for parsing this string: rawresp0 = """<response> <comment>Привет.</comment> </response>""" I need to get: Привет. But the code below for some reason returns: Привет. None Whats wrong def pars_resp(text): reg = re.compile(ur'(?<=<comment>).+(?=</comment>)', re.U) print reg.search(unicode...
[ "You have two prints. The first one prints the result of your search and the second prints the return value of pars_resp, which is None since you don't return something.\nChange it either to\ndef pars_resp(text):\n reg = re.compile(ur'(?<=<comment>).+(?=</comment>)', re.U)\n print reg.search(unicode(text, \"U...
[ 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008239772_python_regex.txt
Q: Value changing at multiple positions in a list of list when trying to change at one place The following Code in python: matrix = [[0]*3]*2 matrix[0][1] = 1 seeems to be changing the value at all the matrix[][1]th positions, matrix becomes [[0,1,0],[0,1,0]] instead of [[0,1,0],[0,0,0]]. Is this a problem with how...
Value changing at multiple positions in a list of list when trying to change at one place
The following Code in python: matrix = [[0]*3]*2 matrix[0][1] = 1 seeems to be changing the value at all the matrix[][1]th positions, matrix becomes [[0,1,0],[0,1,0]] instead of [[0,1,0],[0,0,0]]. Is this a problem with how the variable is initialised or is the default behaviour in python. Also How do I change only o...
[ "There are some subtleties on how the multiplication operator * works on lists in python. \nMore generally, there are differences on its effects when applied on immutable objects such integers or strings, and how those it has when applied on mutable objects like lists and dictionaries.\nThis might clarify the issue...
[ 6, 3 ]
[]
[]
[ "matrix", "python" ]
stackoverflow_0008240054_matrix_python.txt
Q: How to add an event with content to a non-default google calendar? I have refer to http://www.pauldeden.com/2009/01/creating-application-to-insert-events.html to add an quick event with title and time but without content to a non-default google calendar using python. if i use event.content = atom.data.Content(tex...
How to add an event with content to a non-default google calendar?
I have refer to http://www.pauldeden.com/2009/01/creating-application-to-insert-events.html to add an quick event with title and time but without content to a non-default google calendar using python. if i use event.content = atom.data.Content(text=content) to give content to the event,the console of Ubuntu says: Att...
[ "I would need your code to be sure, but I believe you are not creating the variable content correctly. \nYou should be careful to make sure that content is of type content when initializing it. Maybe you are just using it as a string?\nWith your code I can provide a better answer.\nHave you tried with the new v3 AP...
[ 2 ]
[]
[]
[ "google_calendar_api", "python" ]
stackoverflow_0006275201_google_calendar_api_python.txt
Q: Running a method just once at the beginning before any tests are run in PyUnit Im using PyUnit to write unit tests for my code. The setup method is called everytime before any test is run. Is there a way i can define a method that will be run just once at the beginning before any tests are run ? Please Help Thank ...
Running a method just once at the beginning before any tests are run in PyUnit
Im using PyUnit to write unit tests for my code. The setup method is called everytime before any test is run. Is there a way i can define a method that will be run just once at the beginning before any tests are run ? Please Help Thank You
[ "You can use setUpClass or setUpModule in Python 2.7 and 3.2.\n", "How about using the constructor of your test class?\n" ]
[ 4, 0 ]
[]
[]
[ "python", "python_unittest", "tdd", "unit_testing" ]
stackoverflow_0008240444_python_python_unittest_tdd_unit_testing.txt
Q: Convert text-processing script to web app in Python So I have a Python text-processing script, and I need to create a web page with two textareas. The first one is for data input, and the second one is for (async) on-the-fly displaying the result of passing the data to my script. What is the easiest/fastest way to...
Convert text-processing script to web app in Python
So I have a Python text-processing script, and I need to create a web page with two textareas. The first one is for data input, and the second one is for (async) on-the-fly displaying the result of passing the data to my script. What is the easiest/fastest way to achive this with Python?
[ "I believe using bottle micro web framework whould be the easiest and fastest. you could also checkout flask microwebframework which is pretty much the same idea\n", "You can use lightweight web framework like bottle to create a web server. The server then serves a html that contains some javascript firing AJAX ...
[ 1, 1 ]
[]
[]
[ "python", "text_processing", "web_applications" ]
stackoverflow_0008240512_python_text_processing_web_applications.txt
Q: assertRaises doesn't catch errors I have this script import unittest,itertools,random ##testclass class Testcomb(unittest.TestCase): def test_input(self): self.assertRaises(TypeError,calculate_combinations,dict(comb1), 5) def calculate_combinations(combin,target): counter = 0 for L in range...
assertRaises doesn't catch errors
I have this script import unittest,itertools,random ##testclass class Testcomb(unittest.TestCase): def test_input(self): self.assertRaises(TypeError,calculate_combinations,dict(comb1), 5) def calculate_combinations(combin,target): counter = 0 for L in range(0, len(combin)+1): for subset in...
[ "The exception that makes your test fail is triggered by the dict(comb1) part of the assertion.\n>>> comb1=[1,2,3,4]\n>>> dict(comb1)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: cannot convert dictionary update sequence element #0 to a sequence\n\nOn the contrary, the as...
[ 3 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0008240901_python_unit_testing.txt
Q: using HTMLparser on multiple calls I am bulding my own parser which was not using the search engine API and only returning the URL's with the search results in the bing environment, using python. I created the usual HTMLParser class and in the main i created the class instance parser = MyHTMLParser() parser.feed(c...
using HTMLparser on multiple calls
I am bulding my own parser which was not using the search engine API and only returning the URL's with the search results in the bing environment, using python. I created the usual HTMLParser class and in the main i created the class instance parser = MyHTMLParser() parser.feed(content) This works for single calls but...
[ "Before you feed the parser instance a new document you should reset it.\nE.g. parser.reset()\nSee: http://docs.python.org/library/htmlparser.html\n" ]
[ 2 ]
[]
[]
[ "html_parsing", "python", "url" ]
stackoverflow_0008241078_html_parsing_python_url.txt
Q: Saving entities in django-nonrel with google appengine Update: I've noticed that entities are saved (and available at the Datastore Viewer) when I save them using views (and the create_object function). But when I use shell (manage.py shell) to create and save new entity it isn't commited to the storage (but still...
Saving entities in django-nonrel with google appengine
Update: I've noticed that entities are saved (and available at the Datastore Viewer) when I save them using views (and the create_object function). But when I use shell (manage.py shell) to create and save new entity it isn't commited to the storage (but still can be seen in Tes.objects.all()). I started playing with ...
[ "This is a gotcha that causes a lot of confusion. From the djangoappengine docs:\n\nAlso, never run manage.py runserver together with other management\n commands at the same time. The changes won't take effect. That's an\n App Engine SDK limitation which might get fixed in a later release.\n\nSo you can't do mana...
[ 4 ]
[ "Shoudn't it be t.put() if you are creating an entity rather than saving it? I use put() to create an entity and it works for me. And if you import django you may want to know that there are alternatives to django such as my choice GAE + Jinja2 + WTForms especially now that google.db.djangoforms is deprecated selec...
[ -1 ]
[ "django_nonrel", "google_app_engine", "python" ]
stackoverflow_0008226800_django_nonrel_google_app_engine_python.txt
Q: Multi-Coloured bars in matplotlib I have a graph in matplotlib (that displays correctly), but I was hoping to have a different colour for each bar (still the same bar graph though). Is this possible? Thanks A: If you color at graph creation time: In [15]: x= range(5) In [16]: y = [10, 23, 12, 45, 32] In [17]: co...
Multi-Coloured bars in matplotlib
I have a graph in matplotlib (that displays correctly), but I was hoping to have a different colour for each bar (still the same bar graph though). Is this possible? Thanks
[ "If you color at graph creation time:\nIn [15]: x= range(5)\nIn [16]: y = [10, 23, 12, 45, 32]\nIn [17]: color = ['r', 'b', 'y', 'g', 'c']\nIn [18]: lines = bar(x, y, color=color)\n\n\nIf you want to change color of first bar after graph creation, then note that you got a list of your bars in lines:\nIn [19]: lines...
[ 2 ]
[]
[]
[ "matplotlib", "python", "python_3.x" ]
stackoverflow_0007604071_matplotlib_python_python_3.x.txt
Q: import data from excel to postgres in python using pyodbc I am importing data from MS-Excel to PostgreSQL in python(2.6) using pyodbc. The problem faced is: There are characters like left single quotation mark(ANSI hex code : 0x91), etc in the excel source. Now, when it is import into PostgreSQL using pyodbc, it t...
import data from excel to postgres in python using pyodbc
I am importing data from MS-Excel to PostgreSQL in python(2.6) using pyodbc. The problem faced is: There are characters like left single quotation mark(ANSI hex code : 0x91), etc in the excel source. Now, when it is import into PostgreSQL using pyodbc, it terminates and gives the error DatabaseError: invalid byte seque...
[ "Find out the real encoding of the source document. It might be WIN1251. Either transcode it (for instance with iconv) or set the client_encoding of PostgreSQL accordingly.\nIf you don't have a setting in pyodbc (which I don't know), you can always issue a plain SQL command:\nSET CLIENT_ENCODING TO 'WIN1251';\n\nMo...
[ 1 ]
[]
[]
[ "excel", "postgresql", "pyodbc", "python", "unicode" ]
stackoverflow_0008238617_excel_postgresql_pyodbc_python_unicode.txt
Q: Retrieving value from Excel table from an intersection of values using Python I have a table in Excel and I want to be able to read it (I know how to achieve this) but also tell Python that if there are certain values of d, D and B, for it to return the dimension value in the top first row as a variable in my prog...
Retrieving value from Excel table from an intersection of values using Python
I have a table in Excel and I want to be able to read it (I know how to achieve this) but also tell Python that if there are certain values of d, D and B, for it to return the dimension value in the top first row as a variable in my programme. I have read various posts concerning intersections and I am not sure whether...
[ "Here's how to search your table, based on guesses as to what you want. You should be able to do the loop-over-5-tables stunt yourself.\ndef search(table_iterator, d, D, B):\n headings = next(table_iterator)\n junk = next(table_iterator)\n key = [d, D]\n for row in table_iterator:\n if row[0:2] !...
[ 1 ]
[]
[]
[ "import_from_excel", "python", "xlrd" ]
stackoverflow_0008240061_import_from_excel_python_xlrd.txt
Q: In Python, retrieving Xml attribute value from xml.dom.minidom import parseString, parse dom = parse('response.xml') xmlTag = dom.getElementsByTagName('link')[0].toxml() How do I get the attribute 'href' of the xml for rel="alternate": <link rel='alternate' type='text/html' href='http://www.youtube.com/watc...
In Python, retrieving Xml attribute value
from xml.dom.minidom import parseString, parse dom = parse('response.xml') xmlTag = dom.getElementsByTagName('link')[0].toxml() How do I get the attribute 'href' of the xml for rel="alternate": <link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=gfyKPbic&amp;feature=youtube_gdata'/> <li...
[ "DOC = \"\"\"<root>\n <link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=gfyKPbic&amp;feature=youtube_gdata'/>\n <link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/gf7zhyKPbic/responses'/>\n</root>\...
[ 3 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0008240849_python_xml.txt
Q: python2.7 - taking a value from a dictionary, where the key is a variable I'm trying to load a specific key from a dictionary, with keys like "character 1", "translation 1", etc. (I'm working a a flashcard program for my chinese studies). First, I load the dictionary flawlessly from a .txt file with f = codecs.ope...
python2.7 - taking a value from a dictionary, where the key is a variable
I'm trying to load a specific key from a dictionary, with keys like "character 1", "translation 1", etc. (I'm working a a flashcard program for my chinese studies). First, I load the dictionary flawlessly from a .txt file with f = codecs.open(('%s.txt' % list_name),'r','utf-8') quiz_list = eval(f.read()) Then, I want ...
[ "A more general solution to this problem, instead of flattening the data structure into a dictionary keyed by strings, is to use a better data structure. For instance, if you have a lot of keys that look like \"translation n\" for numbers n, you'd be better off making translation a dictionary keyed by numbers. You...
[ 2, 1 ]
[]
[]
[ "dictionary", "python", "variables" ]
stackoverflow_0008241446_dictionary_python_variables.txt
Q: Why doesn't the % operator work the same in Python and Java? Python 2.7.1: print -34 % 4 # outputs 2 Java 1.5.0: System.out.println(-34 % 4); // outputs -2 Which is correct? Why the difference? The wikipedia article on modulo says When either a or n is negative, this naive definition breaks down and programming...
Why doesn't the % operator work the same in Python and Java?
Python 2.7.1: print -34 % 4 # outputs 2 Java 1.5.0: System.out.println(-34 % 4); // outputs -2 Which is correct? Why the difference? The wikipedia article on modulo says When either a or n is negative, this naive definition breaks down and programming languages differ in how these values are defined. Maybe this isn...
[ "It's just a convention the language has chosen. There is no one choice that is more mathematically correct than another.\nHints for the reasons for Python's choice can be found in the source: http://hg.python.org/cpython/file/2.7/Objects/intobject.c#l567\nPython's version is the one more commonly used in number ...
[ 6, 0, 0 ]
[ "In c/c++ the result is -2. So I would guess that is why Java went the other way. They were very interested in attracting C++ devs in the beginning.\n" ]
[ -1 ]
[ "java", "python" ]
stackoverflow_0008237469_java_python.txt
Q: BeautifulSoup python - save value of tag as string I'm new at BeautifulSoup and have scoured the online docos but couldn't find what I was after, I just need to store the value of a tag into a variable so that it can be written to a file afterwards Here is the code: import urllib2 from BeautifulSoup import Beautif...
BeautifulSoup python - save value of tag as string
I'm new at BeautifulSoup and have scoured the online docos but couldn't find what I was after, I just need to store the value of a tag into a variable so that it can be written to a file afterwards Here is the code: import urllib2 from BeautifulSoup import BeautifulSoup f = open('C:\test.txt', 'w') url = "http://www.wu...
[ "By your error it seems the solution is:\nf.write(timestamp + ',' + dayTemp[0] + '\\n')\n\n", "The problem is that [u'8'] is a list containing one object, a Unicode string. If you want to get the (only) object in that list, you index it to get its first entry:\n[u'8'][0] # is u'8'\n\nor you can pattern-match its ...
[ 1, 1, 1 ]
[]
[]
[ "beautifulsoup", "html_parsing", "python" ]
stackoverflow_0008241574_beautifulsoup_html_parsing_python.txt
Q: How to let the Tkinter textarea accept dropping an external file on Python 3.X? I googled some drag and drop tutorial, most of them is about drag and drop the internal element, within the application. But I would like to drop an external file on the textarea, it can displays back the file path to me, it will be ni...
How to let the Tkinter textarea accept dropping an external file on Python 3.X?
I googled some drag and drop tutorial, most of them is about drag and drop the internal element, within the application. But I would like to drop an external file on the textarea, it can displays back the file path to me, it will be nice, but how can I do so? Thanks? Any ideas? PS: Using python3.X
[ "I guess you'd already take a look at the TkDND extension for Tkinter.\nLooking at its docs seems like it has some support for drag and drop external targets too:\n\n\"For example under windows the type \"FILENAME\" can be used in order to\n receive a single filename from the Explorer or the type \"NetscapeURL\"\n...
[ 1 ]
[]
[]
[ "drag_and_drop", "python", "python_3.x", "tkinter" ]
stackoverflow_0008237742_drag_and_drop_python_python_3.x_tkinter.txt
Q: Writing a table to a matplotlib pdf file I am using matplotlib and a modified version of this example to generate plots in pdf files. So I am plotting each plot on a single page and the results are just fine. Now I would like to list all the data used in the plots in a rather long table. This table should be place...
Writing a table to a matplotlib pdf file
I am using matplotlib and a modified version of this example to generate plots in pdf files. So I am plotting each plot on a single page and the results are just fine. Now I would like to list all the data used in the plots in a rather long table. This table should be placed below the last plot (so not each plot should...
[ "In principle, you can place almost any TeX stuff onto a plot using something like plt.text(1,2,r'$a^2+b^2=42$'). For aligning equations things like eqnarray work as well, like this. Just don't forget to use raw strings, for otherwise python can misinterpret TeX commands which start with backslashes. \n", "Unle...
[ 0, 0 ]
[]
[]
[ "latex", "matplotlib", "pdf", "python" ]
stackoverflow_0007712577_latex_matplotlib_pdf_python.txt
Q: How to i18n method comment for displays django-admindoc I am writing a method to my class and I like internationalize my projects. Now I'm developing a really multilingual system. I want to translate documentation. About how to translate new line after the definition of the method is nothing in the django document...
How to i18n method comment for displays django-admindoc
I am writing a method to my class and I like internationalize my projects. Now I'm developing a really multilingual system. I want to translate documentation. About how to translate new line after the definition of the method is nothing in the django documentation.I'm try write: from django.utils.translation import ug...
[ "If you specifiy __doc__ attribute as first statement, it should be literal and not expression.\nI think this could work:\nfrom django.utils.translation import ugettext_lazy as _\nclass Items(Model):\n __doc__ = _('translatable description for Items')\n\n def total(self):\n return self.__total\n tot...
[ 1 ]
[]
[]
[ "django", "docutils", "gettext", "internationalization", "python" ]
stackoverflow_0008066706_django_docutils_gettext_internationalization_python.txt
Q: Timing issues in Python nose test I have some unit tests that are timing sensitive: an action is timed and an error is triggered if it takes too long. When run individually, these tests pass, but when running nosetest recursively on my modules, they often fail. I run concurrent tests, which likely is one reason wh...
Timing issues in Python nose test
I have some unit tests that are timing sensitive: an action is timed and an error is triggered if it takes too long. When run individually, these tests pass, but when running nosetest recursively on my modules, they often fail. I run concurrent tests, which likely is one reason why the timing is off. Is there any way t...
[ "I think your problem is dependent from how you implemented the timing. The solution I would personally adopt would be to set an environment variable that controls the behaviour of the tests. Candidates could be:\n\nif WITH_TIMING == False [turn off timing altogether]\nTIME_STRETCH_FACTOR = ... [apply a time-stretc...
[ 1 ]
[]
[]
[ "nose", "nosetests", "python" ]
stackoverflow_0008242209_nose_nosetests_python.txt
Q: fast data move from file to some StringIO In Python I have a file stream, and I want to copy some part of it into a StringIO. I want this to be fastest as possible, with minimum copy. But if I do: data = file.read(SIZE) stream = StringIO(data) I think 2 copies was done, no? One copy into data from file, another c...
fast data move from file to some StringIO
In Python I have a file stream, and I want to copy some part of it into a StringIO. I want this to be fastest as possible, with minimum copy. But if I do: data = file.read(SIZE) stream = StringIO(data) I think 2 copies was done, no? One copy into data from file, another copy inside StringIO into internal buffer. Can I...
[ "In short: you can't avoid 2 copies using StringIO.\nSome assumptions: \n\nYou're using cStringIO, otherwise it would be silly to optimize this much.\nIt's speed and not memory efficiency you're after. If not, see Jakob Bowyer's solution, or use a variant using file.read(SOME_BYTE_COUNT) if your file is binary.\nYo...
[ 8, 6, 2, 0 ]
[]
[]
[ "python", "stream" ]
stackoverflow_0008240647_python_stream.txt
Q: How does the warmup service work in python google app engine? Can someone give an example of how the warmup inbound service works in the python runtime of Google App Engine? I've read this: http://code.google.com/appengine/docs/python/config/appconfig.html#Inbound_Services, but it doesn't give me much of an exampl...
How does the warmup service work in python google app engine?
Can someone give an example of how the warmup inbound service works in the python runtime of Google App Engine? I've read this: http://code.google.com/appengine/docs/python/config/appconfig.html#Inbound_Services, but it doesn't give me much of an example after the GET request is sent (I can't seem to ever pick it up) M...
[ "App Engine sends warm up requests only if there is some constant traffic on your app. It won't get always called if instances stand mostly idle.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008235716_google_app_engine_python.txt
Q: Usage of M2Crypto package I want to encrypt the communication between a LabView and a Python code. I did some preliminary research and I found the AES library for LabView. The M2Crypto module supports AES. My question is if the AES is the best solution for TCP communication. Can anybody provide a simple example i...
Usage of M2Crypto package
I want to encrypt the communication between a LabView and a Python code. I did some preliminary research and I found the AES library for LabView. The M2Crypto module supports AES. My question is if the AES is the best solution for TCP communication. Can anybody provide a simple example in python?
[ "I have looked at the SOS AES library, and it seems that it's adding some data to the encrypted data, they use when de-encrypting.\nYou might want to try out my library available at LAVA and bitbucket.\n" ]
[ 1 ]
[]
[]
[ "labview", "m2crypto", "python" ]
stackoverflow_0008240791_labview_m2crypto_python.txt
Q: load data into table in Mysql I created 4 columns for a table cur.execute("""CREATE TABLE videoinfo ( id INT UNSIGNED PRIMARY KEY AUTO INCREMENT, date DATETIME NOT NULL, src_ip CHAR(32), hash CHAR(150)); """) I have a .txt file which has three columns of data inside. I want to use LOAD DATA LOC...
load data into table in Mysql
I created 4 columns for a table cur.execute("""CREATE TABLE videoinfo ( id INT UNSIGNED PRIMARY KEY AUTO INCREMENT, date DATETIME NOT NULL, src_ip CHAR(32), hash CHAR(150)); """) I have a .txt file which has three columns of data inside. I want to use LOAD DATA LOCAL INFILEcommand to insert data, bu...
[ "AUTO INCREMENT isn't valid syntax. If you check MySQL's documentation for the CREATE TABLE statement, you'll see the proper keyword is AUTO_INCREMENT.\nAdditionally, date is a keyword, so you'll need to quote it with backticks, as mentioned on the MySQL identifier documentation page. The documentation also lists a...
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0008242810_mysql_python.txt
Q: python all possible pairs of 2 list elements, and getting the index of that pair let's say I have two lists: a = list(1,2,3) b = list(4,5,6) So I can have 9 pairs of these list members: (1,4) (1,5) (1,6) (2,4) (2,5) (2,6) (3,4) (3,5) (3,6) Now, given two list members like above, can I find out the pair's index...
python all possible pairs of 2 list elements, and getting the index of that pair
let's say I have two lists: a = list(1,2,3) b = list(4,5,6) So I can have 9 pairs of these list members: (1,4) (1,5) (1,6) (2,4) (2,5) (2,6) (3,4) (3,5) (3,6) Now, given two list members like above, can I find out the pair's index? Like (1,4) from above would be the 1st pair.
[ "And to complete the answer and stay in the example:\nimport itertools \n\na = [1, 2, 3]\nb = [4, 5, 6]\nc = list(itertools.product(a, b))\n\nidx = c.index((1,4))\n\nBut this will be the zero-based list index, so 0 instead of 1.\n", "One way to do this:\n\nFind the first element of the pair your are looking for ...
[ 53, 9 ]
[]
[]
[ "cartesian_product", "list", "python", "tuples" ]
stackoverflow_0008242832_cartesian_product_list_python_tuples.txt
Q: Get template name in template tag ( Django ) is there a way to get the template name ( being parsed ) in a template tag ? I have read searched and found nothing, only this previous post Getting the template name in django template which doesn't help me much, since the answer relies on settings.DEBUG being true, w...
Get template name in template tag ( Django )
is there a way to get the template name ( being parsed ) in a template tag ? I have read searched and found nothing, only this previous post Getting the template name in django template which doesn't help me much, since the answer relies on settings.DEBUG being true, which in my case can't be. I don't really know wher...
[ "Looking at the source, while the Template object would have access to the template name (via .name) this value is never passed on to the Parser object and therefore not available to template tags.\nThere are various ways of making the template name available to the template itself (by adding it to the context) but...
[ 3, 2 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0008240181_django_django_templates_python.txt
Q: Creating a dictionary from csv file I was given the following problem and I am a little uncertain. I understand that the dictionary contains each town and their distance from each city, but is it structured like {Albury: 925,1440,352,3937,308,3583,565......} or something different? The following table was downl...
Creating a dictionary from csv file
I was given the following problem and I am a little uncertain. I understand that the dictionary contains each town and their distance from each city, but is it structured like {Albury: 925,1440,352,3937,308,3583,565......} or something different? The following table was downloaded from the web and saved in a file dis...
[ "If you add \nimport pprint\npprint.pprint(t)\n\nat the bottom of the script and execute it, you will see your data structure quite clearly. It will look something like this:\n{'Albury': {'Adelaide': 925,\n 'Brisbane': 1440,\n (...)\n 'Sydney': 565},\n 'Alice Springs': {'Adelaide': ...
[ 1 ]
[]
[]
[ "csv", "dictionary", "for_loop", "python" ]
stackoverflow_0008210161_csv_dictionary_for_loop_python.txt
Q: Why does the python datetime class have a 'fromtimestamp' method, but not a 'totimestamp' method? Python's datetime class has a fromtimestamp method to create a datetime object from a timestamp, but doesn't provide a totimestamp method for the other way round... I'm aware that with something like time.mktime(x.tim...
Why does the python datetime class have a 'fromtimestamp' method, but not a 'totimestamp' method?
Python's datetime class has a fromtimestamp method to create a datetime object from a timestamp, but doesn't provide a totimestamp method for the other way round... I'm aware that with something like time.mktime(x.timetuple()) you can convert the datetime object to a timestamp, but this looks unnecessary complicated to...
[ "I do remember a discussion/bug report about this thing while I wondered about this some time back. Long story short: plenty of proposals have been made, but for some reason, none have been accepted.\nThe point is I think best summed up in this reply:\n\nPlenty have proposed a satisfactory solution. No one has com...
[ 13 ]
[]
[]
[ "datetime", "python", "timestamp" ]
stackoverflow_0008243556_datetime_python_timestamp.txt
Q: How to Stop Django Thread I have a website that uses Jquery and Python. I have an Ajax Request that performs a python function. Inside the Python Function there is an interface with Linux that executes a C++ Library. The problem I am having is when I create two requests to execute this C++ Library from AJAX via P...
How to Stop Django Thread
I have a website that uses Jquery and Python. I have an Ajax Request that performs a python function. Inside the Python Function there is an interface with Linux that executes a C++ Library. The problem I am having is when I create two requests to execute this C++ Library from AJAX via Python. The C++ Task could take...
[ "Seems like you need an asynchronous execution for your \"blocking\" C++ Lib. There are several approaches for this kind of problems but IMO threading is deferentially the wrong one...\nOne approach is to use an asynchronous web server like Tornado to handle asynchronous requests. The other (and the one I like more...
[ 0 ]
[]
[]
[ "ajax", "django", "javascript", "jquery", "python" ]
stackoverflow_0008234723_ajax_django_javascript_jquery_python.txt
Q: Is a context manager right for this job? The code pasted below does the following: creates an import hook creates a context manager which sets the meta_path and cleans on exit. dumps all the imports done by a program passed in input in imports.log Now I was wondering if using a context manager is a good idea in ...
Is a context manager right for this job?
The code pasted below does the following: creates an import hook creates a context manager which sets the meta_path and cleans on exit. dumps all the imports done by a program passed in input in imports.log Now I was wondering if using a context manager is a good idea in this case, because actually I don't have the s...
[ "I think this concept is ok. As well, I don't see any reasons against having the clean-up stuff in a finally: clause, so the context manager fits perfectly.\nYour cc is None, because you told it to be so.\nIf you don't want that, change your __enter__ method to return something else:\n\nThe value returned by this m...
[ 3, 2, 1 ]
[]
[]
[ "contextmanager", "decorator", "python" ]
stackoverflow_0008243451_contextmanager_decorator_python.txt
Q: Moving into collective SVN and using jarn.mkrelease I've got a product, currently available here: http://svn.plone.org/svn/collective/RestrictedSize.RestrictedSize/ And I'm trying to use jarn.mkrelease to release an egg. However, I get this message when running mkrelease: ~/demo$ PYTHONPATH=mkrelease/ ./mkrelease/...
Moving into collective SVN and using jarn.mkrelease
I've got a product, currently available here: http://svn.plone.org/svn/collective/RestrictedSize.RestrictedSize/ And I'm trying to use jarn.mkrelease to release an egg. However, I get this message when running mkrelease: ~/demo$ PYTHONPATH=mkrelease/ ./mkrelease/bin/mkrelease -d pypi NBF/src/RestrictedSize/ Releasing R...
[ "That's because the standard for svn directory structure is:\n<myproduct>\n /branches\n /tags\n /trunk\n\nand that product expects exactly that structure. You should move all the code in a new trunk directory and than add also branches and tags.\n" ]
[ 3 ]
[]
[]
[ "plone", "pypi", "python", "svn" ]
stackoverflow_0008241218_plone_pypi_python_svn.txt
Q: Python webbrowser outputting page to console on Windows I'm writing a PyGTK application on Windows, and in a function, I'm trying to open a webpage with the webbrowser module. It should be the simplest thing in the world, but instead of opening in a browser, it prints the HTML source of the page to the console. Do...
Python webbrowser outputting page to console on Windows
I'm writing a PyGTK application on Windows, and in a function, I'm trying to open a webpage with the webbrowser module. It should be the simplest thing in the world, but instead of opening in a browser, it prints the HTML source of the page to the console. Does anyone know why this would happen? The code in question: o...
[ "What it normally tries to do (on Windows) is using os.startfile(url), which launches the default application for http urls. You can check what this does by typing start http://www.example.com at the command prompt. If this has the same effect, you know what the problem is, and you should reconfigure your default b...
[ 3, 1 ]
[]
[]
[ "python", "python_webbrowser", "windows" ]
stackoverflow_0008234690_python_python_webbrowser_windows.txt
Q: NTP timestamps in Python I need to generate a timestamp in NTP format in Python. Specifically, I need to calculate the number of seconds since 1st January 1900, as a 32-bit number. (NTP timestamps are actually 64 bits, with the other 32 bits representing fractions of seconds - I'm not worried about this part). H...
NTP timestamps in Python
I need to generate a timestamp in NTP format in Python. Specifically, I need to calculate the number of seconds since 1st January 1900, as a 32-bit number. (NTP timestamps are actually 64 bits, with the other 32 bits representing fractions of seconds - I'm not worried about this part). How should I go about doing thi...
[ "From the python ntplib : \nSYSTEM_EPOCH = datetime.date(*time.gmtime(0)[0:3])\nNTP_EPOCH = datetime.date(1900, 1, 1)\nNTP_DELTA = (SYSTEM_EPOCH - NTP_EPOCH).days * 24 * 3600\n\ndef ntp_to_system_time(date):\n \"\"\"convert a NTP time to system time\"\"\"\n return date - NTP_DELTA\n\ndef system_to_ntp_time(da...
[ 3, 3, 2, 1 ]
[]
[]
[ "ntp", "python" ]
stackoverflow_0008244204_ntp_python.txt
Q: creating message box as sheets for mac in PyQt I used message box as seperate dialog instead of sheets for mac OS, now i m working on it to spawn a sheet as message box instead of seperate one. I have tried setting the message box as a modal one: (messagebox.setWindowModality(QtCore.Qt.WindowModal)) and setting m...
creating message box as sheets for mac in PyQt
I used message box as seperate dialog instead of sheets for mac OS, now i m working on it to spawn a sheet as message box instead of seperate one. I have tried setting the message box as a modal one: (messagebox.setWindowModality(QtCore.Qt.WindowModal)) and setting message box, parent dialog window flags as sheet (par...
[ "A dialog cannot be shown as a sheet with exec_().\nInstead, simply use QMessageBox.open(), which, on a Mac, is roughly equivalent to:\nmessagebox.finished.connect(self.handler)\nmessagebox.setWindowModality(QtCore.Qt.WindowModal)\nmessagebox.setParent(messagebox.parentWidget(), QtCore.Qt.Sheet)\nmessagebox.setResu...
[ 2, 0 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0008239780_pyqt_python_qt.txt
Q: creating a spread sheet with python I had a txt file with content as shown below: 'marks: 40,66,34,88,70' i want to make a spread sheet with the content of txt file. (illustrated with referrence to 1 txt file, supposing to handle many). is there any module to handle spreadsheets? how can i achieve this? A: The ...
creating a spread sheet with python
I had a txt file with content as shown below: 'marks: 40,66,34,88,70' i want to make a spread sheet with the content of txt file. (illustrated with referrence to 1 txt file, supposing to handle many). is there any module to handle spreadsheets? how can i achieve this?
[ "The csv module can export in a format that can be read by nearly all spreadsheet programs with little difficulty. It's not really clear from your question what you want to put in such a file, though.\n", "http://sourceforge.net/projects/pyexcelerator/\ncan be used to create Excel files easily. Check out the exa...
[ 1, 0, 0, 0 ]
[]
[]
[ "python", "python_module" ]
stackoverflow_0005385593_python_python_module.txt
Q: load multiple txt files into mysql I have more than 40 txt files needed to be loaded into a table in Mysql. Each file contains 3 columns of data, each column lists one specific type of data, but in general the format of each txt file is exactly the same, but these file names are various, first I tried LOAD DATA LO...
load multiple txt files into mysql
I have more than 40 txt files needed to be loaded into a table in Mysql. Each file contains 3 columns of data, each column lists one specific type of data, but in general the format of each txt file is exactly the same, but these file names are various, first I tried LOAD DATA LOCAL INFILE 'path/*.txt' INTO TABLE xxx" ...
[ "If you want to avoid merging your text files, you can easily \"scan\" the folder and run the SQL import query for each file:\nimport os \n\nfor dirpath, dirsInDirpath, filesInDirPath in os.walk(\"yourFolderContainingTxtFiles\"):\n for myfile in filesInDirPath:\n sqlQuery = \"LOAD DATA INFILE %s INTO TABL...
[ 2, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0008243095_mysql_python.txt
Q: Is there anything like Python Itertools in Perl? Python has great module for working with iterators called itertools Is there any analog in Perl? I know about Object-Iterate but it has only imap and igrep. A: List::Gen does a lot of that. A: While I don't know exactly what iterators you need, CPAN is full of t...
Is there anything like Python Itertools in Perl?
Python has great module for working with iterators called itertools Is there any analog in Perl? I know about Object-Iterate but it has only imap and igrep.
[ "List::Gen does a lot of that.\n", "While I don't know exactly what iterators you need, CPAN is full of them, it really depends on what you need. I needed iterators over all the combinations possible in an array: there's a CPAN module for that.\n" ]
[ 7, 4 ]
[]
[]
[ "perl", "python", "python_itertools" ]
stackoverflow_0008242972_perl_python_python_itertools.txt
Q: Test Highcharts with selenium webdriver I would like to test the accuracy of a Highcharts graph presenting data from a JSON file (which I already read) using Python and Selenium Webdriver. How can I read the Highchart data from the website? thank you, Evgeny A: The highchart data is converted to an SVG path, so ...
Test Highcharts with selenium webdriver
I would like to test the accuracy of a Highcharts graph presenting data from a JSON file (which I already read) using Python and Selenium Webdriver. How can I read the Highchart data from the website? thank you, Evgeny
[ "The highchart data is converted to an SVG path, so you'd have to interpret the path yourself. I'm not sure why you would want to do this, actually: in general you can trust 3rd party libraries to work as advertised; the testing of that code should reside in that library.\nIf you still want to do it, then you'd hav...
[ 2 ]
[]
[]
[ "highcharts", "python", "selenium" ]
stackoverflow_0008242244_highcharts_python_selenium.txt
Q: Match a term ending with digit I have a list of words, with patterns either "term" or "termNUM", e.g. "term" or "term02". I want to save all terms that ends with digit but remove the ones are purely alphabets. I am totally new to regex, I tried few options, and get the following: new_list = [x for x in old_list if...
Match a term ending with digit
I have a list of words, with patterns either "term" or "termNUM", e.g. "term" or "term02". I want to save all terms that ends with digit but remove the ones are purely alphabets. I am totally new to regex, I tried few options, and get the following: new_list = [x for x in old_list if re.match("[(^a-zA-Z_)\d]", x)] It ...
[ "r\".*\\d\"\n\nThat's any character (.), any number of times (*) followed by a digit (\\d). Your list comprehension is correct.\nYou could also do\n[x for x in old_list if x[-1].isdigit()]\n\nassuming the empty string is not in the list. I'd prefer this option, as it's more explicit as to what it does.\n", "Why u...
[ 3, 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008245193_python_regex.txt
Q: Python Decorate all methods of subclass, and provide means to override I am working on finding a way to reduce boilerplate decorators. We have a lot of classes that use a @decorate. For example: class MyClass(Base): @decorate def fun1(self): pass @decorate def fun2(self): pa...
Python Decorate all methods of subclass, and provide means to override
I am working on finding a way to reduce boilerplate decorators. We have a lot of classes that use a @decorate. For example: class MyClass(Base): @decorate def fun1(self): pass @decorate def fun2(self): pass def fun3(self): pass I want to make it so by default the d...
[ "Rather than making the user of my class specify a __metaclass__ attribute I would just have them derive from my base class that defines it. No need to expose the plumbing unnecessarily.\nOther than that, looks good, though. Your @dont_decorate function decorator can be implemented by setting an attribute on the ...
[ 4 ]
[]
[]
[ "python", "python_2.5" ]
stackoverflow_0008245135_python_python_2.5.txt
Q: Regular expression and unicode literals I'd like to remove some characters from a string (either byte string or unicode string) using a regular expression like this: pattern = re.compile(ur'\u00AE|\u2122', re.UNICODE) If the characters are specified as unicode literals the resulting regexp does not work properly o...
Regular expression and unicode literals
I'd like to remove some characters from a string (either byte string or unicode string) using a regular expression like this: pattern = re.compile(ur'\u00AE|\u2122', re.UNICODE) If the characters are specified as unicode literals the resulting regexp does not work properly on byte string. q = 'Canon\xc2\xae EOS 7D' ...
[ "Because a standard (byte) string is not a Unicode string. Python does not know what encoding it's in (or if it's even Unicode at all!), and so has no way to determine whether a particular Unicode character matches some character in it. The solution is to tell Python it's Unicode, using the unicode() function, as y...
[ 2 ]
[]
[]
[ "python", "regex", "unicode", "unicode_literals" ]
stackoverflow_0008245392_python_regex_unicode_unicode_literals.txt
Q: Browserless access to LinkedIn with Python I'm writing a command-line application that accesses linkedin. I'm using the python-linkedin API. Things work as I expected, but I have a really big gripe about the authentication process. Currently, I need to: Start my application and wait for it to print an authentic...
Browserless access to LinkedIn with Python
I'm writing a command-line application that accesses linkedin. I'm using the python-linkedin API. Things work as I expected, but I have a really big gripe about the authentication process. Currently, I need to: Start my application and wait for it to print an authentication URL Go to that URL with my browser Give my...
[ "As you are planning on authorizing yourself just once, and then making calls to the API for your own information, I would just manually retrieve your access token rather than worrying about automating it.\nThe user access token generated by LinkedIn when you authorize a given application is permanent unless you sp...
[ 2, 1 ]
[]
[]
[ "linkedin", "mechanize", "python" ]
stackoverflow_0008213638_linkedin_mechanize_python.txt
Q: Trouble building Numpy 1.6.1 on Ubuntu 9.04--no __config__.py I do research at my school by sshing into one of the machines in our lab. I do not have root access to these machines, so when I need to install new Python modules I typically build them in a local directory and modify my PYTHONPATH to point to this dir...
Trouble building Numpy 1.6.1 on Ubuntu 9.04--no __config__.py
I do research at my school by sshing into one of the machines in our lab. I do not have root access to these machines, so when I need to install new Python modules I typically build them in a local directory and modify my PYTHONPATH to point to this directory, rather than installing them to the standard directories (wh...
[ "Well, I got numpy working by setting PYTHONPATH to point to the build/libXXX folder, but I was doing so to install scipy, which still demands some files as dependencies that don't exist in the either build directory I was trying. But that's another issue.\n" ]
[ 0 ]
[]
[]
[ "numpy", "python", "ubuntu" ]
stackoverflow_0008219782_numpy_python_ubuntu.txt
Q: Pagination problem with Django haystack i'm using django-haystack with simple engine, the search is fine, but the pagination is not working. This is the code of my search results template {% if query %} <br> <div id="contenido_pagina"> {% for result in page.object_list %} {% if result.objec...
Pagination problem with Django haystack
i'm using django-haystack with simple engine, the search is fine, but the pagination is not working. This is the code of my search results template {% if query %} <br> <div id="contenido_pagina"> {% for result in page.object_list %} {% if result.object.get_model == '[Video] ' %} {% if result...
[ "I had this issue as well. From debugging the code it looks like it's an issue with the paginator and the searchqueryset. Unfortunately i didn't have more time to devote to it and ended up moving on to whoosh for development environment.\n", "Just encountered this. Seems as though it's a known limitation of the ...
[ 0, 0 ]
[]
[]
[ "django", "django_haystack", "django_pagination", "django_templates", "python" ]
stackoverflow_0004917247_django_django_haystack_django_pagination_django_templates_python.txt
Q: python add dictionary to existing dictionary What am I doing wrong here? The append inside the dictionary doesn't seem to be working final = [] topid = { "ida" : "ida", "idb" : "idb", "idc" : "idc", "subid" : {} } for subid in subids: insubid = { "name" : subid.name, "sida" ...
python add dictionary to existing dictionary
What am I doing wrong here? The append inside the dictionary doesn't seem to be working final = [] topid = { "ida" : "ida", "idb" : "idb", "idc" : "idc", "subid" : {} } for subid in subids: insubid = { "name" : subid.name, "sida" : "sida", "sidb" : "sidb", "sidc" ...
[ "I'm not sure this is what you want, but by using append, your code is expecting subid to be a list. If that's what you are going for, you should be able to change this:\ntopid = { \n \"ida\" : \"ida\",\n \"idb\" : \"idb\",\n \"idc\" : \"idc\",\n \"subid\" : {}\n}\n\nto this:\ntopid = { \n \"ida\" :...
[ 11, 7 ]
[]
[]
[ "python" ]
stackoverflow_0008245892_python.txt
Q: Using Python networkx for exploring network properties I'm trying to make a code for getting Twitter network properties. But I got an error on my code. I don't know how come it happened. The error is this: Traceback (most recent call last): File "Network_property.py", line 14, in <module> followee = line.str...
Using Python networkx for exploring network properties
I'm trying to make a code for getting Twitter network properties. But I got an error on my code. I don't know how come it happened. The error is this: Traceback (most recent call last): File "Network_property.py", line 14, in <module> followee = line.strip().split('\t')[1] IndexError: list index out of range The...
[ "The error has nothing specifically to do with networkx. What is happening is that for some line line.strip().split('\\t') is returning only a single field. I'd guess that the problem is with blank lines in your file. Compare:\n>>> ''.split(\"\\t\")\n['']\n>>> ''.split(\"\\t\")[1]\nTraceback (most recent call last)...
[ 1, 1 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0008245660_networkx_python.txt
Q: Selenium is not sending keys to my gwt-SuggestBox I'm using selenium, scripting in python, to test a webpage that has a gwt-SuggestBox: <div id="streamSuggestBox"> <table> <tbody><tr> <td> <div class="gwt-Label errorText">Stream:</div> </td> <td> <div><input type="text" class="gwt-SuggestBox"></div> </td> ...
Selenium is not sending keys to my gwt-SuggestBox
I'm using selenium, scripting in python, to test a webpage that has a gwt-SuggestBox: <div id="streamSuggestBox"> <table> <tbody><tr> <td> <div class="gwt-Label errorText">Stream:</div> </td> <td> <div><input type="text" class="gwt-SuggestBox"></div> </td> </tr> </tbody></table> </div> selenium can find the di...
[ "You can try to directly set the value attribute. Sorry the code below is in C#, but the concept should be the same in python:\nstring script = \"arguments[0].setAttribute('value', argument[1])\";\nIWebElement suggestionBox = //find it somehow...\ndriver.ExecuteScript(script, suggestionBox , \"I typed this!\");\n\n...
[ 0, 0 ]
[]
[]
[ "gwt", "python", "selenium", "suggestbox" ]
stackoverflow_0008215702_gwt_python_selenium_suggestbox.txt
Q: QWidget not showing after calling show() In My App, I have a QWidget which is not showing after I call show(), even though isVisible returns true. This widget is created from an event of the main application window. But when its started on its own, i.e., as the only widget on an app, it shows up normally. Anyone k...
QWidget not showing after calling show()
In My App, I have a QWidget which is not showing after I call show(), even though isVisible returns true. This widget is created from an event of the main application window. But when its started on its own, i.e., as the only widget on an app, it shows up normally. Anyone knows what may cause this behavior? Other widge...
[ "The relevant code is in hidx/GUI/main.py:\n@pyqtSignature(\"\")\ndef on_actionScatterplot_Matrix_activated(self):\n ...\n spm = scatmat.ScatMat(pars, self.currentdbname)\n print \"==>\", spm.pw.isVisible()\n spm.pw.hide()\n spm.pw.showMaximized()\n print spm.pw.size()\n print \"==>\", spm.pw.i...
[ 4 ]
[]
[]
[ "pyqt", "pyqt4", "python", "show" ]
stackoverflow_0008242770_pyqt_pyqt4_python_show.txt
Q: Embedding Vs Linking in MongoDB.when to embed and when to link? I read this page but didn't get when to use embedding feature and when to use linking.I have a project in django for which I am using MongoDB.In my models.py file I have following models: class Projects(models.Model): projectName =models.CharField...
Embedding Vs Linking in MongoDB.when to embed and when to link?
I read this page but didn't get when to use embedding feature and when to use linking.I have a project in django for which I am using MongoDB.In my models.py file I have following models: class Projects(models.Model): projectName =models.CharField(max_length = 100,unique=True,db_index=True) projectManager = Emb...
[ "In your example, yes, changing the name of a user implies that if you use embedding then you must update all other documents with an extra step. What is more appropriate in your situation is linking (referencing). This involves an extra step at query time, but because of your particular \"business logic\", it is b...
[ 4, 3 ]
[]
[]
[ "django", "django_nonrel", "mongodb", "python" ]
stackoverflow_0008239819_django_django_nonrel_mongodb_python.txt
Q: how (in maya) can i get the 3D position of the mouse? i have created a dragger context in maya using the following code, pos holds my 2D coordinates of mouse cursor, i want to convert it into 3D coordinate to be the source of the ray i want to launch,, i want it either through python scripting or through the pytho...
how (in maya) can i get the 3D position of the mouse?
i have created a dragger context in maya using the following code, pos holds my 2D coordinates of mouse cursor, i want to convert it into 3D coordinate to be the source of the ray i want to launch,, i want it either through python scripting or through the python api,, import maya.cmds as mc mc.draggerContext( 'testCo...
[ "Actually, you might wanna look into the space(sp) flag in the draggerContext command help.\nmc.draggerContext('sampleContext', dragCommand='getCursorPos()', space='world')\n\ndef getCursorPos():\n print mc.draggerContext( 'testContext', query=1, dragPoint=1) \n\n...should print you the worldspace XYZ values of ...
[ 1, 0 ]
[]
[]
[ "3d", "autodesk", "maya", "python", "scripting" ]
stackoverflow_0001881592_3d_autodesk_maya_python_scripting.txt
Q: Why does this python code work? I have written a simple python module, it has this code: _log = logging.getLogger("mymodule") _started = False def set_log_level(level): _log.setLevel(level) if not _started: _hdlr = logging.FileHandler('mymodule.log') When I call set_log_level() program fails beca...
Why does this python code work?
I have written a simple python module, it has this code: _log = logging.getLogger("mymodule") _started = False def set_log_level(level): _log.setLevel(level) if not _started: _hdlr = logging.FileHandler('mymodule.log') When I call set_log_level() program fails because symbol _started is not found. It ...
[ "I don't think your program fails for the reason you think. There's no need to use the global declaration within a function unless you actually modify that variable. (Otherwise, you'd need to use global for every access of something in that namespace, even calling other functions.)\nI'm not sure what actually happe...
[ 4 ]
[]
[]
[ "global", "module", "python", "visibility" ]
stackoverflow_0008246696_global_module_python_visibility.txt
Q: Py2exe version number for com dll Is there are a way to add to the dll which py2exe makes a version tag? If I generate a new dll I need to see which function/clases are already implemented and I need to see if there are are already a newer dll that is tagged by a date or a version number (by myself created VN for ...
Py2exe version number for com dll
Is there are a way to add to the dll which py2exe makes a version tag? If I generate a new dll I need to see which function/clases are already implemented and I need to see if there are are already a newer dll that is tagged by a date or a version number (by myself created VN for example).
[ "Use version parameter as in:\nsetup(\n windows = [\n {'script': PyAppName,\n 'icon_resources':[(0, Icon)],\n 'dest_base' : Exe[:-4],\n 'version' : AppVers,\n 'company_name' : \"JoaquinAbian\",\n 'copyright' : \"No Copyrights\",\n...
[ 4 ]
[]
[]
[ "com", "dll", "py2exe", "python", "version" ]
stackoverflow_0008242840_com_dll_py2exe_python_version.txt
Q: Identifying with regexes and Python the title of a particular paragraph containing an unique word (and French Judges) I'm doing some data analysis over the judge appointment system in France, and using some code to do so. But I've run into a regex problem. My data, is made of a big list of courts and judges appoin...
Identifying with regexes and Python the title of a particular paragraph containing an unique word (and French Judges)
I'm doing some data analysis over the judge appointment system in France, and using some code to do so. But I've run into a regex problem. My data, is made of a big list of courts and judges appointments. Here's an example list : Appellate Court of Paris Blabla about the jugdge : Mr Dominique Martin, blahblahblah Bla...
[ "Using lxml to parse the html:\nimport lxml.html as LH\nimport re\n\nurl='http://www.legifrance.gouv.fr/affichTexte.do?cidTexte=JORFTEXT000022472292'\ndoc=LH.parse(url)\ndata=(p.text_content() for p in doc.xpath('//p'))\nnext(data) # Skip the paragraph before the first court\nresult={}\nfor court,text in zip(*[data...
[ 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008216729_python_regex.txt
Q: python: urllib2 using different network interface I have the following code: f = urllib2.urlopen(url) data = f.read() f.close() It's running on a machine with two network interfaces. I'd like to specify which interface I want the code to use. Specifically, I want it to use the one other than the one it is using b...
python: urllib2 using different network interface
I have the following code: f = urllib2.urlopen(url) data = f.read() f.close() It's running on a machine with two network interfaces. I'd like to specify which interface I want the code to use. Specifically, I want it to use the one other than the one it is using by default... but I can figure out which is which if I c...
[ "Not yet a complete solution, but if you were using only simple socket objects, you could do what you need this way : \nimport socket\ns = socket.socket()\ns.bind((\"127.0.0.1\", 0)) # replace \"127.0.0.1\" by the local IP of the interface to use\ns.connect((\"remote_server.com\", 80))\n\nThus, you will force th...
[ 3, 2 ]
[]
[]
[ "interface", "network_interface", "networking", "python", "sockets" ]
stackoverflow_0008245810_interface_network_interface_networking_python_sockets.txt
Q: How convert an embedded Neo4j graph db to GraphML with Python? I want to store my embedded Neo4j Graph db to GraphML to draw it with a tool like yEd. I'm managing the graph db with python27. Does any body knows a way to do that? A: If you can afford to do it outside of the process -- which means you'll need to s...
How convert an embedded Neo4j graph db to GraphML with Python?
I want to store my embedded Neo4j Graph db to GraphML to draw it with a tool like yEd. I'm managing the graph db with python27. Does any body knows a way to do that?
[ "If you can afford to do it outside of the process -- which means you'll need to shut down your existing process working on the embedded database and restart when finished with the export-- you can use Gremlin to do it. Here's the commands you'll need:\ng = new Neo4jGraph(\"/YOUR/GRAPH/DIRECTORY\")\nwriter = new Gr...
[ 1, 0 ]
[]
[]
[ "graphml", "neo4j", "neo4j.py", "python" ]
stackoverflow_0008228221_graphml_neo4j_neo4j.py_python.txt
Q: Recommended Django setup? I am about to embark a major django project. If I install the latest stable release... is the a suggested setup ie. this OS, this RDBMS, this version of python etc?? I'm normally a CentOS man but their repos don't play too well with the django requirements... A: Ubuntu is far and away a...
Recommended Django setup?
I am about to embark a major django project. If I install the latest stable release... is the a suggested setup ie. this OS, this RDBMS, this version of python etc?? I'm normally a CentOS man but their repos don't play too well with the django requirements...
[ "Ubuntu is far and away a better platform nowadays. I'm a refugee from RHEL and Fedora. Get Ubuntu 9.10, and if you'd like, spawn it on Amazon ec2 for total flexibility (i.e. launch it in about 90 seconds, play around, do what you want, delete it, and only pay a buck). Otherwise, just use Ubuntu on the desktop.\...
[ 2, 1, 1, 0 ]
[]
[]
[ "apache", "django", "python" ]
stackoverflow_0002192685_apache_django_python.txt
Q: Using column_validators in pycassa I'm trying to setup some column_validators in pycassa but having troubles in doing so with some kind of supercolum setup: I don't seem to be able to set a validator for a column contained in a supercolumn. I'm trying something like cf.column_validators['supercolumn_name']['colu...
Using column_validators in pycassa
I'm trying to setup some column_validators in pycassa but having troubles in doing so with some kind of supercolum setup: I don't seem to be able to set a validator for a column contained in a supercolumn. I'm trying something like cf.column_validators['supercolumn_name']['column_name'] = types.FloatType() which doe...
[ "You probably don't want to be modifying column_validators directly. Those are set automatically based on the column_metadata properties of the column family. You can use the 'alter_column' command in pycassa to modify the column family schema in Cassandra. Then column_validators will be set correctly permanently.\...
[ 4 ]
[]
[]
[ "cassandra", "pycassa", "python" ]
stackoverflow_0008244725_cassandra_pycassa_python.txt
Q: How do I create a list of timedeltas in python? I've been searching through this website and have seen multiple references to time deltas, but haven't quite found what I'm looking for. Basically, I have a list of messages that are received by a comms server and I want to calcuate the latency time between each mes...
How do I create a list of timedeltas in python?
I've been searching through this website and have seen multiple references to time deltas, but haven't quite found what I'm looking for. Basically, I have a list of messages that are received by a comms server and I want to calcuate the latency time between each message out and in. It looks like this: 161336.934072 -...
[ "First of all, don't write out the raw log lines. Secondly use a dict.\ntdeltas = {} # this is an empty dict\nif \"T\" in line:\n get Refid number\n if Refid in tedeltas:\n tdeltas[Refid] = timestamp - tdeltas[Refid]\n else:\n tdeltas[Refid] = timestamp\n\nThen at the end, convert to a list and prin...
[ 1, 0 ]
[]
[]
[ "datetime", "python", "timedelta" ]
stackoverflow_0008246411_datetime_python_timedelta.txt
Q: inverting dictionary in python I have this dictionary {'jackie chan': ('rush hour', 'rush hour 2'), 'crish tucker': ('rush hour', 'rush hour 2')} I want the inverse dictionary to be {'rush hour': ('jackie chan', 'crish tucker'), 'rush hour 2': ('jackie chan', 'crish tucker')} I already got the function t...
inverting dictionary in python
I have this dictionary {'jackie chan': ('rush hour', 'rush hour 2'), 'crish tucker': ('rush hour', 'rush hour 2')} I want the inverse dictionary to be {'rush hour': ('jackie chan', 'crish tucker'), 'rush hour 2': ('jackie chan', 'crish tucker')} I already got the function to inverse but it doesn't look like t...
[ "You can easily do this with collections.defaultdict:\ndef invert_dict(d):\n inverted_dict = collections.defaultdict(set)\n for actor, movies in d.iteritems():\n for movie in movies:\n inverted_dict.add(actor)\n return inverted_dict\n\n", "Your code has two problems\nThe first problem y...
[ 5, 4, 0, 0, 0, 0, 0 ]
[ "A dictionary is by default not not sortable, so you can not sort it. You can look into the structure ordered dictionary if the order matters\n" ]
[ -1 ]
[ "dictionary", "python" ]
stackoverflow_0008246484_dictionary_python.txt
Q: Capture stdout and stderr from SAS in Windows? I want to call a SAS program from another program on Windows. I have some experience invoking SAS from the command line in batch mode, but no real experience receiving messages from it and handling those messages. I have googled around and found quite a bit of infor...
Capture stdout and stderr from SAS in Windows?
I want to call a SAS program from another program on Windows. I have some experience invoking SAS from the command line in batch mode, but no real experience receiving messages from it and handling those messages. I have googled around and found quite a bit of information about reading from stdin from within a SAS pr...
[ "I don't have a windows version of SAS handy, but on UNIX I redirect to STDOUT like this:\ndata _null_;\n file STDOUT;\n do i=1 to 10;\n put i=;\n end;\nrun;\n\nNot sure how to redirect the error log to STDERR, but printing to STDERR would look like this:\nods listing file=STDERR;\n\nproc print data=sas...
[ 2, 2 ]
[ "Googled redirecting the log to STDERR for you:\n proc printto log=STDERR;\n run;\n\n data _null_;\n 1=x;\n run;\n\n" ]
[ -1 ]
[ "python", "sas" ]
stackoverflow_0008234999_python_sas.txt
Q: WTForms decimalfield raises type error on getting u'' input I am using WTForms with cherrypy with a decimal field but I'm getting a typeError exception when I pass a u"" string to it. It says it needs a float when it runs the _value function. It would be nice for wtforms to respond with its validation error but ...
WTForms decimalfield raises type error on getting u'' input
I am using WTForms with cherrypy with a decimal field but I'm getting a typeError exception when I pass a u"" string to it. It says it needs a float when it runs the _value function. It would be nice for wtforms to respond with its validation error but its excepting. I'm passing u"" to the decimal field. It works wh...
[ "So I found out you have to use werkzueg multidict and pass the kwargs to that for your forms for cherrypy.\nhttp://groups.google.com/group/wtforms/msg/27a20dab9d24ca80\n" ]
[ 0 ]
[]
[]
[ "python", "wtforms" ]
stackoverflow_0008246162_python_wtforms.txt
Q: AttributeError in trying to access a python function I am trying to access a python function of a class into another script. This gives me the following error : AttributeError: 'module' object has no attribute 'functionName' The function is present in a class and is accessed via classname.functionName() call. Is ...
AttributeError in trying to access a python function
I am trying to access a python function of a class into another script. This gives me the following error : AttributeError: 'module' object has no attribute 'functionName' The function is present in a class and is accessed via classname.functionName() call. Is there anything that I am missing ? -update- My code is: ...
[ "A function inside a class is called a method. You can access it from another module with\nimport module\nmodule.Classname.method\n\nHowever, unless that method is a special kind of method call a staticmethod or classmethod, \nyou won't be able to call it with module.Classname.method().\nInstead, you'd need to make...
[ 6, 2, 1 ]
[]
[]
[ "python", "python_module" ]
stackoverflow_0008243436_python_python_module.txt
Q: Which Python web framework has the most employment opportunities? (And which has features like Ruby on Rails?) What is the best Python web framework that one should get into if one is interested in job prospects where that framework is being used? I am a co-op student. When applying for jobs I remember seeing Pyth...
Which Python web framework has the most employment opportunities? (And which has features like Ruby on Rails?)
What is the best Python web framework that one should get into if one is interested in job prospects where that framework is being used? I am a co-op student. When applying for jobs I remember seeing Python for web development mentioned in many of the jobs, but can’t remember which frameworks were mentioned. I am inter...
[ "There are many frameworks in Python, but the most popular is probably Django. It's also famous for its good docs. I, personally, like Pyramid because of its flexibility. You should just check a few of them (google for \"python web framework\"), and then decide.\nWhen it comes to gems, they are not Rails' but Ruby'...
[ 4, 3, 1 ]
[]
[]
[ "django", "pylons", "python", "ruby_on_rails", "web_frameworks" ]
stackoverflow_0008247508_django_pylons_python_ruby_on_rails_web_frameworks.txt
Q: Error while trying to open CSV file in python Python rookie here. Trying to use the CSV module, but I get an error: IOError: [Errno 2] No such file or directory: 'books.csv' The actual CSV file is stored on my desktop. I suppose this means Python can't find the file? If so, how can I fix this? Many thanks in adva...
Error while trying to open CSV file in python
Python rookie here. Trying to use the CSV module, but I get an error: IOError: [Errno 2] No such file or directory: 'books.csv' The actual CSV file is stored on my desktop. I suppose this means Python can't find the file? If so, how can I fix this? Many thanks in advance!
[ "Since your file name includes no path component, it is implicitly assigned to be in the current directory. Unless your current directory is the desktop, you won't be able to find the file.\nEither give it a full pathname, or move to the desktop and run your script from there.\n" ]
[ 3 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0008247767_csv_python.txt
Q: PyAMF DatabaseError: 'This query is not supported by the database.' when returning the User object This is the error I'm getting: ERROR 2011-11-19 04:19:55,441 django.py:164] Error encoding AMF request Traceback (most recent call last): File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-uni...
PyAMF DatabaseError: 'This query is not supported by the database.' when returning the User object
This is the error I'm getting: ERROR 2011-11-19 04:19:55,441 django.py:164] Error encoding AMF request Traceback (most recent call last): File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/remoting/gateway/django.py", line 161, in __call__ logger=self.logger, timezone_off...
[ "You should not have to to allow for blank=True, null=True for User model. Normally django.contrib.auth.models.AnonymousUser takes care of anonymous requests. It may or may not fix the issue, but it is worth trying, i.e.: \nclass ChallengeAct(RewardActBase):\n user = models.ForeignKey(User)\n ....\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_nonrel", "pyamf", "python" ]
stackoverflow_0008191976_django_django_nonrel_pyamf_python.txt
Q: Python - How to cut a string in Python? Suppose that I have the following string: http://www.domain.com/?s=some&two=20 How can I take off what is after & including the & and have this string: http://www.domain.com/?s=some A: Well, to answer the immediate question: >>> s = "http://www.domain.com/?s=some&two=20" ...
Python - How to cut a string in Python?
Suppose that I have the following string: http://www.domain.com/?s=some&two=20 How can I take off what is after & including the & and have this string: http://www.domain.com/?s=some
[ "Well, to answer the immediate question:\n>>> s = \"http://www.domain.com/?s=some&two=20\"\n\nThe rfind method returns the index of right-most substring:\n>>> s.rfind(\"&\")\n29\n\nYou can take all elements up to a given index with the slicing operator:\n>>> \"foobar\"[:4]\n'foob'\n\nPutting the two together:\n>>> ...
[ 56, 49, 7, 4, 2, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0008247792_python_string.txt
Q: App Engine MapReduce mapper wrong model kind passed Hey I was following the documentation here: Google MapReduce class StationsBlobstoreHandler(webapp.RequestHandler): '''''' def get(self): mr_job = mapreduce_pipeline.MapPipeline( 'calculate_sha1_stations_logos', 'radioflag.admin.mapreduce.blob...
App Engine MapReduce mapper wrong model kind passed
Hey I was following the documentation here: Google MapReduce class StationsBlobstoreHandler(webapp.RequestHandler): '''''' def get(self): mr_job = mapreduce_pipeline.MapPipeline( 'calculate_sha1_stations_logos', 'radioflag.admin.mapreduce.blobfixstations.station_avatar_mapper', 'mapreduce.in...
[ "OK I have found that i should use DatastoreInputReader instead of DatastoreEntityInputReader.\nSorry :)\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "mapreduce", "python" ]
stackoverflow_0008247602_google_app_engine_mapreduce_python.txt
Q: Sending data back from controller in Pylons using jQuery Form Plugin I'm trying to figure out how to send a variable from the controller's view back with the success callback using jQuery Form Plugin. In the example on the website, they show how to do it with PHP, which is fine, but we're using Pylons (I'm on the ...
Sending data back from controller in Pylons using jQuery Form Plugin
I'm trying to figure out how to send a variable from the controller's view back with the success callback using jQuery Form Plugin. In the example on the website, they show how to do it with PHP, which is fine, but we're using Pylons (I'm on the front-end). Therefore, I'd like to know basically how to send a variable f...
[ "Figured it out by using responseText within the success callback. I chose json as the dataType.\n" ]
[ 0 ]
[]
[]
[ "ajax", "jquery", "pylons", "python" ]
stackoverflow_0008191128_ajax_jquery_pylons_python.txt
Q: How do I approach this named-entity classification task? I am asking a related question here but this question is more general. I have taken a large corpora and annotated some words with their named-entities. In my case, they are domain-specific and I call them: Entity, Action, Incident. I want to use these as a s...
How do I approach this named-entity classification task?
I am asking a related question here but this question is more general. I have taken a large corpora and annotated some words with their named-entities. In my case, they are domain-specific and I call them: Entity, Action, Incident. I want to use these as a seed for extracting more named-entities. For example, following...
[ "This is not named-entity recognition at all, since none of the labeled parts are names, so the feature sets for NER systems won't help you (English NER systems tend to rely on capitalization quite strongly and will prefer nouns). This is a kind of information extraction/semantic interpretation. I suspect this is g...
[ 1, 0, 0 ]
[]
[]
[ "machine_learning", "nlp", "nltk", "python" ]
stackoverflow_0008219915_machine_learning_nlp_nltk_python.txt
Q: Use Python to manipulate txt file presentation of key-value grouping I am trying to use Python in order to manipulate a text file from Format A: Key1 Key1value1 Key1value2 Key1value3 Key2 Key2value1 Key2value2 Key2value3 Key3... Into Format B: Key1 Key1value1 Key1 Key1value2 Key1 Key1value3...
Use Python to manipulate txt file presentation of key-value grouping
I am trying to use Python in order to manipulate a text file from Format A: Key1 Key1value1 Key1value2 Key1value3 Key2 Key2value1 Key2value2 Key2value3 Key3... Into Format B: Key1 Key1value1 Key1 Key1value2 Key1 Key1value3 Key2 Key2value1 Key2 Key2value2 Key2 Key2value3 Key3 Key3value1.....
[ "Do it in one pass, without storing the lines:\nwith open(\"input\") as infile, open(\"ouptut\", \"w\") as outfile:\n for line in infile:\n if line.startswith(\"chr\"):\n key = line.strip()\n else:\n print >> outfile, key, line.rstrip(\"\\n\")\n\nThis code assumes the first li...
[ 5, 0, 0 ]
[]
[]
[ "key_value", "python", "text_files" ]
stackoverflow_0008247499_key_value_python_text_files.txt
Q: Can a Heroku app use different/multiple ports? Web services on Heroku normally use the PORT environment variable, but I want to run a custom mail server on Heroku. So I need to expose 2 ports, preferably 110 and 25, but I can live with alternatives. Is it possible? A: No, just running some quick tests against th...
Can a Heroku app use different/multiple ports?
Web services on Heroku normally use the PORT environment variable, but I want to run a custom mail server on Heroku. So I need to expose 2 ports, preferably 110 and 25, but I can live with alternatives. Is it possible?
[ "No, just running some quick tests against the heroku proxy (proxy.heroku.com) I can only make connections to ports 80 and 443. Being as heroku don't provide any POP/SMTP it doesn't make sense for them to have those ports open I'm afraid.\n", "Dotcloud allows this: https://github.com/pepijndevos/Twemail\n", "Cu...
[ 3, 1, 0 ]
[]
[]
[ "email", "heroku", "port", "python" ]
stackoverflow_0008107748_email_heroku_port_python.txt