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: storing 'object' Does PyTables support storing Python objects? something like this : dtype = np.dtype([('Name', '|S2'), ('objValue', object)]) data = np.zeros(3, dtype) file.createArray(box3,'complicated',data) I get error when trying to do this of course... How to properly store arrays of objects?Is it possible? Thanks A: You can save generic Python object with Pytables: >>> dtype = np.dtype([('Name', '|S2'), ('objValue', object)]) >>> data = np.zeros(3, dtype) >>> file = tables.openFile('/tmp/test.h5', 'w') >>> myobjects = file.createVLArray(file.root, 'myobjects', tables.ObjectAtom()) >>> myobjects.append(data) >>> myobjects[0] array([('', 0), ('', 0), ('', 0)], dtype=[('Name', '|S2'), ('objValue', '|O8')]) However, this will use pickle (cPickle in fact) behind the scenes, so you won't be able to access these objects from other languages (pickle is a serialization format only supported by Python itself). A: Try the pickle module if you want to store complicated data somewhere it isn't supported by the library in question.
storing 'object'
Does PyTables support storing Python objects? something like this : dtype = np.dtype([('Name', '|S2'), ('objValue', object)]) data = np.zeros(3, dtype) file.createArray(box3,'complicated',data) I get error when trying to do this of course... How to properly store arrays of objects?Is it possible? Thanks
[ "You can save generic Python object with Pytables:\n>>> dtype = np.dtype([('Name', '|S2'), ('objValue', object)])\n>>> data = np.zeros(3, dtype)\n>>> file = tables.openFile('/tmp/test.h5', 'w')\n>>> myobjects = file.createVLArray(file.root, 'myobjects', tables.ObjectAtom())\n>>> myobjects.append(data)\n>>> myobject...
[ 5, 1 ]
[]
[]
[ "pytables", "python" ]
stackoverflow_0004104812_pytables_python.txt
Q: what is the right regex for this? what is the regex for such a task? --> replace "[[...:" with "[[" That is to say, I want to replace *some text * inside [[...: with [[. The problem with my code is that it remove *text * inside the first [[ ]] >>> string = "Some text here [[dont remove me]] and some extra text [[remove me:and let this]] here." >>> clean = re.sub(r'\[\[.+:', '[[', string) >>> clean 'Some text here [[and let this]] here.' >>> A: re.sub(r'\[\[[^:\]]+:', '[[', string) [^:\]] is used instead of . to constrain that the stuff to remove is limited within a tag. A: Instead of . use an expression that excludes : and the closing ]]: r'\[\[(?:[^:\]]|\][^\]])*:'
what is the right regex for this?
what is the regex for such a task? --> replace "[[...:" with "[[" That is to say, I want to replace *some text * inside [[...: with [[. The problem with my code is that it remove *text * inside the first [[ ]] >>> string = "Some text here [[dont remove me]] and some extra text [[remove me:and let this]] here." >>> clean = re.sub(r'\[\[.+:', '[[', string) >>> clean 'Some text here [[and let this]] here.' >>>
[ "re.sub(r'\\[\\[[^:\\]]+:', '[[', string)\n\n[^:\\]] is used instead of . to constrain that the stuff to remove is limited within a tag.\n", "Instead of . use an expression that excludes : and the closing ]]:\nr'\\[\\[(?:[^:\\]]|\\][^\\]])*:'\n\n" ]
[ 1, 0 ]
[]
[]
[ "python", "regex", "replace" ]
stackoverflow_0004148039_python_regex_replace.txt
Q: SQL zero instead of null This function: for i in Selection: cursor.execute(Query) ydata[i] = [int(x[0]) for x in cursor.fetchall()] raises: ValueError: invalid literal for int(): NULL if a null value is found. How can I make my query return zeros instead of nulls so that I can fix this? (I am plotting the data, so I cannot add "is not null" to my select statement. A: You can fix this before it gets to Python with a case statement in your query: CASE WHEN FIELD_NAME IS NULL THEN 0 ELSE FIELD_NAME END, begin edit Other SQL variants do it differently (taken from other answers): COALESCE(FIELD_NAME, 0) or IFNULL(FIELD_NAME, 0) end edit Or handle it in your list comp like so (assumes NULL is a predefined object or constant): ydata[i] = [(int(x[0]) if x[0] != NULL else 0) for x in cursor.fetchall()] Or create a customer conversion function: def field_to_int(val): if val == NULL: return 0 else: return int(val) for i in Selection: cursor.execute(Query) ydata[i] = [field_to_int(x[0]) for x in cursor.fetchall()] A: Put IFNULL(fieldname, 0) AS fieldname in the field list of the query. A: You'd use IFNULL ...IFNULL(MyField, 0) AS MyField... A: The error doesn't make sense; Python doesn't have "NULL", it has "None". The cleanest thing to do is use SQL coalesce: SELECT COALESCE(value, 0) to convert SQL NULL to 0. If you're getting None, and you know the values are integers, then you can safely say int(x[0] or 0).
SQL zero instead of null
This function: for i in Selection: cursor.execute(Query) ydata[i] = [int(x[0]) for x in cursor.fetchall()] raises: ValueError: invalid literal for int(): NULL if a null value is found. How can I make my query return zeros instead of nulls so that I can fix this? (I am plotting the data, so I cannot add "is not null" to my select statement.
[ "You can fix this before it gets to Python with a case statement in your query:\nCASE WHEN FIELD_NAME IS NULL THEN 0 ELSE FIELD_NAME END,\n\nbegin edit\nOther SQL variants do it differently (taken from other answers):\nCOALESCE(FIELD_NAME, 0)\n\nor\nIFNULL(FIELD_NAME, 0)\n\nend edit\nOr handle it in your list comp ...
[ 6, 2, 2, 2 ]
[]
[]
[ "null", "python", "sql", "sqlite", "zero" ]
stackoverflow_0004148205_null_python_sql_sqlite_zero.txt
Q: 'meta' extension for Markdown not loading in Python2.6? I'm trying to get the meta extension working with markdown in Python 2.6. The code looks like this: import markdown as m print "Markdown version: ", m.version file = "file.md" md = m.Markdown( extensions = ['meta']) # doesn't complain print "Registered extensions: ", md.registeredExtensions text = open(file) try: md.convert(file) except AttributeError as a: print "Error: ", a print "Meta: ", md.Meta And my file looks like this: Title: Chaleur Date: 2010-07-11 Author: Gui13 Simple md test ![Chaleur](../content/chaleur.jpg) What I'd like to get is something like 'title' : 'Chaleur', 'date' : '2010-07-11', 'author' : 'gui13' when printing the md.Meta. What I get is this: $ python test.py Markdown version: 2.1.0 Registered extensions: [] Meta: {} So it looks like the meta extension is not even loaded, whereas it should be (meta is supposed to be included in Markdown since version 2.0). Do you know what is the problem? A: convert() expects text. Replace md.convert(file) by md.convert(open(file).read()). import markdown as m print "Markdown version: ", m.version file = "file.md" md = m.Markdown(extensions=['meta']) # doesn't complain print "Registered extensions: ", md.registeredExtensions print "Preprocessors:", md.preprocessors.keys() text = open(file).read() try: print md.convert(text) except AttributeError as a: print "Error: ", a print "Meta: ", md.Meta Output: Markdown version: 2.1.0 Registered extensions: [] Preprocessors: ['meta', 'html_block', 'reference'] <p>Simple md test <img alt="Chaleur" src="../content/chaleur.jpg" /></p> Meta: {u'date': [u'2010-07-11'], u'author': [u'Gui13'], u'title': [u'Chaleur']}
'meta' extension for Markdown not loading in Python2.6?
I'm trying to get the meta extension working with markdown in Python 2.6. The code looks like this: import markdown as m print "Markdown version: ", m.version file = "file.md" md = m.Markdown( extensions = ['meta']) # doesn't complain print "Registered extensions: ", md.registeredExtensions text = open(file) try: md.convert(file) except AttributeError as a: print "Error: ", a print "Meta: ", md.Meta And my file looks like this: Title: Chaleur Date: 2010-07-11 Author: Gui13 Simple md test ![Chaleur](../content/chaleur.jpg) What I'd like to get is something like 'title' : 'Chaleur', 'date' : '2010-07-11', 'author' : 'gui13' when printing the md.Meta. What I get is this: $ python test.py Markdown version: 2.1.0 Registered extensions: [] Meta: {} So it looks like the meta extension is not even loaded, whereas it should be (meta is supposed to be included in Markdown since version 2.0). Do you know what is the problem?
[ "convert() expects text. Replace md.convert(file) by md.convert(open(file).read()).\nimport markdown as m\n\nprint \"Markdown version: \", m.version\nfile = \"file.md\"\nmd = m.Markdown(extensions=['meta']) # doesn't complain\n\nprint \"Registered extensions: \", md.registeredExtensions\nprint \"Preprocessors:\", m...
[ 2 ]
[]
[]
[ "markdown", "meta", "python" ]
stackoverflow_0004148036_markdown_meta_python.txt
Q: Python: map in place I was wondering if there is a way to run map on something. The way map works is it takes an iterable and applies a function to each item in that iterable producing a list. Is there a way to have map modify the iterable object itself? A: A slice assignment is often ok if you need to modify a list in place mylist[:] = map(func, mylist) A: It's simple enough to write: def inmap(f, x): for i, v in enumerate(x): x[i] = f(v) a = range(10) inmap(lambda x: x**2, a) print a A: You can use a lambda (or a def) or better list comprehension (if it is sufficient): [ do_things_on_iterable for item in iterable ] Anyway you may want to be more explicit with a for loop if the things become too much complex. For example you can do something like, that but imho it's ugly: [ mylist.__setitem__(i,thing) for i,thing in enumerate(mylist) ] A: Just write the obvious code to do it. for i, item in enumerate(sequence): sequence[i] = f(item)
Python: map in place
I was wondering if there is a way to run map on something. The way map works is it takes an iterable and applies a function to each item in that iterable producing a list. Is there a way to have map modify the iterable object itself?
[ "A slice assignment is often ok if you need to modify a list in place\nmylist[:] = map(func, mylist)\n\n", "It's simple enough to write:\ndef inmap(f, x):\n for i, v in enumerate(x):\n x[i] = f(v)\n\na = range(10)\ninmap(lambda x: x**2, a)\nprint a\n\n", "You can use a lambda (or a def) or better ...
[ 13, 4, 1, 1 ]
[]
[]
[ "iterable", "map_function", "python" ]
stackoverflow_0003000461_iterable_map_function_python.txt
Q: Django relative urls and https I have a Django project using https for certain part of the url (/account/, /admin/, /purchase/). When on one of this page in https mode, all the relative inner links {% url foo %} will point to https://my_url. However I do not want to have those pages shown as https :home, contacts ... What are the solutions for this kind of requirements ? Enforcing absolute url ? http://{{ domain }}{% url foo %} is not too nice. A: Idea: you can use a custom middleware to redirect from https to http (or vice versa) for centrain URLs or URL patterns. This could also be done in Apache (or other web server) configuration. A: As Tomasz suggests, one way to do it is to set up middleware to redirect to and from https as necessary. Here's one implementation - the idea is to decorate those views that should be served under https, and when the user navigates to a view that shouldn't be secure from one that is, the middleware redirects them automatically back to the http version of the page. A: Could use your webserver to rewrite to http, that way Django doesn't even need to know. A: I find this snippet takes care of the situation nicely. Views that need SSL will have them, via a redirect from the http to https version of the url, and vice-versa. Yes, on a https page, the outbound link to a non-https page in your site will still start with https, but the user will be redirected to the http version. (There is a gotcha, however: it won't work if you're posting from http to https and vice versa) A: maybe this can serve for you http://code.djangoproject.com/wiki/ContributedMiddleware#SSLMiddlewarebyStephenZabel an contributed SSL Middleware
Django relative urls and https
I have a Django project using https for certain part of the url (/account/, /admin/, /purchase/). When on one of this page in https mode, all the relative inner links {% url foo %} will point to https://my_url. However I do not want to have those pages shown as https :home, contacts ... What are the solutions for this kind of requirements ? Enforcing absolute url ? http://{{ domain }}{% url foo %} is not too nice.
[ "Idea: you can use a custom middleware to redirect from https to http (or vice versa) for centrain URLs or URL patterns. This could also be done in Apache (or other web server) configuration.\n", "As Tomasz suggests, one way to do it is to set up middleware to redirect to and from https as necessary. Here's one i...
[ 4, 4, 2, 2, 2 ]
[]
[]
[ "django", "https", "python", "ssl" ]
stackoverflow_0004148009_django_https_python_ssl.txt
Q: Patterns in Binary Fractions with Python Researching pattern identification requires to identify the repeating patterns in binary representations of fractions of rational numbers. bin(2**24/n) strips the leading zeros, e.g. bin(2**24/11) -> 0b101110100010111010001 instead of 0b000101110100010111010001. The number of leading zeros is variable of course. The obvious pattern here is 0001011101... I am a nubee with Python still on the learning curve. Is there a Python-appropriate way to approach this? A: This can be done with string formatting, in 2.6+: >>> '{0:024b}'.format(23) '000000000000000000010111' A: You might find the bitstring module useful if you have more advanced needs than string formatting can provide. >>> from bitstring import BitArray >>> a = BitArray(24) # 24 zero bits >>> a.uint = 2**24/11 # set the unsigned integer propery >>> a.bin # get the binary propery '000101110100010111010001' It will never cut off leading zero bits, and can do a few other useful tricks >>> a.uint /= 2 >>> a.bin '000010111010001011101000' >>> list(a.findall('0b1011')) [4, 14] >>> a *= 2 # concatenation >>> a.bin '000010111010001011101000000010111010001011101000' >>> a.replace('0b00001', '0xe') 2 # 2 replacements made >>> a.bin '1110011101000101110100011100111010001011101000' I'm not sure of what your exact needs are, so all this could be overkill and you might not want to use an external library in any case, but Python in-built support for bit arrays is a little basic.
Patterns in Binary Fractions with Python
Researching pattern identification requires to identify the repeating patterns in binary representations of fractions of rational numbers. bin(2**24/n) strips the leading zeros, e.g. bin(2**24/11) -> 0b101110100010111010001 instead of 0b000101110100010111010001. The number of leading zeros is variable of course. The obvious pattern here is 0001011101... I am a nubee with Python still on the learning curve. Is there a Python-appropriate way to approach this?
[ "This can be done with string formatting, in 2.6+:\n>>> '{0:024b}'.format(23)\n'000000000000000000010111'\n\n", "You might find the bitstring module useful if you have more advanced needs than string formatting can provide. \n>>> from bitstring import BitArray\n>>> a = BitArray(24) # 24 zero bits\n>>> a....
[ 4, 2 ]
[]
[]
[ "binary", "numbers", "python" ]
stackoverflow_0004148132_binary_numbers_python.txt
Q: Overwriting a specific row in a csv file using Python's CSV module I'm using Python's csv module to do some reading and writing of csv files. I've got the reading fine and appending to the csv fine, but I want to be able to overwrite a specific row in the csv. For reference, here's my reading and then writing code to append: #reading b = open("bottles.csv", "rb") bottles = csv.reader(b) bottle_list = [] bottle_list.extend(bottles) b.close() #appending b=open('bottles.csv','a') writer = csv.writer(b) writer.writerow([bottle,emptyButtonCount,100, img]) b.close() And I'm using basically the same for the overwrite mode(which isn't correct, it just overwrites the whole csv file): b=open('bottles.csv','wb') writer = csv.writer(b) writer.writerow([bottle,btlnum,100,img]) b.close() In the second case, how do I tell Python I need a specific row overwritten? I've scoured Gogle and other stackoverflow posts to no avail. I assume my limited programming knowledge is to blame rather than Google. A: I will add to Steven Answer : import csv bottle_list = [] # Read all data from the csv file. with open('a.csv', 'rb') as b: bottles = csv.reader(b) bottle_list.extend(bottles) # data to override in the format {line_num_to_override:data_to_write}. line_to_override = {1:['e', 'c', 'd'] } # Write data to the csv file and replace the lines in the line_to_override dict. with open('a.csv', 'wb') as b: writer = csv.writer(b) for line, row in enumerate(bottle_list): data = line_to_override.get(line, row) writer.writerow(data) A: You cannot overwrite a single row in the CSV file. You'll have to write all the rows you want to a new file and then rename it back to the original file name. Your pattern of usage may fit a database better than a CSV file. Look into the sqlite3 module for a lightweight database.
Overwriting a specific row in a csv file using Python's CSV module
I'm using Python's csv module to do some reading and writing of csv files. I've got the reading fine and appending to the csv fine, but I want to be able to overwrite a specific row in the csv. For reference, here's my reading and then writing code to append: #reading b = open("bottles.csv", "rb") bottles = csv.reader(b) bottle_list = [] bottle_list.extend(bottles) b.close() #appending b=open('bottles.csv','a') writer = csv.writer(b) writer.writerow([bottle,emptyButtonCount,100, img]) b.close() And I'm using basically the same for the overwrite mode(which isn't correct, it just overwrites the whole csv file): b=open('bottles.csv','wb') writer = csv.writer(b) writer.writerow([bottle,btlnum,100,img]) b.close() In the second case, how do I tell Python I need a specific row overwritten? I've scoured Gogle and other stackoverflow posts to no avail. I assume my limited programming knowledge is to blame rather than Google.
[ "I will add to Steven Answer :\nimport csv\n\nbottle_list = []\n\n# Read all data from the csv file.\nwith open('a.csv', 'rb') as b:\n bottles = csv.reader(b)\n bottle_list.extend(bottles)\n\n# data to override in the format {line_num_to_override:data_to_write}. \nline_to_override = {1:['e', 'c', 'd'] }\n\n# ...
[ 18, 4 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0004148772_csv_python.txt
Q: Use of *args and **kwargs So I have difficulty with the concept of *args and **kwargs. So far I have learned that: *args = list of arguments - as positional arguments **kwargs = dictionary - whose keys become separate keyword arguments and the values become values of these arguments. I don't understand what programming task this would be helpful for. Maybe: I think to enter lists and dictionaries as arguments of a function AND at the same time as a wildcard, so I can pass ANY argument? Is there a simple example to explain how *args and **kwargs are used? Also the tutorial I found used just the "*" and a variable name. Are *args and **kwargs just placeholders or do you use exactly *args and **kwargs in the code? A: The syntax is the * and **. The names *args and **kwargs are only by convention but there's no hard requirement to use them. You would use *args when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. For example: >>> def print_everything(*args): for count, thing in enumerate(args): ... print( '{0}. {1}'.format(count, thing)) ... >>> print_everything('apple', 'banana', 'cabbage') 0. apple 1. banana 2. cabbage Similarly, **kwargs allows you to handle named arguments that you have not defined in advance: >>> def table_things(**kwargs): ... for name, value in kwargs.items(): ... print( '{0} = {1}'.format(name, value)) ... >>> table_things(apple = 'fruit', cabbage = 'vegetable') cabbage = vegetable apple = fruit You can use these along with named arguments too. The explicit arguments get values first and then everything else is passed to *args and **kwargs. The named arguments come first in the list. For example: def table_things(titlestring, **kwargs) You can also use both in the same function definition but *args must occur before **kwargs. You can also use the * and ** syntax when calling a function. For example: >>> def print_three_things(a, b, c): ... print( 'a = {0}, b = {1}, c = {2}'.format(a,b,c)) ... >>> mylist = ['aardvark', 'baboon', 'cat'] >>> print_three_things(*mylist) a = aardvark, b = baboon, c = cat As you can see in this case it takes the list (or tuple) of items and unpacks it. By this it matches them to the arguments in the function. Of course, you could have a * both in the function definition and in the function call. A: One place where the use of *args and **kwargs is quite useful is for subclassing. class Foo(object): def __init__(self, value1, value2): # do something with the values print value1, value2 class MyFoo(Foo): def __init__(self, *args, **kwargs): # do something else, don't care about the args print 'myfoo' super(MyFoo, self).__init__(*args, **kwargs) This way you can extend the behaviour of the Foo class, without having to know too much about Foo. This can be quite convenient if you are programming to an API which might change. MyFoo just passes all arguments to the Foo class. A: Here's an example that uses 3 different types of parameters. def func(required_arg, *args, **kwargs): # required_arg is a positional-only parameter. print required_arg # args is a tuple of positional arguments, # because the parameter name has * prepended. if args: # If args is not empty. print args # kwargs is a dictionary of keyword arguments, # because the parameter name has ** prepended. if kwargs: # If kwargs is not empty. print kwargs >>> func() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: func() takes at least 1 argument (0 given) >>> func("required argument") required argument >>> func("required argument", 1, 2, '3') required argument (1, 2, '3') >>> func("required argument", 1, 2, '3', keyword1=4, keyword2="foo") required argument (1, 2, '3') {'keyword2': 'foo', 'keyword1': 4} A: Here's one of my favorite places to use the ** syntax as in Dave Webb's final example: mynum = 1000 mystr = 'Hello World!' print("{mystr} New-style formatting is {mynum}x more fun!".format(**locals())) I'm not sure if it's terribly fast when compared to just using the names themselves, but it's a lot easier to type! A: One case where *args and **kwargs are useful is when writing wrapper functions (such as decorators) that need to be able accept arbitrary arguments to pass through to the function being wrapped. For example, a simple decorator that prints the arguments and return value of the function being wrapped: def mydecorator( f ): @functools.wraps( f ) def wrapper( *args, **kwargs ): print "Calling f", args, kwargs v = f( *args, **kwargs ) print "f returned", v return v return wrapper A: *args and **kwargs are special-magic features of Python. Think of a function that could have an unknown number of arguments. For example, for whatever reasons, you want to have function that sums an unknown number of numbers (and you don't want to use the built-in sum function). So you write this function: def sumFunction(*args): result = 0 for x in args: result += x return result and use it like: sumFunction(3,4,6,3,6,8,9). **kwargs has a diffrent function. With **kwargs you can give arbitrary keyword arguments to a function and you can access them as a dictonary. def someFunction(**kwargs): if 'text' in kwargs: print kwargs['text'] Calling someFunction(text="foo") will print foo. A: Just imagine you have a function but you don't want to restrict the number of parameter it takes. Example: >>> import operator >>> def multiply(*args): ... return reduce(operator.mul, args) Then you use this function like: >>> multiply(1,2,3) 6 or >>> numbers = [1,2,3] >>> multiply(*numbers) 6 A: The names *args and **kwargs or **kw are purely by convention. It makes it easier for us to read each other's code One place it is handy is when using the struct module struct.unpack() returns a tuple whereas struct.pack() uses a variable number of arguments. When manipulating data it is convenient to be able to pass a tuple to struck.pack() eg. tuple_of_data = struct.unpack(format_str, data) # ... manipulate the data new_data = struct.pack(format_str, *tuple_of_data) without this ability you would be forced to write new_data = struct.pack(format_str, tuple_of_data[0], tuple_of_data[1], tuple_of_data[2],...) which also means the if the format_str changes and the size of the tuple changes, I'll have to go back and edit that really long line A: Note that *args/**kwargs is part of function-calling syntax, and not really an operator. This has a particular side effect that I ran into, which is that you can't use *args expansion with the print statement, since print is not a function. This seems reasonable: def myprint(*args): print *args Unfortunately it doesn't compile (syntax error). This compiles: def myprint(*args): print args But prints the arguments as a tuple, which isn't what we want. This is the solution I settled on: def myprint(*args): for arg in args: print arg, print A: These parameters are typically used for proxy functions, so the proxy can pass any input parameter to the target function. def foo(bar=2, baz=5): print bar, baz def proxy(x, *args, **kwargs): # reqire parameter x and accept any number of additional arguments print x foo(*args, **kwargs) # applies the "non-x" parameter to foo proxy(23, 5, baz='foo') # calls foo with bar=5 and baz=foo proxy(6)# calls foo with its default arguments proxy(7, bar='asdas') # calls foo with bar='asdas' and leave baz default argument But since these parameters hide the actual parameter names, it is better to avoid them. A: You can have a look at python docs (docs.python.org in the FAQ), but more specifically for a good explanation the mysterious miss args and mister kwargs (courtesy of archive.org) (the original, dead link is here). In a nutshell, both are used when optional parameters to a function or method are used. As Dave says, *args is used when you don't know how many arguments may be passed, and **kwargs when you want to handle parameters specified by name and value as in: myfunction(myarg=1)
Use of *args and **kwargs
So I have difficulty with the concept of *args and **kwargs. So far I have learned that: *args = list of arguments - as positional arguments **kwargs = dictionary - whose keys become separate keyword arguments and the values become values of these arguments. I don't understand what programming task this would be helpful for. Maybe: I think to enter lists and dictionaries as arguments of a function AND at the same time as a wildcard, so I can pass ANY argument? Is there a simple example to explain how *args and **kwargs are used? Also the tutorial I found used just the "*" and a variable name. Are *args and **kwargs just placeholders or do you use exactly *args and **kwargs in the code?
[ "The syntax is the * and **. The names *args and **kwargs are only by convention but there's no hard requirement to use them.\nYou would use *args when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. For example:\n>>> ...
[ 1768, 506, 339, 74, 49, 44, 20, 18, 10, 8, 3 ]
[]
[]
[ "args", "keyword_argument", "python" ]
stackoverflow_0003394835_args_keyword_argument_python.txt
Q: Help with this typerror in a dictionary benfordd = dict() for attr in attrs: benfordd.setdefault(attr, []).extend([val*1e6 for val in x if not np.isnan(val)]) the above is just parts of my code, why is it that when I run this in ipython, I get this: TypeError: function not supported for these types, and can't coerce safely to supported types. does anyone know what values are needed for this? attr are strings. p.s., what does "val" stand for? A: I believe this error can occur when using Sage with numpy. The reason is that Sage preparses your input, so that e.g. 0.6**2 is translated to RealNumber('0.6') ** Integer(2). This allows it to handle real numbers with arbitrary precision. Unfortunately, numpy can't handle these, because it doesn't know what a RealNumber is. If you define RealNumber = float, the code should work; see the docs.
Help with this typerror in a dictionary
benfordd = dict() for attr in attrs: benfordd.setdefault(attr, []).extend([val*1e6 for val in x if not np.isnan(val)]) the above is just parts of my code, why is it that when I run this in ipython, I get this: TypeError: function not supported for these types, and can't coerce safely to supported types. does anyone know what values are needed for this? attr are strings. p.s., what does "val" stand for?
[ "I believe this error can occur when using Sage with numpy. The reason is that Sage preparses your input, so that e.g. 0.6**2 is translated to RealNumber('0.6') ** Integer(2). This allows it to handle real numbers with arbitrary precision. Unfortunately, numpy can't handle these, because it doesn't know what a Real...
[ 1 ]
[]
[]
[ "dictionary", "python", "typeerror" ]
stackoverflow_0004149076_dictionary_python_typeerror.txt
Q: Python-style pickling for C++? Does anyone know of a "language level" facility for pickling in C++? I don't want something like Boost serialization, or Google Protocol Buffers. Instead, something that could automatically serialize all the members of a class (with an option to exclude some members, either because they're not serializable, or else because I just don't care to save them for later). This could be accomplished with an extra action at parse time, that would generate code to handle the automatic serialization. Has anyone heard of anything like that? A: I don't believe there's any way to do this in a language with no run-time introspection capabilities. A: something that could automatically serialize all the members of a class This is not possible in C++. Python, C#, Java et al. use run-time introspection to achieve this. You can't do that in C++, RTTI is not powerful enough. In essence, there is nothing in the C++ language that would enable someone to discover the member variables of an object at run-time. Without that, you can't automatically serialize them. A: There's the standard C++ serialization with the << and >> operators, although you'll have to implement these for each of your classes (which it sounds like you don't want to do). Some practitioners say you should alway implement these operators, although of course, most of us rarely do. A: perhaps xml Data Binding? gsoap is just one of many options. You can automatically generate code for mapping between data structure and xml schema. Not sure that setting this up would be easier than other options you mention A: One quick way to do this that I got working once when I needed to save a struct to a file was to cast my struct to a char array and write it out to a file. Then when I wanted to load my struct back in, I would read the entire file (in binary mode), and cast the whole thing to my struct's type. Easy enough and exploits the fact that structs are stored as a contiguous block in memory. I wouldn't expect this to work with convoluted data structures or pointers, though, but food for thought.
Python-style pickling for C++?
Does anyone know of a "language level" facility for pickling in C++? I don't want something like Boost serialization, or Google Protocol Buffers. Instead, something that could automatically serialize all the members of a class (with an option to exclude some members, either because they're not serializable, or else because I just don't care to save them for later). This could be accomplished with an extra action at parse time, that would generate code to handle the automatic serialization. Has anyone heard of anything like that?
[ "I don't believe there's any way to do this in a language with no run-time introspection capabilities.\n", "\nsomething that could automatically\n serialize all the members of a class\n\nThis is not possible in C++. Python, C#, Java et al. use run-time introspection to achieve this. You can't do that in C++, RTT...
[ 4, 2, 1, 1, 0 ]
[]
[]
[ "boost", "c++", "pickle", "python", "serialization" ]
stackoverflow_0004149086_boost_c++_pickle_python_serialization.txt
Q: Dynamic images resizing I'm working on project where we are trying to adopt and resize template images to the various resolutions. For example if the website is viewed in 800px width (800x600) and 1024px width or larger the image size should be viewed in same quality. I've had in mind to use sprite with 3 types of images for each range of this template , but I'm looking for other ideas , php gd maybe ? Any python solution ? A: Well, for resizing it would of course be better to use GD... But indexed, I think. So that you have an upload script that automatically generates the images' in other sizes, and saves them somewhere. However, it matters whether you have more disk space, or performance... Performance would get worse IF you have many people viewing these images. Disk space would get worse IF you have A LOT of these images. A: Python Imaging Library will give you dynamic resizing, processing, etc. A: If you are resizing to a known set of resolutions, you can just resize your images once and store them. If you need to resize for any possible resolution, you will need a library to do that for you. In PHP, GD or ImageMagik are both good. If you do this, you may want to add caching for the most common resolutions. This will take up more disc space, but will save you the cost of recalculating all the images every time. Note that it can be difficult to detect the true resolution though. If the browser window is resized, the resolution you think the screen is may not be the actual resolution the user can see. The same can happen if they have toolbars or sidebars opened. A: Why not resize the image on the client using JavaScript? <head> <script> function resize() { ww = window.innerWidth wh = window.innerHeight photo = document.getElementById("photo") // You probably wouldn't actually make the image fill the window, you'd pick // some appropriate size. photo.setAttribute("width", ww) photo.setAttribute("height", wh) } </head> <body onload="resize()" onresize="resize()"> <img id="photo" src="photo.jpg"> A: Getting the inner window width is quite hard, as different browsers use different variables. However, this is what I use on my website. It gets the inner window width rather reliably, and then sets the image width/height. It shouldn't be too hard to modify this code to set the src of the image desired. function set_image_sizes(){ if (window.innerHeight != undefined) { height = window.innerHeight; width = window.innerWidth; } else if (document.documentElement.clientHeight > 0) { height = document.documentElement.clientHeight; width = document.documentElement.clientWidth; } else { height = document.body.clientHeight; width = document.body.clientWidth; } $('#image').css('height', height); $('#image').css('width', width); }
Dynamic images resizing
I'm working on project where we are trying to adopt and resize template images to the various resolutions. For example if the website is viewed in 800px width (800x600) and 1024px width or larger the image size should be viewed in same quality. I've had in mind to use sprite with 3 types of images for each range of this template , but I'm looking for other ideas , php gd maybe ? Any python solution ?
[ "Well, for resizing it would of course be better to use GD... But indexed, I think. So that you have an upload script that automatically generates the images' in other sizes, and saves them somewhere.\nHowever, it matters whether you have more disk space, or performance... Performance would get worse IF you have ma...
[ 4, 2, 2, 1, 1 ]
[]
[]
[ "javascript", "jquery", "php", "python" ]
stackoverflow_0004149112_javascript_jquery_php_python.txt
Q: How can I access any element in a web page with Python? I would like to access any element in a web page. I know how to do that when I have a form (form = cgi.FieldStorage()), but not when I have, for example, a table. How can I do that? Thanks A: If you are familiar with javascript, you should be familiar with the DOM. This should help you to get the information you want, seeing how this parses HTML, among other things. Then it's up to you to extract the information you need A: HTML parsing using either HTMLParser or Beautiful Soup if you're trying to get data from a web page. You can't really write data to an HTML table like you could do with CGI and forms, so I'm hoping this is what you want. I personally recommend Beautiful Soup if you want intelligent parsing behavior. A: The way to access a table is to parse the HTML. This is different from accessing form data, in that it's not dynamic. Since you mentioned CGI, I'm assuming you're working on the server side of things and that you have the ability to serve whatever content you want. So you could use whatever data you're representing in the table in its raw form before turning it into HTML too. A: You can access only data, posted by form (or as GET parameters). So, you can extract data you need using JavaScript and post it through form
How can I access any element in a web page with Python?
I would like to access any element in a web page. I know how to do that when I have a form (form = cgi.FieldStorage()), but not when I have, for example, a table. How can I do that? Thanks
[ "If you are familiar with javascript, you should be familiar with the DOM. This should help you to get the information you want, seeing how this parses HTML, among other things. Then it's up to you to extract the information you need\n", "HTML parsing using either HTMLParser or Beautiful Soup if you're trying to ...
[ 1, 0, 0, 0 ]
[]
[]
[ "cgi", "html_parsing", "python" ]
stackoverflow_0004149598_cgi_html_parsing_python.txt
Q: replace some part of a word with regex how do you delete text inside <ref> *some text*</ref> together with ref itself? in '...and so on<ref>Oxford University Press</ref>.' re.sub(r'<ref>.+</ref>', '', string) only removes <ref> if <ref> is followed by a whitespace EDIT: it has smth to do with word boundaries I guess...or? EDIT2 What I need is that it will math the last (closing) </ref> even if it is on a newline. A: I don't really see you problem, because the code pasted will remove the <ref>...</ref> part of the string. But if what you mean is that and empty ref tag is not removed: re.sub(r'<ref>.+</ref>', '', '...and so on<ref></ref>.') Then what you need to do is change the .+ with .* A + means one or more, while * means zero or more. From http://docs.python.org/library/re.html: '.' (Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline. '*' Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s. '+' Causes the resulting RE to match 1 or more repetitions of the preceding RE. ab+ will match ‘a’ followed by any non-zero number of ‘b’s; it will not match just ‘a’. '?' Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either ‘a’ or ‘ab’. A: You might want to be cautious not to remove a whole lot of text just because there are more than one closing </ref>s. Below regex would be more accurate in my opinion: r'<ref>[^<]*</ref>' This would prevent the 'greedy' matching. BTW: There is a great tool called The Regex Coach to analyze and test your regexes. You can find it at: http://www.weitz.de/regex-coach/ edit: forgot to add code tag in the first paragraph. A: You could make a fancy regex to do just what you intend, but you need to use DOTALL and non-greedy search, and you need to understand how regexes work in general, which you don't. Your best option is to use string methods rather than regexes, which is more pythonic anyway: while '<reg>' in string: begin, end = string.split('<reg>', 1) trash, end = end.split('</reg>', 1) string = begin + end If you want to be very generic, allowing strange capitalization of the tags or whitespaces and properties in the tags, you shouldn't do this either, but invest in learning a html/xml parsing library. lxml currently seems to be widely recommended and well-supported. A: If you try to do this with regular expressions you're in for a world of trouble. You're effectively trying to parse something but your parser isn't up to the task. Matching greedily across strings probably eats up too much, as in this example: <ref>SDD</ref>...<ref>XX</ref> You'd end up cleraning up the entire middle. You really want a parser, something like Beautiful Soup. from BeautifulSoup import BeautifulSoup, Tag s = "<a>sfsdf</a> <ref>XX</ref> || <ref>YY</ref>" soup = BeautifulSoup(s) x = soup.findAll("ref") for z in x: soup.ref.replaceWith('!') soup # <a>sfsdf</a> ! || !
replace some part of a word with regex
how do you delete text inside <ref> *some text*</ref> together with ref itself? in '...and so on<ref>Oxford University Press</ref>.' re.sub(r'<ref>.+</ref>', '', string) only removes <ref> if <ref> is followed by a whitespace EDIT: it has smth to do with word boundaries I guess...or? EDIT2 What I need is that it will math the last (closing) </ref> even if it is on a newline.
[ "I don't really see you problem, because the code pasted will remove the <ref>...</ref> part of the string. But if what you mean is that and empty ref tag is not removed:\nre.sub(r'<ref>.+</ref>', '', '...and so on<ref></ref>.')\n\nThen what you need to do is change the .+ with .*\nA + means one or more, while * me...
[ 3, 1, 1, 0 ]
[]
[]
[ "python", "ref", "replace" ]
stackoverflow_0004149517_python_ref_replace.txt
Q: One last step! (python tuning) I have this code: emailRows = [] for rowTuple in listOfRows: #row loop emailLine = [] for tup in rowTuple: #field loop emailLine.append(str(tup).center(20)) emailRows.append('\t'.join([field.strip().center(20) for field in emailLine])) rows = '\n'.join(emailRows) emailBody = emailBody + rows which i've so far changed to this code: emailRows = [] for rowTuple in listOfRows: #row loop emailRows.append('\t'.join([field.strip().center(20) for field in [str(tup).center(20) for tup in rowTuple]])) rows = '\n'.join(emailRows) emailBody = emailBody + rows I'm not sure but it seems like I can get rid of the last for loop somehow. I need some help doing this, though. A: '\n'.join(('\t'.join([field.strip().center(20) for field in [str(tup).center(20) for tup in rowTuple]])) for rowTuple in listOfRows) Wow, that's obfuscated. I hope cProfile says this guy is a heavy hitter. A: I'm not convinced the result is worth the effort, but if you're going to go down the route of eliminating all your for loops in favour of comprehensions, you should note that you can use generator expressions instead of list comprehensions to avoid creating (and then throwing away) intermediate lists. A: You can use map() instead for x in seq: rows='\n'.join(map(lambda row: '\t'.join(map(lambda cell: str(cell).center(20), row)), listOfRows)) Also you can try reduce() instead join(): def cell_format(cell): return str(cell).center(20) def row_format(res, cell): return res+'\t'+cell def rows_format(res, row): return res+'\n'+row rows=reduce(rows_format, map(lambda row: reduce(row_format, map(cell_format, row)), listOfRows)) But you first example looks much more pretty))
One last step! (python tuning)
I have this code: emailRows = [] for rowTuple in listOfRows: #row loop emailLine = [] for tup in rowTuple: #field loop emailLine.append(str(tup).center(20)) emailRows.append('\t'.join([field.strip().center(20) for field in emailLine])) rows = '\n'.join(emailRows) emailBody = emailBody + rows which i've so far changed to this code: emailRows = [] for rowTuple in listOfRows: #row loop emailRows.append('\t'.join([field.strip().center(20) for field in [str(tup).center(20) for tup in rowTuple]])) rows = '\n'.join(emailRows) emailBody = emailBody + rows I'm not sure but it seems like I can get rid of the last for loop somehow. I need some help doing this, though.
[ "'\\n'.join(('\\t'.join([field.strip().center(20) for\n field in [str(tup).center(20) for\n tup in rowTuple]])) for rowTuple in listOfRows)\n\nWow, that's obfuscated. I hope cProfile says this guy is a heavy hitter.\n", "I'm not convinced the result is worth the effort, but if you're going to go down th...
[ 1, 1, 1 ]
[]
[]
[ "functional_programming", "join", "python" ]
stackoverflow_0004149496_functional_programming_join_python.txt
Q: Django validate form based on multiple fields (file fields) Is there a way in django to validate a form based on multiple fields. I have seen some examples where people recommend overriding a form's clean method and raising a ValidationError if it fails to meet your custom validation. The problem for me is that I'm not sure you can check whether or not a file was uploaded from within the clean method. I have only been able to access them using the request objects and you do not have access to the request object within the form's clean method. A: The method you've described (raising ValidationError from within Form.clean) is the official way to do multi-field validation. You can access uploaded files from self.files within the clean method. From django/forms/forms.py: class BaseForm(StrAndUnicode): # This is the main implementation of all the Form logic. Note that this # class is different than Form. See the comments by the Form class for more # information. Any improvements to the form API should be made to *this* # class, not to the Form class. def __init__(self, data=None, files=None, ...): self.is_bound = data is not None or files is not None self.data = data or {} self.files = files or {} ...
Django validate form based on multiple fields (file fields)
Is there a way in django to validate a form based on multiple fields. I have seen some examples where people recommend overriding a form's clean method and raising a ValidationError if it fails to meet your custom validation. The problem for me is that I'm not sure you can check whether or not a file was uploaded from within the clean method. I have only been able to access them using the request objects and you do not have access to the request object within the form's clean method.
[ "The method you've described (raising ValidationError from within Form.clean) is the official way to do multi-field validation.\nYou can access uploaded files from self.files within the clean method. From django/forms/forms.py:\nclass BaseForm(StrAndUnicode):\n # This is the main implementation of all the Form ...
[ 3 ]
[]
[]
[ "django", "model_view_controller", "python" ]
stackoverflow_0004149908_django_model_view_controller_python.txt
Q: How to use pythons map with a non-iterable and iterable set of parameters? To make a simple example, I don't care about the practicality, just the implemenation. Say I create some class with a few methods. I want to create a list containing whether or not they're callable. So I can take this example from: Finding what methods an object has [method for method in dir(object) if callable(getattr(object, method))] It's great for what it does, but if for the heck of it, I want to use map and I have object, which is a non-iterable item... map(callable,map(getattr,object,dir(object))) To focus on the real problem: I have an iterable list, and a non iterable item. What is the best solution that lets me use some non-iterable item and an iterable item, so that I can utilize map? A: I will admit to not understanding why, since the LC works, but: map(lambda x: callable(getattr(object, x)), dir(object)) A: If you're not clear on what the lambda above does, equivalently you could define: def myMap(fun1,obj,iterlist): def fun2(x): return fun1(obj,x) return map(fun2,iterlist) And then, call map(callable,myMap(getattr,object,dir(object))) for example: map(callable,myMap(getattr,myMap,dir(myMap))) Though using lambda is more pythonic. A: Sometime LC is just the right way to do it >>> from itertools import izip, repeat, starmap >>> map(callable, starmap(getattr, zip(repeat(object), dir(object)))) This also works, but requires dir(object) twice >>> map(callable, map(getattr, repeat(object, len(dir(object))), dir(object))) and finally >>> from itertools import izip_longest >>> map(callable, starmap(getattr, izip_longest([], dir(object), fillvalue=object)))
How to use pythons map with a non-iterable and iterable set of parameters?
To make a simple example, I don't care about the practicality, just the implemenation. Say I create some class with a few methods. I want to create a list containing whether or not they're callable. So I can take this example from: Finding what methods an object has [method for method in dir(object) if callable(getattr(object, method))] It's great for what it does, but if for the heck of it, I want to use map and I have object, which is a non-iterable item... map(callable,map(getattr,object,dir(object))) To focus on the real problem: I have an iterable list, and a non iterable item. What is the best solution that lets me use some non-iterable item and an iterable item, so that I can utilize map?
[ "I will admit to not understanding why, since the LC works, but:\nmap(lambda x: callable(getattr(object, x)), dir(object))\n\n", "If you're not clear on what the lambda above does, equivalently you could define:\ndef myMap(fun1,obj,iterlist):\n def fun2(x):\n return fun1(obj,x)\n return m...
[ 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004149783_python.txt
Q: Logging hierarchy vs. root logger? Somewhere in the bowels of my code I have something like: logger = logging.getLogger('debug0.x') The way I understand it, this should only respond when I have previously done something like: logging.basicConfig(filename='10Nov2010a.txt',level=logging.DEBUG, name='debug0') note that name has been defined as debug0. However, I have discovered that if do logging.basicConfig(filename='10Nov2010a.txt',level=logging.DEBUG) without the name keyword, then the debug0.x logger defined above reacts, and writes to the log file. I was thinking it would only react in the first case, when the logger had been named. I'm confused. A: The Python logging module organizes loggers in a hierarchy. All loggers are descendants of the root logger. Each logger passes log messages on to its parent. New loggers are created with the getLogger() function. The function call logging.getLogger('debug0.x') creates a logger x which is a child of debug0 which itself is a child of the root logger. When logging to this logger, it will pass on the message to its parent, and its parent will pass the message to the root logger. You configured the root logger to log to a file by the basicConfig() function, so your message will end up there. A: If you check out the code or the doc: >>> print logging.basicConfig.__doc__ Do basic configuration for the logging system. This function does nothing if the root logger already has handlers configured. ............... A number of optional keyword arguments may be specified, which can alter the default behaviour. filename Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler. filemode Specifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to 'a'). format Use the specified format string for the handler. datefmt Use the specified date/time format. level Set the root logger level to the specified level. stream Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with 'filename' - if both are present, 'stream' is ignored. logging.basicConfig does not use name argument at all. It initializes the root logger. While getLogger takes a "name" argument >>> print logging.getLogger.__doc__ Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger.
Logging hierarchy vs. root logger?
Somewhere in the bowels of my code I have something like: logger = logging.getLogger('debug0.x') The way I understand it, this should only respond when I have previously done something like: logging.basicConfig(filename='10Nov2010a.txt',level=logging.DEBUG, name='debug0') note that name has been defined as debug0. However, I have discovered that if do logging.basicConfig(filename='10Nov2010a.txt',level=logging.DEBUG) without the name keyword, then the debug0.x logger defined above reacts, and writes to the log file. I was thinking it would only react in the first case, when the logger had been named. I'm confused.
[ "The Python logging module organizes loggers in a hierarchy. All loggers are descendants of the root logger. Each logger passes log messages on to its parent.\nNew loggers are created with the getLogger() function. The function call logging.getLogger('debug0.x') creates a logger x which is a child of debug0 whic...
[ 119, 17 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0004150148_logging_python.txt
Q: How to get self into a Python method without explicitly accepting it I'm developing a documentation testing framework -- basically unit tests for PDFs. Tests are (decorated) methods of instances of classes defined by the framework, and these are located and instantiated at runtime and the methods are invoked to execute the tests. My goal is to cut down on the amount of quirky Python syntax that the people who will write tests need to be concerned about, as these people may or may not be Python programmers, or even very much programmers at all. So I would like them to be able to write "def foo():" instead of "def foo(self):" for methods, but still be able to use "self" to access members. In an ordinary program I would consider this a horrible idea, but in a domain-specific-languagey kind of program like this one, it seems worth a try. I have successfully eliminated the self from the method signature by using a decorator (actually, since I am using a decorator already for the test cases, I would just roll it into that), but "self" does not then refer to anything in the test case method. I have considered using a global for self, and even come up with an implementation that more or less works, but I'd rather pollute the smallest namespace possible, which is why I would prefer to inject the variable directly into the test case method's local namespace. Any thoughts? A: My accepted answer to this question was pretty dumb but I was just starting out. Here's a much better way. This is only scantily tested but it's good for a demonstration of the proper way to do this thing which is improper to do. It works on 2.6.5 for sure. I haven't tested any other versions but no opcodes are hardcoded into it so it should be about as portable as most other 2.x code. add_self can be applied as a decorator but that would defeat the purpose (why not just type 'self'?) It would be easy to adapt the metaclass from my other answer to apply this function instead. import opcode import types def instructions(code): """Iterates over a code string yielding integer [op, arg] pairs If the opcode does not take an argument, just put None in the second part """ code = map(ord, code) i, L = 0, len(code) extended_arg = 0 while i < L: op = code[i] i+= 1 if op < opcode.HAVE_ARGUMENT: yield [op, None] continue oparg = code[i] + (code[i+1] << 8) + extended_arg extended_arg = 0 i += 2 if op == opcode.EXTENDED_ARG: extended_arg = oparg << 16 continue yield [op, oparg] def write_instruction(inst): """Takes an integer [op, arg] pair and returns a list of character bytecodes""" op, oparg = inst if oparg is None: return [chr(op)] elif oparg <= 65536L: return [chr(op), chr(oparg & 255), chr((oparg >> 8) & 255)] elif oparg <= 4294967296L: # The argument is large enough to need 4 bytes and the EXTENDED_ARG opcode return [chr(opcode.EXTENDED_ARG), chr((oparg >> 16) & 255), chr((oparg >> 24) & 255), chr(op), chr(oparg & 255), chr((oparg >> 8) & 255)] else: raise ValueError("Invalid oparg: {0} is too large".format(oparg)) def add_self(f): """Add self to a method Creates a new function by prepending the name 'self' to co_varnames, and incrementing co_argcount and co_nlocals. Increase the index of all other locals by 1 to compensate. Also removes 'self' from co_names and decrease the index of all names that occur after it by 1. Finally, replace all occurrences of `LOAD_GLOBAL i,j` that make reference to the old 'self' with 'LOAD_FAST 0,0'. Essentially, just create a code object that is exactly the same but has one more argument. """ code_obj = f.func_code try: self_index = code_obj.co_names.index('self') except ValueError: raise NotImplementedError("self is not a global") # The arguments are just the first co_argcount co_varnames varnames = ('self', ) + code_obj.co_varnames names = tuple(name for name in code_obj.co_names if name != 'self') code = [] for inst in instructions(code_obj.co_code): op = inst[0] if op in opcode.haslocal: # The index is now one greater because we added 'self' at the head of # the tuple inst[1] += 1 elif op in opcode.hasname: arg = inst[1] if arg == self_index: # This refers to the old global 'self' if op == opcode.opmap['LOAD_GLOBAL']: inst[0] = opcode.opmap['LOAD_FAST'] inst[1] = 0 else: # If `self` is used as an attribute, real global, module # name, module attribute, or gets looked at funny, bail out. raise NotImplementedError("Abnormal use of self") elif arg > self_index: # This rewrites the index to account for the old global 'self' # having been removed. inst[1] -= 1 code += write_instruction(inst) code = ''.join(code) # type help(types.CodeType) at the interpreter prompt for this one new_code_obj = types.CodeType(code_obj.co_argcount + 1, code_obj.co_nlocals + 1, code_obj.co_stacksize, code_obj.co_flags, code, code_obj.co_consts, names, varnames, '<OpcodeCity>', code_obj.co_name, code_obj.co_firstlineno, code_obj.co_lnotab, code_obj.co_freevars, code_obj.co_cellvars) # help(types.FunctionType) return types.FunctionType(new_code_obj, f.func_globals) class Test(object): msg = 'Foo' @add_self def show(msg): print self.msg + msg t = Test() t.show('Bar') A: little upgrade for aaronasterling's solution( i haven't enough reputation to comment it ): def wrap(f): @functools.wraps(f) def wrapper(self,*arg,**kw): f.func_globals['self'] = self return f(*arg,**kw) return wrapper but both this solutions will work unpredictable if f function will be called recursively for different instance, so you have to clone it like this: import types class wrap(object): def __init__(self,func): self.func = func def __get__(self,obj,type): new_globals = self.func.func_globals.copy() new_globals['self'] = obj return types.FunctionType(self.func.func_code,new_globals) class C(object): def __init__(self,word): self.greeting = word @wrap def greet(name): print(self.greeting+' , ' + name+ '!') C('Hello').greet('kindall') A: Here's a one line method decorator that seems to do the job without modifying any Special attributes of Callable types* marked Read-only: # method decorator -- makes undeclared 'self' argument available to method injectself = lambda f: lambda self: eval(f.func_code, dict(self=self)) class TestClass: def __init__(self, thing): self.attr = thing @injectself def method(): print 'in TestClass::method(): self.attr = %r' % self.attr return 42 test = TestClass("attribute's value") ret = test.method() print 'return value:', ret # output: # in TestClass::method(): self.attr = "attribute's value" # return value: 42 Note that unless you take precautions to prevent it, a side-effect of the eval() function may be it adding a few entries -- such as a reference to the __builtin__ module under the key __builtins__ -- automatically to the dict passed to it. @kendall: Per your comment about how you're using this with methods being in container classes (but ignoring the injection of additional variables for the moment) -- is the following something like what you're doing? It's difficult for me to understand how things are split up between the framework and what the users write. It sounds like an interesting design pattern to me. # method decorator -- makes undeclared 'self' argument available to method injectself = lambda f: lambda self: eval(f.func_code, dict(self=self)) class methodclass: def __call__(): print 'in methodclass::__call__(): self.attr = %r' % self.attr return 42 class TestClass: def __init__(self, thing): self.attr = thing method = injectself(methodclass.__call__) test = TestClass("attribute's value") ret = test.method() print 'return value:', ret # output # in methodclass::__call__(): self.attr = "attribute's value" # return value: 42 A: The trick is to add 'self' to f.func_globals. This works in python2.6. I really should get around to installing other versions to test stuff like this on. Sorry for the wall of code but I cover two cases: doing it with a metaclass and doing it with a decorator. For your usecase, I think the metaclass is better since the whole point of this exercise is to shield users from syntax. import new, functools class TestMeta(type): def __new__(meta, classname, bases, classdict): for item in classdict: if hasattr(classdict[item], '__call__'): classdict[item] = wrap(classdict[item]) return type.__new__(meta, classname, bases, classdict) def wrap(f): @functools.wraps(f) def wrapper(self): f.func_globals['self'] = self return f() return wrapper def testdec(f): @functools.wraps(f) def wrapper(): return f() return wrapper class Test(object): __metaclass__ = TestMeta message = 'You can do anything in python' def test(): print self.message @testdec def test2(): print self.message + ' but the wrapper funcion can\'t take a self argument either or you get a TypeError' class Test2(object): message = 'It also works as a decorator but (to me at least) feels better as a metaclass' @wrap def test(): print self.message t = Test() t2 = Test2() t.test() t.test2() t2.test() A: This might be a use case for decorators - you give them a small set of lego bricks to build functions with, and the complicated framework stuff is piped in via @testcase or somesuch. Edit: You didn't post any code, so this is going to be sketchy, but they don't need to write methods. They can write ordinary functions without "self", and you could use decorators like in this example from the article I linked: class myDecorator(object): def __init__(self, f): print "inside myDecorator.__init__()" f() # Prove that function definition has completed def __call__(self): print "inside myDecorator.__call__()" @myDecorator def aFunction(): print "inside aFunction()"
How to get self into a Python method without explicitly accepting it
I'm developing a documentation testing framework -- basically unit tests for PDFs. Tests are (decorated) methods of instances of classes defined by the framework, and these are located and instantiated at runtime and the methods are invoked to execute the tests. My goal is to cut down on the amount of quirky Python syntax that the people who will write tests need to be concerned about, as these people may or may not be Python programmers, or even very much programmers at all. So I would like them to be able to write "def foo():" instead of "def foo(self):" for methods, but still be able to use "self" to access members. In an ordinary program I would consider this a horrible idea, but in a domain-specific-languagey kind of program like this one, it seems worth a try. I have successfully eliminated the self from the method signature by using a decorator (actually, since I am using a decorator already for the test cases, I would just roll it into that), but "self" does not then refer to anything in the test case method. I have considered using a global for self, and even come up with an implementation that more or less works, but I'd rather pollute the smallest namespace possible, which is why I would prefer to inject the variable directly into the test case method's local namespace. Any thoughts?
[ "My accepted answer to this question was pretty dumb but I was just starting out. Here's a much better way. This is only scantily tested but it's good for a demonstration of the proper way to do this thing which is improper to do. It works on 2.6.5 for sure. I haven't tested any other versions but no opcodes are h...
[ 6, 5, 4, 3, 2 ]
[]
[]
[ "local", "python", "self", "variables" ]
stackoverflow_0003453976_local_python_self_variables.txt
Q: multi lines python indentation on emacs Im an emacs newbie, I want emacs to be able to indent my code like this egg = spam.foooooo('vivivivivivivivivi')\ .foooooo('emacs', 'emacs', 'emacs', 'emacs') It's not possible to do this automatically by default (without manually inserting spaces or C-c >), since emacs always indents 4 spaces (unless Im splitting multiple arguments over multiple lines). Whats the best approach to do this? PS: If this is a bad idea (against PEP 8 or something) please do tell me A: I agree with Aaron about the desirability of your stylistic choice, but since I also agree with him that Emacs Lisp is fun, I'll describe how you might go about implementing this. Emacs python-mode computes the indentation of a line in the function python-calculate-indentation and the relevant section for handling continuation lines is buried deep inside the function, with no easy way to configure it. So we have two options: Replace the whole of python-calculate-indentation with our own version (a maintenance nightmare whenever python-mode changes); or "Advise" the function python-calculate-indentation: that is, wrap it in our own function that handles the case we're interested in, and otherwise defers to the original. Option (2) seems just about doable in this case. So let's go for it! The first thing to do is to read the manual on advice which suggests that our advice should look like this: (defadvice python-calculate-indentation (around continuation-with-dot) "Handle continuation lines that start with a dot and try to line them up with a dot in the line they continue from." (unless (this-line-is-a-dotted-continuation-line) ; (TODO) ad-do-it)) Here ad-do-it is a magic token that defadvice substitutes with the original function. Coming from a Python background you might well ask, "why not do this decorator-style?" The Emacs advice mechanism is designed (1) to keep advice well separated from the original; and (2) to have multiple pieces of advice for a single function that don't need to co-operate; (3) to allow you individual control over which pieces of advice are turned on and off. You could certainly imagine writing something similar in Python. Here's how to tell if the current line is a dotted continuation line: (beginning-of-line) (when (and (python-continuation-line-p) (looking-at "\\s-*\\.")) ;; Yup, it's a dotted continuation line. (TODO) ...) There's one problem with this: that call to beginning-of-line actually moves point to the beginning of the line. Oops. We don't want to move point around when merely calculating indention. So we better wrap this up in a call to save-excursion to make sure that point doesn't go a-wandering. We can find the dot that we need to line up with by skipping backwards over tokens or parenthesized expressions (what Lisp calls "S-expressions" or "sexps") until either we find the dot, or else we get to the start of the statement. A good Emacs idiom for doing a search in a restricted part of the buffer is to narrow the buffer to contain just the part we want: (narrow-to-region (point) (save-excursion (end-of-line -1) (python-beginning-of-statement) (point))) and then keep skipping sexps backwards until we find the dot, or until backward-sexp stops making progress: (let ((p -1)) (while (/= p (point)) (setq p (point)) (when (looking-back "\\.") ;; Found the dot to line up with. (setq ad-return-value (1- (current-column))) ;; Stop searching backward and report success (TODO) ...) (backward-sexp))) Here ad-return-value is a magic variable that defadvice uses for the return value from the advised function. Ugly but practical. Now there are two problems with this. The first is that backward-sexp can signal an error in certain circumstances, so we better catch that error: (ignore-errors (backward-sexp)) The other problem is that of breaking out of the loop and also indicating success. We can do both at once by declaring a named block and then calling return-from. Blocks and exits are Common Lisp features so we'll need to (require 'cl) Let's put it all together: (require 'cl) (defadvice python-calculate-indentation (around continuation-with-dot) "Handle continuation lines that start with a dot and try to line them up with a dot in the line they continue from." (unless (block 'found-dot (save-excursion (beginning-of-line) (when (and (python-continuation-line-p) (looking-at "\\s-*\\.")) (save-restriction ;; Handle dotted continuation line. (narrow-to-region (point) (save-excursion (end-of-line -1) (python-beginning-of-statement) (point))) ;; Move backwards until we find a dot or can't move backwards ;; any more (e.g. because we hit a containing bracket) (let ((p -1)) (while (/= p (point)) (setq p (point)) (when (looking-back "\\.") (setq ad-return-value (1- (current-column))) (return-from 'found-dot t)) (ignore-errors (backward-sexp)))))))) ;; Use original indentation. ad-do-it)) (ad-activate 'python-calculate-indentation) I won't claim that this is the best way to do this, but it illustrates a bunch of moderately tricky Emacs and Lisp features: advice, excursions, narrowing, moving over sexps, error handling, blocks and exits. Enjoy! A: That's pretty ugly and would require you to write some emacs lisp. I need to learn emacs lisp so if it wasn't so ugly, I would probably be up for doing it. But it is and I'm not. Looks like you get to learn emacs lisp :) (if you actually want to do this). I'm sort of jealous. At any rate, you said that informing you that this is a bad idea was an acceptable answer so here goes: That's a terrible stylistic choice. Isn't egg = spam.foo('viviviv') egg = egg.foo('emacs', 'emacs', 'emacs') easier to read? While not specifically against PEP 8, it is mentioned that use of the line continuation character should be kept to a minimum. Also, this most definitively and objectively goes against the spirit of PEP 8. I'm just not sure how ;)
multi lines python indentation on emacs
Im an emacs newbie, I want emacs to be able to indent my code like this egg = spam.foooooo('vivivivivivivivivi')\ .foooooo('emacs', 'emacs', 'emacs', 'emacs') It's not possible to do this automatically by default (without manually inserting spaces or C-c >), since emacs always indents 4 spaces (unless Im splitting multiple arguments over multiple lines). Whats the best approach to do this? PS: If this is a bad idea (against PEP 8 or something) please do tell me
[ "I agree with Aaron about the desirability of your stylistic choice, but since I also agree with him that Emacs Lisp is fun, I'll describe how you might go about implementing this.\nEmacs python-mode computes the indentation of a line in the function python-calculate-indentation and the relevant section for handlin...
[ 25, 3 ]
[]
[]
[ "elisp", "emacs", "indentation", "python" ]
stackoverflow_0004057988_elisp_emacs_indentation_python.txt
Q: Python: Nesting counters For my customers, iterating through multiple counters is turning into a recurring task. The most straightforward way would be something like this: cntr1 = range(0,2) cntr2 = range(0,5) cntr3 = range(0,7) for li in cntr1: for lj in cntr2: for lk in cntr3: print li, lj, lk The number of counters can be anywhere from 3 on up and those nested for loops start taking up real estate. Is there a Pythonic way to do something like this? for li, lj, lk in mysteryfunc(cntr1, cntr2, cntr3): print li, lj, lk I keep thinking that something in itertools would fit this bill, but I'm just not familiar enough with itertools to make sense of the options. Is there already a solution such as itertools, or do I need to roll my own? Thanks, j A: What you want is itertools.product for li, lj, lk in itertools.product(cntr1, cntr2, cntr3): print li, lj, lk Will do exactly what you are requesting. The name derives from the concept of a Cartesian product.
Python: Nesting counters
For my customers, iterating through multiple counters is turning into a recurring task. The most straightforward way would be something like this: cntr1 = range(0,2) cntr2 = range(0,5) cntr3 = range(0,7) for li in cntr1: for lj in cntr2: for lk in cntr3: print li, lj, lk The number of counters can be anywhere from 3 on up and those nested for loops start taking up real estate. Is there a Pythonic way to do something like this? for li, lj, lk in mysteryfunc(cntr1, cntr2, cntr3): print li, lj, lk I keep thinking that something in itertools would fit this bill, but I'm just not familiar enough with itertools to make sense of the options. Is there already a solution such as itertools, or do I need to roll my own? Thanks, j
[ "What you want is itertools.product\nfor li, lj, lk in itertools.product(cntr1, cntr2, cntr3):\n print li, lj, lk\n\nWill do exactly what you are requesting. The name derives from the concept of a Cartesian product. \n" ]
[ 7 ]
[]
[]
[ "iteration", "python" ]
stackoverflow_0004150467_iteration_python.txt
Q: Determine Index of Highest Value in Python's NumPy I want to generate an array with the index of the highest max value of each row. a = np.array([ [1,2,3], [6,5,4], [0,1,0] ]) maxIndexArray = getMaxIndexOnEachRow(a) print maxIndexArray [[2], [0], [1]] There's a np.argmax function but it doesn't appear to do what I want... A: The argmax() function does do what you want: print a.argmax(axis=1) array([2, 0, 1])
Determine Index of Highest Value in Python's NumPy
I want to generate an array with the index of the highest max value of each row. a = np.array([ [1,2,3], [6,5,4], [0,1,0] ]) maxIndexArray = getMaxIndexOnEachRow(a) print maxIndexArray [[2], [0], [1]] There's a np.argmax function but it doesn't appear to do what I want...
[ "The argmax() function does do what you want:\nprint a.argmax(axis=1)\narray([2, 0, 1])\n\n" ]
[ 20 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0004150542_numpy_python.txt
Q: cherrypy and relative path in WSGI app running cherrypy with mod_wsgi on apache along with another php app. The cherrypy app is NOT mounted on root, but rather on something like 'localhost/apps/myapp' via WSGIScriptAlias in the apache config file. In testapp.py, I have tried the following, and when I try to access localhost/apps/myapp in a browser: app = cherrypy.tree.mount(MyApp(), '', 'settings.config') #FAILS WITH 404 and app = cherrypy.tree.mount(MyApp(), '/apps/myapp', 'settings.config') # WORKS The first case fails because cherrypy expects to be at the server root, instead of relative to where it is mounted via WSGI in apache. Is there a preferred way to make cherrypy apps work relative to the path they are mounted in apache under WSGIScriptAlias? Basically, I'll be running several cherrypy apps under several different paths, and would prefer if apache handled the dispatching (i.e. cherrypy just runs the app and doesn't worry about the relative path). This way i can avoid updating several different python files/config files everytime some of the relative paths on the server change. Any suggestions? btw, the cherrypy app is currently passed to the wsgi application as follows: app = cherrypy.tree.mount(HelloWorld(), '', 'settings.config') return app(environ, start_response) A: I am doing this, although this would require cherrypy to know the relative path: class Dir: pass root = Dir() root.apps = Dir() root.apps.myapp = MyApp() cherrypy.tree.mount(root) This allows me to structure the application in any way I need. I'm using nginx and not Apache, but I don't think it'll make any difference. Although it gets a bit wordy if you're using long paths with not much else in between. cherrypy can support other dispatchers which might be better suited to what you're trying to do, or perhaps you need to write a custom one. A: how should this app = cherrypy.tree.mount(MyApp(), '', 'settings.config') resolve http://localhost/apps/myapp ? have u tried http://localhost/ or http://localhost/MyApp. it is also important where u have defined your WSGIScriptAlias in Apache. vhost, location?
cherrypy and relative path in WSGI app
running cherrypy with mod_wsgi on apache along with another php app. The cherrypy app is NOT mounted on root, but rather on something like 'localhost/apps/myapp' via WSGIScriptAlias in the apache config file. In testapp.py, I have tried the following, and when I try to access localhost/apps/myapp in a browser: app = cherrypy.tree.mount(MyApp(), '', 'settings.config') #FAILS WITH 404 and app = cherrypy.tree.mount(MyApp(), '/apps/myapp', 'settings.config') # WORKS The first case fails because cherrypy expects to be at the server root, instead of relative to where it is mounted via WSGI in apache. Is there a preferred way to make cherrypy apps work relative to the path they are mounted in apache under WSGIScriptAlias? Basically, I'll be running several cherrypy apps under several different paths, and would prefer if apache handled the dispatching (i.e. cherrypy just runs the app and doesn't worry about the relative path). This way i can avoid updating several different python files/config files everytime some of the relative paths on the server change. Any suggestions? btw, the cherrypy app is currently passed to the wsgi application as follows: app = cherrypy.tree.mount(HelloWorld(), '', 'settings.config') return app(environ, start_response)
[ "I am doing this, although this would require cherrypy to know the relative path:\nclass Dir: pass\nroot = Dir()\nroot.apps = Dir()\nroot.apps.myapp = MyApp()\ncherrypy.tree.mount(root)\n\nThis allows me to structure the application in any way I need. I'm using nginx and not Apache, but I don't think it'll make any...
[ 1, 0 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0004129929_cherrypy_python.txt
Q: Django: Obtaining the absolute URL without access to a request object I have a model like the one below. When an instance is created, I want to send out an e-mail to an interested party: class TrainStop(models.Model): name = models.CharField(max_length=32) notify_email = models.EmailField(null=True, blank=True) def new_stop_created(sender, instance, created, *args, **kwargs): # Only for new stops if not created or instance.id is None: return # Send the status link if instance.notify_email: send_mail( subject='Stop submitted: %s' % instance.name, message='Check status: %s' % reverse('stop_status', kwargs={'status_id':str(instance.id),}), from_email='admin@example.com', recipient_list=[instance.notify_email,] ) signals.post_save.connect(new_stop_created, sender=TrainStop) However, the reverse call only returns the path portion of the URL. Example: /stops/9/status/. I need a complete URL like http://example.com/stops/9/status/. How would I go about retrieving the hostname and port (for test instances that do not use port 80) of the current website? My initial thought was to make this available via a variable in settings.py that I could then access as needed. However, thought someone might have a more robust suggestion. A: There's the sites framework, as yedpodtrzitko mentioned, but, as you mentioned, it's very much a manual setup. There's requiring a setting in settings.py, but it's only slightly less manual than setting up sites. (It can handle multiple domains, just as well as sites and the SITE_ID setting can). There's an idea for replacing get_absolute_url, that would make stuff like this easier, though I think its implementation suffers from the same problem (how to get the domain, scheme [http vs https], etc). I've been toying with the idea of a middleware that examines incoming requests and constructs a "most likely domain" setting of some sort based on the frequency of the HTTP HOST header's value. Or perhaps it could set this setting on each request individually, so you could always have the current domain to work with. I haven't gotten to the point of seriously looking into it, but it's a thought. A: For getting current site there's object Site: If you don’t have access to the request object, you can use the get_current() method of the Site model’s manager. You should then ensure that your settings file does contain the SITE_ID setting. This example is equivalent to the previous one: from django.contrib.sites.models import Site def my_function_without_request(): current_site = Site.objects.get_current() if current_site.domain == 'foo.com': # Do something pass else: # Do something else. pass More info: http://docs.djangoproject.com/en/dev/ref/contrib/sites/
Django: Obtaining the absolute URL without access to a request object
I have a model like the one below. When an instance is created, I want to send out an e-mail to an interested party: class TrainStop(models.Model): name = models.CharField(max_length=32) notify_email = models.EmailField(null=True, blank=True) def new_stop_created(sender, instance, created, *args, **kwargs): # Only for new stops if not created or instance.id is None: return # Send the status link if instance.notify_email: send_mail( subject='Stop submitted: %s' % instance.name, message='Check status: %s' % reverse('stop_status', kwargs={'status_id':str(instance.id),}), from_email='admin@example.com', recipient_list=[instance.notify_email,] ) signals.post_save.connect(new_stop_created, sender=TrainStop) However, the reverse call only returns the path portion of the URL. Example: /stops/9/status/. I need a complete URL like http://example.com/stops/9/status/. How would I go about retrieving the hostname and port (for test instances that do not use port 80) of the current website? My initial thought was to make this available via a variable in settings.py that I could then access as needed. However, thought someone might have a more robust suggestion.
[ "There's the sites framework, as yedpodtrzitko mentioned, but, as you mentioned, it's very much a manual setup.\nThere's requiring a setting in settings.py, but it's only slightly less manual than setting up sites. (It can handle multiple domains, just as well as sites and the SITE_ID setting can).\nThere's an ide...
[ 5, 4 ]
[]
[]
[ "django", "django_settings", "django_signals", "python" ]
stackoverflow_0004150258_django_django_settings_django_signals_python.txt
Q: sqlite returning nothing after 2nd cursor.fetchall() Why do I get nothing when I execute cursor.fetchall() twice after a cursor.execute()? Is there anyway of preventing this from happening? Do I need to store the information on a variable? Is it suppose to work this way? A: fetchall does what it says--it fetches all. There's nothing left after that. To get more results, you'd need to run another query (or the same query again). From the python db-api 2.0 specification: cursor.fetchall() Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples). Note that the cursor's arraysize attribute can affect the performance of this operation. cursor.fetchone() Fetch the next row of a query result set, returning a single sequence, or None when no more data is available. [6]
sqlite returning nothing after 2nd cursor.fetchall()
Why do I get nothing when I execute cursor.fetchall() twice after a cursor.execute()? Is there anyway of preventing this from happening? Do I need to store the information on a variable? Is it suppose to work this way?
[ "fetchall does what it says--it fetches all. There's nothing left after that. To get more results, you'd need to run another query (or the same query again).\nFrom the python db-api 2.0 specification:\n\ncursor.fetchall() \n\n Fetch all (remaining) rows of a query result, returning\n them as a seque...
[ 5 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0004150957_python_sqlite.txt
Q: Exception: Failed to start new browser session: Error while launching browser Selenium in Python I am getting the following errors when running a basic Selenium test script in Python: ====================================================================== ERROR: test_untitled (__main__.TestTesting) ---------------------------------------------------------------------- Traceback (most recent call last): File "TestTesting.py", line 15, in setUp self.selenium.start() File "/usr/lib/python2.6/dist-packages/selenium.py", line 166, in start result = self.get_string("getNewBrowserSession", [self.browserStartCommand, self.browserURL]) File "/usr/lib/python2.6/dist-packages/selenium.py", line 195, in get_string result = self.do_command(verb, args) File "/usr/lib/python2.6/dist-packages/selenium.py", line 191, in do_command raise Exception, data Exception: Failed to start new browser session: Error while launching browser ---------------------------------------------------------------------- Ran 1 test in 20.427s FAILED (errors=1) The code was generated from the Selenium IDE, the firefox plug in, so I am not sure why it doesn't work. My guess is some sort of configuration is incorrect, but I am not sure. Here is my code: from selenium import selenium class TestTesting(unittest.TestCase): def setUp(self): self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*firefox", "http://www.google.com/") self.selenium.start() def test_untitled(self): sel = self.selenium sel.open("/firefox?client=firefox-a&rls=org.mozilla:en-US:official") sel.type("sf", "test") sel.click("btnG") sel.wait_for_page_to_load("30000") def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main() The server is running on Ubuntu. How can I avoid this error? A: The fix that I got to work was that the display for firefox was not set. So I needed to execute the following statement: export DISPLAY=:0 right before I started the Selenium server. This solve the issue, but a new one has arisen. A: This normally happens when another firefox is already opened. i.e. You are using specific FF profile to tet application. When you run the script, close FF. A: Temporarily launching the selenium server as root did the trick for me: sudo java -jar selenium-server.jar
Exception: Failed to start new browser session: Error while launching browser Selenium in Python
I am getting the following errors when running a basic Selenium test script in Python: ====================================================================== ERROR: test_untitled (__main__.TestTesting) ---------------------------------------------------------------------- Traceback (most recent call last): File "TestTesting.py", line 15, in setUp self.selenium.start() File "/usr/lib/python2.6/dist-packages/selenium.py", line 166, in start result = self.get_string("getNewBrowserSession", [self.browserStartCommand, self.browserURL]) File "/usr/lib/python2.6/dist-packages/selenium.py", line 195, in get_string result = self.do_command(verb, args) File "/usr/lib/python2.6/dist-packages/selenium.py", line 191, in do_command raise Exception, data Exception: Failed to start new browser session: Error while launching browser ---------------------------------------------------------------------- Ran 1 test in 20.427s FAILED (errors=1) The code was generated from the Selenium IDE, the firefox plug in, so I am not sure why it doesn't work. My guess is some sort of configuration is incorrect, but I am not sure. Here is my code: from selenium import selenium class TestTesting(unittest.TestCase): def setUp(self): self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*firefox", "http://www.google.com/") self.selenium.start() def test_untitled(self): sel = self.selenium sel.open("/firefox?client=firefox-a&rls=org.mozilla:en-US:official") sel.type("sf", "test") sel.click("btnG") sel.wait_for_page_to_load("30000") def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main() The server is running on Ubuntu. How can I avoid this error?
[ "The fix that I got to work was that the display for firefox was not set. So I needed to execute the following statement:\nexport DISPLAY=:0\n\nright before I started the Selenium server. This solve the issue, but a new one has arisen. \n", "This normally happens when another firefox is already opened. i.e. You a...
[ 2, 0, 0 ]
[]
[]
[ "python", "selenium", "ubuntu" ]
stackoverflow_0003388714_python_selenium_ubuntu.txt
Q: Storing tokenized text in the db? I have a simple question. I'm doing some light crawling so new content arrives every few days. I've written a tokenizer and would like to use it for some text mining purposes. Specifically, I'm using Mallet's topic modeling tool and one of the pipe is to tokenize the text into tokens before further processing can be done. With the amount of text in my database, it takes a substantial amount of time tokenizing the text (I'm using regex here). As such, is it a norm to store the tokenized text in the db so that tokenized data can be readily available and tokenizing can be skipped if I need them for other text mining purposes such as Topic modeling, POS tagging? What are the cons of this approach? A: Caching Intermediate Representations It's pretty normal to cache the intermediate representations created by slower components in your document processing pipeline. For example, if you needed dependency parse trees for all the sentences in each document, it would be pretty crazy to do anything except parsing the documents once and then reusing the results. Slow Tokenization However, I'm surprise that tokenization is really slow for you, since the stuff downstream from tokenization is usually the real bottleneck. What package are you using to do the tokenization? If you're using Python and you wrote your own tokenization code, you might want to try one of the tokenizers included in NLTK (e.g., TreebankWordTokenizer). Another good tokenizer, albeit one that is not written in Python, is the PTBTokenizer included with the Stanford Parser and the Stanford CoreNLP end-to-end NLP pipeline. A: I store tokenized text in a MySQL database. While I don't always like the overhead of communication with the database, I've found that there are lots of processing tasks that I can ask the database to do for me (like search the dependency parse tree for complex syntactic patterns).
Storing tokenized text in the db?
I have a simple question. I'm doing some light crawling so new content arrives every few days. I've written a tokenizer and would like to use it for some text mining purposes. Specifically, I'm using Mallet's topic modeling tool and one of the pipe is to tokenize the text into tokens before further processing can be done. With the amount of text in my database, it takes a substantial amount of time tokenizing the text (I'm using regex here). As such, is it a norm to store the tokenized text in the db so that tokenized data can be readily available and tokenizing can be skipped if I need them for other text mining purposes such as Topic modeling, POS tagging? What are the cons of this approach?
[ "Caching Intermediate Representations\nIt's pretty normal to cache the intermediate representations created by slower components in your document processing pipeline. For example, if you needed dependency parse trees for all the sentences in each document, it would be pretty crazy to do anything except parsing the ...
[ 1, 1 ]
[]
[]
[ "caching", "nlp", "postgresql", "python", "tokenize" ]
stackoverflow_0004122940_caching_nlp_postgresql_python_tokenize.txt
Q: (Python) List traversal in a nested for-loop? I can't figure out what's happening here. I've got a few lists set up, one for each individual color with corresponding RGB values as its member, and then the list, colors[], that contains each individual color list. Then I've got a nested for loop: the outer loop creates columns of color-filled rectangles and the inner loop advances the row. Not complicated, as I see it. I'm trying to use numdown to traverse the colors[] list so that every two rows the color changes to the member corresponding in colors[]. The problem is that when I use the inner list's numover, it works fine, except obviously I get the wrong color pattern (colors advance across rather than down). If I use numdown to traverse the list, only the member white seems to be accessed, even though if in the inner for-loop I 'print(numdown)' or even 'print(colors[numdown])' the correct value is printed. Why is this the case? Why if I use the inner-for's numover are the list member's accessed correctly, but if I use the outer-for's numdown it breaks? It occurs to me that this might have something to do with pygame, though I wouldn't have any idea what. (Additionally, as really I am just starting with Python, if you see anything else worth jumping on, method or style-wise, please feel free to point it out.) import pygame, sys from pygame.locals import * #initialize pygame pygame.init() #assign display window dimensions winwidth = 400 winheight = 700 #number of rows, number of colums numrows = range(1,11) numcols = range(1,11) #Keeping brick size proportionate to the window size brickwidth = winwidth / (len(numrows)) brickheight = winheight / 4 #Pixel space above the breakout area bricktopspace = winheight / 7 #Set display window width, height windowSurface = pygame.display.set_mode((winwidth, winheight), 0, 0) brickxcoord = 0 blue = [0, 0, 255] green = [0, 255, 0] yellow = [255, 255, 0] red = [255, 0, 0] white = [255, 255, 255] colors = range(0,11) colors[1] = white colors[2] = white colors[3] = red colors[4] = red colors[5] = green colors[6] = green colors[7] = yellow colors[8] = yellow colors[9] = blue colors[10] = blue class Setup(): for numdown in numcols: for numover in numrows: print(numdown) pygame.draw.rect(windowSurface, colors[numdown], (brickxcoord, bricktopspace, brickwidth, brickheight)) brickxcoord = brickxcoord + brickwidth bricktopspace = bricktopspace + brickheight class Main(): Setup() pygame.display.update() A: I can't say anything about the pygame method, but a more idiomatic way to declare the list would be colors = [] colors.append(white) ... rather than creating and then overwriting a range. You could even do colors = [white, white, ...] though that would probably be an ugly line. Also, your first list element is always at position "0", so you will wind up with a list that has elements [0, white, white, ...] rather than [white, white, ...] since you start defining colors at colors[1]. A: uhh... a bit late but if you're still around. Something like this? I've modified it a bit but trying to keep as close to your structure as possible: import pygame, sys from pygame.locals import * #assign display window dimensions winwidth = 400 winheight = 700 #number of rows, number of colums numrows = 10 numcols = 10 #Keeping brick size proportionate to the window size brickwidth = winwidth / numcols brickheight = winheight / numcols #initialize pygame pygame.init() #Set display window width, height windowSurface = pygame.display.set_mode((winwidth, winheight), 0, 0) #Colours blue = [0, 0, 255] green = [0, 255, 0] yellow = [255, 255, 0] red = [255, 0, 0] white = [255, 255, 255] colours = [white, white, red, red, green, green, yellow, yellow, blue, blue] class Setup(): def __init__(self): #Setup nest for loop to generate 2d array of blocks. for y in range(0, numrows): for x in range(0, numcols): #Using modulo to get the different colours for rows, we use y as the changing key col_index = y % len(colours) pygame.draw.rect(windowSurface, colours[col_index], (x*brickwidth, y*brickheight, brickwidth, brickheight)) class Main(): Setup() pygame.display.update() Because you wanted a fix number or rows and columns, you can have two variables stating how many rows and columns you need. Then you use those to determine the sizes of the blocks as you have done. I've changed the colours to the array as suggested, personally that's how I'd do it too (for one it's shorter and you can read it as a sequence). Also, if you wanted to change the sequence, you just have to move the items around. Lastly, I used two for loops that use the numrows and numcols as the range limits. If you think of your times tables, including the 0, it creates a perfect grid. Just think of the first loop as the rows and the nested loop as the column. Well, good luck.
(Python) List traversal in a nested for-loop?
I can't figure out what's happening here. I've got a few lists set up, one for each individual color with corresponding RGB values as its member, and then the list, colors[], that contains each individual color list. Then I've got a nested for loop: the outer loop creates columns of color-filled rectangles and the inner loop advances the row. Not complicated, as I see it. I'm trying to use numdown to traverse the colors[] list so that every two rows the color changes to the member corresponding in colors[]. The problem is that when I use the inner list's numover, it works fine, except obviously I get the wrong color pattern (colors advance across rather than down). If I use numdown to traverse the list, only the member white seems to be accessed, even though if in the inner for-loop I 'print(numdown)' or even 'print(colors[numdown])' the correct value is printed. Why is this the case? Why if I use the inner-for's numover are the list member's accessed correctly, but if I use the outer-for's numdown it breaks? It occurs to me that this might have something to do with pygame, though I wouldn't have any idea what. (Additionally, as really I am just starting with Python, if you see anything else worth jumping on, method or style-wise, please feel free to point it out.) import pygame, sys from pygame.locals import * #initialize pygame pygame.init() #assign display window dimensions winwidth = 400 winheight = 700 #number of rows, number of colums numrows = range(1,11) numcols = range(1,11) #Keeping brick size proportionate to the window size brickwidth = winwidth / (len(numrows)) brickheight = winheight / 4 #Pixel space above the breakout area bricktopspace = winheight / 7 #Set display window width, height windowSurface = pygame.display.set_mode((winwidth, winheight), 0, 0) brickxcoord = 0 blue = [0, 0, 255] green = [0, 255, 0] yellow = [255, 255, 0] red = [255, 0, 0] white = [255, 255, 255] colors = range(0,11) colors[1] = white colors[2] = white colors[3] = red colors[4] = red colors[5] = green colors[6] = green colors[7] = yellow colors[8] = yellow colors[9] = blue colors[10] = blue class Setup(): for numdown in numcols: for numover in numrows: print(numdown) pygame.draw.rect(windowSurface, colors[numdown], (brickxcoord, bricktopspace, brickwidth, brickheight)) brickxcoord = brickxcoord + brickwidth bricktopspace = bricktopspace + brickheight class Main(): Setup() pygame.display.update()
[ "I can't say anything about the pygame method, but a more idiomatic way to declare the list would be\ncolors = []\ncolors.append(white)\n...\n\nrather than creating and then overwriting a range. You could even do\ncolors = [white, white, ...]\n\nthough that would probably be an ugly line. Also, your first list elem...
[ 3, 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0004150888_pygame_python.txt
Q: Django search_fields & Many-To-One Relations As an example, I have two models: Household and Person: from django.db import models class Household(models.Model): address = # ... class Person(models.Model): household = models.ForeignKey(Household) name = # ... How can I search for Households by names of Persons inside the Django admin? A: As mentioned in the docs for search_fields: You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API "follow" notation: search_fields = ['foreign_key__related_fieldname'] For example, if you have a blog entry with an author, the following definition would enable search blog entries by the email address of the author: search_fields = ['user__email'] This should also work "backwards", as in your example. search_fields = ['person__name']
Django search_fields & Many-To-One Relations
As an example, I have two models: Household and Person: from django.db import models class Household(models.Model): address = # ... class Person(models.Model): household = models.ForeignKey(Household) name = # ... How can I search for Households by names of Persons inside the Django admin?
[ "As mentioned in the docs for search_fields:\n\nYou can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API \"follow\" notation:\nsearch_fields = ['foreign_key__related_fieldname']\n\nFor example, if you have a blog entry with an author, the following definition would enable search ...
[ 7 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004151256_django_python.txt
Q: How can this be made to do fewer calculations? It is very inefficient with large numbers num = input () fact = 0 while fact != num: fact = fact + 1 rem = num % fact if rem == 0: print fact A: You only need to go to the square root of the input number to get all the factors (not as far as half the number, as suggested elsewhere). For example, 24 has factors 1, 2, 3, 4, 6, 8, 12, 24. sqrt(24) is approx 4.9. Check 1 and also get 24, check 2 and also get 12, check 3 and also get 8, check 4 and also get 6. Since 5 > 4.9, no need to check it. (Yes, I know 24 isn't the best example as all whole numbers less than sqrt(24) are factors of 24.) factors = set() for i in xrange(math.floor(math.sqrt(x))+1): if x % i == 0: factors.add(i) factors.add(x/i) print factors There are some really complicated ways to do better for large numbers, but this should get you a decent runtime improvement. Depending on your application, caching could also save you a lot of time. A: Use for loops, for starters. Then, let Python increment for you, and get rid of the unnecessary rem variable. This code does exactly the same as your code, except in a "Pythonic" way. num = input() for x in xrange(1, num): if (num % x) == 0: print fact xrange(x, y) returns a generator for all integers from x up to, but not including y. A: So that prints out all the factors of a number? The first obvious optimisation is that you could quit when fact*2 is greater than num. Anything greater than half of num can't be a factor. That's half the work thrown out instantly. The second is that you'd be better searching for the prime factorisation and deriving all the possible factors from that. There are a bunch of really smart algorithms for that sort of thing. A: Once you get halfway there (once fact>num/2), your not going to discover any new numbers as the numbers above num/2 can be discovered by calculating num/fact for each one (this can also be used to easily print each number with its pair). The following code should cust the time down by a few seconds on every calculation and cut it in half where num is odd. Hopefully you can follow it, if not, ask. I'll add more if I think of something later. def even(num): '''Even numbers can be divided by odd numbers, so test them all''' fact=0 while fact<num/2: fact+=1 rem=num % fact if rem == 0: print '%s and %s'%(fact,num/fact) def odd(num): '''Odd numbers can't be divided by even numbers, so why try?''' fact=-1 while fact<num/2: fact+=2 rem=num % fact if rem == 0: print '%s and %s'%(fact,num/fact) while True: num=input(':') if str(num)[-1] in '13579': odd(num) else: even(num) A: Research integer factorization methods. A: Yes. Use a quantum computer Shor's algorithm, named after mathematician Peter Shor, is a quantum algorithm (an algorithm which runs on a quantum computer) for integer factorization formulated in 1994. Informally it solves the following problem: Given an integer N, find its prime factors. On a quantum computer, to factor an integer N, Shor's algorithm runs in polynomial time (the time taken is polynomial in log N, which is the size of the input). Specifically it takes time O((log N)3), demonstrating that the integer factorization problem can be efficiently solved on a quantum computer and is thus in the complexity class BQP. This is exponentially faster than the most efficient known classical factoring algorithm, the general number field sieve, which works in sub-exponential time — about O(e1.9 (log N)1/3 (log log N)2/3). The efficiency of Shor's algorithm is due to the efficiency of the quantum Fourier transform, and modular exponentiation by squarings. A: Unfortunately in Python, the divmod operation is implemented as a built-in function. Despite hardware integer division often producing the quotient and the remainder simultaneously, no non-assembly language that I'm aware of has implemented a /% or //% basic operator. So: the following is a better brute-force algorithm if you count machine operations. It gets all factors in O(sqrt(N)) time without having to calculate sqrt(N) -- look, Mum, no floating point! # even number fact = 0 while 1: fact += 1 fact2, rem = divmod(num, fact) if not rem: yield fact yield fact2 if fact >= fact2 - 1: # fact >= math.sqrt(num) break
How can this be made to do fewer calculations? It is very inefficient with large numbers
num = input () fact = 0 while fact != num: fact = fact + 1 rem = num % fact if rem == 0: print fact
[ "You only need to go to the square root of the input number to get all the factors (not as far as half the number, as suggested elsewhere). For example, 24 has factors 1, 2, 3, 4, 6, 8, 12, 24. sqrt(24) is approx 4.9. Check 1 and also get 24, check 2 and also get 12, check 3 and also get 8, check 4 and also get ...
[ 3, 2, 2, 2, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004150563_python.txt
Q: Why list as key dictionary, will still show itself as tuple as key dictionary When I define a dictionary which use list as key collections.defaultdict(list) When I print it out, it shows itself is using tuple as key. May I know why? import collections tuple_as_dict_key = collections.defaultdict(tuple) tuple_as_dict_key['abc', 1, 2] = 999 tuple_as_dict_key['abc', 3, 4] = 999 tuple_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) print tuple_as_dict_key list_as_dict_key = collections.defaultdict(list) list_as_dict_key['abc', 1, 2] = 999 list_as_dict_key['abc', 3, 4] = 999 list_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) # Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ... print list_as_dict_key A: The parameter to defaultdict is not the type of the key, it is a function that creates default data. Your test cases don't exercise this because you're filling the dict with defined values and not using any defaults. If you were to try to get the value list_as_dict_key['abc', 7, 8] it would return an empty list, since that is what you defined as a default value and you never set the value at that index. A: There's a nice article explaining the answer to why you can't use a list as key here. A: When you're adding values to your dictionary you're doing it the same way in both cases and they're treated as a tuple. What you're passing to the constructor is the default value for any keys that are not present. Your default value in this case happens to be of type "type", but that has absolutely nothing to do with how other keys are treated. A: Dictionary keys can only be immutable types. Since a list is a mutable type it must be converted to an immutable type such as a tuple to be used as a dictionary key, and this conversion is being done automatically. A: defaultdict is not setting the key as a list. It's setting the default value. >>> from collections import defaultdict >>> d1 = collections.defaultdict(list) >>> d1['foo'] [] >>> d1['foo'] = 37 >>> d1['foo'] 37 >>> d1['bar'] [] >>> d1['bar'].append(37) >>> d1['bar'] [37] The way that you're getting a tuple as the key type is normal dict behaviour: >>> d2 = dict() >>> d2[37, 19, 2] = [14, 19] >>> d2 {(37, 19, 2): [14, 19]} The way Python works with subscripting is that a is a, a, b is a tuple, a:b is a slice object. See how it works with a list: >>> mylist = [1, 2, 3] >>> mylist[4, 5] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list indices must be integers, not tuple It's taken 4, 5 as a tuple. The dict has done the same.
Why list as key dictionary, will still show itself as tuple as key dictionary
When I define a dictionary which use list as key collections.defaultdict(list) When I print it out, it shows itself is using tuple as key. May I know why? import collections tuple_as_dict_key = collections.defaultdict(tuple) tuple_as_dict_key['abc', 1, 2] = 999 tuple_as_dict_key['abc', 3, 4] = 999 tuple_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) print tuple_as_dict_key list_as_dict_key = collections.defaultdict(list) list_as_dict_key['abc', 1, 2] = 999 list_as_dict_key['abc', 3, 4] = 999 list_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) # Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ... print list_as_dict_key
[ "The parameter to defaultdict is not the type of the key, it is a function that creates default data. Your test cases don't exercise this because you're filling the dict with defined values and not using any defaults. If you were to try to get the value list_as_dict_key['abc', 7, 8] it would return an empty list, s...
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004151589_python.txt
Q: Python: referencing lines in a table I am trying to take lines from a file and put them into a table that will be displayed on the web. I need to be able to reference these lines individually to alter the table information using an if...else statement. Can anyone help me find a way to reference these lines when they are pulled through - this is my code so far. #for each line in emaildomains - print out on page to view print '<form method=\'post\' name="updateUsers">' print '<table border="1">' print '<tr>' print '<th>Email Address</th>' print '<th>Delete Email</th>' print '<th>Make Changes?</th>' print '</tr>' n=1 for line in emaildomains: print '<tr>' print '<td><input type="text" name=\"useraddress\", n, value ="%s">' %line print '<input type="hidden" name=useraddress_org value ="%s"></td>' %line print '<td><input type=\"radio\" name=\"deleteRadio\", n, style=margin-left:50px></td>' print '<td><input type="submit" value="Edit Users" /></td>' print '</tr>' n+=1 print '</table>' print '</form>' A: Set an id HTML attribute for each table entry (or row, depending on your needs). E.g. <tr id="Foo"> A: Use format strings to your advantage. For instance, If I wanted to conditionally add a greeting, I would default the variable to the empty string and change it, based on my mood. Also: Instead of instantiating and maintaining a counter, consider using enumerate(). Try to steer clear of escaping characters. Maintain a clean consistent style (i.e. you had some html attributes using ', some using ", and one not using anything). Example: #for each line in emaildomains - print out on page to view table_fs = """ <form method="post" name="updateUsers"> %s <table border="1"> <tr> <th>Email Address</th> <th>Delete Email</th> <th>Make Changes?</th> </tr> %s </table> </form> """ line_fs = """ <td> %s <input type="text" name="useraddress" %s value ="%s"> <input type="hidden" name="useraddress_org" value ="%s"> </td> <td><input type="radio" name="deleteRadio", n, style=margin-left:50px></td> <td><input type="submit" value="Edit Users" /></td> """ good_mood = '' if i_have_cookies: good_mood = '<h1>I LOVE COOKIES!</h1>' lines = [] for n, line in enumerate(emaildomains, 1): greeting = '' if i_like_this_persion: greeting = 'Hi!' line = [] line.append(line_fs%(greeting, n, line, line)) cells_string = '\n'.join(['<td>%s</td>'%x for x in line]) row_string = '<tr>%s</tr>'%(cells_string) lines.append(row_string) rows_string = '\n'.join(lines) print table_fs%(good_mood, rows_string) P.S. It's a little late, and I'm a bit tired, so I'm sorry if I can't spell, or I missed anything.
Python: referencing lines in a table
I am trying to take lines from a file and put them into a table that will be displayed on the web. I need to be able to reference these lines individually to alter the table information using an if...else statement. Can anyone help me find a way to reference these lines when they are pulled through - this is my code so far. #for each line in emaildomains - print out on page to view print '<form method=\'post\' name="updateUsers">' print '<table border="1">' print '<tr>' print '<th>Email Address</th>' print '<th>Delete Email</th>' print '<th>Make Changes?</th>' print '</tr>' n=1 for line in emaildomains: print '<tr>' print '<td><input type="text" name=\"useraddress\", n, value ="%s">' %line print '<input type="hidden" name=useraddress_org value ="%s"></td>' %line print '<td><input type=\"radio\" name=\"deleteRadio\", n, style=margin-left:50px></td>' print '<td><input type="submit" value="Edit Users" /></td>' print '</tr>' n+=1 print '</table>' print '</form>'
[ "Set an id HTML attribute for each table entry (or row, depending on your needs). E.g.\n<tr id=\"Foo\">\n\n", "Use format strings to your advantage. For instance, If I wanted to conditionally add a greeting, I would default the variable to the empty string and change it, based on my mood. Also:\n\nInstead of inst...
[ 2, 0 ]
[]
[]
[ "html", "html_table", "python" ]
stackoverflow_0004150828_html_html_table_python.txt
Q: Downloading a file in Python import urllib2, sys if len(sys.argv) !=3: print "Usage: download.py <link> <saveas>" sys.exit(1) site = urllib2.urlopen(sys.argv[1]) meta = site.info() print "Size: ", meta.getheaders("Content-Length") f = open(sys.argv[2], 'wb') f.write(site.read()) f.close() I'm wondering how to display the file name and size before downloading and how to display the download progress of the file. Any help will be appreciated. A: using urllib.urlretrieve import urllib, sys def progress_callback(blocks, block_size, total_size): #blocks->data downloaded so far (first argument of your callback) #block_size -> size of each block #total-size -> size of the file #implement code to calculate the percentage downloaded e.g print "downloaded %f%%" % blocks/float(total_size) if len(sys.argv) !=3: print "Usage: download.py " sys.exit(1) site = urllib.urlopen(sys.argv[1]) (file, headers) = urllib.urlretrieve(site, sys.argv[2], progress_callback) print headers A: To display the filename: print f.name To see all the cool things you can do with the file: dir(f) I'm not sure I know what you mean when you say: how to display how long it has before the file is finished downloading If you want to display the time it took for the download, then you might want to take a look at the timeit module. I this is not what you are looking for, then please update the question, so I can try to give you a better answer
Downloading a file in Python
import urllib2, sys if len(sys.argv) !=3: print "Usage: download.py <link> <saveas>" sys.exit(1) site = urllib2.urlopen(sys.argv[1]) meta = site.info() print "Size: ", meta.getheaders("Content-Length") f = open(sys.argv[2], 'wb') f.write(site.read()) f.close() I'm wondering how to display the file name and size before downloading and how to display the download progress of the file. Any help will be appreciated.
[ "using urllib.urlretrieve\n\n\n import urllib, sys\n\n def progress_callback(blocks, block_size, total_size):\n #blocks->data downloaded so far (first argument of your callback)\n #block_size -> size of each block\n #total-size -> size of the file\n #implement code to calculate th...
[ 5, 1 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0004151841_python_urllib2.txt
Q: Pythonic way to rewrite the following C++ string processing code Previous, I am having a C++ string processing code which is able to do this. input -> Hello 12 output-> Hello input -> Hello 12 World output-> Hello World input -> Hello12 World output-> Hello World input -> Hello12World output-> HelloWorld The following is the C++ code. std::string Utils::toStringWithoutNumerical(const std::string& str) { std::string result; bool alreadyAppendSpace = false; for (int i = 0, length = str.length(); i < length; i++) { const char c = str.at(i); if (isdigit(c)) { continue; } if (isspace(c)) { if (false == alreadyAppendSpace) { result.append(1, c); alreadyAppendSpace = true; } continue; } result.append(1, c); alreadyAppendSpace = false; } return trim(result); } May I know in Python, what is the Pythonic way for implementing such functionality? Is regular expression able to achieve so? Thanks. A: Edit: This reproduces more accurately what the C++ code does than the previous version. s = re.sub(r"\d+", "", s) s = re.sub(r"(\s)\s*", "\1", s) In particular, if the first whitespace in a run of several whitespaces is a tab, it will preserve the tab. Further Edit: To replace by a space anyway, this works: s = re.sub(r"\d+", "", s) s = re.sub(r"\s+", " ", s) A: Python has a lot of built-in functions that can be very powerful when used together. def RemoveNumeric(str): return ' '.join(str.translate(None, '0123456789').split()) >>> RemoveNumeric('Hello 12') 'Hello' >>> RemoveNumeric('Hello 12 World') 'Hello World' >>> RemoveNumeric('Hello12 World') 'Hello World' >>> RemoveNumeric('Hello12World') 'HelloWorld' A: import re re.sub(r'[0-9]+', "", string) A: import re re.sub(r"(\s*)\d+(\s*)", lambda m: m.group(1) or m.group(2), string) Breakdown: \s* matches zero or more whitespace. \d+ matches one or more digits. The parentheses are used to capture the whitespace. The replacement parameter is normally a string, but it can alternatively be a function which constructs the replacement dynamically. lambda is used to create an inline function which returns whichever of the two capture groups is non-empty. This preserves a space if there was whitespace and returns an empty string if there wasn't any. A: The regular expression answers are clearly the right way to do this. But if you're interested in a way to do if you didn't have a regex engine, here's how: class filterstate(object): def __init__(self): self.seenspace = False def include(self, c): isspace = c.isspace() if (not c.isdigit()) and (not (self.seenspace and isspace)): self.seenspace = isspace return True else: return False def toStringWithoutNumerical(s): fs = filterstate() return ''.join((c for c in s if fs.include(c)))
Pythonic way to rewrite the following C++ string processing code
Previous, I am having a C++ string processing code which is able to do this. input -> Hello 12 output-> Hello input -> Hello 12 World output-> Hello World input -> Hello12 World output-> Hello World input -> Hello12World output-> HelloWorld The following is the C++ code. std::string Utils::toStringWithoutNumerical(const std::string& str) { std::string result; bool alreadyAppendSpace = false; for (int i = 0, length = str.length(); i < length; i++) { const char c = str.at(i); if (isdigit(c)) { continue; } if (isspace(c)) { if (false == alreadyAppendSpace) { result.append(1, c); alreadyAppendSpace = true; } continue; } result.append(1, c); alreadyAppendSpace = false; } return trim(result); } May I know in Python, what is the Pythonic way for implementing such functionality? Is regular expression able to achieve so? Thanks.
[ "Edit: This reproduces more accurately what the C++ code does than the previous version.\ns = re.sub(r\"\\d+\", \"\", s)\ns = re.sub(r\"(\\s)\\s*\", \"\\1\", s)\n\nIn particular, if the first whitespace in a run of several whitespaces is a tab, it will preserve the tab.\nFurther Edit: To replace by a space anyway,...
[ 7, 5, 1, 0, 0 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0004150832_c++_python.txt
Q: Simple sqlite question When I use: for i in Selection: Q = "SELECT columnA FROM DB WHERE wbcode='"+i+"' and commodity='1'" cursor.execute(Q) ydata[i] = cursor.fetchall() I get: ydata = {'GBR': [(u'695022',), (u'774291',), (u'791499',)... ]} How can I change my code to get: ydata = {'GBR': [695022, 774291, 791499,...]} Thank you very much. obs: this is just a a simplified example. try to refrain from making recommendations about sql injection. A: [int(x[0]) for x in cursor.fetchall()] A: Based on this and another question of yours, you need to understand SQLite's affinity and how you are populating the database. Other databases require that the values stored in a column are all of the same type - eg all strings or all integers. SQLite allows you to store anything so the type in each row can be different. To a first approximation, if you put in a string for that row then you'll get a string out, put in an integer and you'll get an integer out. In your case you are getting strings out because you put strings in instead of integers. However you can declare a column affinity and SQLite will try to convert when you insert data. For example if a column has integer affinity then if what you insert can be safely/correctly converted to an integer then SQLite will do so, so the string "1" will indeed be stored as the integer 1 while "1 1" will be stored as the string "1 1". Read this page to understand the details. You'll find things a lot easier getting data out if you put it in using the correct types. http://www.sqlite.org/datatype3.html If you are importing CSV data then start the APSW shell and use ".help import" to get some suggestions on how to deal with this.
Simple sqlite question
When I use: for i in Selection: Q = "SELECT columnA FROM DB WHERE wbcode='"+i+"' and commodity='1'" cursor.execute(Q) ydata[i] = cursor.fetchall() I get: ydata = {'GBR': [(u'695022',), (u'774291',), (u'791499',)... ]} How can I change my code to get: ydata = {'GBR': [695022, 774291, 791499,...]} Thank you very much. obs: this is just a a simplified example. try to refrain from making recommendations about sql injection.
[ "[int(x[0]) for x in cursor.fetchall()]\n\n", "Based on this and another question of yours, you need to understand SQLite's affinity and how you are populating the database. Other databases require that the values stored in a column are all of the same type - eg all strings or all integers. SQLite allows you to...
[ 4, 2 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0004147338_python_sql_sqlite.txt
Q: Why is dictionary in object not different from the other? I have the following Python code: #!/usr/bin/env python2.6 class container(object): name = 'container' configuration = {'var1': 'var1', 'var2': 'var2'} if __name__ == "__main__": container1 = container() container2 = container() container2.name = 'container2' container2.configuration['var2'] = 'newvar2' print container1.name print container1.configuration['var2'] I expect this to print 'container' and 'var2', but for the latter it prints 'newvar2' instead Why does the configuration variable point to the same dictionary for both objects? How can I fix this? Most answers are already explaining that name and configuration are class variables. Why does the change of container2.name not influence container1.name? A: Because configuration is a class variable and not an instance variable. Fixing this should fix your problem. class container(object): def __init__(self): self.name = 'container' self.configuration = {'var1': 'var1', 'var2': 'var2'} What's going on here is that configuration ends up living in containter.__dict__ instead of in the dictionaries of its instances when you make it a class variable. This means that c.configuration is just accessing container.__dict__['configuration'] for all instances c. For any class variable, an assignment of the form c.foo = x, creates an entry for foo in c.__dict__ which shadows its entry in container.__dict__. So a lookup will return that first. If you delete it, then a lookup will go back to retrieving the class instance. You could do c = container() c.configuration = x and then c.configuration would be whatever x was. But inserting a key isn't an assignment, it's a method call on an existing object accessed through an existing binding. You could get away with making name a class variable but if you want it to change from one instance to another then it should be an instance variable (unless you want a class wide default of course). so: An assignment (using =, setattr or directly inserting in __dict__) on an instance will shadow a class variable. The class variable is still there. A lookup (calling a method, accessing the value) on an instance will grab an instance attribute if it exists and a class variable otherwise. A: Because name and configuration are class or static members of the container class and they are shared for all the instances of container. Use self.name, self.configuration for instance variables: class container(object): def __init__(self): self.name = "container" self.configuration = {} A: self.name = 'container' self.configuration = {'var1': 'var1', 'var2': 'var2'} In init() if they are the class variables.
Why is dictionary in object not different from the other?
I have the following Python code: #!/usr/bin/env python2.6 class container(object): name = 'container' configuration = {'var1': 'var1', 'var2': 'var2'} if __name__ == "__main__": container1 = container() container2 = container() container2.name = 'container2' container2.configuration['var2'] = 'newvar2' print container1.name print container1.configuration['var2'] I expect this to print 'container' and 'var2', but for the latter it prints 'newvar2' instead Why does the configuration variable point to the same dictionary for both objects? How can I fix this? Most answers are already explaining that name and configuration are class variables. Why does the change of container2.name not influence container1.name?
[ "Because configuration is a class variable and not an instance variable. Fixing this should fix your problem.\nclass container(object):\n def __init__(self):\n self.name = 'container'\n\n self.configuration = {'var1': 'var1',\n 'var2': 'var2'}\n\nWhat's going on here is ...
[ 3, 3, 0 ]
[]
[]
[ "object", "python" ]
stackoverflow_0004152210_object_python.txt
Q: In Django, what is the best way to manage both a mobile and desktop site? I'd like everything to function correctly, except when it's mobile, the entire site will used a set of specific templates. Also, I'd like to autodetect if it's mobile. If so, then use that set of templates throughout the entire site. A: Have two sets of templates, one for mobile, one for desktop. Store the filenames in a pair of dictionaries, and use the User-agent header to detect which set should be used. Also allow manual selection of which site to use via a session entry. A: If you place a class on your body (Django uses something similar to specify what column style to use), you could use the same templates but simply use different stylesheets. I'm not sure what main differences you are using separate templates for, but this might allow you to cut down on re-coding the templates multiple times. A: best practice: use minidetector to add the extra info to the request, then use django's built in request context to pass it to your templates like so. from django.shortcuts import render_to_response from django.template import RequestContext def my_view_on_mobile_and_desktop(request) ..... render_to_response('regular_template.html', {'my vars to template':vars}, context_instance=RequestContext(request)) then in your template you are able to introduce stuff like: <html> <head> {% block head %} <title>blah</title> {% if request.mobile %} <link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-mobile.css"> {% else %} <link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-desktop.css"> {% endif %} </head> <body> <div id="navigation"> {% include "_navigation.html" %} </div> {% if not request.mobile %} <div id="sidebar"> <p> sidebar content not fit for mobile </p> </div> {% endif %> <div id="content"> <article> {% if not request.mobile %} <aside> <p> aside content </p> </aside> {% endif %} <p> article content </p> </aricle> </div> </body> </html> A: There are different strategies. If you've a lot of views that renders to template files for the web version, and don't want to rewrite all views checking if the request is coming from a mobile user-agent, you'd be better writing a Middleware. A workflow could be like this: def process request: if from_mobile: settings.TEMPLATE_DIRS=settings.TEMPLATE_MOBILE_DIRS else: settings.TEMPLATE_DIRS=settings.TEMPLATE_WEB_DIRS There is only a little problem here: As Django Documentation reports, it's not correct to change settings at runtime: http://docs.djangoproject.com/en/dev/topics/settings/#altering-settings-at-runtime So you may want to call django.conf.settings.configure(default_settings, **settings) A: The answer depends heavily on the type of your target audience. If you target for modern mobile browsers equivalents to their desktop counterparts (such as WebKit-based), all you need is specific stylesheet with appropriate media query (you are basically designing for low-res rather than mobile). Totally different strategy is needed if your site (e.g. airline schedules) must to be accessible widest possible range of mobile devices, some of running very old / limited browsers. Then custom (html) templates may be easiest way to go. A: You might want to check out mobilesniffer and django-bloom to see if they fit your purposes.
In Django, what is the best way to manage both a mobile and desktop site?
I'd like everything to function correctly, except when it's mobile, the entire site will used a set of specific templates. Also, I'd like to autodetect if it's mobile. If so, then use that set of templates throughout the entire site.
[ "Have two sets of templates, one for mobile, one for desktop. Store the filenames in a pair of dictionaries, and use the User-agent header to detect which set should be used. Also allow manual selection of which site to use via a session entry.\n", "If you place a class on your body (Django uses something similar...
[ 9, 1, 1, 0, 0, 0 ]
[]
[]
[ "css", "django", "mobile", "python", "templates" ]
stackoverflow_0002396938_css_django_mobile_python_templates.txt
Q: Import an existing python project to XCode I've got a python project I've been making in terminal with vim etc.. I've read that XCode supports Python development at that it supports SVN (which I am using) but I can't find documentation on how to start a new XCode project from an existing code repository. Other developers are working on the project not using XCode - They won't mind if I add a project file or something, but they will mind if I have to reorganise the whole thing. A: I don't think it's worth using Xcode for a pure python project. Although the Xcode editor does syntax-highlight Python code, Xcode does not give you any other benefit for writing a pure-python app. On OS X, I would recommend TextMate as a text editor or Eclipse with PyDev as a more full-featured IDE. A: I recommend against doing so. Creating groups (which look like folders) in Xcode doesn't actually create folders in the filesystem. This wreaks havoc on the module hierarchy. Also, the SCM integration in Xcode is very clunky. After becoming accustomed to using Subversion with Eclipse, the Subversion support in Xcode is hopelessly primitive. It's almost easier to just do svn commands on the command line just so it's clear what's going on. If you must use Xcode, use it to open individual py files. Use it as a slow, relatively featureless text editor. If you must use Xcode for SCM, take a look at their guide to using Xcode with Subversion. A: There are no special facilities for working with non-Cocoa Python projects with Xcode. Therefore, you probably just want to create a project with the "Empty Project" template (under "Other") and just drag in your source code. For convenience, you may want to set up an executable in the project. You can do this by ctrl/right-clicking in the project source list and choosing "Add" > "New Custom Executable...". You can also add a target, although I'm not sure what this would buy you. A: Also see: http://lethain.com/entry/2008/aug/22/an-epic-introduction-to-pyobjc-and-cocoa/
Import an existing python project to XCode
I've got a python project I've been making in terminal with vim etc.. I've read that XCode supports Python development at that it supports SVN (which I am using) but I can't find documentation on how to start a new XCode project from an existing code repository. Other developers are working on the project not using XCode - They won't mind if I add a project file or something, but they will mind if I have to reorganise the whole thing.
[ "I don't think it's worth using Xcode for a pure python project. Although the Xcode editor does syntax-highlight Python code, Xcode does not give you any other benefit for writing a pure-python app. On OS X, I would recommend TextMate as a text editor or Eclipse with PyDev as a more full-featured IDE.\n", "I reco...
[ 7, 2, 1, 1 ]
[]
[]
[ "macos", "python", "xcode" ]
stackoverflow_0000709397_macos_python_xcode.txt
Q: plotting sparce time with matplotlib I want to plot a trading timeseries, e.g. close of 5 min bars. The markets are closed over night. So I have two queries: How to plot time in MatPlotLib (as well as date). E.g. so I need to implement a new axis or new hourLocators etc. How to remove overnight gaps from my plot. I.e. I want the last bar on Monday evening to be visually contiguous with the first bar of Tuesday morning. (Multiple plots won't work here as I need to display several days and pan the view.) A: Look at this example. It skips weekend gaps in a series of daily data and is very easy to adapt to your case.
plotting sparce time with matplotlib
I want to plot a trading timeseries, e.g. close of 5 min bars. The markets are closed over night. So I have two queries: How to plot time in MatPlotLib (as well as date). E.g. so I need to implement a new axis or new hourLocators etc. How to remove overnight gaps from my plot. I.e. I want the last bar on Monday evening to be visually contiguous with the first bar of Tuesday morning. (Multiple plots won't work here as I need to display several days and pan the view.)
[ "Look at this example. It skips weekend gaps in a series of daily data and is very easy to adapt to your case.\n" ]
[ 3 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0004152396_matplotlib_python.txt
Q: Render Externally Defined Block In Django Template I'm writing a simple blog-like application for Django and am trying to get the effect of having a front page with posts limited to 5, with a comprehensive archive that lists something like 100 posts at a time. (100 is not realistic, just throwing a number out there) Since the blog post blocks will look exactly the same between the two pages minus the number being shown, I'd like to put the corresponding HTML in a separate template that I can include or link to from the actual templates being rendered. I've looked over the documentation, and the include tag looked promising, but it apparently renders outside of the current context, which is not helpful to my cause, since it wouldn't get the objects to loop through. Outside of that, I can't see any other way to do what I want. Is this possible or am I just out of luck and going to have to violate DRY? Code is below to give you an idea of what I want. Thanks ####################### # news/frontpage.html # ####################### {% extends "news/base.html" %} {% block site_title %} - Front Page{% endblock %} {% block center_col %} {{ block.super }} <a href="/news/">View Older Blog Posts</a> {% endblock %} {% block blog_rows %} {% for object in object_list %} # Blog post content would go here, however it is to be included. {% endfor %} {% endblock %} A: You're looking for an inclusion tag. A: Why don't you filter for the blog posts you want to show in your view? That way you can keep the template the same: {% for object in blogposts %} # ... {% endfor %} You define blogposts in your view, which either includes 5 or 100 posts. A: Ignacio is right that you want an inclusion tag, but you should know that the include tag does not render outside the current context - it very definitely uses the same context as the block it's in. Your problem is probably that you're trying to call blogpost_set on the object_list - but the relationship is not with the list of objects, it's with each individual object in the list. You'd need to iterate through object_list and then through blogpost_set.all on each one.
Render Externally Defined Block In Django Template
I'm writing a simple blog-like application for Django and am trying to get the effect of having a front page with posts limited to 5, with a comprehensive archive that lists something like 100 posts at a time. (100 is not realistic, just throwing a number out there) Since the blog post blocks will look exactly the same between the two pages minus the number being shown, I'd like to put the corresponding HTML in a separate template that I can include or link to from the actual templates being rendered. I've looked over the documentation, and the include tag looked promising, but it apparently renders outside of the current context, which is not helpful to my cause, since it wouldn't get the objects to loop through. Outside of that, I can't see any other way to do what I want. Is this possible or am I just out of luck and going to have to violate DRY? Code is below to give you an idea of what I want. Thanks ####################### # news/frontpage.html # ####################### {% extends "news/base.html" %} {% block site_title %} - Front Page{% endblock %} {% block center_col %} {{ block.super }} <a href="/news/">View Older Blog Posts</a> {% endblock %} {% block blog_rows %} {% for object in object_list %} # Blog post content would go here, however it is to be included. {% endfor %} {% endblock %}
[ "You're looking for an inclusion tag.\n", "Why don't you filter for the blog posts you want to show in your view? That way you can keep the template the same:\n{% for object in blogposts %}\n# ...\n{% endfor %}\n\nYou define blogposts in your view, which either includes 5 or 100 posts.\n", "Ignacio is right tha...
[ 2, 0, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0004152710_django_django_templates_python.txt
Q: Authentication in Facebook Canvas App using New Graph API I am building a Facebook canvas application that loads in an iframe with Django. I would like the login process to work similarly to the way Zynga does it. In this method, if you are not logged in you are redirected to a Facebook login page and then to a permissions request page for the app (without any popups). As far as I can tell Zynga must be using FBML and just forwarding to URL's that look like: http://www.facebook.com/login.php?api_key=[api_key]&canvas=1&fbconnect=0&next=[return_url] Is there anyway to achieve a similar effect in a python app that loads in an iframe? There is a method here that shows how to achieve the correct redirects using the new php sdk, but I am trying to use the new python SDK which only has the method: def get_user_from_cookie(cookies, app_id, app_secret): """ Parses the cookie set by the official Facebook JavaScript SDK. cookies should be a dictionary-like object mapping cookie names to cookie values. ... """ I have some working code that uses the Javascript SDK and the get_user_from_cookie method: <div id="fb-root"> <script src="http://connect.facebook.net/en_US/all.js"></script> </div> <script type="text/javascript"> FB.init({ apiKey: 'apikey', status: true, cookie: true, xfbml: true}); FB.Event.subscribe('auth.login', function(response) { // Reload the application in the logged-in state window.top.location = 'http://apps.facebook.com/myapp/'; }); </script> <fb:login-button>Install MyApp</fb:login-button> The problem with this method is that it requires the user to click a button to login and then work through the popup authentication screens. (Note: a popup also occurs if I call FB.login directly) So... is there a way to use the javascript SDK to redirect to the login page rather than loading it as a popup? Thanks for any help! --Eric A: Is there a way to use the javascript SDK to redirect to the login page rather than loading it as a popup? No. The JavaScript SDK will open a new window rather than redirect the current window. To present the user with a full-screen version of the authorization dialog, you need to redirect them to https://graph.facebook.com/oauth/authorize?client_id={{ application_id }}&redirect_uri={{ redirect_uri }}. Note that you cannot do this from server-side code, as that would only redirect the iframe and Facebook does not allow it. You'll need an intermediate document that redirects the parent window. <!DOCTYPE html> <!-- This document redirects the parent window to the authorization dialog automatically, or falls back to a link if the client does not support JavaScript. --> <html> <head> <script type="text/javascript"> window.parent.location = 'https://graph.facebook.com/oauth/authorize?client_id={{ application_id }}&redirect_uri={{ redirect_uri }}'; </script> </head> <body> You must <a target="_top" href="https://graph.facebook.com/oauth/authorize?client_id={{ application_id }}&redirect_uri={{ redirect_uri }}">authorize this application</a> in order to proceed. </body> </html> Once the user has authorized your application, he or she will be redirected to the URI you specified inredirect_uri and Facebook will populate the GET parameter signed_request with all kinds of delicious information (see the documentation on signed requests) that you can use to make requests to Facebook on the user's behalf. Note that if you plan on saving this signed request (or anything else) to a cookie in a canvas application, you need set compact P3P policies in your headers; otherwise, all versions of Internet Explorer will ignore your cookies. P3P: CP="IDC CURa ADMa OUR IND PHY ONL COM STA" I've written a library that makes it really easy to make Facebook canvas applications powered by Django, which takes care of all these things for you. It's called Fandjango, and it's available on github. A: You should use OAuth as described in the documentation about authentication within Canvas Applications. The Python SDK you are already using contains an example which you should be ready to use almost out of the box.
Authentication in Facebook Canvas App using New Graph API
I am building a Facebook canvas application that loads in an iframe with Django. I would like the login process to work similarly to the way Zynga does it. In this method, if you are not logged in you are redirected to a Facebook login page and then to a permissions request page for the app (without any popups). As far as I can tell Zynga must be using FBML and just forwarding to URL's that look like: http://www.facebook.com/login.php?api_key=[api_key]&canvas=1&fbconnect=0&next=[return_url] Is there anyway to achieve a similar effect in a python app that loads in an iframe? There is a method here that shows how to achieve the correct redirects using the new php sdk, but I am trying to use the new python SDK which only has the method: def get_user_from_cookie(cookies, app_id, app_secret): """ Parses the cookie set by the official Facebook JavaScript SDK. cookies should be a dictionary-like object mapping cookie names to cookie values. ... """ I have some working code that uses the Javascript SDK and the get_user_from_cookie method: <div id="fb-root"> <script src="http://connect.facebook.net/en_US/all.js"></script> </div> <script type="text/javascript"> FB.init({ apiKey: 'apikey', status: true, cookie: true, xfbml: true}); FB.Event.subscribe('auth.login', function(response) { // Reload the application in the logged-in state window.top.location = 'http://apps.facebook.com/myapp/'; }); </script> <fb:login-button>Install MyApp</fb:login-button> The problem with this method is that it requires the user to click a button to login and then work through the popup authentication screens. (Note: a popup also occurs if I call FB.login directly) So... is there a way to use the javascript SDK to redirect to the login page rather than loading it as a popup? Thanks for any help! --Eric
[ "\nIs there a way to use the\n javascript SDK to redirect to the\n login page rather than loading it as a\n popup?\n\nNo. The JavaScript SDK will open a new window rather than redirect the current window.\nTo present the user with a full-screen version of the authorization dialog, you need to redirect them to ht...
[ 13, 0 ]
[]
[]
[ "django", "facebook", "javascript", "python" ]
stackoverflow_0003302908_django_facebook_javascript_python.txt
Q: is it possible not to use "self" in a class? Possible Duplicate: Python: How to avoid explicit 'self'? In python class if I need to reference the class member variable, I need to have a self. before it. This is anonying, can I not use that but reference the class member? Thanks. Bin A: No. >>> import this ... Explicit is better than implicit. ... A: To reference a class variables, you do not need explicit self. You need it for referencing object (class instance) variables. To reference a class variable, you can simply use that class name, like this: class C: x = 1 def set(self, x): C.x = x print C.x a = C() a.set(2) print a.x print C.x the first print would give you 1, and others 2. Although that is probably not what you want/need. (Class variables are bound to a class, not object. That means they are shared between all instances of that class. Btw, using self.x in the example above would mask class variable.) A: I don't know of a way to access object properties as if they're globals without unpacking it explicitly or something. If you don't like typing self, you can name it whatever you want, a one letter name for instance. A: Writing self explicitly is actually helpful. This encourages readability - one of Python's strengths. I personally consider it very useful. A similar argument in C++ is that when you use using namespace std, just to save repetitive prefixing of the std namespace. Though this may save time, it should not be done. So get used to writing self. And seriously, how long does it take! A: Python makes the reference to self explicit for a reason. The primary goal of the Python project is readability and simplicity. The "one correct way to do it" is to have a self argument and an explicit reference. Do not question the benevolent one ...
is it possible not to use "self" in a class?
Possible Duplicate: Python: How to avoid explicit 'self'? In python class if I need to reference the class member variable, I need to have a self. before it. This is anonying, can I not use that but reference the class member? Thanks. Bin
[ "No.\n>>> import this\n...\nExplicit is better than implicit.\n...\n\n", "To reference a class variables, you do not need explicit self. You need it for referencing object (class instance) variables. To reference a class variable, you can simply use that class name, like this:\nclass C:\n x = 1\n def set(se...
[ 6, 3, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004152850_python.txt
Q: sqlite: check reader/writer lock I have 2 processes which both access an sqlite3 database. While reading is not a problem in sqlite, only one process can write to the database. According to the faq: http://www.sqlite.org/faq.html#q5 sqlite uses reader/writer locks. How do i check if the database is locked for writing by another process, both from python and c++? [edit] I mean executing a query is an option, but it takes performance depending on the query. So the question is also what type of query do i use to minimize this effect. I also would like to lock/unlock the database myself. A: When SQLite tries to access a locked database, it's default behaviour is to return SQLITE_BUSY. The documentation describes ways to add custom handling to this event: http://www.sqlite.org/faq.html#q5. I understand from the documentation that any function you call that tries to write to this locked database will simply return SQLITE_BUSY, and that will be your notification that the database is locked. If you are worried about performing a write that won't be completed, you could implement a busy handler callback (sqlite3_busy_handler) in conjuction with a busy timeout (sqlite3_busy_timeout), which would retry the write after x milliseconds. [edit] In http://www.sqlite.org/c3ref/io_methods.html, it mentions a struct of function pointers, one of which is xCheckReservedLock(), which returns true if the file is locked. In this struct are all the other lock related functions. I am unsure about accessing these from outside the sqlite library, but it could be worth investigating. I think you do it through this interface: http://www.sqlite.org/c3ref/file_control.html
sqlite: check reader/writer lock
I have 2 processes which both access an sqlite3 database. While reading is not a problem in sqlite, only one process can write to the database. According to the faq: http://www.sqlite.org/faq.html#q5 sqlite uses reader/writer locks. How do i check if the database is locked for writing by another process, both from python and c++? [edit] I mean executing a query is an option, but it takes performance depending on the query. So the question is also what type of query do i use to minimize this effect. I also would like to lock/unlock the database myself.
[ "When SQLite tries to access a locked database, it's default behaviour is to return SQLITE_BUSY. The documentation describes ways to add custom handling to this event: http://www.sqlite.org/faq.html#q5.\nI understand from the documentation that any function you call that tries to write to this locked database will...
[ 2 ]
[]
[]
[ "c++", "python", "sqlite" ]
stackoverflow_0004153091_c++_python_sqlite.txt
Q: If I have a queue (SQS, AMQP), how do I notify my worker servers when there is an object in it? A lot of times my queue will remain empty. But when it does fill up, how does that queue notify my server to execute a python script? I could make it so that the python script hits the queue every 5 seconds, but that's silly. A: You should have a consumer on the queue, which registers a callback. The consumer will then poll the queue and call the callback when an item is received. You don't say how you're accessing the queue, but a library like carrot does this for you.
If I have a queue (SQS, AMQP), how do I notify my worker servers when there is an object in it?
A lot of times my queue will remain empty. But when it does fill up, how does that queue notify my server to execute a python script? I could make it so that the python script hits the queue every 5 seconds, but that's silly.
[ "You should have a consumer on the queue, which registers a callback. The consumer will then poll the queue and call the callback when an item is received.\nYou don't say how you're accessing the queue, but a library like carrot does this for you.\n" ]
[ 0 ]
[]
[]
[ "amqp", "distributed", "events", "python", "queue" ]
stackoverflow_0004153006_amqp_distributed_events_python_queue.txt
Q: How do I send midi Control Change messages (CC's) using pyPortMidi or pygame? I'm using Python along with Pygame which uses pyPortMidi for it's midi module, and I'm currently sending NoteOn and NoteOff messages through Midi Yoke to Ableton live, which works great. But I can't seem to figure out how I send CC messages.. Anyone? The (working) class basically looks like this. class MidiIO: def __init__(self, device_id = None, inst=0): pygame.midi.init() pygame.fastevent.init() if device_id is None: self.output_id = pygame.midi.get_default_output_id() else: self.output_id = device_id self._print_device_info() port = self.output_id print ("using output_id :%s:" % port) self.midi_out = pygame.midi.Output(port, 0) self.midi_out.set_instrument(inst) self.pressed = False def midiOut(self, btns, note=60, vel=100): if btns == 1: if not self.pressed: self.midi_out.note_on(note, vel) self.pressed = 1 elif btns == 0: self.midi_out.note_off(note) self.pressed = 0 A: It looks like you would use the write_short method to write raw MIDI packets, or the write method if you want to send several of them at once. So, for example, if you want to send the value 123 on controller 17, that would look like this: self.midi_out.write_short(0xb0, 17, 123) The reason you probably didn't notice this in the documentation is that the term "status" is often used in the MIDI protocol to refer to the message type (ie, note on, note off, control change, etc.). A: if you also need a way to send NRPNs , additionally to CCs, drop me a message and I will send you my code, as I am making a midi app with pygame that communicates both with MIDI CCs and NRPNs. By the way be careful with those note on and note off messages. Some synth /midi controllers send the same status message for a note off and note off, while others send diffirent note off and note on status messages. You will have to safeguard that your app is not confused by the status messages . You will have also to check the status messages so to make sure that it is a message and not a CC message, or vice versa, or else you might trigger notes instead of sending CC messages. What I did was to make a simple MIDI receive pygame app that helped me study what the midi messages contained and how they formed while triggering notes and twisting knobs on my Alesis Andromeda A6 synthesizer, using simple print statements. By the way what type of app you are making ? I am very intrested. Good luck!!!
How do I send midi Control Change messages (CC's) using pyPortMidi or pygame?
I'm using Python along with Pygame which uses pyPortMidi for it's midi module, and I'm currently sending NoteOn and NoteOff messages through Midi Yoke to Ableton live, which works great. But I can't seem to figure out how I send CC messages.. Anyone? The (working) class basically looks like this. class MidiIO: def __init__(self, device_id = None, inst=0): pygame.midi.init() pygame.fastevent.init() if device_id is None: self.output_id = pygame.midi.get_default_output_id() else: self.output_id = device_id self._print_device_info() port = self.output_id print ("using output_id :%s:" % port) self.midi_out = pygame.midi.Output(port, 0) self.midi_out.set_instrument(inst) self.pressed = False def midiOut(self, btns, note=60, vel=100): if btns == 1: if not self.pressed: self.midi_out.note_on(note, vel) self.pressed = 1 elif btns == 0: self.midi_out.note_off(note) self.pressed = 0
[ "It looks like you would use the write_short method to write raw MIDI packets, or the write method if you want to send several of them at once. So, for example, if you want to send the value 123 on controller 17, that would look like this:\nself.midi_out.write_short(0xb0, 17, 123)\n\nThe reason you probably didn't...
[ 3, 0 ]
[]
[]
[ "midi", "pygame", "python" ]
stackoverflow_0004011498_midi_pygame_python.txt
Q: Portable Python (Mac -> Windows) I have a lovely Macbook now, and I'm enjoying coding on the move. I'm also enjoying coding in Python. However, I'd like to distribute the end result to friends using Windows, as an executable. I know that Py2Exe does this, but I don't know how portable Python is across operating systems. Can anyone offer any advice? I'm using PyGame too. Many thanks A: The Python scripts are reasonably portable, as long as the interpreter and relevant libraries are installed. Generated .exe and .app files are not. A: Py2exe generates Windows executables, so they will only work on the Windows Platform. The FAQ at http://www.py2exe.org/index.cgi/FAQ has more information on how it all works. Essentially it provides what is needed to run on Win9x as well as more current platforms. NOTE: the FAQ mentions some potential gotchas with character encodings and the work arounds. With python, it is common enough on Unix based systems, as several Linux distributions have their custom maintenance scripts written in the language. So the Python scripts will be just as portable as Ruby scripts, etc. As long as the target machine has the interpreter and you are not using external programs that are only on one type of platform, others will be able to use your work. A: If you are planning to include Linux in your portability criteria, it's worth remembering that many distributions still package 2.6 (or even 2.5), and will probably be a version behind in the 3.x series as well (I'm assuming your using 2.x given the PyGame requirement though). Versions of PyGame seem to vary quite heavily between distros as well. A: Personally I experienced huge difficult with all the Exe builder, py2exe , cx_freeze etc. Bugs and errors all the time , keep displaying an issue with atexit module. I find just by including the python distro way more convinient. There is one more advantage beside ease of use. Each time you build an EXE for a python app, what you essential do is include the core of the python installation but only with the modules your app is using. But even in that case your app may increase from a mere few Kbs that the a python module is to more than 15 mbs because of the inclusion of python installation. Of course installing the whole python will take more space but each time you send your python apps they will be only few kbs long. Plus you want have to go to the hussle of bundling the exe each time you change even a coma to your python app. Or I think you do , I dont know if just replacing the py module can help you avoid this. In any case installing python and pygame is as easy as installing any other application in windows. In linux via synaptic is also extremly easy. MACOS is abit tricky though. MACOS already come with python pre installed, Snow leopard has 2.6.1 python installed. However if you app is using a python later than that and include the install of python with your app, you will have to instruct the user to set via "GET INFO -> open with" the python launcher app which is responsible for launcing python apps to use your version of python and not the onboard default 2.6.1 version, Its not difficult and it only takes a few seconds, even a clueless user can do this. Python is extremely portable, python pygame apps cannot only run unchanged to the three major platform , Windows , MACOS ,Linux . They can even run on mobile and portable devices as well. If you need to build app that runs across platform , python is dead easy and highly recomended.
Portable Python (Mac -> Windows)
I have a lovely Macbook now, and I'm enjoying coding on the move. I'm also enjoying coding in Python. However, I'd like to distribute the end result to friends using Windows, as an executable. I know that Py2Exe does this, but I don't know how portable Python is across operating systems. Can anyone offer any advice? I'm using PyGame too. Many thanks
[ "The Python scripts are reasonably portable, as long as the interpreter and relevant libraries are installed. Generated .exe and .app files are not.\n", "Py2exe generates Windows executables, so they will only work on the Windows Platform. The FAQ at http://www.py2exe.org/index.cgi/FAQ has more information on ho...
[ 3, 2, 0, 0 ]
[]
[]
[ "portability", "pygame", "python" ]
stackoverflow_0004086675_portability_pygame_python.txt
Q: python class property does not evaluated in the if condition I have a python class as follow class Application(models.Model): name = models.CharField(help_text="Application's name",max_length=200) current_status = models.IntegerField(null=True, blank=True) class Meta: ordering = ["name"] @property def status(self): """Returns the current ApplicationStatus object of this Application.""" try: return ApplicationStatus.objects.get(id = self.current_status) except ApplicationStatus.DoesNotExist as e: print e return None In another class I check the property status as in the following statements app = Application() if app.status is None: #do some thing else: print app.status Although I am sure that the status of the application is not None, the else print statement print None and when I try to access the status like app.status.id, the application throws an exception NoneType has no property id. When I changed the condition to: app = Application() st = app.status if st is None: #do some thing else: #do another thing it works fine. Can someone tell my why the python properties does not evaluated in the print statement? A: You said: Although I am sure that the status of the application is not None, the else clause is executed The code you posted is: if app.status is None: #do some thing else: #do another thing If the status is not None then the else clause will be executed. What I can't understand if how the second case is working, since the else clause should be executed here too. A: you said that app.status passed the first if condition (so it's not None) but when you print it, it prints None... that's clear, the first time app.status returns something different from None, the second time something changed and app.status ( wich is evaluated every time) returns None in fact if you store the value returned by app.status in another var ( so it's not modified) it works fine... A: I think the reason is that you are executing 2 times the same code but with a different context : Try this test : print app.status print app.status The first print should be not None, but the second yes : You have to look what changed into the Application object between the two call (do you have signals, etc...) Try to print self.current_status in the status function. A: Maybe the problem is on the ApplicationStatus class. In fact, what you're doing in the non working sample, is invoking "ApplicationStatus.objects.get(id = self.current_status)" twice. Probably, in the first time, it does return a valid value, and does change it's state, so in the second invocation, it does returns None (or throws an ApplicationStatus.DoesNotExist). So, my suggestion: take a look at ApplicationStatus code.
python class property does not evaluated in the if condition
I have a python class as follow class Application(models.Model): name = models.CharField(help_text="Application's name",max_length=200) current_status = models.IntegerField(null=True, blank=True) class Meta: ordering = ["name"] @property def status(self): """Returns the current ApplicationStatus object of this Application.""" try: return ApplicationStatus.objects.get(id = self.current_status) except ApplicationStatus.DoesNotExist as e: print e return None In another class I check the property status as in the following statements app = Application() if app.status is None: #do some thing else: print app.status Although I am sure that the status of the application is not None, the else print statement print None and when I try to access the status like app.status.id, the application throws an exception NoneType has no property id. When I changed the condition to: app = Application() st = app.status if st is None: #do some thing else: #do another thing it works fine. Can someone tell my why the python properties does not evaluated in the print statement?
[ "You said:\n\nAlthough I am sure that the status of the application is not None, the else clause is executed\n\nThe code you posted is:\nif app.status is None:\n #do some thing\nelse:\n #do another thing\n\nIf the status is not None then the else clause will be executed.\nWhat I can't understand if ho...
[ 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004143057_python.txt
Q: Python and Server Load Is there a way, using Python, to check the server load of a Linux machine periodically and inform me of it in some way? A: Python has a function to get the system's load average as part of the os module >>> import os >>> os.getloadavg() (1.1200000000000001, 1.0600000000000001, 0.79000000000000004) From there, you can do whatever checks you need, and then email you, or similar. A: os.getloadavg()
Python and Server Load
Is there a way, using Python, to check the server load of a Linux machine periodically and inform me of it in some way?
[ "Python has a function to get the system's load average as part of the os module\n>>> import os\n>>> os.getloadavg()\n(1.1200000000000001, 1.0600000000000001, 0.79000000000000004)\n\nFrom there, you can do whatever checks you need, and then email you, or similar.\n", "os.getloadavg()\n" ]
[ 48, 9 ]
[]
[]
[ "python" ]
stackoverflow_0004153881_python.txt
Q: python uninstall and update packages I want to update all eggs and uninstall some I installed using easy_install. How could I do that? I've been looking for ways of updating/removing eggs and I find out that it's just one big crap - there is no way to do that other than writing my own software for that. Is that really so great crap that I cannot update/remove all? A: Look at this post.
python uninstall and update packages
I want to update all eggs and uninstall some I installed using easy_install. How could I do that? I've been looking for ways of updating/removing eggs and I find out that it's just one big crap - there is no way to do that other than writing my own software for that. Is that really so great crap that I cannot update/remove all?
[ "Look at this post.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004153873_python.txt
Q: Why is self only a convention and not a real Python keyword? As far as I know, self is just a very powerful convention and it's not really a reserved keyword in Python. Java and C# have this as a keyword. I really find it weird that they didn't make a reserved keyword for it in Python. Is there any reason behind this? A: Because self is just a parameter to a function, like any other parameter. For example, the following call: a = A() a.x() essentially gets converted to: a = A() A.x(a) Not making self a reserved word has had the fortunate result as well that for class methods, you can rename the first parameter to something else (normally cls). And of course for static methods, the first parameter has no relationship to the instance it is called on e.g.: class A: def method(self): pass @classmethod def class_method(cls): pass @staticmethod def static_method(): pass class B(A): pass b = B() b.method() # self is b b.class_method() # cls is B b.static_method() # no parameter passed A: Guido van Rossum has blogged on why explicit self has to stay: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html I believe that post provides some insight into the design decisions behind explicit self. A: Because a method is just a function who's first parameter is used to pass the object. You can write a method like this: class Foo(object): pass def setx(self, x): self.x = x Foo.setx = setx foo = Foo() foo.setx(42) print foo.x # Prints 42. Whatever the merit or otherwise of this philosophy, it does result in a more unified notion of functions and methods.
Why is self only a convention and not a real Python keyword?
As far as I know, self is just a very powerful convention and it's not really a reserved keyword in Python. Java and C# have this as a keyword. I really find it weird that they didn't make a reserved keyword for it in Python. Is there any reason behind this?
[ "Because self is just a parameter to a function, like any other parameter. For example, the following call:\n\na = A()\na.x()\n\nessentially gets converted to:\n\na = A()\nA.x(a)\n\nNot making self a reserved word has had the fortunate result as well that for class methods, you can rename the first parameter to som...
[ 5, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004131582_python.txt
Q: How to use comparison and ' if not' in python? In one piece of my program I doubt if i use the comparison correctly. i want to make sure that ( u0 <= u < u0+step ) before do something. if not (u0 <= u) and (u < u0+step): u0 = u0+ step # change the condition until it is satisfied else: do something. # condition is satisfied A: You can do: if not (u0 <= u <= u0+step): u0 = u0+ step # change the condition until it is satisfied else: do sth. # condition is satisfied Using a loop: while not (u0 <= u <= u0+step): u0 = u0+ step # change the condition until it is satisfied do sth. # condition is satisfied A: Operator precedence in python You can see that not X has higher precedence than and. Which means that the not only apply to the first part (u0 <= u). Write: if not (u0 <= u and u < u0+step): or even if not (u0 <= u < u0+step): A: In this particular case the clearest solution is the S.Lott answer But in some complex logical conditions I would prefer use some boolean algebra to get a clear solution. Using De Morgan's law ¬(A^B) = ¬Av¬B not (u0 <= u and u < u0+step) (not u0 <= u) or (not u < u0+step) u0 > u or u >= u0+step then if u0 > u or u >= u0+step: pass ... in this case the «clear» solution is not more clear :P A: Why think? If not confuses you, switch your if and else clauses around to avoid the negation. i want to make sure that ( u0 <= u < u0+step ) before do sth. Just write that. if u0 <= u < u0+step: "do sth" # What language is "sth"? No vowels. An odd-looking word. else: u0 = u0+ step Why overthink it? If you need an empty if -- and can't work out the logic -- use pass. if some-condition-that's-too-complex-for-me-to-invert: pass else: do real work here A: There are two ways. In case of doubt, you can always just try it. If it does not work, you can add extra braces to make sure, like that: if not ((u0 <= u) and (u < u0+step)):
How to use comparison and ' if not' in python?
In one piece of my program I doubt if i use the comparison correctly. i want to make sure that ( u0 <= u < u0+step ) before do something. if not (u0 <= u) and (u < u0+step): u0 = u0+ step # change the condition until it is satisfied else: do something. # condition is satisfied
[ "You can do:\nif not (u0 <= u <= u0+step):\n u0 = u0+ step # change the condition until it is satisfied\nelse:\n do sth. # condition is satisfied\n\nUsing a loop:\nwhile not (u0 <= u <= u0+step):\n u0 = u0+ step # change the condition until it is satisfied\ndo sth. # condition is satisfied\n\n", "Operator...
[ 57, 10, 4, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004153260_python.txt
Q: Anyone know of a C++ or Python library that will divide an image into pieces of arbitrary shape? I'm working on a project involving puzzles made out of user-supplied images. I have been very hard-pressed to find a library that will serve my purposes. I would like to write the program in either Python or C++. I have been considering using Qt (or PyQt) to do it, so if you know of a library that will work with Qt it would be nice, though at this point anything would be nice. A: You can't expect to find a library for any specific task. In this case, you need image-processing library, which is able to: draw image region with transparent background. You have piece configuration, use it as a mask to cut out edges. save drawn image to some format. Qt graphics is totally able to do all that.
Anyone know of a C++ or Python library that will divide an image into pieces of arbitrary shape?
I'm working on a project involving puzzles made out of user-supplied images. I have been very hard-pressed to find a library that will serve my purposes. I would like to write the program in either Python or C++. I have been considering using Qt (or PyQt) to do it, so if you know of a library that will work with Qt it would be nice, though at this point anything would be nice.
[ "You can't expect to find a library for any specific task. In this case, you need image-processing library, which is able to:\n\ndraw image region with transparent background. You have piece configuration, use it as a mask to cut out edges.\nsave drawn image to some format.\n\nQt graphics is totally able to do all ...
[ 2 ]
[]
[]
[ "c++", "image_processing", "pyqt", "python", "qt" ]
stackoverflow_0004151746_c++_image_processing_pyqt_python_qt.txt
Q: Python - generate the time difference I am trying to generate a report for the usage statistics.Below is the sample data that i have in in an array and this is fetched from Mysql table.How to implement a logic saying that if the user is idle for more than 30 minutes he has not used the system else calculate the time mean time of the usage. timestamp=[] for i in timestamp: print i 2010-04-20 10:07:30 2010-04-20 10:07:38 2010-04-20 10:07:52 2010-04-20 10:08:22 2010-04-20 10:08:22 2010-04-20 10:09:46 2010-04-20 10:10:37 2010-04-20 10:10:58 2010-04-20 10:11:50 2010-04-20 10:12:13 2010-04-20 10:12:13 2010-04-20 10:25:38 2010-04-20 10:26:01 2010-04-20 10:26:01 2010-04-20 10:26:06 2010-04-20 10:26:29 2010-04-20 10:26:29 2010-04-20 10:26:35 2010-04-20 10:27:21 2010-04-20 01:32:46 2010-04-20 01:32:47 2010-04-20 01:32:57 2010-04-20 01:32:59 2010-04-20 01:33:03 2010-04-20 01:33:03 2010-04-20 01:33:05 2010-04-20 01:33:11 2010-04-20 01:33:15 2010-04-20 01:34:49 2010-04-20 01:34:55 2010-04-20 01:35:02 2010-04-20 01:35:17 2010-04-20 01:35:20 2010-04-20 01:36:49 2010-04-20 01:36:52 2010-04-20 01:36:52 2010-04-20 01:37:11 2010-04-20 01:37:15 2010-04-20 01:37:17 2010-04-20 01:50:11 2010-04-20 01:50:15 2010-04-20 01:50:18 2010-04-20 01:50:20 2010-04-20 01:50:33 2010-04-20 01:50:36 2010-04-20 01:51:56 A: I think this is what you want. It goes through the list calculating the difference between each entry and the previous one. If the difference is bigger than or equal 30 minutes it ignores it. If it is less than 30 minutes it adds it to the total usage for that user. (I'm assuming all the timestamps are for the same user.) from datetime import datetime,timedelta # Convert the timestamps to datetime objects usetimes = sorted(datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in timestamp) # Set the idle time to compare with later idletime = timedelta(minutes = 30) # Start the running total with a timedelta of 0 usage = timedelta() last = usetimes[0] for d in usetimes[1:]: delta = d - last if delta < idletime: usage += delta last = d print "total usage:",usage If you want to use sum() and zip() you can cut down the lines of code, but I'm not sure if it's as readable: from datetime import datetime,timedelta usetimes = sorted(datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in timestamp) idletime = timedelta(minutes = 30) usage = sum((x - y for x,y in zip(usetimes[1:],usetimes[:-1]) if x - y < idletime),timedelta()) print "total usage:", usage In this case, if the list of timestamps is very long you could consider using izip from itertools instead of zip.
Python - generate the time difference
I am trying to generate a report for the usage statistics.Below is the sample data that i have in in an array and this is fetched from Mysql table.How to implement a logic saying that if the user is idle for more than 30 minutes he has not used the system else calculate the time mean time of the usage. timestamp=[] for i in timestamp: print i 2010-04-20 10:07:30 2010-04-20 10:07:38 2010-04-20 10:07:52 2010-04-20 10:08:22 2010-04-20 10:08:22 2010-04-20 10:09:46 2010-04-20 10:10:37 2010-04-20 10:10:58 2010-04-20 10:11:50 2010-04-20 10:12:13 2010-04-20 10:12:13 2010-04-20 10:25:38 2010-04-20 10:26:01 2010-04-20 10:26:01 2010-04-20 10:26:06 2010-04-20 10:26:29 2010-04-20 10:26:29 2010-04-20 10:26:35 2010-04-20 10:27:21 2010-04-20 01:32:46 2010-04-20 01:32:47 2010-04-20 01:32:57 2010-04-20 01:32:59 2010-04-20 01:33:03 2010-04-20 01:33:03 2010-04-20 01:33:05 2010-04-20 01:33:11 2010-04-20 01:33:15 2010-04-20 01:34:49 2010-04-20 01:34:55 2010-04-20 01:35:02 2010-04-20 01:35:17 2010-04-20 01:35:20 2010-04-20 01:36:49 2010-04-20 01:36:52 2010-04-20 01:36:52 2010-04-20 01:37:11 2010-04-20 01:37:15 2010-04-20 01:37:17 2010-04-20 01:50:11 2010-04-20 01:50:15 2010-04-20 01:50:18 2010-04-20 01:50:20 2010-04-20 01:50:33 2010-04-20 01:50:36 2010-04-20 01:51:56
[ "I think this is what you want. It goes through the list calculating the difference between each entry and the previous one. If the difference is bigger than or equal 30 minutes it ignores it. If it is less than 30 minutes it adds it to the total usage for that user. (I'm assuming all the timestamps are for the ...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0004154116_python.txt
Q: 0A hex bug on writing to file? I have a little problem: why does this code somefile = open('foo.txt', 'w') somefile.write('0B0B0B'.decode('hex')) somefile.close() write 0B0B0B in file, and this code somefile = open('foo.txt', 'w') somefile.write('0A0A0A'.decode('hex')) somefile.close() write 0D0A0D0A0D0A in file? Where does that '0D' come from? A: It comes from the \n -> \r\n transformation due to the fact that you're running on Windows. Open the file in binary mode ('wb') if you want to avoid this.
0A hex bug on writing to file?
I have a little problem: why does this code somefile = open('foo.txt', 'w') somefile.write('0B0B0B'.decode('hex')) somefile.close() write 0B0B0B in file, and this code somefile = open('foo.txt', 'w') somefile.write('0A0A0A'.decode('hex')) somefile.close() write 0D0A0D0A0D0A in file? Where does that '0D' come from?
[ "It comes from the \\n -> \\r\\n transformation due to the fact that you're running on Windows. Open the file in binary mode ('wb') if you want to avoid this.\n" ]
[ 9 ]
[]
[]
[ "hex", "python" ]
stackoverflow_0004154369_hex_python.txt
Q: JavaScript, Django, and Google App Engine - Replace Text My goal is to associate a tooltip (containing a definition) to certain words on the client side using JS. The text is generated with Django/Python (from a GAE datastore). To accomplish this, I need to scan a block of text for multiple key words that require definitions and dynamically create a html 'title' for the tooltip. I have succesfully done this for one key word at a time, however, I seem to be unable to do a search for and replace multiple values within the same block of text (when I try to accomplish with a django forloop, the entire original string appears once for each replace command - see below). My code: var str="<p>Paragraph of text containing key words such as test1 and test2! </p>"; {% for i in thing %} document.write(str.replace(/{{i.word}}/gi, "<strong><a title='{{i.tooltip}}'> {{i.word}}</a></strong>")); {% endfor %} This results in: "Paragraph of text containing key words such as keyword1 and keyword2! Paragraph of text containing key words such as keyword1 and keyword2!" My desired output is: "Paragraph of text containing key words such as keyword1 and keyword2!" Any assistance would be greatly appreciated, I have a very limited knowledge in JS. A: The easiest way to do this would be to simply build up the string within the Django for loop, replacing on it each time, then only outputting it at the end: {% for i in thing %} str = str.replace(/{{i.word}}/gi, "<strong><a title='{{i.tooltip}}'> {{i.word}}</a></strong>")); {% endfor %} document.write(str);
JavaScript, Django, and Google App Engine - Replace Text
My goal is to associate a tooltip (containing a definition) to certain words on the client side using JS. The text is generated with Django/Python (from a GAE datastore). To accomplish this, I need to scan a block of text for multiple key words that require definitions and dynamically create a html 'title' for the tooltip. I have succesfully done this for one key word at a time, however, I seem to be unable to do a search for and replace multiple values within the same block of text (when I try to accomplish with a django forloop, the entire original string appears once for each replace command - see below). My code: var str="<p>Paragraph of text containing key words such as test1 and test2! </p>"; {% for i in thing %} document.write(str.replace(/{{i.word}}/gi, "<strong><a title='{{i.tooltip}}'> {{i.word}}</a></strong>")); {% endfor %} This results in: "Paragraph of text containing key words such as keyword1 and keyword2! Paragraph of text containing key words such as keyword1 and keyword2!" My desired output is: "Paragraph of text containing key words such as keyword1 and keyword2!" Any assistance would be greatly appreciated, I have a very limited knowledge in JS.
[ "The easiest way to do this would be to simply build up the string within the Django for loop, replacing on it each time, then only outputting it at the end:\n{% for i in thing %}\nstr = str.replace(/{{i.word}}/gi, \"<strong><a title='{{i.tooltip}}'> {{i.word}}</a></strong>\"));\n{% endfor %}\ndocument.write(str);\...
[ 1 ]
[]
[]
[ "django", "google_app_engine", "javascript", "python", "str_replace" ]
stackoverflow_0004154317_django_google_app_engine_javascript_python_str_replace.txt
Q: Python script to switch user automatically I'm working on windows xp. How can i write a simple script which would automatically log me out of this account and log into another account on this computer upon execution of a trigger point I set in my application?? Please help. A: What do you need to do on another account? If you want to run some commands on another account os.system and runas will help you. A: To logoff, call ExitWindowsEx() with EWX_LOGOFF (0). To automatically login afterwards, write DefaultUserName and DefaultPassword to HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon. You may also need to set AutoAdminLogon to 1. Don't forget to later remove the registry keys or it'll just keep logging into that user forever. In python, you can use ctypes to call the function and _winreg to write to the registry. # setup login from _winreg import * key = OpenKey(HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon', 0, KEY_ALL_ACCESS) SetValueEx(key, "DefaultUserName", 0, REG_SZ, "username") SetValueEx(key, "DefaultPassword", 0, REG_SZ, "password") SetValueEx(key, "AutoAdminLogon", 0, REG_DWORD, 1) CloseKey(key) # logoff import ctypes ctypes.windll.user32.ExitWindowsEx(0,0) A: I'm going to go out on a limb here, and suggest there probably isn't any Python library that can do this directly. Instead, you will need to call some C win32 functions from Python. I think your best bet is to split this up into two separate questions. The first question is "How do I programmatically, in Win32, initiate a log-out and log in as a different user?" That will hopefully be answered by some Windows expert, even if they are unfamiliar with Python. I don't know much about this, but it sounds awfully ambitious. Triggering a log-out might be possible, but triggering a log-in as a different user (presumably stopping to ask the user for a password) The second question is "How do I call these win32 functions from within Python?" That is a fairly regular request and there should be the expertise on StackOverflow to help.
Python script to switch user automatically
I'm working on windows xp. How can i write a simple script which would automatically log me out of this account and log into another account on this computer upon execution of a trigger point I set in my application?? Please help.
[ "What do you need to do on another account? If you want to run some commands on another account os.system and runas will help you.\n", "To logoff, call ExitWindowsEx() with EWX_LOGOFF (0). To automatically login afterwards, write DefaultUserName and DefaultPassword to HKLM\\SOFTWARE\\Microsoft\\Windows NT\\Curren...
[ 3, 2, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0004153969_python_windows.txt
Q: Python YouTube Gdata Player Error I'm trying something really simple: get a list of player urls from the youtube gdata module, def getlist(): index = 1 prev = 0 urls = [] while True: uri = "http://gdata.youtube.com/feeds/api/playlists/E005D335B57338D1?start-index=%i&max-results=50" % index feed = yt_service.GetYouTubeVideoFeed(uri) for entry in feed.entry: urls.append(entry.media.player.url) if prev == len(urls): break prev = len(urls) index += 50 return urls However, the following error occurs when calling getlist: >>> urls = getlist() Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> getlist() File "<pyshell#1>", line 9, in getlist urls.append(entry.media.player.url) AttributeError: 'NoneType' object has no attribute 'url' I have no idea why this is happening, it worked a couple weeks ago... Any ideas? A: You should add a check to guarantee that the player is not null: ... for entry in feed.entry: if entry.media.player is not None: urls.append(entry.media.player.url) ...
Python YouTube Gdata Player Error
I'm trying something really simple: get a list of player urls from the youtube gdata module, def getlist(): index = 1 prev = 0 urls = [] while True: uri = "http://gdata.youtube.com/feeds/api/playlists/E005D335B57338D1?start-index=%i&max-results=50" % index feed = yt_service.GetYouTubeVideoFeed(uri) for entry in feed.entry: urls.append(entry.media.player.url) if prev == len(urls): break prev = len(urls) index += 50 return urls However, the following error occurs when calling getlist: >>> urls = getlist() Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> getlist() File "<pyshell#1>", line 9, in getlist urls.append(entry.media.player.url) AttributeError: 'NoneType' object has no attribute 'url' I have no idea why this is happening, it worked a couple weeks ago... Any ideas?
[ "You should add a check to guarantee that the player is not null:\n...\nfor entry in feed.entry:\n if entry.media.player is not None:\n urls.append(entry.media.player.url)\n...\n\n" ]
[ 1 ]
[]
[]
[ "gdata", "python", "youtube" ]
stackoverflow_0003938703_gdata_python_youtube.txt
Q: Capturing tablet data at constant rate, instead of at frame rate (python, pygame, wintab, cgkit) First of all, I am not a veteran programmer i any language. But I've been tinkering with python pretty substantially the last couple of months so I wouldn't consider my self completely green either. Some keywords for you: - Windows - Python 2.6 - Pygame, CGKit Okay, so I've got the CGKit module, which contains a WinTab wrapper for capturing data from the Wacom tablet. WinTab requires a certain window to be active in order for it to start capturing, and for that I'm using PyGame. However, PyGame is pretty brutal on the CPU and gives me between 100-200 fps on drawing simple text and rectangles (meters for the wacom input data.) and about 200-400 fps when not 'blitting' anything. Now, the tablet hardware, and the WinTab API support a transfer rate of 200hz, which is all good. The problem is that the data I'm getting from WinTab isn't at 200hz (5ms per packet) but is instead at the current framerate of my PyGame window, which, on top of everything, is not static. So you see the problem. In order for WinTab to acquire any data, it has to have a window assigned to it and it need to be 'active'. But having a PyGame window open, means that the stream of data is limited to the framerate of the pygame window. I'm sure there are other window managers I could be using that won't take up any or little CPU, but what I'd really like is for WinTab to acquire the data at constant 200hz rate without any dependencies. I'm thinking threading. Breaking up the gather-data and drawing parts, but since WinTab need a window to get any data in the first place, I can't figure out how that would be possible. Also note that I've never threaded anything before, although I do understand the concept. So, hope I made the problem reasonably clear. The question is, how can I get the data at a minimum of 200hz, while still being able to do maybe 20-30 fps on my PyGame window? A: without being experienced on the subject, I would say that threads are not a good idea for precise timing functions. From what I studied there is not a precise timing enforced on them . I remember there is a function inside the time pygame module that forces your code to run at a specific time and thus limits the FPS. That is for if your code runs too fast. Now if your app is proving too slow for the 200Mhz rate, that is it takes more than 5ms to loop then you will have to move some of your code to C/C++ domain and avoid using pygame for at least that part. I advice using cython , since cython allow you to write only python code and you dont need to know C/C++. But of course you can mix python with C/C++ and even Fortran with cython, its extremely flexible and easy to use. Cython Website My experience with pygame on an Atom 1,6 processor , which is of course very slow, gave me 1 ms for zero redraws, so pygame can be really fast but not blazzing fast. It will highly depend on what you draw in the screen during your loop. I would guess that on a core duo that 1 ms should drop to at least 0.3 ms. So it will also depend on your processing speed. Another approach is the multiprocessing module, which it can take full avantage of multiple cores and assign one core for your app and another core for receiving data from the tablet. Multiprocessing module documentation There are literally hundrends of ways to speed up python.
Capturing tablet data at constant rate, instead of at frame rate (python, pygame, wintab, cgkit)
First of all, I am not a veteran programmer i any language. But I've been tinkering with python pretty substantially the last couple of months so I wouldn't consider my self completely green either. Some keywords for you: - Windows - Python 2.6 - Pygame, CGKit Okay, so I've got the CGKit module, which contains a WinTab wrapper for capturing data from the Wacom tablet. WinTab requires a certain window to be active in order for it to start capturing, and for that I'm using PyGame. However, PyGame is pretty brutal on the CPU and gives me between 100-200 fps on drawing simple text and rectangles (meters for the wacom input data.) and about 200-400 fps when not 'blitting' anything. Now, the tablet hardware, and the WinTab API support a transfer rate of 200hz, which is all good. The problem is that the data I'm getting from WinTab isn't at 200hz (5ms per packet) but is instead at the current framerate of my PyGame window, which, on top of everything, is not static. So you see the problem. In order for WinTab to acquire any data, it has to have a window assigned to it and it need to be 'active'. But having a PyGame window open, means that the stream of data is limited to the framerate of the pygame window. I'm sure there are other window managers I could be using that won't take up any or little CPU, but what I'd really like is for WinTab to acquire the data at constant 200hz rate without any dependencies. I'm thinking threading. Breaking up the gather-data and drawing parts, but since WinTab need a window to get any data in the first place, I can't figure out how that would be possible. Also note that I've never threaded anything before, although I do understand the concept. So, hope I made the problem reasonably clear. The question is, how can I get the data at a minimum of 200hz, while still being able to do maybe 20-30 fps on my PyGame window?
[ "without being experienced on the subject, I would say that threads are not a good idea for precise timing functions. From what I studied there is not a precise timing enforced on them . \nI remember there is a function inside the time pygame module that forces your code to run at a specific time and thus limits th...
[ 1 ]
[]
[]
[ "pygame", "python", "windows" ]
stackoverflow_0003993900_pygame_python_windows.txt
Q: How to see "Actual execution plan" of our query in python? I have a sql query in python which is pretty slow, it contain some inner join, And some one suggest that in this case we can: turn on the "Show Actual Execution Plan" option and then take a close look at what is causing the slowdown. Here some one has similar prolem as me : Slow SQL Query due to inner and left join? Does anyone know how can I see the "Actual Execution Plan" and "estimated Execution Plan" in sqlite inside a python script? I found some defenitions here : http://www.simple-talk.com/sql/performance/execution-plan-basics/ But still don't know how to do it in python, Any recommendation? cheers Atieh A: You issue the EXPLAIN query the same as you would any other query.
How to see "Actual execution plan" of our query in python?
I have a sql query in python which is pretty slow, it contain some inner join, And some one suggest that in this case we can: turn on the "Show Actual Execution Plan" option and then take a close look at what is causing the slowdown. Here some one has similar prolem as me : Slow SQL Query due to inner and left join? Does anyone know how can I see the "Actual Execution Plan" and "estimated Execution Plan" in sqlite inside a python script? I found some defenitions here : http://www.simple-talk.com/sql/performance/execution-plan-basics/ But still don't know how to do it in python, Any recommendation? cheers Atieh
[ "You issue the EXPLAIN query the same as you would any other query.\n" ]
[ 4 ]
[]
[]
[ "python", "sql_execution_plan", "sqlite" ]
stackoverflow_0004155046_python_sql_execution_plan_sqlite.txt
Q: AttributeError: 'myWindow' object has no attribute 'txtFirstName' I'm trying to make a simple PyQT4 application that will let me show the text from two textboxes in a single message box. It's pretty straight forward, so I'm sure I'm missing something really tiny. Thanks for your help. import sys from PyQt4 import QtGui, QtCore class myWindow(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) #The setGeometry method is used to position the control. #Order: X, Y position - Width, Height of control. self.resize(500,350) self.center() self.setWindowTitle("Sergio's QT Application.") self.setWindowIcon(QtGui.QIcon('menuScreenFolderShadow.png')) self.setToolTip('<i>Welcome</i> to the <b>first</b> app ever!') QtGui.QToolTip.setFont(QtGui.QFont('Helvetica', 12)) txtFirstName = QtGui.QLineEdit('', self) txtFirstName.setGeometry(35, 35, 150, 20) txtLastName = QtGui.QLineEdit('', self) txtLastName.setGeometry(35, 60, 150, 20) btnSubmit = QtGui.QPushButton('Say hello.', self) btnSubmit.setGeometry(340, 250, 150, 35) self.connect(btnSubmit, QtCore.SIGNAL("clicked()"), self.clicked) btnQuit = QtGui.QPushButton('Exit Application', self) btnQuit.setGeometry(340, 300, 150, 35) self.connect(btnQuit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) def clicked(self): QtGui.QMessageBox.about(self, "Just dropped by to say hi!", "Welcome to this tutorial %s %s!" % ( self.txtFirstName.text(), self.txtLastName.text())) def center(self): screen = QtGui.QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) app = QtGui.QApplication(sys.argv) mainForm = myWindow() mainForm.show() sys.exit(app.exec_()) Here's the error message I receive: Traceback (most recent call last): File "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\PyQTTests\src\pyqttests.py", line 36, in clicked self.txtFirstName.text(), self.txtLastName.text())) AttributeError: 'myWindow' object has no attribute 'txtFirstName' A: The problem is in __init__, where txtLastName is created. It's not created as a class member, but rather as a local variable inside the __init__ method. To make it a class member you can later refer to, use self.: self.txtFirstName = QtGui.QLineEdit('', self) self.txtFirstName.setGeometry(35, 35, 150, 20) self.txtLastName = QtGui.QLineEdit('', self) self.txtLastName.setGeometry(35, 60, 150, 20)
AttributeError: 'myWindow' object has no attribute 'txtFirstName'
I'm trying to make a simple PyQT4 application that will let me show the text from two textboxes in a single message box. It's pretty straight forward, so I'm sure I'm missing something really tiny. Thanks for your help. import sys from PyQt4 import QtGui, QtCore class myWindow(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) #The setGeometry method is used to position the control. #Order: X, Y position - Width, Height of control. self.resize(500,350) self.center() self.setWindowTitle("Sergio's QT Application.") self.setWindowIcon(QtGui.QIcon('menuScreenFolderShadow.png')) self.setToolTip('<i>Welcome</i> to the <b>first</b> app ever!') QtGui.QToolTip.setFont(QtGui.QFont('Helvetica', 12)) txtFirstName = QtGui.QLineEdit('', self) txtFirstName.setGeometry(35, 35, 150, 20) txtLastName = QtGui.QLineEdit('', self) txtLastName.setGeometry(35, 60, 150, 20) btnSubmit = QtGui.QPushButton('Say hello.', self) btnSubmit.setGeometry(340, 250, 150, 35) self.connect(btnSubmit, QtCore.SIGNAL("clicked()"), self.clicked) btnQuit = QtGui.QPushButton('Exit Application', self) btnQuit.setGeometry(340, 300, 150, 35) self.connect(btnQuit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) def clicked(self): QtGui.QMessageBox.about(self, "Just dropped by to say hi!", "Welcome to this tutorial %s %s!" % ( self.txtFirstName.text(), self.txtLastName.text())) def center(self): screen = QtGui.QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) app = QtGui.QApplication(sys.argv) mainForm = myWindow() mainForm.show() sys.exit(app.exec_()) Here's the error message I receive: Traceback (most recent call last): File "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\PyQTTests\src\pyqttests.py", line 36, in clicked self.txtFirstName.text(), self.txtLastName.text())) AttributeError: 'myWindow' object has no attribute 'txtFirstName'
[ "The problem is in __init__, where txtLastName is created. It's not created as a class member, but rather as a local variable inside the __init__ method. To make it a class member you can later refer to, use self.: \n self.txtFirstName = QtGui.QLineEdit('', self)\n self.txtFirstName.setGeometry(35, 35, 150, 2...
[ 3 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0004155559_pyqt_python.txt
Q: How can I display a picture on a control in PyQt4? I'd like to display a picture on my form using PyQt4. Here is my code: import sys from PyQt4 import QtGui, QtCore class myWindow(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) #The setGeometry method is used to position the control. #Order: X, Y position - Width, Height of control. self.resize(500,350) self.center() self.setWindowTitle("Sergio's QT Application.") self.setWindowIcon(QtGui.QIcon('menuScreenFolderShadow.png')) self.setToolTip('<i>Welcome</i> to the <b>first</b> app ever!') QtGui.QToolTip.setFont(QtGui.QFont('Helvetica', 12)) self.txtFirstName = QtGui.QLineEdit('', self) self.txtFirstName.setGeometry(35, 35, 150, 20) self.txtLastName = QtGui.QLineEdit('', self) self.txtLastName.setGeometry(35, 60, 150, 20) self.pictureA = QtGui.QIcon("C:\Users\Sergio.Tapia\Downloads\Palm.png") self.pictureA.setGeometry(128,128, 200, 200) btnSubmit = QtGui.QPushButton('Say hello.', self) btnSubmit.setGeometry(340, 250, 150, 35) self.connect(btnSubmit, QtCore.SIGNAL("clicked()"), self.clicked) btnQuit = QtGui.QPushButton('Exit Application', self) btnQuit.setGeometry(340, 300, 150, 35) self.connect(btnQuit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) def clicked(self): QtGui.QMessageBox.about(self, "Just dropped by to say hi!", "Welcome to this tutorial %s %s!" % ( self.txtFirstName.text(), self.txtLastName.text())) def center(self): screen = QtGui.QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) app = QtGui.QApplication(sys.argv) mainForm = myWindow() mainForm.show() sys.exit(app.exec_()) It says that: Traceback (most recent call last): File "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\PyQTTests\src\pyqttests.py", line 47, in mainForm = myWindow() File "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\PyQTTests\src\pyqttests.py", line 25, in init self.pictureA.setGeometry(128,128, 200, 200) AttributeError: 'QIcon' object has no attribute 'setGeometry' If I remove that setGeometry line, the application launches but the picture isn't displayed anywhere. Thanks for the help! A: There are many ways, for example using the QPixmap class. Once again, I encourage you to take a look at the examples available with PyQt. For example, examples\animation\appchooser\, or examples\widgets\icons\
How can I display a picture on a control in PyQt4?
I'd like to display a picture on my form using PyQt4. Here is my code: import sys from PyQt4 import QtGui, QtCore class myWindow(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) #The setGeometry method is used to position the control. #Order: X, Y position - Width, Height of control. self.resize(500,350) self.center() self.setWindowTitle("Sergio's QT Application.") self.setWindowIcon(QtGui.QIcon('menuScreenFolderShadow.png')) self.setToolTip('<i>Welcome</i> to the <b>first</b> app ever!') QtGui.QToolTip.setFont(QtGui.QFont('Helvetica', 12)) self.txtFirstName = QtGui.QLineEdit('', self) self.txtFirstName.setGeometry(35, 35, 150, 20) self.txtLastName = QtGui.QLineEdit('', self) self.txtLastName.setGeometry(35, 60, 150, 20) self.pictureA = QtGui.QIcon("C:\Users\Sergio.Tapia\Downloads\Palm.png") self.pictureA.setGeometry(128,128, 200, 200) btnSubmit = QtGui.QPushButton('Say hello.', self) btnSubmit.setGeometry(340, 250, 150, 35) self.connect(btnSubmit, QtCore.SIGNAL("clicked()"), self.clicked) btnQuit = QtGui.QPushButton('Exit Application', self) btnQuit.setGeometry(340, 300, 150, 35) self.connect(btnQuit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) def clicked(self): QtGui.QMessageBox.about(self, "Just dropped by to say hi!", "Welcome to this tutorial %s %s!" % ( self.txtFirstName.text(), self.txtLastName.text())) def center(self): screen = QtGui.QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) app = QtGui.QApplication(sys.argv) mainForm = myWindow() mainForm.show() sys.exit(app.exec_()) It says that: Traceback (most recent call last): File "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\PyQTTests\src\pyqttests.py", line 47, in mainForm = myWindow() File "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\PyQTTests\src\pyqttests.py", line 25, in init self.pictureA.setGeometry(128,128, 200, 200) AttributeError: 'QIcon' object has no attribute 'setGeometry' If I remove that setGeometry line, the application launches but the picture isn't displayed anywhere. Thanks for the help!
[ "There are many ways, for example using the QPixmap class. Once again, I encourage you to take a look at the examples available with PyQt. For example, examples\\animation\\appchooser\\, or examples\\widgets\\icons\\\n" ]
[ 1 ]
[]
[]
[ "image", "pyqt", "python" ]
stackoverflow_0004155752_image_pyqt_python.txt
Q: match a paragraph starts with some letter I have a file that contains paragraphs starting with AB, I wanted to get all these paragraphs, I used the following code, but it returns nothing: import re paragraphs = re.findall(r'AB[.\n]+AD',text) #AD is the beginning of the next paragraph Any idea why did not this work? Thanks A: Try: re.findall(r'AB.+?(?=AD)', text, re.DOTALL) The re.DOTALL flag will let the dot cover everything included the newlines. And (?=AD) will match everything up to the last character before AD, but will not include AD into the matched string. You can then rstrip() the resulting strings to remove all newlines from the end. A: from the python re module documentation: [] Used to indicate a set of characters. Characters can be listed individually, or a range of characters can be indicated by giving two characters and separating them by a '-'. Special characters are not active inside sets. this means that . inside the brackets matches a dot, and not any character as it would anywhere else in a regexp.
match a paragraph starts with some letter
I have a file that contains paragraphs starting with AB, I wanted to get all these paragraphs, I used the following code, but it returns nothing: import re paragraphs = re.findall(r'AB[.\n]+AD',text) #AD is the beginning of the next paragraph Any idea why did not this work? Thanks
[ "Try:\nre.findall(r'AB.+?(?=AD)', text, re.DOTALL)\n\nThe re.DOTALL flag will let the dot cover everything included the newlines. And (?=AD) will match everything up to the last character before AD, but will not include AD into the matched string.\nYou can then rstrip() the resulting strings to remove all newlines ...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004155794_python_regex.txt
Q: Starting jython program from python using subprocess module? I have a jython server script (called rajant_server.py) that interacts with a java api file to communicate over special network radios. I have a python program which acts as a client (and does several other things as well). Currently, I have to start the server first by opening a command/terminal window and typing: cd [path to directory containing rajant_server.py jython rajant_server.py Once the server successfully connects it waits for the client, which I start by running: cd [path to directory containing python client program] python main.py When the client connects, the server prints out information (currently for debug) in it's command/terminal window, and the client program prints out debug information in it's command/terminal window. What I want to do is do away with the complex process by calling jython from my 'main.py' program using the subprocess module. The problem is two fold: 1 - I need the rajant_server.py program to open in it's own terminal/command window 2 - jython needs to be run in the directory where the rajant_server.py file is stored, in other words, typing the following into the command/Terminal Window doesn't work (don't ask me why): jython C:/code_dir/comm/server/rajant_server.py but: cd C:/code_dir/comm/server jython rajant_server.py does work. Okay... I just got something to work. It seems like a bit of a hack, so I would still love ideas on a better approach. Here is what I am currently doing: serverfile = r'rajant_server_v2.py' serverpath = os.path.join(os.path.realpath('.'),'Comm',serverfile) serverpath = os.path.normpath(serverpath) [path,file] = os.path.split(serverpath) command = '/C jython '+file+'\n' savedir = os.getcwd() os.chdir(path) rajantserver = subprocess.Popen(["cmd",command],\ creationflags = subprocess.CREATE_NEW_CONSOLE) #Change Directory back os.chdir(savedir) #Start Client rajant = rajant_comm.rajant_comm() rajant.start() If you have a solution that will work in both linux & windows you would be my hero. For some reason I couldn't change the stdin or stdout specifications on the subprocess when I added creationflags = subprocess.CREATE_NEW_CONSOLE. A: The Popen function in subprocess accepts an optional parameter 'cwd', to define the current working directory of the child process. rajantserver = subprocess.Popen(["cmd",command],\ creationflags = subprocess.CREATE_NEW_CONSOLE,\ cwd = path) You can get rid of the os.getcwd call and the two os.chdir calls this way. If you want to be able to use this script on Linux, you have to do without 'cmd'. So call Popen with ["jython", file] as first argument. EDIT: I've just seen that CREATE_NEW_CONSOLE is not defined in the subprocess module when running on Linux. Use this: creationflags = getattr(subprocess,"CREATE_NEW_CONSOLE",0),\ This will be the same as before, except it falls back to the default value 0 when the subprocess module does not define CREATE_NEW_CONSOLE.
Starting jython program from python using subprocess module?
I have a jython server script (called rajant_server.py) that interacts with a java api file to communicate over special network radios. I have a python program which acts as a client (and does several other things as well). Currently, I have to start the server first by opening a command/terminal window and typing: cd [path to directory containing rajant_server.py jython rajant_server.py Once the server successfully connects it waits for the client, which I start by running: cd [path to directory containing python client program] python main.py When the client connects, the server prints out information (currently for debug) in it's command/terminal window, and the client program prints out debug information in it's command/terminal window. What I want to do is do away with the complex process by calling jython from my 'main.py' program using the subprocess module. The problem is two fold: 1 - I need the rajant_server.py program to open in it's own terminal/command window 2 - jython needs to be run in the directory where the rajant_server.py file is stored, in other words, typing the following into the command/Terminal Window doesn't work (don't ask me why): jython C:/code_dir/comm/server/rajant_server.py but: cd C:/code_dir/comm/server jython rajant_server.py does work. Okay... I just got something to work. It seems like a bit of a hack, so I would still love ideas on a better approach. Here is what I am currently doing: serverfile = r'rajant_server_v2.py' serverpath = os.path.join(os.path.realpath('.'),'Comm',serverfile) serverpath = os.path.normpath(serverpath) [path,file] = os.path.split(serverpath) command = '/C jython '+file+'\n' savedir = os.getcwd() os.chdir(path) rajantserver = subprocess.Popen(["cmd",command],\ creationflags = subprocess.CREATE_NEW_CONSOLE) #Change Directory back os.chdir(savedir) #Start Client rajant = rajant_comm.rajant_comm() rajant.start() If you have a solution that will work in both linux & windows you would be my hero. For some reason I couldn't change the stdin or stdout specifications on the subprocess when I added creationflags = subprocess.CREATE_NEW_CONSOLE.
[ "The Popen function in subprocess accepts an optional parameter 'cwd', to define the current working directory of the child process.\nrajantserver = subprocess.Popen([\"cmd\",command],\\\n creationflags = subprocess.CREATE_NEW_CONSOLE,\\\n cwd = path)\n\nYou can get rid of the os.getcwd call and the t...
[ 1 ]
[]
[]
[ "jython", "python", "subprocess" ]
stackoverflow_0004129883_jython_python_subprocess.txt
Q: Good tutorials on profiling and speeding up bottlenecks in python with C/C++ looking to learn more about the above. Any recommendations for packages and tutorials about the above ? A: The Python extension documentation does a pretty good job of describing how to create C-extensions for your bottlenecks.
Good tutorials on profiling and speeding up bottlenecks in python with C/C++
looking to learn more about the above. Any recommendations for packages and tutorials about the above ?
[ "The Python extension documentation does a pretty good job of describing how to create C-extensions for your bottlenecks.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0004156355_python.txt
Q: Python - detect keyboard layout Playing around with RFID reader in serial, using python to output to console through uinput/ The thing is, doing the conversion from fake-rfid-keyboard-codes to code sent to uinput/, I would better know if I am using a QWERTY or an AZERTY ('a' becoming 'q', etc...) Back here in Belgium, especially during the event I am working on we are highly susceptible to have both keyboard layouts, I have to support both 'on-the-fly' Any os.*() function to do the job? Thanx ! A: You could start by looking at setxkbmap -print, but generally this is nontrivial. Why not instead set the keyboard layout to QWERTY for the virtual keyboard device you're creating with uinput? X supports separate layouts for each device. xinput list # find the device ID, say, 12 setxkbmap -device 12 us # use it In my experience, whenever I plug in an external USB keyboard it always starts out as US English, so I'm not sure that's even necessary.
Python - detect keyboard layout
Playing around with RFID reader in serial, using python to output to console through uinput/ The thing is, doing the conversion from fake-rfid-keyboard-codes to code sent to uinput/, I would better know if I am using a QWERTY or an AZERTY ('a' becoming 'q', etc...) Back here in Belgium, especially during the event I am working on we are highly susceptible to have both keyboard layouts, I have to support both 'on-the-fly' Any os.*() function to do the job? Thanx !
[ "You could start by looking at setxkbmap -print, but generally this is nontrivial.\nWhy not instead set the keyboard layout to QWERTY for the virtual keyboard device you're creating with uinput? X supports separate layouts for each device.\nxinput list # find the device ID, say, 12\nsetxkbmap -de...
[ 1 ]
[]
[]
[ "keyboard", "layout", "linux", "python" ]
stackoverflow_0002989691_keyboard_layout_linux_python.txt
Q: How to create a python 2.x package - simple case Please show the simple and up to date standard way to create a python package for python 2.x I'd prefer to use pip for installing the package later. The package should contain a single class: class hello: def greet(self): print "hello" One should be able to do the following later: pip install my_package-0.1.1.... And then using it: from my_package import hello h = hello.hello() h.greet() What I am asking for is: The directory and file layout Contents of the files command to create the distributable package file command to install the package from the distributable package file (using preferably pip) There are several howtos that I found but I am still not sure how this very simple and stripped down case (no nested packages, removal off all files and features that can be omitted for the most simple case) would be handled and which is the modern way to do it. I would like this question to enter community wiki state, so you won't get any points and I will give enough time and will mark an answer accepted after several days, also considering the votes and comments. Edit: I have a first running example that I want to share, I used Marius Gedminas's answer for it. It does not contain everything that should be there, but it works, so it can demonstrate the core of the technical process. To add more necessary parts please read Marius's answer below. Directory structure: MyProject/ setup.py my_package.py README.txt MANIFEST.in setup.py: from setuptools.import setup setup(name='MyProject', version='0.1', py_modules=['my_package']) my_package.py: class hello: def greet(self): print "hello" MANIFEST.in: include *.txt To create the package from this folder, go into the folder MyProject and run: $ python setup.py sdist This will create a file MyProject-0.1.tar.gz in a subfolder dist/. Copy this file to a folder on the target machine. On the target machine run this command in the folder containing MyProject-0.1.tar.gz: sudo pip install MyProject-0.1.tar.gz It can be necessary to logout and re-login on the target machine now, so the package will be found. Afterwards you can test the package on the target machine using the python shell: $ python >>> import my_package >>> h = my_package.hello() >>> h.greet() hello >>> Once this works please remember to add the other necessary contents, see Marius's answer below. A: Start simple Simplest one-file package: MyProject/ setup.py my_package.py Simplest setup.py: from setuptools import setup setup(name='MyProject', version='0.1', author='Your Name', author_email='your.name@example.com', license='MIT', description='Example package that says hello', py_modules=['my_package']) Including extra files in the package Next you should probably add a README: MyProject/ MANIFEST.in README.rst setup.py my_package.py Note the new file -- MANIFEST.in. It specifies which non-Python files ought to be included in your source distribution: include *.rst People will tell you "oh, skip the manifest, just add the files to source control, setuptools will find them". Ignore that advice, it's too error-prone. Making the PyPI page useful It's useful to make the README.rst available for people to view online, on the Python Package Index. So change your setup.py to do from setuptools import setup with open('README.rst') as f: readme = f.read() setup(name='MyProject', ... description='Example package that says hello', long_description=readme, ...) Use ReStructuredText markup for prettier pages. Use python setup.py --long-description | rst2html to catch ReStructuredText errors early. More than one Python module in a package One file will not be enough soon, so change it to a package (confusing terminology warning: Python package as in a directory with a __init__ py, not as in a distributable self-contained archive): MyProject/ MANIFEST.in README.rst setup.py my_package/ __init__.py some_module.py and change setup.py to from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() setup(name='MyProject', version='0.2', author='Your Name', author_email='your@email', license='MIT', description='Example package that says hello', long_description=readme, packages=find_packages()) Releasing to the public Get a PyPI account -- you only need to do this once. To make a release, make sure the version number in setup.py is correct, then run python setup.py sdist register upload That's it. Telling people to install it Tell them to pip install MyProject (same name you specified in setup.py as the name argument to setup()) A: The following is copied from the Distutils Tutorial. File layout: top |-- package | |-- __init__.py | |-- module.py | `-- things | |-- cross.png | |-- fplogo.png | `-- tick.png |-- runner |-- MANIFEST.in |-- README `-- setup.py To make the installation tarball, you simply run: python setup.py sdist To install the package, use pip or easy_install: pip install my_package-1.2.3.tar.bz2 or easy_install my_package-1.2.3.tar.bz2 Also, you can upload it to PyPI, first register it: python setup.py register then upload the source tarball python setup.py sdist upload You can upload binary eggs as well (though not necessary): python setup.py bdist_egg upload Then folks can install it like this: pip install my_package==1.2.3 or, easy_install my_package==1.2.3
How to create a python 2.x package - simple case
Please show the simple and up to date standard way to create a python package for python 2.x I'd prefer to use pip for installing the package later. The package should contain a single class: class hello: def greet(self): print "hello" One should be able to do the following later: pip install my_package-0.1.1.... And then using it: from my_package import hello h = hello.hello() h.greet() What I am asking for is: The directory and file layout Contents of the files command to create the distributable package file command to install the package from the distributable package file (using preferably pip) There are several howtos that I found but I am still not sure how this very simple and stripped down case (no nested packages, removal off all files and features that can be omitted for the most simple case) would be handled and which is the modern way to do it. I would like this question to enter community wiki state, so you won't get any points and I will give enough time and will mark an answer accepted after several days, also considering the votes and comments. Edit: I have a first running example that I want to share, I used Marius Gedminas's answer for it. It does not contain everything that should be there, but it works, so it can demonstrate the core of the technical process. To add more necessary parts please read Marius's answer below. Directory structure: MyProject/ setup.py my_package.py README.txt MANIFEST.in setup.py: from setuptools.import setup setup(name='MyProject', version='0.1', py_modules=['my_package']) my_package.py: class hello: def greet(self): print "hello" MANIFEST.in: include *.txt To create the package from this folder, go into the folder MyProject and run: $ python setup.py sdist This will create a file MyProject-0.1.tar.gz in a subfolder dist/. Copy this file to a folder on the target machine. On the target machine run this command in the folder containing MyProject-0.1.tar.gz: sudo pip install MyProject-0.1.tar.gz It can be necessary to logout and re-login on the target machine now, so the package will be found. Afterwards you can test the package on the target machine using the python shell: $ python >>> import my_package >>> h = my_package.hello() >>> h.greet() hello >>> Once this works please remember to add the other necessary contents, see Marius's answer below.
[ "Start simple\nSimplest one-file package:\nMyProject/\n setup.py\n my_package.py\n\nSimplest setup.py:\nfrom setuptools import setup\nsetup(name='MyProject',\n version='0.1',\n author='Your Name',\n author_email='your.name@example.com',\n license='MIT',\n description='Example package ...
[ 32, 4 ]
[]
[]
[ "packaging", "python", "python_2.x" ]
stackoverflow_0004155914_packaging_python_python_2.x.txt
Q: Python Puzzle code review(spoiler) I have been working on the problems presented in Python Challenge. One of the problems asks to sift through a mess of characters and pick out the rarest character/s. My methodology was to read the characters from a text file, store the characters/occurrence as a key/value pair in a dictionary. Sort the dictionary by value and invert the dictionary where the occurrence is the key and the string of characters is the value. Assuming that the rarest character occurs only once, I return the values where the key of this inverted dictionary equals one. The input(funkymess.txt) is like this: %%$@$^_#)^)&!_+]!*@&^}@@%%+$&[(_@%+%$*^@$^!+]!&#)*}{}}!}]$[%}@[{@#_^{*...... The code is as follows: from operator import itemgetter characterDict = dict() #put the characters in a dictionary def putEncounteredCharactersInDictionary(lineStr): for character in lineStr: if character in characterDict: characterDict[character] = characterDict[character]+1 else: characterDict[character] = 1 #Sort the character dictionary def sortCharacterDictionary(characterDict): sortCharDict = dict() sortsortedDictionaryItems = sorted(characterDict.iteritems(),key = itemgetter(1)) for key, value in sortsortedDictionaryItems: sortCharDict[key] = value return sortCharDict #invert the sorted character dictionary def inverseSortedCharacterDictionary(sortedCharDict): inv_map = dict() for k, v in sortedCharDict.iteritems(): inv_map[v] = inv_map.get(v, []) inv_map[v].append(k) return inv_map f = open('/Users/Developer/funkymess.txt','r') for line in f: #print line processline = line.rstrip('\n') putEncounteredCharactersInDictionary(processline) f.close() sortedCharachterDictionary = sortCharacterDictionary(characterDict) #print sortedCharachterDictionary inversedSortedCharacterDictionary = inverseSortedCharacterDictionary(sortedCharachterDictionary) print inversedSortedCharacterDictionary[1]r Can somebody take a look and provide me with some pointers on whether I am on the right track here and if possible provide some feedback on possible optimizations/best-practices and potential refactorings both from the language as well as from an algorithmic standpoint. Thanks A: Refactoring: A Walkthrough I want to walk you through the process of refactoring. Learning to program is not just about knowing the end result, which is what you usually get when you ask a question on Stack Overflow. It's about how to get to that answer yourself. When people post short, dense answers to a question like this it's not always obvious how they arrived at their solutions. So let's do some refactoring and see what we can do to simplify your code. We'll rewrite, delete, rename, and rearrange code until no more improvements can be made. Simplify your algorithms Python need not be so verbose. It is usually a code smell when you have explicit loops operating over lists and dicts in Python, rather than using list comprehensions and functions that operate on containers as a whole. Use defaultdict to store character counts A defaultdict(int) will generate entries when they are accessed if they do not exist. This let's us eliminate the if/else branch when counting characters. from collections import defaultdict characterDict = defaultdict(int) def putEncounteredCharactersInDictionary(lineStr): for character in lineStr: characterDict[character] += 1 Sorting dicts Dictionaries don't guarantee any ordering on their keys. You cannot assume that the items are stored in the same order that you insert them. So sorting the dict entries and then putting them right back into another dict just scrambles them right back up. This means that your function is basically a no-op. After you sort the items you will need to keep them as a list of tuples to retain their sorting order. Removing that code we can then reduce this method down to a single line. def sortCharacterDictionary(characterDict): return sorted(characterDict.iteritems(), key=itemgetter(1)) Inverting dicts Given the previous comment you won't actually have a dict any more after sorting. But assuming you did, this function is one of those cases where explicit looping is discouraged. In Python, always be thinking how you can operate over collections all at once rather than one item at a time. def inverseSortedCharacterDictionary(sortedCharDict): return dict((v, k) for k, v in sortedCharDict.iteritems()) All in one line we (1) iterate over the key/value pairs in the dict; (2) switch them and create inverted value/key tuples; (3) create a dict out of these inverted tuples. Comment and name wisely Your method names are long and descriptive. There's no need to repeat the same information in comments. Use comments only when your code isn't self-descriptive, such as when you have a complex algorithm or an unusual construct that isn't immediately obvious. On the naming front, your names are unnecessarily long. I would stick with far less descriptive names, and also make them more generic. Instead of inverseSortedCharacterDictionary, try just invertedDict. That's all that method does, it inverts a dict. It doesn't actually matter if it's passed a sorted character dict or any other type of dict. As a rule of thumb, try to use the most generic names possible so that your methods and variables can be as generic as possible. More generic means more reusable. characters = defaultdict(int) def countCharacters(string): for ch in string: characters[ch] += 1 def sortedCharacters(characters): return sorted(characters.iteritems(), key=itemgetter(1)) def invertedDict(d): return dict((v, k) for k, v in d.iteritems()) Reduce volume Using temporary variables and helper methods is a good programming practice, and I applaud you for doing so in your program. However, now that we have them simple enough that each one is only one or two lines we probably don't even need them any more. Here's your program body after changing the functions as above: f = open('funkymess.txt', 'r') for line in f: countCharacters(line.rstrip('\n')) f.close() print sortedCharacters(characters)[0] And then let's just go ahead and inline those helper methods since they're so simple. Here's the final program after all the refactoring: Final program #!/usr/bin/env python from operator import itemgetter from collections import defaultdict characters = defaultdict(int) f = open('funkymess.txt','r') for line in f: for ch in line.rstrip('\n'): characters[ch] += 1 f.close() print sorted(characters.iteritems(), key=itemgetter(1))[0] A: You don't even need as much code as that, because Python already has a class that counts elements in an iterable for you! The following does all of what you asked for. from collections import Counter counter = Counter(open(<...>).read()) print min(counter, key=counter.get) Explanation: collections is a standard module in Python containing some commonly-used data structures. In particular, it contains Counter, which is a subclass of dict designed to count the frequency of stuff. It takes an iterable and counts all the characters in it. Now as you may know, in Python strings are iterables and their elements are the single characters. So we can open the file, read all its contents at once, and feed that large string into a Counter. This makes a dict-like object which maps characters to their frequencies. Finally, we want to find the least frequent charater, given this dictionary of their frequencies. In other words, we want the minimum element of counter, sorted by its value in the dictionary. Python has a built-in function for taking the minimum of things, naturally called min. If you want to sort the data by something, you can pass it an optional key argument and it will sort the list by key of that list. In this case, we ask min to find the minimum element as sorted by counter.get; in other words, we sort by its frequency! A: That's way too much code. [k for k, v in characterdict.iteritems() if v = min(characterdict.items(), key=operator.itemgetter(1))[0]] Optimize as desired (e.g. store the minimum in another variable first). A: Here's the code that I used to solve this puzzle: comment = open('comment.txt').read() for c in sorted(set(comment)): print ' %-3s %6d' % (repr(c)[1:-1], comment.count(c)) It sorts characters alphabetically rather than by frequency, but the rarest characters are very easy to pick up from the output. If I wanted frequency sorting, I'd use collections.Counter like katrielalex suggested (if I remembered about its existence), or from collections import defaultdict comment = open('comment.txt').read() counts = defaultdict(int) for c in comment: counts[c] += 1 for c in sorted(counts, key=counts.get): print ' %-3s %6d' % (repr(c)[1:-1], counts[c]) A: Another way (not very compact) to accomplish your task: text = """%$@$^_#)^)&!_+]!*@&^}@@%%+$&[(_@%+%$*^@$^!+]!&#)*}{}}!}""" chars = set(text) L = [[c, text.count(c)] for c in chars] L.sort(key=lambda sublist: sublist[1]) >>> L [('(', 1), ('[', 1), ('{', 1), ('#', 2), (']', 2), (')', 3), ('*', 3), ('_', 3), ('&', 4), ('+', 4), ('!', 5), ('%', 5), ('$', 5), ('}', 5), ('^', 5), ('@', 6)] >>>
Python Puzzle code review(spoiler)
I have been working on the problems presented in Python Challenge. One of the problems asks to sift through a mess of characters and pick out the rarest character/s. My methodology was to read the characters from a text file, store the characters/occurrence as a key/value pair in a dictionary. Sort the dictionary by value and invert the dictionary where the occurrence is the key and the string of characters is the value. Assuming that the rarest character occurs only once, I return the values where the key of this inverted dictionary equals one. The input(funkymess.txt) is like this: %%$@$^_#)^)&!_+]!*@&^}@@%%+$&[(_@%+%$*^@$^!+]!&#)*}{}}!}]$[%}@[{@#_^{*...... The code is as follows: from operator import itemgetter characterDict = dict() #put the characters in a dictionary def putEncounteredCharactersInDictionary(lineStr): for character in lineStr: if character in characterDict: characterDict[character] = characterDict[character]+1 else: characterDict[character] = 1 #Sort the character dictionary def sortCharacterDictionary(characterDict): sortCharDict = dict() sortsortedDictionaryItems = sorted(characterDict.iteritems(),key = itemgetter(1)) for key, value in sortsortedDictionaryItems: sortCharDict[key] = value return sortCharDict #invert the sorted character dictionary def inverseSortedCharacterDictionary(sortedCharDict): inv_map = dict() for k, v in sortedCharDict.iteritems(): inv_map[v] = inv_map.get(v, []) inv_map[v].append(k) return inv_map f = open('/Users/Developer/funkymess.txt','r') for line in f: #print line processline = line.rstrip('\n') putEncounteredCharactersInDictionary(processline) f.close() sortedCharachterDictionary = sortCharacterDictionary(characterDict) #print sortedCharachterDictionary inversedSortedCharacterDictionary = inverseSortedCharacterDictionary(sortedCharachterDictionary) print inversedSortedCharacterDictionary[1]r Can somebody take a look and provide me with some pointers on whether I am on the right track here and if possible provide some feedback on possible optimizations/best-practices and potential refactorings both from the language as well as from an algorithmic standpoint. Thanks
[ "Refactoring: A Walkthrough\nI want to walk you through the process of refactoring. Learning to program is not just about knowing the end result, which is what you usually get when you ask a question on Stack Overflow. It's about how to get to that answer yourself. When people post short, dense answers to a questio...
[ 7, 4, 2, 1, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0004156699_algorithm_python.txt
Q: Passing array of strings as parameter in python ctypes This is a followup to Multi-dimensional char array (array of strings) in python ctypes . I have a c function that manipulates an array of strings. The data type is static, so this helps: void cfunction(char strings[8][1024]) { printf("string0 = %s\nstring1 = %s\n",strings[0],strings[1]); strings[0][2] = 'd'; //this is just some dumb modification strings[1][2] = 'd'; return; } I create the data type in python and use it like so: words = ((c_char * 8) * 1024)() words[0].value = "foo" words[1].value = "bar" libhello.cfunction(words) print words[0].value print words[1].value The output looks like this: string0 = fod string1 = fod bar It looks like I am improperly passing the words object to my C function; it doesn't //see// the second array value, yet writing to the location in memory doesn't cause a segfault. Something else odd about the declared words object: words[0].value = foo len(words[0].value) = 3 sizeof(words[0]) = 8 repr(words[0].raw) = 'foo\x00\x00\x00\x00\x00' Why is an object declared as 1024 characters long giving truncated sizeof and raw values? A: I think you need to define words as: words = ((c_char * 1024) * 8)() This would be an array of length 8 of character strings of length 1024.
Passing array of strings as parameter in python ctypes
This is a followup to Multi-dimensional char array (array of strings) in python ctypes . I have a c function that manipulates an array of strings. The data type is static, so this helps: void cfunction(char strings[8][1024]) { printf("string0 = %s\nstring1 = %s\n",strings[0],strings[1]); strings[0][2] = 'd'; //this is just some dumb modification strings[1][2] = 'd'; return; } I create the data type in python and use it like so: words = ((c_char * 8) * 1024)() words[0].value = "foo" words[1].value = "bar" libhello.cfunction(words) print words[0].value print words[1].value The output looks like this: string0 = fod string1 = fod bar It looks like I am improperly passing the words object to my C function; it doesn't //see// the second array value, yet writing to the location in memory doesn't cause a segfault. Something else odd about the declared words object: words[0].value = foo len(words[0].value) = 3 sizeof(words[0]) = 8 repr(words[0].raw) = 'foo\x00\x00\x00\x00\x00' Why is an object declared as 1024 characters long giving truncated sizeof and raw values?
[ "I think you need to define words as:\nwords = ((c_char * 1024) * 8)()\n\nThis would be an array of length 8 of character strings of length 1024.\n" ]
[ 5 ]
[]
[]
[ "ctypes", "pointers", "python" ]
stackoverflow_0004156992_ctypes_pointers_python.txt
Q: moving on from python I use python heavily for manipulating data and then packaging it for statistical modeling (R through RPy2). Feeling a little restless, I would like to branch out into other languages where Faster than python It's free There's good books, documentations and tutorials Very suitable for data manipulation Lots of libraries for statistical modeling Any recommendations? A: Use Cython or PyPy or Unladen Swallow. Now you've got Python that's faster than Python and also satisfies all of your requirements. A: If you just want to learn a new language you could take a look at scala. The language is influenced by languages like ruby, python and erlang, but is staticaly typed and runs on the JVM. The speed is comparable to Java. And you can use all the java libraries, plus reuse a lot of your python code through jython. A: I didn't see you mention SciPy on your list... I tend like R syntax better, but they cover much of the same ground. SciPy has faster matrix and array structures than the general purpose Python ones. Mostly places where I have wanted to use Cython, SciPy has been just as easy / fast. GNU/Octave is an open/free version of Matlab which might also interest you. A: You can always learn or brush up on C/C++, then go with a hybrid approach. If something you're doing in pure python is too slow, write a C-extension for it. If you want to use a library for which there isn't a pure-python implementation or existing wrapper, write your own wrapper, perhaps with the help of something like SWIG. This way you can focus on just those areas that are giving you problems, while continuing to use the rest of your code and accumulated python knowledge.
moving on from python
I use python heavily for manipulating data and then packaging it for statistical modeling (R through RPy2). Feeling a little restless, I would like to branch out into other languages where Faster than python It's free There's good books, documentations and tutorials Very suitable for data manipulation Lots of libraries for statistical modeling Any recommendations?
[ "Use Cython or PyPy or Unladen Swallow. Now you've got Python that's faster than Python and also satisfies all of your requirements.\n", "If you just want to learn a new language you could take a look at scala. The language is influenced by languages like ruby, python and erlang, but is staticaly typed and runs o...
[ 3, 1, 1, 0 ]
[]
[]
[ "programming_languages", "python" ]
stackoverflow_0004155955_programming_languages_python.txt
Q: How to get a list of local drives without SUBST'ituted ones in Python / Windows? I'm looking for a way to get all the local drives on a Windows machine, So far, I tried with two options 1) # Win32Com from win32com.client import Dispatch import sys fso = Dispatch('Scripting.FileSystemObject') for drive in fso.Drives: print drive, drive.DriveType 2) # win32api import win32api import win32file drives = (drive for drive in win32api.GetLogicalDriveStrings().split("\000") if drive) for drive in drives: print drive, win32file.GetDriveType(drive) This two ways works (almost) fine, I get my drive list such as: A: 1 // Removable C: 2 // Fixed D: 2 E: 2 G: 2 // Fixed (??? SUBST'ed drive) I: 4 // Cd-Rom X: 3 // Network but the G: drive is a SUBST'ed drive (eg: created with SUBST G: C:\TEST), and I cannot find the way to differentiate it from a "real" local drive. Any ideas? TIA, Pablo A: Google tells me that if you try and fetch a GUID for a SUBST-ed drive it will fail: >>> import win32file >>> win32file.GetVolumeNameForVolumeMountPoint("C:\\") '\\\\?\\Volume{50c800a9-c62e-11df-b5bb-806e6f6e6963}\\' >>> win32file.GetVolumeNameForVolumeMountPoint("K:\\") Traceback (most recent call last): File "<stdin>", line 1, in <module> pywintypes.error: (87, 'GetVolumeNameForVolumeMountPoint', 'The parameter is incorrect.') This seems to work but may not be reliable.
How to get a list of local drives without SUBST'ituted ones in Python / Windows?
I'm looking for a way to get all the local drives on a Windows machine, So far, I tried with two options 1) # Win32Com from win32com.client import Dispatch import sys fso = Dispatch('Scripting.FileSystemObject') for drive in fso.Drives: print drive, drive.DriveType 2) # win32api import win32api import win32file drives = (drive for drive in win32api.GetLogicalDriveStrings().split("\000") if drive) for drive in drives: print drive, win32file.GetDriveType(drive) This two ways works (almost) fine, I get my drive list such as: A: 1 // Removable C: 2 // Fixed D: 2 E: 2 G: 2 // Fixed (??? SUBST'ed drive) I: 4 // Cd-Rom X: 3 // Network but the G: drive is a SUBST'ed drive (eg: created with SUBST G: C:\TEST), and I cannot find the way to differentiate it from a "real" local drive. Any ideas? TIA, Pablo
[ "Google tells me that if you try and fetch a GUID for a SUBST-ed drive it will fail:\n>>> import win32file\n>>> win32file.GetVolumeNameForVolumeMountPoint(\"C:\\\\\")\n'\\\\\\\\?\\\\Volume{50c800a9-c62e-11df-b5bb-806e6f6e6963}\\\\'\n>>> win32file.GetVolumeNameForVolumeMountPoint(\"K:\\\\\")\nTraceback (most recent ...
[ 1 ]
[]
[]
[ "python", "windows_xp" ]
stackoverflow_0004157904_python_windows_xp.txt
Q: Python reading a tabbed text file into a series of lists Hi as an inexperieced python user I would appreciate any help with the following programming challenge: I have a text file with tabulated data, I want to read it and put the values on each line into different python lists. The file looks like this: 1 303233.479 233942.326 52.500 0.000 97 47 39.5 INFINITY 0.00034 0.00000 PBT PBT A001 B001 2 303386.031 233921.445 52.553 153.975 97 47 39.5 INFINITY 0.00034 0.00000 TS A001 3 303397.931 233919.897 52.557 165.975 96 38 54.2 -300.000 0.00034 0.00000 SC A002 4 303405.224 233919.137 52.559 173.308 95 14 52.6 -300.000 0.00034 6.25000 PC B002 There are 13 colums and I want to put the values into 13 lists, I understand how to do this for a couple of colums but I am a bit stumped at how to do this for 13 colummns. #Here is my pathetic attempt at this pntnums = [] #a xcogo = [] #b ycogo = [] #c zcogo = [] #d chain = [] #e bearing = [] #f rad = [] #g grad = [] #h mval = [] #i HCOD = [] #j VCOD = [] #k fd = file("align.txt").readlines(): a, b, c, d, e, f, g, h, i, j, k, = [int(s) for s in l.split()] pntnums.append(int(a)) xcogo.append(int(b)) ycogo.append(int(c)) zcogo.append(int(d)) chain.append(int(e)) bearing.append(int(f)) rad.append(int(g)) grad.append(int(h)) mval.append(int(i)) HCOD.append(int(j)) VCOD.append(int(k)) for val in pntnums: print val #and the corresponding output: Traceback (most recent call last): File "C:\MYPY\test.py", line 2, in <module> dataDict = dict(zip([float(i[1]) for i in data], [j[0] for j in data])) IndexError: list index out of range Any help on this would be most appreciated (evan a url), as I have searched and could not find a solution. newuser A: You should use a csv.reader; this is a built-in class in Python designed specifically for reading files like this. >>> import csv >>> fieldnames = ("pntnums", "xcogo", "ycogo", "zcogo", "bearing", "rad", "grad", "mval", "HCOD", "VCOD") >>> reader = csv.DictReader(open(...), delimiter="\t", fieldnames=fieldnames) You can then iterate over the elements of reader and it will give you dictionaries: >>> import pprint >>> for row in reader: ... pprint.pprint(row) ... {None: ['0.00000', 'PBT PBT', 'A001 B001 '], 'HCOD': 'INFINITY', 'VCOD': '0.00034', 'bearing': '0.000', 'grad': '47', 'mval': '39.5', 'pntnums': '1', 'rad': '97', 'xcogo': '303233.479', 'ycogo': '233942.326', 'zcogo': '52.500'} {None: ['0.00000', 'TS', 'A001'], 'HCOD': 'INFINITY', 'VCOD': '0.00034', 'bearing': '153.975', 'grad': '47', 'mval': '39.5', 'pntnums': '2', 'rad': '97', 'xcogo': '303386.031', 'ycogo': '233921.445', 'zcogo': '52.553'} {None: ['0.00000', 'SC', 'A002'], 'HCOD': '-300.000', 'VCOD': '0.00034', 'bearing': '165.975', 'grad': '38', 'mval': '54.2', 'pntnums': '3', 'rad': '96', 'xcogo': '303397.931', 'ycogo': '233919.897', 'zcogo': '52.557'} {None: ['6.25000', 'PC', 'B002'], 'HCOD': '-300.000', 'VCOD': '0.00034', 'bearing': '173.308', 'grad': '14', 'mval': '52.6', 'pntnums': '4', 'rad': '95', 'xcogo': '303405.224', 'ycogo': '233919.137', 'zcogo': '52.559'} (The data probably don't match up exactly with the fields here, because I don't have the original tab-separated text, just what I can copy-paste from SO. It will work if you feed it the original file =).)
Python reading a tabbed text file into a series of lists
Hi as an inexperieced python user I would appreciate any help with the following programming challenge: I have a text file with tabulated data, I want to read it and put the values on each line into different python lists. The file looks like this: 1 303233.479 233942.326 52.500 0.000 97 47 39.5 INFINITY 0.00034 0.00000 PBT PBT A001 B001 2 303386.031 233921.445 52.553 153.975 97 47 39.5 INFINITY 0.00034 0.00000 TS A001 3 303397.931 233919.897 52.557 165.975 96 38 54.2 -300.000 0.00034 0.00000 SC A002 4 303405.224 233919.137 52.559 173.308 95 14 52.6 -300.000 0.00034 6.25000 PC B002 There are 13 colums and I want to put the values into 13 lists, I understand how to do this for a couple of colums but I am a bit stumped at how to do this for 13 colummns. #Here is my pathetic attempt at this pntnums = [] #a xcogo = [] #b ycogo = [] #c zcogo = [] #d chain = [] #e bearing = [] #f rad = [] #g grad = [] #h mval = [] #i HCOD = [] #j VCOD = [] #k fd = file("align.txt").readlines(): a, b, c, d, e, f, g, h, i, j, k, = [int(s) for s in l.split()] pntnums.append(int(a)) xcogo.append(int(b)) ycogo.append(int(c)) zcogo.append(int(d)) chain.append(int(e)) bearing.append(int(f)) rad.append(int(g)) grad.append(int(h)) mval.append(int(i)) HCOD.append(int(j)) VCOD.append(int(k)) for val in pntnums: print val #and the corresponding output: Traceback (most recent call last): File "C:\MYPY\test.py", line 2, in <module> dataDict = dict(zip([float(i[1]) for i in data], [j[0] for j in data])) IndexError: list index out of range Any help on this would be most appreciated (evan a url), as I have searched and could not find a solution. newuser
[ "You should use a csv.reader; this is a built-in class in Python designed specifically for reading files like this.\n>>> import csv\n>>> fieldnames = (\"pntnums\", \"xcogo\", \"ycogo\", \"zcogo\", \"bearing\",\n \"rad\", \"grad\", \"mval\", \"HCOD\", \"VCOD\")\n>>> reader = csv.DictReader(open(...)...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0004158030_python.txt
Q: How to write this in a simpler way i = 0 for x in range(0, 5): for y in range(0, 5): if 0 == outputAfterLearning[i]: image.putpixel((x, y), (0, 0, 0)) elif 1 == outputAfterLearning[i]: image.putpixel((x, y), (255, 255, 255)) i += 1 for x in range(0, 5): for y in range(5, 10): if 0 == outputAfterLearning[i]: image.putpixel((x, y), (0, 0, 0)) elif 1 == outputAfterLearning[i]: image.putpixel((x, y), (255, 255, 255)) i += 1 for x in range(5, 10): for y in range(0, 5): if 0 == outputAfterLearning[i]: image.putpixel((x, y), (0, 0, 0)) elif 1 == outputAfterLearning[i]: image.putpixel((x, y), (255, 255, 255)) i += 1 for x in range(5, 10): for y in range(5, 10): if 0 == outputAfterLearning[i]: image.putpixel((x, y), (0, 0, 0)) elif 1 == outputAfterLearning[i]: image.putpixel((x, y), (255, 255, 255)) i += 1 As you can see, I am iterating over an image using 5x5px squares and setting pixels in them. The above code is obviosuly for image with dimensions 10x10px but I would like to write the above code in a more general way so I can use it for larger images (say 30x30px) without adding 32 new for loops. A: xdim, ydim = 10, 10 xblocksize, yblocksize = 5, 5 for xblock in range(0, xdim, xblocksize): for yblock in range(0, ydim, yblocksize): for x in range(xblock, xblock+xblocksize): for y in range(yblock, yblock+yblocksize): # the common code. But I would create a generator for the block iteration: def blocked(xdim, ydim, xblocksize, yblocksize): for xblock in range(0, xdim, xblocksize): for yblock in range(0, ydim, yblocksize): for x in range(xblock, xblock+xblocksize): for y in range(yblock, yblock+yblocksize): yield (x, y) and use putpixel as color = [(0,0,0),(255,255,255)] for colorcode, pixelloc in zip(outputAfterLearning, blocked(10, 10, 5, 5)): if 0 <= colorcode < len(color): # ^ omit this if outputAfterLearning[i] is always valid image.putpixel(pixelloc, color[colorcode])
How to write this in a simpler way
i = 0 for x in range(0, 5): for y in range(0, 5): if 0 == outputAfterLearning[i]: image.putpixel((x, y), (0, 0, 0)) elif 1 == outputAfterLearning[i]: image.putpixel((x, y), (255, 255, 255)) i += 1 for x in range(0, 5): for y in range(5, 10): if 0 == outputAfterLearning[i]: image.putpixel((x, y), (0, 0, 0)) elif 1 == outputAfterLearning[i]: image.putpixel((x, y), (255, 255, 255)) i += 1 for x in range(5, 10): for y in range(0, 5): if 0 == outputAfterLearning[i]: image.putpixel((x, y), (0, 0, 0)) elif 1 == outputAfterLearning[i]: image.putpixel((x, y), (255, 255, 255)) i += 1 for x in range(5, 10): for y in range(5, 10): if 0 == outputAfterLearning[i]: image.putpixel((x, y), (0, 0, 0)) elif 1 == outputAfterLearning[i]: image.putpixel((x, y), (255, 255, 255)) i += 1 As you can see, I am iterating over an image using 5x5px squares and setting pixels in them. The above code is obviosuly for image with dimensions 10x10px but I would like to write the above code in a more general way so I can use it for larger images (say 30x30px) without adding 32 new for loops.
[ "xdim, ydim = 10, 10\nxblocksize, yblocksize = 5, 5\nfor xblock in range(0, xdim, xblocksize):\n for yblock in range(0, ydim, yblocksize):\n for x in range(xblock, xblock+xblocksize):\n for y in range(yblock, yblock+yblocksize):\n # the common code.\n\nBut I would create a generator for th...
[ 4 ]
[]
[]
[ "optimization", "python", "refactoring" ]
stackoverflow_0004158045_optimization_python_refactoring.txt
Q: Why does Python raise TypeError rather than SyntaxError? A question purely for curiosity's sake. This is obviously invalid syntax: foo = {} foo['bar': 'baz'] It's obvious what happened, the developer moved a line out of the dictionary definition but didn't change it from the literal dictionary declaration to the assignment syntax (and has been suitably mocked as a result). But my question is, why does Python raise TypeError: unhashable type here rather than SyntaxError? What type is it attempting to hash? Just doing this: 'bar': 'baz' is a SyntaxError, as is this: ['bar': 'baz'] so I can't see what type is being created that is unhashable. A: Using the colon in an indexing operation generates a slice object, which is not hashable. A: I just want to add some detail to Ignacio answer (which is great) and that take me some time to understand and for people like me that didn't get it (i may be the only one that didn't get it because i didn't see anyone asking i didn't understand but how knows :) ) : the first time i wonder what slice ? dictionary indexing don't accept slicing ? but this is a stupid question from my part because i forget that python is dynamic (how stupid i'm ) so when python compile the code the fist time python don't know if foo is a dictionary or a list so it just read any expression like this foo['foo':'bar'] as a slice , to know that you can just do: def f(): foo = {} foo['bar':'foo'] and by using dis module you will see that the expression 'bar':'foo' has been automatically convert to a slice: dis.dis(f) 2 0 BUILD_MAP 0 3 STORE_FAST 0 (foo) 3 6 LOAD_FAST 0 (foo) 9 LOAD_CONST 1 ('bar') 12 LOAD_CONST 2 ('foo') 15 SLICE+3 <<<<<<<<<<<<<<<<<<<<<< HERE!!!!!! 16 POP_TOP 17 LOAD_CONST 0 (None) 20 RETURN_VALUE in the first time i admit i didn't think about this and i did go directly to the source code of python trying to understand why, because the __getitems__ of list is not like __getitem__ of a dictionary but now i understand why because if it a slice and slice are unhashable it should raise unhashable type, so here is the code of dictionary __getitem__: static PyObject * dict_subscript(PyDictObject *mp, register PyObject *key) { PyObject *v; long hash; PyDictEntry *ep; assert(mp->ma_table != NULL); if (!PyString_CheckExact(key) || // if check it's not a string (hash = ((PyStringObject *) key)->ob_shash) == -1) { hash = PyObject_Hash(key); // check if key (sliceobject) is hashable which is false if (hash == -1) return NULL; } .... Hope this can help some people like me to understand the great response of Ignacio, and sorry if i just duplicate the answer of Ignacio :)
Why does Python raise TypeError rather than SyntaxError?
A question purely for curiosity's sake. This is obviously invalid syntax: foo = {} foo['bar': 'baz'] It's obvious what happened, the developer moved a line out of the dictionary definition but didn't change it from the literal dictionary declaration to the assignment syntax (and has been suitably mocked as a result). But my question is, why does Python raise TypeError: unhashable type here rather than SyntaxError? What type is it attempting to hash? Just doing this: 'bar': 'baz' is a SyntaxError, as is this: ['bar': 'baz'] so I can't see what type is being created that is unhashable.
[ "Using the colon in an indexing operation generates a slice object, which is not hashable.\n", "I just want to add some detail to Ignacio answer (which is great) and that take me some time to understand and for people like me that didn't get it (i may be the only one that didn't get it because i didn't see anyon...
[ 65, 22 ]
[]
[]
[ "python" ]
stackoverflow_0004157278_python.txt
Q: How to have recognized all the libraries Rpy2 R How to have recognized all the libraries Rpy2 R. Rpy2 not recognizing the libraries, utils, and tools. import rpy2.robjects as robjects R = robjects.r >>> R['library']("utils") RVector - Python:0x7f65fc85cfc8 / R:0x19bb980 >>> R['library']("tools") RVector - Python:0x7f65fc85f5a8 / R:0x2419140 (>>> from rpy2.robjects.packages import importr Traceback (most recent call last): File "", line 1, in ImportError: No module named packages ) as I can update Rpy2 to load all the libraries without problems or R that can be done. PS: I use R 2.10 and python 2.6 on ubuntu A: In order to get the importr command to work, you probably need to upgrade your version of rpy2 -- try checking your version: print rpy2.__version__ I believe you need version 2.1.0 or greater. The following works for me under 2.1.7 but not on 2.0.3: In [1]: import rpy2.robjects as robjects In [2]: R = robjects.r In [3]: from rpy2.robjects.packages import importr In [4]: importr("utils") Out[4]: <rpy2.robjects.packages.SignatureTranslatedPackage object at 0x1e96310> I'm not sure what you're trying to do, as those libraries should work without any extra importing, as Gavin has mentioned. A: Unless I am mistaken - I don't use Rpy2 - these packages (they are not libraries by the way) are loaded automatically when R is started; you do not need to do anything else to make use of them. All the user-visible functions in these packages are made available during R start up. Also, you can't update these packages - they are R. You only get updates when you update R itself. In this they differ from the Recommended packages (like nlme, mgcv, MASS etc) which are also on CRAN and which are updated more frequently in between R version updates.
How to have recognized all the libraries Rpy2 R
How to have recognized all the libraries Rpy2 R. Rpy2 not recognizing the libraries, utils, and tools. import rpy2.robjects as robjects R = robjects.r >>> R['library']("utils") RVector - Python:0x7f65fc85cfc8 / R:0x19bb980 >>> R['library']("tools") RVector - Python:0x7f65fc85f5a8 / R:0x2419140 (>>> from rpy2.robjects.packages import importr Traceback (most recent call last): File "", line 1, in ImportError: No module named packages ) as I can update Rpy2 to load all the libraries without problems or R that can be done. PS: I use R 2.10 and python 2.6 on ubuntu
[ "In order to get the importr command to work, you probably need to upgrade your version of rpy2 -- try checking your version:\nprint rpy2.__version__\n\nI believe you need version 2.1.0 or greater. The following works for me under 2.1.7 but not on 2.0.3:\nIn [1]: import rpy2.robjects as robjects\n\nIn [2]: R = robj...
[ 4, 1 ]
[]
[]
[ "linux", "python", "r", "rpy2", "ubuntu" ]
stackoverflow_0004157926_linux_python_r_rpy2_ubuntu.txt
Q: Django/Python: how can i filter with Model's custom method?? Is this possible? I have a model with a custom method. Here's the example: class MyModel(models) id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) nickname = models.CharField(max_length=50) time_created = models.DateTimeField(auto_now_add=True) def sample_method(self) right_now = datetime.now() created_time = self.time_created time2compare = timedelta(minutes=3) timeout = True if(right_now - created_time) > time2compare: timeout = False return timeout What I'm trying to do is do something like this (i know this doesn't work) queryset = MyModel.objects.filter(timeout=False) How could i solve this problem? Thanks! A: You cannot use a custom method on your model for filtering, because the filters will be resolved to saw sql, which will not be possible with some python code. Nonetheless the following should solve your problem: import datetime queryset = MyModel.objects.filter(\ time_created__lt=(datetime.now()-datetime.timedelta(minutes=3))) A: Your timeout test is very trivial to reimplement as a queryset filter. For a really complex test that can't be expressed in Django query language or raw SQL, you can write something like: def sample_filter(self, method_name, arg=False) for i in self.objects.all(): if getattr(self, method_name)() == arg: yield i This method will return an iterator to every instance x of the Model where x.method_name() == arg. However, this can't be chained like a queryset.
Django/Python: how can i filter with Model's custom method?? Is this possible?
I have a model with a custom method. Here's the example: class MyModel(models) id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) nickname = models.CharField(max_length=50) time_created = models.DateTimeField(auto_now_add=True) def sample_method(self) right_now = datetime.now() created_time = self.time_created time2compare = timedelta(minutes=3) timeout = True if(right_now - created_time) > time2compare: timeout = False return timeout What I'm trying to do is do something like this (i know this doesn't work) queryset = MyModel.objects.filter(timeout=False) How could i solve this problem? Thanks!
[ "You cannot use a custom method on your model for filtering, because the filters will be resolved to saw sql, which will not be possible with some python code. Nonetheless the following should solve your problem:\nimport datetime\nqueryset = MyModel.objects.filter(\\\n time_created__lt=(datetime.now()-datetime....
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004157984_django_python.txt
Q: Is Django 1.3 alpha available in pypi yet? I have a buildout script that gets django as a dependency. I'd like to play with Django 1.3 in my project, but I don't want to download and install it, I'd like my buildout to do that. Does anyone know how I can do this, or am I better off just downloading from the website and placing django in the appropriate spot? UPDATE: I got this to work by changing the following in the setup.py file setup( install_requires = ('django=1.3-alpha-1',), dependency_links = ('http://www.djangoproject.com/download/1.3-alpha-1/tarball/#egg=django-1.3-alpha-1',), ) A: Either you wait for django to be released in PyPI or you include it with your packaging solution. Edit: If you want buildout to do it all for you, you can use the url attribute and let it download the package from the django website.
Is Django 1.3 alpha available in pypi yet?
I have a buildout script that gets django as a dependency. I'd like to play with Django 1.3 in my project, but I don't want to download and install it, I'd like my buildout to do that. Does anyone know how I can do this, or am I better off just downloading from the website and placing django in the appropriate spot? UPDATE: I got this to work by changing the following in the setup.py file setup( install_requires = ('django=1.3-alpha-1',), dependency_links = ('http://www.djangoproject.com/download/1.3-alpha-1/tarball/#egg=django-1.3-alpha-1',), )
[ "Either you wait for django to be released in PyPI or you include it with your packaging solution.\nEdit: If you want buildout to do it all for you, you can use the url attribute and let it download the package from the django website.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004158337_django_python.txt
Q: reading very large file where format is newline independent My Python code supports reading and writing data in a file format created by others called the BLT format. The BLT format is white space and newline independent in that a newline is treated just like other white space. The primary entry in this format is a "ballot" which ends with a "0", e.g., 1 2 3 0 Since the format is newline independent, it could also be written as 1 2 3 0 Or you could have multiple ballots on a line: 1 2 3 0 4 5 6 0 These files can be very large so I don't want to read an entire file into memory. Line-based reading is complicated since the data is not line-based. What is a good way to process these files in a memory-efficient way? A: For me, the most straightforward way to solve this is with generators. def tokens(filename): with open(filename) as infile: for line in infile: for item in line.split(): yield int(item) def ballots(tokens): ballot = [] for t in tokens: if t: ballot.append(t) else: yield ballot ballot = [] t = tokens("datafile.txt") for b in ballots(t): print b I see @katrielalex posted a generator-using solution while I was posting mine. The difference between ours is that I'm using two separate generators, one for the individual tokens in the file and one for the specific data structure you wish to parse. The former is passed to the latter as a parameter, the basic idea being that you can write a function like ballots() for each of the data structures you wish to parse. You can either iterate over everything yielded by the generator, or call next() on either generator to get the next token or ballot (be prepared for a StopIteration exception when you run out, or else write the generators to generate a sentinel value such as None when they run out of real data, and check for that). It would be pretty straightforward to wrap the whole thing in a class. In fact... class Parser(object): def __init__(self, filename): def tokens(filename): with open(filename) as infile: for line in infile: for item in line.split(): yield int(item) self.tokens = tokens(filename) def ballots(self): ballot = [] for t in self.tokens: if t: ballot.append(t) else: yield ballot ballot = [] p = Parser("datafile.txt") for b in p.ballots(): print b A: Use a generator: >>> def ballots(f): ... ballots = [] ... for line in f: ... for token in line.split(): ... if token == '0': ... yield ballots ... ballots = [] ... else: ... ballots.append(token) This will read the file line by line, split on all whitespace, and append the tokens in the line one by one to a list. Whenever a zero is reached, that ballot is yielded and the list reset to empty.
reading very large file where format is newline independent
My Python code supports reading and writing data in a file format created by others called the BLT format. The BLT format is white space and newline independent in that a newline is treated just like other white space. The primary entry in this format is a "ballot" which ends with a "0", e.g., 1 2 3 0 Since the format is newline independent, it could also be written as 1 2 3 0 Or you could have multiple ballots on a line: 1 2 3 0 4 5 6 0 These files can be very large so I don't want to read an entire file into memory. Line-based reading is complicated since the data is not line-based. What is a good way to process these files in a memory-efficient way?
[ "For me, the most straightforward way to solve this is with generators.\ndef tokens(filename):\n with open(filename) as infile:\n for line in infile:\n for item in line.split():\n yield int(item)\n\ndef ballots(tokens):\n ballot = []\n for t in tokens:\n if t:\n ...
[ 3, 1 ]
[]
[]
[ "file_io", "newline", "python" ]
stackoverflow_0004158265_file_io_newline_python.txt
Q: Why doesn't Python "grouping" work for regular expressions in C? Here is my Python program: import re print re.findall( "([se]{2,30})ting", "testingtested" ) Its output is: ['es'] Which is what I expect. I expect to get back "es" because I searched for 2-30 characters of "e" or "s" which are followed by "ting". Here is my C program: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <regex.h> int main(void) { regex_t preg; regmatch_t pmatch; char string[] = "testingtested"; //Compile the regular expression if ( regcomp( &preg, "([se]{2,30})ting", REG_EXTENDED ) ) { printf( "ERROR!\n" ); return -1; } else { printf( "Compiled\n" ); } //Do the search if ( regexec( &preg, string, 1, &pmatch, REG_NOTEOL ) ) { printf( "No Match\n" ); } else { //Allocate memory on the stack for this char substring[pmatch.rm_eo - pmatch.rm_so + 1]; //Copy the substring over printf( "%d %d\n", pmatch.rm_so, pmatch.rm_eo ); strncpy( substring, &string[pmatch.rm_so], pmatch.rm_eo - pmatch.rm_so ); //Make sure there's a null byte substring[pmatch.rm_eo - pmatch.rm_so] = 0; //Print it out printf( "Match\n" ); printf( "\"%s\"\n", substring ); } //Release the regular expression regfree( &preg ); return EXIT_SUCCESS; } It's output is: Compiled 1 7 Match "esting" Why is the C program including the "ting" in the result? And is there a way for me to exclude the "ting" portion? A: pmatch is the whole match, not the first parenthesized subexpression. Try changing pmatch to an array of 2 elements, then passing 2 in place of 1 to regexec and using the [1] element to get the subexpression match. To others who have cited differences between C and Python and different types of regular expressions, that's all unrelated. This expression is very simple and that's not coming into play. A: While regular expressions are "more or less the same everywhere", the exact supported features differ from implementation to implementation. Unfortunately, you need to consult each regex library's documentation separately when designing your regular expressions.
Why doesn't Python "grouping" work for regular expressions in C?
Here is my Python program: import re print re.findall( "([se]{2,30})ting", "testingtested" ) Its output is: ['es'] Which is what I expect. I expect to get back "es" because I searched for 2-30 characters of "e" or "s" which are followed by "ting". Here is my C program: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <regex.h> int main(void) { regex_t preg; regmatch_t pmatch; char string[] = "testingtested"; //Compile the regular expression if ( regcomp( &preg, "([se]{2,30})ting", REG_EXTENDED ) ) { printf( "ERROR!\n" ); return -1; } else { printf( "Compiled\n" ); } //Do the search if ( regexec( &preg, string, 1, &pmatch, REG_NOTEOL ) ) { printf( "No Match\n" ); } else { //Allocate memory on the stack for this char substring[pmatch.rm_eo - pmatch.rm_so + 1]; //Copy the substring over printf( "%d %d\n", pmatch.rm_so, pmatch.rm_eo ); strncpy( substring, &string[pmatch.rm_so], pmatch.rm_eo - pmatch.rm_so ); //Make sure there's a null byte substring[pmatch.rm_eo - pmatch.rm_so] = 0; //Print it out printf( "Match\n" ); printf( "\"%s\"\n", substring ); } //Release the regular expression regfree( &preg ); return EXIT_SUCCESS; } It's output is: Compiled 1 7 Match "esting" Why is the C program including the "ting" in the result? And is there a way for me to exclude the "ting" portion?
[ "pmatch is the whole match, not the first parenthesized subexpression.\nTry changing pmatch to an array of 2 elements, then passing 2 in place of 1 to regexec and using the [1] element to get the subexpression match.\nTo others who have cited differences between C and Python and different types of regular expressio...
[ 3, 2 ]
[]
[]
[ "c", "python", "regex" ]
stackoverflow_0004158392_c_python_regex.txt
Q: 'WSGIRequest' object has no attribute 'user' in Google App Engine I'm new to django and Google App Engine, and I'm having trouble with using the datastore. Every time I make a query, such as db.GqlQuery("SELECT * FROM Listing ORDER BY date DESC LIMIT 10") I receive the error: 'WSGIRequest' object has no attribute 'user' This error seems to be generated in context_processors.py within the django core. Now, the advice I've found on the Internet said to comment out user-related INSTALLED_APPS and MIDDLEWARE_CLASSES, but this does not seem to help. My code looks like this: MIDDLEWARE_CLASSES = ( # 'django.middleware.common.CommonMiddleware', # 'django.contrib.sessions.middleware.SessionMiddleware', # 'django.contrib.auth.middleware.AuthenticationMiddleware', # 'django.middleware.doc.XViewMiddleware', ) INSTALLED_APPS = ( # 'django.contrib.auth', 'django.contrib.contenttypes', # 'django.contrib.sessions', 'django.contrib.sites', ) My Listing object is defined as the following (it had a author property earlier, but this is now commented out and the object was redefined with a new name): class Listing(db.Model): #author = db.UserProperty() address = db.StringProperty() date = db.DateTimeProperty(auto_now_add=True) coords = db.GeoPtProperty() Does anyone know what is causing this error, and how to fix it? Is it perhaps a case of having to reset the settings somehow? A: UPDATE The solution suggested by sdolan seems to be to add the following to the settings.py of the app: TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.debug", "django.core.context_processors.i18n") This effectively removes the third default processor, django.core.context_processors.auth (which shouldn't be there because for AppEngine we don't want Django's auth component). Thank you, sdolan, for the solution! hopefully someone else can use it, too. :) @Nick, I think it's worth putting this golden piece about CONTEXT_PROCESSORS in the tutorial (http://code.google.com/appengine/articles/django.html) (Original followup to the question) Have the same problem, looking for solution.... All works fine when settings.py contains DEBUG = True but this error pops up (and kills my motivation to proceed with learning) when I switch to DEBUG = False @Nick Johnson, here's the stack trace: Traceback (most recent call last): File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3211, in _HandleRequest self._Dispatch(dispatcher, self.rfile, outfile, env_dict) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3154, in _Dispatch base_env_dict=env_dict) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 527, in Dispatch base_env_dict=base_env_dict) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2404, in Dispatch self._module_dict) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2314, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2212, in ExecuteOrImportScript script_module.main() File "C:\Dev\appengine\djangotest\main.py", line 37, in main util.run_wsgi_app(application) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\webapp\util.py", line 97, in run_wsgi_app run_bare_wsgi_app(add_wsgi_middleware(application)) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\webapp\util.py", line 115, in run_bare_wsgi_app result = application(env, _start_response) File "C:\Program Files (x86)\Google\google_appengine\lib\django\django\core\handlers\wsgi.py", line 189, in __call__ response = self.get_response(request) File "C:\Program Files (x86)\Google\google_appengine\lib\django\django\core\handlers\base.py", line 103, in get_response return callback(request, **param_dict) File "C:\Program Files (x86)\Google\google_appengine\lib\django\django\views\defaults.py", line 79, in page_not_found return http.HttpResponseNotFound(t.render(RequestContext(request, {'request_path': request.path}))) File "C:\Program Files (x86)\Google\google_appengine\lib\django\django\template\context.py", line 100, in __init__ self.update(processor(request)) File "C:\Program Files (x86)\Google\google_appengine\lib\django\django\core\context_processors.py", line 18, in auth 'user': request.user, AttributeError: 'WSGIRequest' object has no attribute 'user'
'WSGIRequest' object has no attribute 'user' in Google App Engine
I'm new to django and Google App Engine, and I'm having trouble with using the datastore. Every time I make a query, such as db.GqlQuery("SELECT * FROM Listing ORDER BY date DESC LIMIT 10") I receive the error: 'WSGIRequest' object has no attribute 'user' This error seems to be generated in context_processors.py within the django core. Now, the advice I've found on the Internet said to comment out user-related INSTALLED_APPS and MIDDLEWARE_CLASSES, but this does not seem to help. My code looks like this: MIDDLEWARE_CLASSES = ( # 'django.middleware.common.CommonMiddleware', # 'django.contrib.sessions.middleware.SessionMiddleware', # 'django.contrib.auth.middleware.AuthenticationMiddleware', # 'django.middleware.doc.XViewMiddleware', ) INSTALLED_APPS = ( # 'django.contrib.auth', 'django.contrib.contenttypes', # 'django.contrib.sessions', 'django.contrib.sites', ) My Listing object is defined as the following (it had a author property earlier, but this is now commented out and the object was redefined with a new name): class Listing(db.Model): #author = db.UserProperty() address = db.StringProperty() date = db.DateTimeProperty(auto_now_add=True) coords = db.GeoPtProperty() Does anyone know what is causing this error, and how to fix it? Is it perhaps a case of having to reset the settings somehow?
[ "UPDATE\nThe solution suggested by sdolan seems to be to add the following to the settings.py of the app:\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\")\nThis effectively removes the third default processor, django.core.context_processor...
[ 1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0003692853_django_google_app_engine_python.txt
Q: Make the readline method of Python recognize both end-of-line variations? I am writing a Python file that needs to read in several files of different types. I am reading the files in line by line with the traditional for line in f after using f = open("file.txt", "r"). This doesn't seem to be working for all files. My guess is some files end with different encodings (such as \r\n versus just \r). I can read the whole file in and do a string split on \r, but that is hugely costly and I'd rather not. Is there a way to make the readline method of Python recognize both end-of-line variations? A: Use the universal newline support -- see http://docs.python.org/library/functions.html#open In addition to the standard fopen() values mode may be 'U' or 'rU'. Python is usually built with universal newline support; supplying 'U' opens the file as a text file, but lines may be terminated by any of the following: the Unix end-of-line convention '\n', the Macintosh convention '\r', or the Windows convention '\r\n'. All of these external representations are seen as '\n' by the Python program. If Python is built without universal newline support a mode with 'U' is the same as normal text mode. Note that file objects so opened also have an attribute called newlines which has a value of None (if no newlines have yet been seen), '\n', '\r', '\r\n', or a tuple containing all the newline types seen. A: You can try to use a generator approach to read the lines by yourself and ignore any EOL characters: def readlines(f): line = [] while True: s = f.read(1) if len(s) == 0: if len(line) > 0: yield line return if s in ('\r','\n'): if len(line) > 0: yield line line = [] else: line.append(s) for line in readlines(yourfile): # ...
Make the readline method of Python recognize both end-of-line variations?
I am writing a Python file that needs to read in several files of different types. I am reading the files in line by line with the traditional for line in f after using f = open("file.txt", "r"). This doesn't seem to be working for all files. My guess is some files end with different encodings (such as \r\n versus just \r). I can read the whole file in and do a string split on \r, but that is hugely costly and I'd rather not. Is there a way to make the readline method of Python recognize both end-of-line variations?
[ "Use the universal newline support -- see http://docs.python.org/library/functions.html#open\n\nIn addition to the standard fopen()\n values mode may be 'U' or 'rU'. Python\n is usually built with universal\n newline support; supplying 'U' opens\n the file as a text file, but lines may\n be terminated by any o...
[ 18, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004158645_python.txt
Q: tuple vs list objects in python Can someone explain me this? >>> [] is [] False >>> () is () True >>> (1,) is (1,) False I understand that I should use "==" instead of "is"to compare the values, I am just wondering why it is this way? A: is is based on object identity. I.E., are the left and right the same object? In all these cases, the objects would ordinarily be different (since you have six separate literals). However, the empty tuples are the same object due to implementation-dependent interning. As you noted, you should never rely on this behavior. Note that mutable objects can not be interned, which means the first must be false. A: Be careful when comparing by id. If an object is GC'd the id can be reused! >>> id([])==id([]) True or even >>> id([1,2,3])==id(["A","B","C"]) True A: Think of it this way: In your first case, for immutable objects like tuples, it's safe for the python implementation to share them if they're identical: >>> a = () >>> b = () >>> a is b True Now consider: >>> a = [] >>> b = [] >>> a.append("foo") >>> print a,b ['foo'] [] It's not possible for a and b to be the same object, because modifying a shouldn't modify b. In your final example, you're back to immutable tuples. The Python implementation is allowed to make them the same object, but isn't required to, and in this case it doesn't (it's basically a space/time tradeoff - if you used a lot of (1,) in your program you could save memory if they were interned, but it would cost runtime to determine if any given tuple was a (1,) that could share the object).
tuple vs list objects in python
Can someone explain me this? >>> [] is [] False >>> () is () True >>> (1,) is (1,) False I understand that I should use "==" instead of "is"to compare the values, I am just wondering why it is this way?
[ "is is based on object identity. I.E., are the left and right the same object?\nIn all these cases, the objects would ordinarily be different (since you have six separate literals). However, the empty tuples are the same object due to implementation-dependent interning. As you noted, you should never rely on thi...
[ 10, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004158361_python.txt
Q: just a canvas in a tkinter window If I try to place a canvas in a tkinter window and nothing else with this code: from tkinter import ttk from tkinter import * from tkinter.ttk import * class Application(Frame): def createWidgets(self): self.can = Canvas(self.master, width=500, height=250) self.can.grid(row=2, column=1) self.can.create_line(0,0,500,200) def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() root = Tk() app = Application(master=root) app.mainloop() root.destroy() a window is never created. I found that adding a button to create a canvas works: from tkinter import ttk from tkinter import * from tkinter.ttk import * class Application(Frame): def makecanvas(self): self.grid_forget() self.can = Canvas(self.master, width=500, height=250) self.can.grid(row=2, column=1) self.can.create_line(0,0,500,200) def createWidgets(self): self.inst = Button(self) self.inst["text"] = "GO!" self.inst["command"] = self.makecanvas self.inst.grid(row=3, column=1, pady=15, sticky=N) def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() root = Tk() app = Application(master=root) app.mainloop() root.destroy() Also, If I comment out the create canvas function, the button I removed with self.grid_forget() doesn't disappear. Is there a better way to do this? A: The problem is that you are mixing geometry managers in the same window. You can only use one within a given parent widget. You can use both within your application as a whole, but you are using them both on widgets that have the same parent. You need to rewrite your code to use only grid, or only pack, for all widgets directly under the root window. Using the grid geometry manager from tkinter import ttk from tkinter import * from tkinter.ttk import * class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid() self.createWidgets() def createWidgets(self): self.can = Canvas(self.master, width=500, height=250) self.can.grid(row=2, column=1) self.can.create_line(0,0,500,200) root = Tk() app = Application(master=root) app.mainloop() root.destroy() Or using the pack geometry manager from tkinter import ttk from tkinter import * from tkinter.ttk import * class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): self.can = Canvas(self.master, width=500, height=250) self.can.pack() self.can.create_line(0,0,500,200) root = Tk() app = Application(master=root) app.mainloop() root.destroy()
just a canvas in a tkinter window
If I try to place a canvas in a tkinter window and nothing else with this code: from tkinter import ttk from tkinter import * from tkinter.ttk import * class Application(Frame): def createWidgets(self): self.can = Canvas(self.master, width=500, height=250) self.can.grid(row=2, column=1) self.can.create_line(0,0,500,200) def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() root = Tk() app = Application(master=root) app.mainloop() root.destroy() a window is never created. I found that adding a button to create a canvas works: from tkinter import ttk from tkinter import * from tkinter.ttk import * class Application(Frame): def makecanvas(self): self.grid_forget() self.can = Canvas(self.master, width=500, height=250) self.can.grid(row=2, column=1) self.can.create_line(0,0,500,200) def createWidgets(self): self.inst = Button(self) self.inst["text"] = "GO!" self.inst["command"] = self.makecanvas self.inst.grid(row=3, column=1, pady=15, sticky=N) def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() root = Tk() app = Application(master=root) app.mainloop() root.destroy() Also, If I comment out the create canvas function, the button I removed with self.grid_forget() doesn't disappear. Is there a better way to do this?
[ "The problem is that you are mixing geometry managers in the same window. You can only use one within a given parent widget. You can use both within your application as a whole, but you are using them both on widgets that have the same parent. \nYou need to rewrite your code to use only grid, or only pack, for all ...
[ 6 ]
[]
[]
[ "geometry", "layout", "python", "tkinter" ]
stackoverflow_0004158087_geometry_layout_python_tkinter.txt
Q: Python: create a list of dictionaries using a list comprehension I have a list of dictionaries, and I want to use it to create another list of dictionaries, slightly amended. Here's what I want to do: entries_expanded[:] = [{entry['id'], myfunction(entry['supplier'])} for entry in entries_expanded] So I end up with another list of dictionaries, just with one entry altered. The syntax above is broken. How can I do what I want? Please let me know if I should expand the code example. A: Isn't this what you want? entries_expanded[:] = [ dict((entry['id'], myfunction(entry['supplier']))) for entry in entries_expanded ] You could think of it as a generator that creates tuples followed by a list comprehension that makes dictionaries: entryiter = ((entry['id'], entry['supplier']) for entry in entries_expanded) tupleiter = ((id, myfunction(supplier)) for id, supplier in entryiter) entries_expanded[:] = [dict(t) for t in tupleiter] Alternatively, it is as the other answer suggests: entryiter = ((entry['id'], entry['supplier']) for entry in entries_expanded) tupleiter = ((id, myfunction(supplier)) for id, supplier in entryiter) entries_expanded[:] = [ dict((('id', id), ('supplier', supplier))) for id, supplier in tupleiter ] A: To create a new dictionary for each, you need to restate the keys: entries_expanded[:] = [{'id':entry['id'], 'supplier':myfunction(entry['supplier'])} for entry in entries_expanded] (If I've understood what you're trying to do correctly, anyway)
Python: create a list of dictionaries using a list comprehension
I have a list of dictionaries, and I want to use it to create another list of dictionaries, slightly amended. Here's what I want to do: entries_expanded[:] = [{entry['id'], myfunction(entry['supplier'])} for entry in entries_expanded] So I end up with another list of dictionaries, just with one entry altered. The syntax above is broken. How can I do what I want? Please let me know if I should expand the code example.
[ "Isn't this what you want?\nentries_expanded[:] = [\n dict((entry['id'], myfunction(entry['supplier']))) \n for entry in entries_expanded\n]\n\nYou could think of it as a generator that creates tuples followed by a list comprehension that makes dictionaries:\nentryiter = ((entry['id'], entry['supplier']) for ...
[ 3, 3 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0004158961_list_comprehension_python.txt
Q: Encoding problems in python x64 i´m trying to write a little script for writting a sqlite table from an archive list saved in a file. the code so far is this: import os import _sqlite3 import sys print sys.path[0] mydir = sys.path[0] print (mydir) def listdir(mydir): lis=[] for root, dirs, files in os.walk(mydir): for name in files: lis.append(os.path.join(root,name)) return lis filename = "list.txt" print ("writting in %s" % filename) file = open(filename, 'w' ) for i in listdir(mydir): file.write(i) file.write("\n") file.close() con = _sqlite3.connect("%s/conection"%mydir) c=con.cursor() c.execute(''' drop table files ''') c.execute('create table files (name text, other text)') file = open(filename,'r') for line in file : a = 1 for t in [("%s"%line, "%i"%a)]: c.execute('insert into files values(?,?)',t) a=a+1 c.execute('select * from files') print c.fetchall() con.commit() c.close() when i run i get the following: Traceback (most recent call last): File "C:\Users\josh\FORGE.py", line 32, in <module> c.execute('insert into files values(?,?)',t) ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings. i´ve tried with the unicode() built in function but still won´t work, saying that he can´t decode the character 0xed or something. I know the problem is on the encoding of the list strings, but i can´t find a way to put them right. any ideas? thanks in advance! A: (zero). please reformat your code after for line in file: do something like line = line.decode('encoding-of-the-file'), with encoding being something like utf-8, or iso-8859-1 -- you have to know your input encoding If you don't know the encoding or not care about having a clean decoding, you can guess the most probable encoding and do a line.decode('uft-8', 'ignore'), omitting all characters not decodable. Also, you can use 'replace', which replaces these chars with the 'Unicode Replacement Character' (\ufffd) use internally and during communication with the database only unicodeobjects, e.g. u'this is unicode' (3). Don't use file as variable name also look here: Best Practices for Python UnicodeDecodeError
Encoding problems in python x64
i´m trying to write a little script for writting a sqlite table from an archive list saved in a file. the code so far is this: import os import _sqlite3 import sys print sys.path[0] mydir = sys.path[0] print (mydir) def listdir(mydir): lis=[] for root, dirs, files in os.walk(mydir): for name in files: lis.append(os.path.join(root,name)) return lis filename = "list.txt" print ("writting in %s" % filename) file = open(filename, 'w' ) for i in listdir(mydir): file.write(i) file.write("\n") file.close() con = _sqlite3.connect("%s/conection"%mydir) c=con.cursor() c.execute(''' drop table files ''') c.execute('create table files (name text, other text)') file = open(filename,'r') for line in file : a = 1 for t in [("%s"%line, "%i"%a)]: c.execute('insert into files values(?,?)',t) a=a+1 c.execute('select * from files') print c.fetchall() con.commit() c.close() when i run i get the following: Traceback (most recent call last): File "C:\Users\josh\FORGE.py", line 32, in <module> c.execute('insert into files values(?,?)',t) ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings. i´ve tried with the unicode() built in function but still won´t work, saying that he can´t decode the character 0xed or something. I know the problem is on the encoding of the list strings, but i can´t find a way to put them right. any ideas? thanks in advance!
[ "(zero). please reformat your code\n\nafter for line in file: do something like line = line.decode('encoding-of-the-file'), with encoding being something like utf-8, or iso-8859-1 -- you have to know your input encoding\nIf you don't know the encoding or not care about having a clean decoding, you can guess the mos...
[ 1 ]
[]
[]
[ "encoding", "python", "sqlite" ]
stackoverflow_0004158840_encoding_python_sqlite.txt
Q: Synchronizing embedded Python in multi-threaded program Here is the example of using Python interpreter in multi-threaded program: #include <python.h> #include <boost/thread.hpp> void f(const char* code) { static volatile auto counter = 0; for(; counter < 20; ++counter) { auto state = PyGILState_Ensure(); PyRun_SimpleString(code); PyGILState_Release(state); boost::this_thread::yield(); } } int main() { PyEval_InitThreads(); Py_Initialize(); PyRun_SimpleString("x = 0\n"); auto mainstate = PyEval_SaveThread(); auto thread1 = boost::thread(f, "print('thread #1, x =', x)\nx += 1\n"); auto thread2 = boost::thread(f, "print('thread #2, x =', x)\nx += 1\n"); thread1.join(); thread2.join(); PyEval_RestoreThread(mainstate); Py_Finalize(); } It looks fine, but it isn't synchronized. Python interpreter releases and reacquires GIL multiple times during PyRun_SimpleString (see docs, p.#2). We can serialize PyRun_SimpleString call by using our own synchronization object, but it's a wrong way. Python has its own synchronization modules - _thread and threading. But they don't work in this code: Py_Initialize(); PyRun_SimpleString(R"( import _thread sync = _thread.allocate_lock() x = 0 )"); auto mainstate = PyEval_SaveThread(); auto thread1 = boost::thread(f, R"( with sync: print('thread #1, x =', x) x += 1 )"); it yields an error File "<string>", line 3, in <module> NameError: name '_[1]' is not defined and deadlocks. How to synchronize embedded python code most efficient way? A: When CPython calls out to a function that may block (or re-enter Python), it releases the global interpreter lock before calling the function, and then re-acquires the lock after the function returns. In your code, it's your call to the built-in print function that causes the interpreter lock to be released and the other thread to run (see string_print in stringobject.c). So you need your own lock: the global interpreter lock is not suitable for ensuring serialization of Python code that does I/O. Since you're using the Boost thread framework, you't probably find it most convenient to use one of the Boost thread synchronization primitives, e.g. boost::interprocess::interprocess_mutex. [Edited: my original answer was wrong, as pointed out by Abyx.] A: with statement has issue in Python 3.1, but it was fixed in Python 3.2 and Python 2.7. So the right solution is to use the threading module for synchronization. To avoid such issues, one shouldn't use multi-threaded code which uses temporary variables in globals dictionary, or use different globals dictionaries for each thread.
Synchronizing embedded Python in multi-threaded program
Here is the example of using Python interpreter in multi-threaded program: #include <python.h> #include <boost/thread.hpp> void f(const char* code) { static volatile auto counter = 0; for(; counter < 20; ++counter) { auto state = PyGILState_Ensure(); PyRun_SimpleString(code); PyGILState_Release(state); boost::this_thread::yield(); } } int main() { PyEval_InitThreads(); Py_Initialize(); PyRun_SimpleString("x = 0\n"); auto mainstate = PyEval_SaveThread(); auto thread1 = boost::thread(f, "print('thread #1, x =', x)\nx += 1\n"); auto thread2 = boost::thread(f, "print('thread #2, x =', x)\nx += 1\n"); thread1.join(); thread2.join(); PyEval_RestoreThread(mainstate); Py_Finalize(); } It looks fine, but it isn't synchronized. Python interpreter releases and reacquires GIL multiple times during PyRun_SimpleString (see docs, p.#2). We can serialize PyRun_SimpleString call by using our own synchronization object, but it's a wrong way. Python has its own synchronization modules - _thread and threading. But they don't work in this code: Py_Initialize(); PyRun_SimpleString(R"( import _thread sync = _thread.allocate_lock() x = 0 )"); auto mainstate = PyEval_SaveThread(); auto thread1 = boost::thread(f, R"( with sync: print('thread #1, x =', x) x += 1 )"); it yields an error File "<string>", line 3, in <module> NameError: name '_[1]' is not defined and deadlocks. How to synchronize embedded python code most efficient way?
[ "When CPython calls out to a function that may block (or re-enter Python), it releases the global interpreter lock before calling the function, and then re-acquires the lock after the function returns. In your code, it's your call to the built-in print function that causes the interpreter lock to be released and th...
[ 4, 2 ]
[]
[]
[ "c", "c++", "multithreading", "python" ]
stackoverflow_0004153140_c_c++_multithreading_python.txt
Q: Find the index of a partial dictionary element in a list I have a list of dictionary as follows: myList=[{'id':1,'key1':'a','key2':'b'},{'id':8,'key1':'c','key2':'d'}, {'id':6,'key1':'a','key2':'p'}] To find index of element, I am currently executing following statement: print myList.index({'id':8,'key1':'c','key2':'d'}) which returns 1 However, I would like to do something like this: print myList.index({'id':8}) should return 1 A: If you're looking for a one-liner (as opposed to reusable code), and your data size is small, you could do something like: [elem["id"] for elem in myList].index(8) which extracts the id from each dict, and then finds the index of the provided id. Depending on what your overall goals and data set look like, this might or might not be what you want... A: Should be relatively simple to implement. Written for Python 3, in Python 2 you should use .iteritems() (doesn't create a temporary list). def partial_dict_index(dicts, dict_part): for i, current_dict in enumerate(dicts): # if this dict has all keys required and the values match if all(key in current_dict and current_dict[key] == val for key, val in dict_part.items()): return i raise ValueError("...") Could use better names though... A: Edit: Please change your accepted answer to @delnan's corrected answer which is very similar and likely performs better.
Find the index of a partial dictionary element in a list
I have a list of dictionary as follows: myList=[{'id':1,'key1':'a','key2':'b'},{'id':8,'key1':'c','key2':'d'}, {'id':6,'key1':'a','key2':'p'}] To find index of element, I am currently executing following statement: print myList.index({'id':8,'key1':'c','key2':'d'}) which returns 1 However, I would like to do something like this: print myList.index({'id':8}) should return 1
[ "If you're looking for a one-liner (as opposed to reusable code), and your data size is small, you could do something like:\n[elem[\"id\"] for elem in myList].index(8)\n\nwhich extracts the id from each dict, and then finds the index of the provided id. Depending on what your overall goals and data set look like, t...
[ 3, 1, 1 ]
[ "You could implement your own list. Here is an example that prints the first found result. I added the ValueError to duplicate the existing behavior of .index().\nclass DictList(list):\n\n def index(self, obj):\n for i, o in enumerate(self):\n if o['id'] == obj['id']:\n return i\...
[ -1 ]
[ "dictionary", "indexing", "python" ]
stackoverflow_0004157400_dictionary_indexing_python.txt
Q: Recursively search networkx graph A question about recursion (and tangentially the graphing library networkx): I have an directed graph with node that have edges that have an attribute ["value"] that can be 0 or 1 (effectively edge weights). I want to be able to examine a node's neighbor recursively until a neighbor's node fails a certain threshold. For example: def checkAll(x): for neighbor in graph.neighbors(x): if neighbor is bad: fail else: checkAll(neighbor) #add all good neighbors here? This isn't working! I'm failing at recursion, basically, I think because of the way the "for" loop is done. Can I get some help? (I looked at this other SO post but it didn't seem particularly relevant?) Thank you! A: disclaimer : I don't know anything about networkx, but from my understanding of your problem, maybe this can help: def examine(node, neighbors_list) for neighbor in graph.neighbors(node): if graph[x]["neighbor"]["value"] = 1: return else: neighbors_list.append(neighbor) examine(neighbor, neighbors_list) x = parent_node neighbors = [] examine(x, neighbors)
Recursively search networkx graph
A question about recursion (and tangentially the graphing library networkx): I have an directed graph with node that have edges that have an attribute ["value"] that can be 0 or 1 (effectively edge weights). I want to be able to examine a node's neighbor recursively until a neighbor's node fails a certain threshold. For example: def checkAll(x): for neighbor in graph.neighbors(x): if neighbor is bad: fail else: checkAll(neighbor) #add all good neighbors here? This isn't working! I'm failing at recursion, basically, I think because of the way the "for" loop is done. Can I get some help? (I looked at this other SO post but it didn't seem particularly relevant?) Thank you!
[ "disclaimer : I don't know anything about networkx, but from my understanding of your problem, maybe this can help:\ndef examine(node, neighbors_list)\n \n for neighbor in graph.neighbors(node):\n if graph[x][\"neighbor\"][\"value\"] = 1:\n return\n else:\n neighbors_list.a...
[ 3 ]
[]
[]
[ "networkx", "python", "recursion" ]
stackoverflow_0004159247_networkx_python_recursion.txt
Q: Bittorrent up-to-date library written in python Is there any up-to-date bittorrent library which is written in python and can be used on windows to write client? Some time ago bitcomet was written in python and it was ok. Any alternatives? And second question: does bittorrent protocol change? For example what may happen if I will use old bitcomet library A: The main bittorrent client, from bittorrent.com is all python based I believe. I have hacked it in the past, and it's very clean code easy to modify.
Bittorrent up-to-date library written in python
Is there any up-to-date bittorrent library which is written in python and can be used on windows to write client? Some time ago bitcomet was written in python and it was ok. Any alternatives? And second question: does bittorrent protocol change? For example what may happen if I will use old bitcomet library
[ "The main bittorrent client, from bittorrent.com is all python based I believe. I have hacked it in the past, and it's very clean code easy to modify.\n" ]
[ 2 ]
[]
[]
[ "bittorrent", "client", "python" ]
stackoverflow_0004159847_bittorrent_client_python.txt
Q: What are efficient practices for importing python modules? I'm writing some views in Django, the are just python functions really. I'm curious as to whether there's a better way for me to arrange my files. It this... import a, b def x(request): return a(request) def y(request): return b(request) Less efficient than putting it in two files? import a def x(request): return a(request) and import b def y(request): return b(request) Since for each request made only one of these functions will be called, it seems to me that having the other one in the same file and importing all the modules the other one needs is a bad idea. Am I right? Does django just import the whole lot anyway? A: Unless you're running Django via CGI (which I really hope you're not), the imports will be cached after the first time they're performed, and this whole argument is meaningless. A: There's not a whole lot of difference, use whatever is most readable. A: You don't need to worry about how many files you use; the difference in performance is negligible. That said, there are more efficient and readable ways to use imports. Only import what you need; never use from x import * unless you are really going to use everything in X. Don't nest imports; instead of import a, b, write: import a import b As for your specific issue, you should have a module to represent a typical course of action. If you always have to run two functions, one after the other, put them in the same file. If not, do whatever makes the most sense to you and the people that you're working with. Remember, imports that take the form import a (as opposed to from x import y, z) are relatively cheap. A: Also, instead of doing this: def x(request): return a(request) it would probably be better to call the original function.
What are efficient practices for importing python modules?
I'm writing some views in Django, the are just python functions really. I'm curious as to whether there's a better way for me to arrange my files. It this... import a, b def x(request): return a(request) def y(request): return b(request) Less efficient than putting it in two files? import a def x(request): return a(request) and import b def y(request): return b(request) Since for each request made only one of these functions will be called, it seems to me that having the other one in the same file and importing all the modules the other one needs is a bad idea. Am I right? Does django just import the whole lot anyway?
[ "Unless you're running Django via CGI (which I really hope you're not), the imports will be cached after the first time they're performed, and this whole argument is meaningless.\n", "There's not a whole lot of difference, use whatever is most readable.\n", "You don't need to worry about how many files you use;...
[ 3, 2, 0, 0 ]
[]
[]
[ "django", "django_views", "python", "python_import" ]
stackoverflow_0004159332_django_django_views_python_python_import.txt
Q: Safely evaluate string in Python to call hashlib I would like to allow people to provide the name of a hash function as a means of digitally fingerprinting some object: def create_ref(obj, hashfn='sha256'): """ Returns a tuple of hexdigest and the method used to generate the digest. >>> create_ref({}, 'sha1') ('bf21a9e8fbc5a3846fb05b4fa0859e0917b2202f', 'sha1') >>> create_ref({}, 'md5') ('99914b932bd37a50b983c5e7c90ae93b', 'md5') """ return (eval('hashlib.%s' % hashfn)(unicode(obj)).hexdigest(), hashfn) Is hard coding hashlib sufficently robust to prevent abuse of eval? A: No. If you apply some of the SQL Injection attack concepts, it would be conceviable for the user to supply something like this: "sha1(...); some_evil_code(); hashlib.sha1" Which would totally blow the "security" away by ending up like this: "hashlib." + "sha1(...); some_evil_code(); hashlib.sha1" + "(your-original-code)" Which would result in 3 statements being run (a fine one, and evil one, and a fine one). (even if the above code has holes in it, the concept could still be exploited) Instead, use the dynamic power of python to make this work! TYPES = ('sha256', 'sha1', 'md5', ...) def create_ref(obj, hashfn='sha256'): if hashfn not in TYPES: raise ValueError("bad type") # look up the actual method fun = getattr(hashlib, hashfn) # and call it on `obj` fun(...) Food for thought! A: instead of eval, try this code: def create_ref(obj, hashfn='sha256'): """ Returns a tuple of hexdigest and the method used to generate the digest. >>> create_ref({}, 'sha1') ('bf21a9e8fbc5a3846fb05b4fa0859e0917b2202f', 'sha1') >>> create_ref({}, 'md5') ('99914b932bd37a50b983c5e7c90ae93b', 'md5') """ allowed = hashlib.algorithms if hashfn in allowed: return (getattr(hashlib,hashfn)(unicode(obj)).hexdigest(), hashfn) else: raise NameError('Not a valid algorithm') This will guarantee that the algorithm provided is a valid algorithm. (Note that hashlib.algorithms is new in 2.7, so if you use an older version, replace hashlib.algorithms with a tuple of allowed algorithms. A: import hashlib ... return (getattr(hashlib, hashfn)(unicode(obj)).hexdigest(), hashfn) i think like this is more safely than using eval()
Safely evaluate string in Python to call hashlib
I would like to allow people to provide the name of a hash function as a means of digitally fingerprinting some object: def create_ref(obj, hashfn='sha256'): """ Returns a tuple of hexdigest and the method used to generate the digest. >>> create_ref({}, 'sha1') ('bf21a9e8fbc5a3846fb05b4fa0859e0917b2202f', 'sha1') >>> create_ref({}, 'md5') ('99914b932bd37a50b983c5e7c90ae93b', 'md5') """ return (eval('hashlib.%s' % hashfn)(unicode(obj)).hexdigest(), hashfn) Is hard coding hashlib sufficently robust to prevent abuse of eval?
[ "No.\nIf you apply some of the SQL Injection attack concepts, it would be conceviable for the user to supply something like this:\n\"sha1(...); some_evil_code(); hashlib.sha1\"\nWhich would totally blow the \"security\" away by ending up like this:\n\"hashlib.\" + \"sha1(...); some_evil_code(); hashlib.sha1\" + \"(...
[ 4, 3, 1 ]
[ "TYPES = {'sha256':hashlib.sha256 , 'sha1': hashlib.sha1, 'md5': hashlib.md5, ...}\ndef create_ref(obj, hashfn='sha256'):\n #var 1 - use sha256 as default on invalid hashfun\n #func=TYPES.get(hashfn, hashlib.sha256)\n\n #var 2 raise error on invalid hashfun\n if TYPES.has_key(hashfn):\n func=TYPE...
[ -1 ]
[ "python" ]
stackoverflow_0004159754_python.txt
Q: Computing averages of records from multiple files with python Dear all, I am beginner in Python. I am looking for the best way to do the following in Python: let's assume I have three text files, each one with m rows and n columns of numbers, name file A, B, and C. For the following, the contents can be indexed as A[i][j], or B[k][l] and so on. I need to compute the average of A[0][0], B[0][0], C[0][0], and writes it to file D at D[0][0]. And the same for the remaining records. For instance, let's assume that : A: 1 2 3 4 5 6 B: 0 1 3 2 4 5 C: 2 5 6 1 1 1 Therefore, file D should be D: 1 2.67 4 2.33 3.33 4 My actual files are of course larger than the present ones, of the order of some Mb. I am unsure about the best solution, if reading all the file contents in a nested structure indexed by filename, or trying to read, for each file, each line and computing the mean. After reading the manual, the fileinput module is not useful in this case because it does not read the lines "in parallel", as I need here, but it reads the lines "serially". Any guidance or advice is highly appreciated. A: Have a look at numpy. It can read the three files into three arrays (using fromfile), calculate the average and export it to a text file (using tofile). import numpy as np a = np.fromfile('A.csv', dtype=np.int) b = np.fromfile('B.csv', dtype=np.int) c = np.fromfile('C.csv', dtype=np.int) d = (a + b + c) / 3.0 d.tofile('D.csv') Size of "some MB" should not be a problem. A: In case of text files, try this: def readdat(data,sep=','): step1 = data.split('\n') step2 = [] for index in step1: step2.append(float(index.split(sep))) return step2 def formatdat(data,sep=','): step1 = [] for index in data: step1.append(sep.join(str(data))) return '\n'.join(step1) and then use these functions to format the text into lists. A: Just for reference, here's how you'd do the same sort of thing without numpy (less elegant, but more flexible): files = zip(open("A.dat"), open("B.dat"), open("C.dat")) outfile = open("D.dat","w") for rowgrp in files: # e.g.("1 2 3\n", "0 1 3\n", "2 5 6\n") intsbyfile = [[int(a) for a in row.strip().split()] for row in rowgrp] # [[1,2,3], [0,1,3], [2,5,6]] intgrps = zip(*intsbyfile) # [(1,0,2), (2,1,5), (3,3,6)] # use float() to ensure we get true division in Python 2. averages = [float(sum(intgrp))/len(intgrp) for intgrp in intgrps] outfile.write(" ".join(str(a) for a in averages) + "\n") In Python 3, zip will only read the files as they are needed. In Python 2, if they're too big to load into memory, use itertools.izip instead.
Computing averages of records from multiple files with python
Dear all, I am beginner in Python. I am looking for the best way to do the following in Python: let's assume I have three text files, each one with m rows and n columns of numbers, name file A, B, and C. For the following, the contents can be indexed as A[i][j], or B[k][l] and so on. I need to compute the average of A[0][0], B[0][0], C[0][0], and writes it to file D at D[0][0]. And the same for the remaining records. For instance, let's assume that : A: 1 2 3 4 5 6 B: 0 1 3 2 4 5 C: 2 5 6 1 1 1 Therefore, file D should be D: 1 2.67 4 2.33 3.33 4 My actual files are of course larger than the present ones, of the order of some Mb. I am unsure about the best solution, if reading all the file contents in a nested structure indexed by filename, or trying to read, for each file, each line and computing the mean. After reading the manual, the fileinput module is not useful in this case because it does not read the lines "in parallel", as I need here, but it reads the lines "serially". Any guidance or advice is highly appreciated.
[ "Have a look at numpy. It can read the three files into three arrays (using fromfile), calculate the average and export it to a text file (using tofile).\nimport numpy as np\n\n\na = np.fromfile('A.csv', dtype=np.int) \nb = np.fromfile('B.csv', dtype=np.int) \nc = np.fromfile('C.csv', dtype=np.int) \n\nd = (a...
[ 1, 0, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0004159582_file_io_python.txt
Q: Django get_query_set override is being cached I'm overriding Django's get_query_set function on one of my models dynamically. I'm doing this to forcibly filter the original query set returned by Model.objects.all/filter/get by a "scenario" value, using a decorator. Here's the decorator's function: # Get the base QuerySet for these models before we modify their # QuerySet managers. This prevents infinite recursion since the # get_query_set function doesn't rely on itself to get this base QuerySet. all_income_objects = Income.objects.all() # Figure out what scenario the user is using. current_scenario = Scenario.objects.get(user=request.user, selected=True) # Modify the imported income class to filter based on the current scenario. Expense.objects.get_query_set = lambda: all_expense_objects.filter(scenario=current_scenario) # Call the method that was initially supposed to # be executed before we were so rudely interrupted. return view(request, **arguments) I'm doing this to DRY up the code, so that all of my queries aren't littered with an additional filter. However, if the scenario changes, no objects are being returned. If I kill all of my python processes on my server, the objects for the newly select scenario appear. I'm thinking that it's caching the modified class, and then when the scenario changes, it's applying another filter that will never make sense, since objects can only have one scenario at a time. This hasn't been an issue with user-based filters because the user never changes for my session. Is passenger doing something stupid to hold onto class objects between requests? Should I be bailing on this weird design pattern and just implement these filters on a per-view basis? There must be a best practice for DRYing filters up that apply across many views based on something dynamic, like the current user. A: What about creating a Manager object for the model which takes the user as an argument where this filtering is done. My understanding of being DRY w/ Django querysets is to use a Model Manager #### view code: def some_view(request): expenses = Expense.objects.filter_by_cur_scenario(request.user) # add additional filters here, or add to manager via more params expenses = expenses.filter(something_else=True) #### models code: class ExpenseManager(models.Manager): def filter_by_cur_scenario(self, user): current_scenario = Scenario.objects.get(user=request.user, selected=True) return self.filter(scenario=current_scenario) class Expense(models.Model): objects = ExpenseManager() Also, one quick caveat on the manager (which may apply to overriding get_query_set): foreign relationships will not take into account any filtering done at this level. For example, you override the MyObject.objects.filter() method to always filter out deleted rows; A model w/ a foreignkey to that won't use that filter function (at least from what I understand -- someone please correct me if I'm wrong). A: I was hoping to have this implementation happen without having to code anything in other views. Essentially, after the class is imported, I want to modify it so that no matter where it's referenced using Expense.objects.get/filter/all it's already been filtered. As a result, there is no implementation required for any of the other views; it's completely transparent. And, even in cases where I'm using it as a ForeignKey, when an object is retrieved using the aforementioned Expense.objects.get/filter/all, they'll be filtered as well.
Django get_query_set override is being cached
I'm overriding Django's get_query_set function on one of my models dynamically. I'm doing this to forcibly filter the original query set returned by Model.objects.all/filter/get by a "scenario" value, using a decorator. Here's the decorator's function: # Get the base QuerySet for these models before we modify their # QuerySet managers. This prevents infinite recursion since the # get_query_set function doesn't rely on itself to get this base QuerySet. all_income_objects = Income.objects.all() # Figure out what scenario the user is using. current_scenario = Scenario.objects.get(user=request.user, selected=True) # Modify the imported income class to filter based on the current scenario. Expense.objects.get_query_set = lambda: all_expense_objects.filter(scenario=current_scenario) # Call the method that was initially supposed to # be executed before we were so rudely interrupted. return view(request, **arguments) I'm doing this to DRY up the code, so that all of my queries aren't littered with an additional filter. However, if the scenario changes, no objects are being returned. If I kill all of my python processes on my server, the objects for the newly select scenario appear. I'm thinking that it's caching the modified class, and then when the scenario changes, it's applying another filter that will never make sense, since objects can only have one scenario at a time. This hasn't been an issue with user-based filters because the user never changes for my session. Is passenger doing something stupid to hold onto class objects between requests? Should I be bailing on this weird design pattern and just implement these filters on a per-view basis? There must be a best practice for DRYing filters up that apply across many views based on something dynamic, like the current user.
[ "What about creating a Manager object for the model which takes the user as an argument where this filtering is done. My understanding of being DRY w/ Django querysets is to use a Model Manager\n#### view code:\ndef some_view(request):\n expenses = Expense.objects.filter_by_cur_scenario(request.user)\n\n # a...
[ 0, 0 ]
[]
[]
[ "django", "django_queryset", "dry", "filter", "python" ]
stackoverflow_0004158283_django_django_queryset_dry_filter_python.txt
Q: Can't import EasyDialogs - ImportError: No module named _Dlg I'm trying to use the EasyDialogs python module to produce some simple dialog boxes for my python script on OSX. Whenever I try and import the EasyDialogs module I get the following error: >>> import EasyDialogs Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/EPD64.framework/Versions/6.2/lib/python2.6/plat-mac/EasyDialogs.py", line 24, in <module> from Carbon.Dlg import GetNewDialog, SetDialogItemText, GetDialogItemText, ModalDialog File "/Library/Frameworks/EPD64.framework/Versions/6.2/lib/python2.6/plat-mac/Carbon/Dlg.py", line 1, in <module> from _Dlg import * ImportError: No module named _Dlg I've tried doing easy_install Carbon, as I thought it may be due to some issue with the Carbon package for python, but that hasn't helped. Any ideas? A: From the paths in your traceback, you appear to be using a 64-bit Enthought Python Distribution. The EasyDialogs module uses various OS X Carbon interfaces, many of which OS X only provides 32-bit versions and have been deprecated by Apple. For this reason, the Python Carbon wrapper and EasyDialogs modules are deprecated in Python 2 and have been removed in Python 3. While they may work in 32-bit mode, you should avoid using them in new code. There are other alternatives available: Tkinter in the standard library, various cross platform GUI frameworks (see here). For more simple dialogs, you could also use the osax package in appscript to use the User Interaction suite of AppleScript's Standard Additions.
Can't import EasyDialogs - ImportError: No module named _Dlg
I'm trying to use the EasyDialogs python module to produce some simple dialog boxes for my python script on OSX. Whenever I try and import the EasyDialogs module I get the following error: >>> import EasyDialogs Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/EPD64.framework/Versions/6.2/lib/python2.6/plat-mac/EasyDialogs.py", line 24, in <module> from Carbon.Dlg import GetNewDialog, SetDialogItemText, GetDialogItemText, ModalDialog File "/Library/Frameworks/EPD64.framework/Versions/6.2/lib/python2.6/plat-mac/Carbon/Dlg.py", line 1, in <module> from _Dlg import * ImportError: No module named _Dlg I've tried doing easy_install Carbon, as I thought it may be due to some issue with the Carbon package for python, but that hasn't helped. Any ideas?
[ "From the paths in your traceback, you appear to be using a 64-bit Enthought Python Distribution. The EasyDialogs module uses various OS X Carbon interfaces, many of which OS X only provides 32-bit versions and have been deprecated by Apple. For this reason, the Python Carbon wrapper and EasyDialogs modules are d...
[ 3 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0004159194_python_user_interface.txt
Q: Can I somehow "compile" a python script to work on PC without Python installed? So I have a Python script: myscript.py I am executing it like this: python D:\myscript.py However, I must have Python installed and included in the PATH environment variable for that to work. Is it somehow possible to "bundle" Python executable with a Python script so other people will be able to run it on their PCs without Python? It is ok if it will work only in Windows. EDIT: After trying the compile.py I get this error: Traceback (most recent call last): File "D:\stuff\compile.py", line 4, in <module> import py2exe ImportError: No module named py2exe A: Here is one way to do it (for Windows, using py2exe). First, install the py2exe on your Windows box. Then create a python script named compile.py, like this: import sys from distutils.core import setup import py2exe entry_point = sys.argv[1] sys.argv.pop() sys.argv.append('py2exe') sys.argv.append('-q') opts = { 'py2exe': { 'compressed': 1, 'optimize': 2, 'bundle_files': 1 } } setup(console=[entry_point], options=opts, zipfile=None) To compile your Python script into a Windows executable, run this script with your program as its argument: $ python compile.py myscript.py It will spit out a binary executable (EXE) with a Python interpreter compiled inside. You can then just distribute this executable file. A: PyInstaller has worked well for me, generating reasonably small packages due to its use of upx. Its dependency detection was better than py2exe at the time as well. It seems not to have a lot of recent development and probably doesn't work with 3.x, however. The source in the repository is a better starting point than the 1.4 package. Also see the wiki page about working with Python 2.6+. From the features list: Packaging of Python programs into standard executables, that work on computers without Python installed. Multiplatform: works under Windows (32-bit and 64-bit), Linux (32-bit and 64-bit) and Mac OS X (32-bit only for now, see MacOsCompatibility). Multiversion: works under any version of Python from 1.5 up to 2.7. NOTE: If you're using Python 2.6+ on Windows, see Python26Win. Flexible packaging mode: Single directory: build a directory containing an executable plus all the external binary modules (.dll, .pyd, .so) used by the program. Single file: build a single executable file, totally self-contained, which runs without any external dependency. Custom: you can automate PyInstaller to do whatever packaging mode you want through a simple script file in Python. Explicit intelligent support for many 3rd-packages (for hidden imports, external data files, etc.), to make them work with PyInstaller out-of-the-box (see SupportedPackages). Full single-file EGG support: required .egg files are automatically inspected for dependencies and bundled, and all the egg-specific features are supported at runtime as well (entry points, etc.). Partial directory EGG support: required .egg directories are automatically inspected for dependencies and bundled, but egg-specific features will not work at runtime. Automatic support for binary libraries used through ctypes (see CtypesDependencySupport for details). Support for automatic binary packing through the well-known UPX compressor. Optional console mode (see standard output and standard error at runtime). Windows-specific features: Support for code-signing executables. Full automatic support for CRTs: no need to manually distribute MSVCR*.DLL, redist installers, manifests, or anything else; true one-file applications that work everywhere! Selectable executable icon. Fully configurable version resource section and manifests in executable. Support for building COM servers. Mac-specific features: Preliminar support for bundles (see MacOsCompatibility) A: You want something like py2exe. A: There are multiple solutions like py2exe, cx-freeze or (only for Mac OS X) py2app. A: Here is a list of them.
Can I somehow "compile" a python script to work on PC without Python installed?
So I have a Python script: myscript.py I am executing it like this: python D:\myscript.py However, I must have Python installed and included in the PATH environment variable for that to work. Is it somehow possible to "bundle" Python executable with a Python script so other people will be able to run it on their PCs without Python? It is ok if it will work only in Windows. EDIT: After trying the compile.py I get this error: Traceback (most recent call last): File "D:\stuff\compile.py", line 4, in <module> import py2exe ImportError: No module named py2exe
[ "Here is one way to do it (for Windows, using py2exe).\nFirst, install the py2exe on your Windows box.\nThen create a python script named compile.py, like this:\nimport sys\nfrom distutils.core import setup\nimport py2exe\n\nentry_point = sys.argv[1]\nsys.argv.pop()\nsys.argv.append('py2exe')\nsys.argv.append('-q')...
[ 29, 13, 11, 9, 7 ]
[]
[]
[ "compilation", "python" ]
stackoverflow_0004158369_compilation_python.txt
Q: Python basics- why aren't the contents of my file printing? I'm running this from eclipse, the file name I'm working with is ex16_text.txt (yes I type it in correctly. It writes to the file correctly (the input appears), but the "print txt.read()" doesn't seem to do anything (prints a blank line), see the output after the code: filename = raw_input("What's the file name we'll be working with?") print "we're going to erase %s" % filename print "opening the file" target = open(filename, 'w') print "erasing the file" target.truncate() print "give me 3 lines to replace file contents:" line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") line3 = raw_input("line 3: ") print "writing lines to file" target.write(line1+"\n") target.write(line2+"\n") target.write(line3) #file read txt = open(filename) print "here are the contents of the %s file:" % filename print txt.read() target.close() Output: What's the file name we'll be working with?ex16_text.txt we're going to erase ex16_text.txt opening the file erasing the file give me 3 lines to replace file contents: line 1: three line 2: two line 3: one writing lines to file here are the contents of the ex16_text.txt file: A: You should flush the file after you have written to it to ensure that the bytes have been written. Also read the warning: Note: flush() does not necessarily write the file’s data to disk. Use flush() followed by os.fsync() to ensure this behavior. You should also close the file if you have finished writing to it and want to open it again with read only access. Note that closing the file also flushes - if you close it then you don't need to flush first. In Python 2.6 or newer you can use the with statement to automatically close the file: with open(filename, 'w') as target: target.write('foo') # etc... # The file is closed when the control flow leaves the "with" block with open(filename, 'r') as txt: print txt.read() A: target.write(line2+"\n") target.write(line3) target.close() #<------- You need to close the file when you're done writing. #file read txt = open(filename)
Python basics- why aren't the contents of my file printing?
I'm running this from eclipse, the file name I'm working with is ex16_text.txt (yes I type it in correctly. It writes to the file correctly (the input appears), but the "print txt.read()" doesn't seem to do anything (prints a blank line), see the output after the code: filename = raw_input("What's the file name we'll be working with?") print "we're going to erase %s" % filename print "opening the file" target = open(filename, 'w') print "erasing the file" target.truncate() print "give me 3 lines to replace file contents:" line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") line3 = raw_input("line 3: ") print "writing lines to file" target.write(line1+"\n") target.write(line2+"\n") target.write(line3) #file read txt = open(filename) print "here are the contents of the %s file:" % filename print txt.read() target.close() Output: What's the file name we'll be working with?ex16_text.txt we're going to erase ex16_text.txt opening the file erasing the file give me 3 lines to replace file contents: line 1: three line 2: two line 3: one writing lines to file here are the contents of the ex16_text.txt file:
[ "You should flush the file after you have written to it to ensure that the bytes have been written. Also read the warning:\n\nNote: flush() does not necessarily write the file’s data to disk. Use flush() followed by os.fsync() to ensure this behavior.\n\nYou should also close the file if you have finished writing t...
[ 6, 4 ]
[]
[]
[ "python" ]
stackoverflow_0004160444_python.txt
Q: algorithm to find the correct set of numbers i will take either python of c# solution i have about 200 numbers: 19.16 98.48 20.65 122.08 26.16 125.83 473.33 125.92 3,981.21 16.81 100.00 43.58 54.19 19.83 3,850.97 20.83 20.83 86.81 37.71 36.33 6,619.42 264.53 ... ... i know that in this set of numbers, there is a combination of numbers that will add up to a certain number let's say it is 2341.42 how do i find out which combination of numbers will add up to that? i am helping someone in accounting track down the correct numbers A: Here's a recursive function in Python that will find ALL solutions of any size with only two arguments (that you need to specify). def find_all_sum_subsets(target_sum, numbers, offset=0): solutions = [] for i in xrange(offset, len(numbers)): value = numbers[i] if target_sum == value: solutions.append([value]) elif target_sum > value: sub_solutions = find_all_sum_subsets(target_sum - value, numbers, i + 1) for sub_solution in sub_solutions: solutions.append(sub_solution + [value]) return solutions Here it is working: >>> find_all_sum_subsets(10, [1,2,3,4,5,6,7,8,9,10,11,12]) [[4, 3, 2, 1], [7, 2, 1], [6, 3, 1], [5, 4, 1], [9, 1], [5, 3, 2], [8, 2], [7, 3], [6, 4], [10]] >>> A: You can use backtracking to generate all the possible solutions. This way you can quickly write your solution. EDIT: You just implement the algoritm in C#: public void backtrack (double sum, String solution, ArrayList numbers, int depth, double targetValue, int j) { for (int i = j; i < numbers.Count; i++) { double potentialSolution = Convert.ToDouble(arrayList[i] + ""); if (sum + potentialSolution > targetValue) continue; else if (sum + potentialSolution == targetValue) { if (depth == 0) { solution = potentialSolution + ""; /*Store solution*/ } else { solution += "," + potentialSolution; /*Store solution*/ } } else { if (depth == 0) { solution = potentialSolution + ""; } else { solution += "," + potentialSolution; } backtrack (sum + potentialSolution, solution, numbers, depth + 1, targetValue, i + 1); } } } You will call this function this way: backtrack (0, "", numbers, 0, 2341.42, 0); The source code was implemented on the fly to answer your question and was not tested, but esencially you can understand what I mean from this code. A: This should be implemented as a recursive algorithm. Basically, for any given number, determine if there is a subset of the remaining numbers for which the sum is your desired value. Iterate across the list of numbers; for each entry, subtract that from your total, and determine if there is a subset of the remaining list which sums up to the new total. If not, try with your original total and the next number in the list (and a smaller sublist, of course). As to implementation: You want to define a method which takes a target number, and a list, and which returns a list of numbers which sum up to that target number. That algorithm should iterate through the list; if an element of the list subtracted from the target number is zero, return that element in a list; otherwise, recurse on the method with the remainder of the list, and the new target number. If any recursion returns a non-null result, return that; otherwise, return null. ArrayList<decimal> FindSumSubset(decimal sum, ArrayList<decimal> list) { for (int i = 0; i < list.Length; i++) { decimal value = list[i]; if (sum - value == 0.0m) { return new ArrayList<decimal>().Add(value); } else { var subset = FindSumSubset(sum - value, list.GetRange(i + 1, list.Length -i); if (subset != null) { return subset.Add(value); } } } return null; } Note, however, that the order of this is pretty ugly, and for significantly larger sets of numbers, this becomes intractable relatively quickly. This should be doable in less than geologic time for 200 decimals, though. A: Try the following approach if finding a combination of any two (2) numbers: float targetSum = 3; float[] numbers = new float[]{1, 2, 3, 4, 5, 6}; Sort(numbers); // Sort numbers in ascending order. int startIndex = 0; int endIndex = numbers.Length - 1; while (startIndex != endIndex) { float firstNumber = numbers[startIndex]; float secondNumber = numbers[endIndex]; float sum = firstNumber + secondNumber; if (sum == targetSum) { // Found a combination. break; } else if (sum < targetSum) { startIndex++; } else { endIndex--; } } Remember that when use floating-point or decimal numbers, rounding could be an issue. A: [Begin Edit]: I misread the original question. I thought that it said that there is some combination of 4 numbers in the list of 200+ numbers that add up to some other number. That is not what was asked, so my answer does not really help much. [End Edit] This is pretty clunky, but it should work if all you need is to find the 4 numbers that add up to a certain value (it could find more than 4 tuples): Just get your 200 numbers into an array (or list or some IEnumerable structure) and then you can use the code that I posted. If you have the numbers on paper, you will have to enter them into the array manually as below. If you have them in softcopy, you can cut and paste them and then add the numbers[x] = xxx code around them. Or, you could cut and paste them into a file and then read the file from disk into an array. double [] numbers = new numbers[200]; numbers[0] = 123; numbers[1] = 456; // // and so on. // var n0 = numbers; var n1 = numbers.Skip(1); var n2 = numbers.Skip(2); var n3 = numbers.Skip(3); var x = from a in n0 from b in n1 from c in n2 from d in n3 where a + b + c + d == 2341.42 select new { a1 = a, b1 = b, c1 = c, d1 = d }; foreach (var aa in x) { Console.WriteLine("{0}, {1}, {2}, {3}", aa.a1, aa.b1, aa.c1, aa.d1 ); }
algorithm to find the correct set of numbers
i will take either python of c# solution i have about 200 numbers: 19.16 98.48 20.65 122.08 26.16 125.83 473.33 125.92 3,981.21 16.81 100.00 43.58 54.19 19.83 3,850.97 20.83 20.83 86.81 37.71 36.33 6,619.42 264.53 ... ... i know that in this set of numbers, there is a combination of numbers that will add up to a certain number let's say it is 2341.42 how do i find out which combination of numbers will add up to that? i am helping someone in accounting track down the correct numbers
[ "Here's a recursive function in Python that will find ALL solutions of any size with only two arguments (that you need to specify).\ndef find_all_sum_subsets(target_sum, numbers, offset=0):\n solutions = []\n for i in xrange(offset, len(numbers)):\n value = numbers[i]\n if target_sum == value:\n...
[ 4, 3, 1, 1, 1 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0004158988_c#_python.txt
Q: Python - Speed up an A Star Pathfinding Algorithm I've coded my first slightly-complex algorithm, an implementation of the A Star Pathfinding algorithm. I followed some Python.org advice on implementing graphs so a dictionary contains all the nodes each node is linked too. Now, since this is all for a game, each node is really just a tile in a grid of nodes, hence how I'm working out the heuristic and my occasional reference to them. Thanks to timeit I know that I can run this function successfully a little over one hundred times a second. Understandably this makes me a little uneasy, this is without any other 'game stuff' going on, like graphics or calculating game logic. So I'd love to see whether any of you can speed up my algorithm, I am completely unfamiliar with Cython or it's kin, I can't code a line of C. Without any more rambling, here is my A Star function. def aStar(self, graph, current, end): openList = [] closedList = [] path = [] def retracePath(c): path.insert(0,c) if c.parent == None: return retracePath(c.parent) openList.append(current) while len(openList) is not 0: current = min(openList, key=lambda inst:inst.H) if current == end: return retracePath(current) openList.remove(current) closedList.append(current) for tile in graph[current]: if tile not in closedList: tile.H = (abs(end.x-tile.x)+abs(end.y-tile.y))*10 if tile not in openList: openList.append(tile) tile.parent = current return path A: An easy optimization is to use sets instead of lists for the open and closed sets. openSet = set() closedSet = set() This will make all of the in and not in tests O(1) instead of O(n). A: I would use the sets as have been said, but I would also use a heap to find the minimum element (the one that will be the next current). This would require keeping both an openSet and an openHeap, but the memory shouldn't really be a problem. Also, sets insert in O(1) and heaps in O(log N) so they will be fast. The only problem is that the heapq module isn't really made to use keys with it. Personally, I would just modify it to use keys. It shouldn't be very hard. Alternatively, you could just use tuples of (tile.H,tile) in the heap. Also, I would follow aaronasterling's idea of using iteration instead of recursion, but also, I would append elements to the end of path and reverse path at the end. The reason is that inserting an item at the 0th place in a list is very slow, (O(N) I believe), while appending is O(1) if I recall correctly. The final code for that part would be: def retracePath(c): path = [c] while c.parent is not None: c = c.parent path.append(c) path.reverse() return path I put return path at the end because it appeared that it should from your code. Here's the final code using sets, heaps and what not: import heapq def aStar(graph, current, end): openSet = set() openHeap = [] closedSet = set() def retracePath(c): path = [c] while c.parent is not None: c = c.parent path.append(c) path.reverse() return path openSet.add(current) openHeap.append((0, current)) while openSet: current = heapq.heappop(openHeap)[1] if current == end: return retracePath(current) openSet.remove(current) closedSet.add(current) for tile in graph[current]: if tile not in closedSet: tile.H = (abs(end.x - tile.x)+abs(end.y-tile.y))*10 if tile not in openSet: openSet.add(tile) heapq.heappush(openHeap, (tile.H, tile)) tile.parent = current return [] A: As suggested above, make closedSet into a set. I tried coding openList as a heap import heapq: import heapq def aStar(self, graph, current, end): closedList = set() path = [] def retracePath(c): path.insert(0,c) if c.parent == None: return retracePath(c.parent) openList = [(-1, current)] heapq.heapify(openList) while openList: score, current = openList.heappop() if current == end: return retracePath(current) closedList.add(current) for tile in graph[current]: if tile not in closedList: tile.H = (abs(end.x-tile.x)+abs(end.y-tile.y))*10 if tile not in openList: openList.heappush((tile.H, tile)) tile.parent = current return path However, you still need to search at if tile not in openList, so I would do this: def aStar(self, graph, current, end): openList = set() closedList = set() def retracePath(c): def parentgen(c): while c: yield c c = c.parent result = [element for element in parentgen(c)] result.reverse() return result openList.add(current) while openList: current = sorted(openList, key=lambda inst:inst.H)[0] if current == end: return retracePath(current) openList.remove(current) closedList.add(current) for tile in graph[current]: if tile not in closedList: tile.H = (abs(end.x-tile.x)+abs(end.y-tile.y))*10 openList.add(tile) tile.parent = current return []
Python - Speed up an A Star Pathfinding Algorithm
I've coded my first slightly-complex algorithm, an implementation of the A Star Pathfinding algorithm. I followed some Python.org advice on implementing graphs so a dictionary contains all the nodes each node is linked too. Now, since this is all for a game, each node is really just a tile in a grid of nodes, hence how I'm working out the heuristic and my occasional reference to them. Thanks to timeit I know that I can run this function successfully a little over one hundred times a second. Understandably this makes me a little uneasy, this is without any other 'game stuff' going on, like graphics or calculating game logic. So I'd love to see whether any of you can speed up my algorithm, I am completely unfamiliar with Cython or it's kin, I can't code a line of C. Without any more rambling, here is my A Star function. def aStar(self, graph, current, end): openList = [] closedList = [] path = [] def retracePath(c): path.insert(0,c) if c.parent == None: return retracePath(c.parent) openList.append(current) while len(openList) is not 0: current = min(openList, key=lambda inst:inst.H) if current == end: return retracePath(current) openList.remove(current) closedList.append(current) for tile in graph[current]: if tile not in closedList: tile.H = (abs(end.x-tile.x)+abs(end.y-tile.y))*10 if tile not in openList: openList.append(tile) tile.parent = current return path
[ "An easy optimization is to use sets instead of lists for the open and closed sets. \nopenSet = set()\nclosedSet = set()\n\nThis will make all of the in and not in tests O(1) instead of O(n).\n", "I would use the sets as have been said, but I would also use a heap to find the minimum element (the one that will ...
[ 39, 10, 5 ]
[]
[]
[ "a_star", "algorithm", "performance", "python" ]
stackoverflow_0004159331_a_star_algorithm_performance_python.txt
Q: Conditional removal of an element from XML document tree My task is to do minor refactoring of some elements of XML tree in python 3, namely replace following structure: <span class="nobr"> <a href="http://www.google.com/"> http://www.google.com/ <sup> <img align="absmiddle" alt="" border="0" class="rendericon" height="7" src="http://jira.atlassian.com/icon.gif" width="7"/> </sup> </a> </span> With: <span class="nobr"> <a href="http://www.google.com/"> http://www.google.com/ </a> </span> I.e. - remove sup element if whole structure exactly corresponds to the one given in 1st example. I need to keep XML document during process, so regexp matching isn't somewhat possible. I already have code which works for my purposes: doc = self.__refactor_links(doc) ... def __refactor_links(self, node): """Recursively seeks for links to refactor them""" for span in node.childNodes: replace = False if isinstance(span, xml.dom.minidom.Element): if span.tagName == "span" and span.getAttribute("class") == "nobr": if span.childNodes.length == 1: a = span.childNodes.item(0) if isinstance(a, xml.dom.minidom.Element): if a.tagName == "a" and a.getAttribute("href"): if a.childNodes.length == 2: aurl = a.childNodes.item(0) if isinstance(aurl, xml.dom.minidom.Text): sup = a.childNodes.item(1) if isinstance(sup, xml.dom.minidom.Element): if sup.tagName == "sup": if sup.childNodes.length == 1: img = sup.childNodes.item(0) if isinstance(img, xml.dom.minidom.Element): if img.tagName == "img" and img.getAttribute("class") == "rendericon": replace = True else: self.__refactor_links(span) if replace: a.removeChild(sup) return node This one doesn't run through all of the tags recursively - if it matches something similar to the structure it seeks - even if it fails, it doesn't continue to look for structure inside these elements, but in my case i'm not ought to do it (although that would be nice to have too, but cost of adding bunch of else: self.__refactor_links(tag) kills it in my eyes). If any condition fails then no removal should occur. Is there a cleaner way to define set of conditions, avoiding huge set of 'ifs'? Some custom data structure may be used to store conditions, e.g. ('sup', ('img', (...))), but i have no idea how it should be processed. If you have any suggestions or examples in python - please help. Thanks. A: This is most definitely a task for an XPath expression, in your case probably in conjunction with lxml. The XPath is probably something along the lines of: //span[@class="nobr"]/a[@href]/sup[img/@class="rendericon"] Match your tree with this XPath expression and remove all matched elements. No need for endless if constructs or recursion. A: I am not good with xml but couldn't you use the find / search on nodes >>> from xml.dom.minidom import parse, parseString >>> dom = parseString(x) >>> k = dom.getElementsByTagName('sup') >>> for l in k: ... p = l.parentNode ... p.removeChild(l) ... <DOM Element: sup at 0x100587d40> >>> >>> print dom.toxml() <?xml version="1.0" ?><span class="nobr"> <a href="http://www.google.com/"> http://www.google.com/ </a> </span> >>> A: Here's a quick thing with lxml. Highly recommend xpath. >>> from lxml import etree >>> doc = etree.XML("""<span class="nobr"> ... <a href="http://www.google.com/"> ... http://www.google.com/ ... <sup> ... <img align="absmiddle" alt="" border="0" class="rendericon" height="7" src="http://jira.atlassian.com/icon.gif" width="7"/> ... </sup> ... </a> ... </span>""") >>> for a in doc.xpath('//span[@class="nobr"]/a[@href="http://www.google.com/"]'): ... for sub in list(a): ... a.remove(sub) ... >>> print etree.tostring(doc,pretty_print=True) <span class="nobr"> <a href="http://www.google.com/"> http://www.google.com/ </a> </span> A: Easily accomplished using lxml and XSLT: >>> from lxml import etree >>> from StringIO import StringIO >>> # create the stylesheet >>> xslt = StringIO(""" <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- this is the standard identity transform --> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> <!-- this replaces the specific node you're looking to replace --> <xsl:template match="span[a[@href='http://www.google.com' and sup[img[ @align='absmiddle' and @border='0' and @class='rendericon' and @height='7' and @src='http://jira.atlassian.com/icon.gif' and @width='7']]]]"> <span class="nobr"> <a href="http://www.google.com/">http://www.google.com/</a> </span> </xsl:template> </xsl:stylesheet>""") >>> # create a transform function from the XSLT stylesheet >>> transform = etree.XSLT(etree.parse(xslt)) >>> # here's a sample source XML instance for testing >>> source = StringIO(""" <test> <span class="nobr"> <a href="http://www.google.com/"> http://www.google.com/ <sup> <img align="absmiddle" alt="" border="0" class="rendericon" height="7" src="http://jira.atlassian.com/icon.gif" width="7"/> </sup> </a> </span> </test>""") >>> # parse the source, transform it to an XSLT result tree, and print the result >>> print etree.tostring(transform(etree.parse(source))) <test> <span class="nobr"><a href="http://www.google.com/">http://www.google.com/</a></span> </test> Edit: I should note that none of the answers - not mine, not MattH's, and certainly not the example OP posted - do what the OP asked for, which is to replace only elements whose structure exactly matches <span class="nobr"> <a href="http://www.google.com/"> http://www.google.com/ <sup> <img align="absmiddle" alt="" border="0" class="rendericon" height="7" src="http://jira.atlassian.com/icon.gif" width="7"/> </sup> </a> </span> For instance, all of these examples will replace the sup if the img has a style attribute, or if the sup has another child besides img. It's possible to construct an XPath expression that is much more strict in how it matches. For instance, instead of using span[a] which matches any span with at least one a child, you can use span[count(@*)=0 and count(*)=1 and a] which matches any span that has no attribute and exactly one child element where that child is an a. You can go pretty crazy with this in your quest for exactitude, e.g.: span[count(@*) = 1 and @class='nobr' and count(*) = 1 and a[count(@*) = 1 and @href='http://www.google.com' and count(*) = 1 and sup[count(@*) = 0 and count(*) = 1 and img[count(*) = 0 and count(@*) = 7 and @align='absmiddle' and @alt='' and @border='0' and @class='rendericon' and @height='7' and @src='http://jira.atlassian.com/icon.gif' and @width='7']]]] which, at every step of the matching, ensures that the element matched contains only exactly the attributes and elements specified and no more. (And it still doesn't verify that they don't contain text, comments, or processing instructions - if you're really serious about exactitude, use count(node()) everywhere this is using count(*).)
Conditional removal of an element from XML document tree
My task is to do minor refactoring of some elements of XML tree in python 3, namely replace following structure: <span class="nobr"> <a href="http://www.google.com/"> http://www.google.com/ <sup> <img align="absmiddle" alt="" border="0" class="rendericon" height="7" src="http://jira.atlassian.com/icon.gif" width="7"/> </sup> </a> </span> With: <span class="nobr"> <a href="http://www.google.com/"> http://www.google.com/ </a> </span> I.e. - remove sup element if whole structure exactly corresponds to the one given in 1st example. I need to keep XML document during process, so regexp matching isn't somewhat possible. I already have code which works for my purposes: doc = self.__refactor_links(doc) ... def __refactor_links(self, node): """Recursively seeks for links to refactor them""" for span in node.childNodes: replace = False if isinstance(span, xml.dom.minidom.Element): if span.tagName == "span" and span.getAttribute("class") == "nobr": if span.childNodes.length == 1: a = span.childNodes.item(0) if isinstance(a, xml.dom.minidom.Element): if a.tagName == "a" and a.getAttribute("href"): if a.childNodes.length == 2: aurl = a.childNodes.item(0) if isinstance(aurl, xml.dom.minidom.Text): sup = a.childNodes.item(1) if isinstance(sup, xml.dom.minidom.Element): if sup.tagName == "sup": if sup.childNodes.length == 1: img = sup.childNodes.item(0) if isinstance(img, xml.dom.minidom.Element): if img.tagName == "img" and img.getAttribute("class") == "rendericon": replace = True else: self.__refactor_links(span) if replace: a.removeChild(sup) return node This one doesn't run through all of the tags recursively - if it matches something similar to the structure it seeks - even if it fails, it doesn't continue to look for structure inside these elements, but in my case i'm not ought to do it (although that would be nice to have too, but cost of adding bunch of else: self.__refactor_links(tag) kills it in my eyes). If any condition fails then no removal should occur. Is there a cleaner way to define set of conditions, avoiding huge set of 'ifs'? Some custom data structure may be used to store conditions, e.g. ('sup', ('img', (...))), but i have no idea how it should be processed. If you have any suggestions or examples in python - please help. Thanks.
[ "This is most definitely a task for an XPath expression, in your case probably in conjunction with lxml. \nThe XPath is probably something along the lines of: \n//span[@class=\"nobr\"]/a[@href]/sup[img/@class=\"rendericon\"]\nMatch your tree with this XPath expression and remove all matched elements.\nNo need for e...
[ 1, 1, 1, 0 ]
[]
[]
[ "pattern_matching", "python", "recursion" ]
stackoverflow_0004159413_pattern_matching_python_recursion.txt
Q: HTML drop-down box with Google App Engine I am creating a Google App Engine web application written in Python, and I would like to create a drop down box that displays different values corresponding to pages of a book that a user could choose from. I would like the action of the drop down box to be to direct the user to the page that corresponds to this link: <a href='/viewpage/{{bookpage.key}}'>{{ bookpage.page }} </a> The "bookpage" entity is passed to the html Thank you! David A: Use a Jump Menu. Here is a pretty straight forward implementation. Basically you'll just add a bit of JavaScript, and instead of writing an a tag, you'll write an option: <option value='/viewpage/{{bookpage.key}}'>{{ bookpage.page }} </option> A: What about <option value='/viewpage/{{bookpage.key.id}}'>{{bookpage.page}}</option>? I hope it's not a dumb answer. A: I'm not familiar with the google-app-engine but, the following javascript seems to do what you want. The python could generate the array variables on the server side, and then everything else would work properly. I included the hardcoded arrays so you can see what is going on, but you can replace the arrays with the python code(assuming bookpage is some kind of dictionary): i = 0 for bp in bookpage.keys(): print("mysites["+str(i)+"] = "+ bookpage[bp])+";" print("sitenames["+str(i)+"] = "+sitenames[bp])+";" i+=1 <html> <body> <script type="text/javascript"> var mysites= new Array(); mysites[0] = "http://www.google.com"; //Generate this line with python mysites[1] = "http://www.bing.com"; //Generate this line with python mysites[2] = "http://www.yahoo.com"; //Generate this line with python var sitenames = new Array(); sitenames[0] = "Google"; //Generate this line with python sitenames[1] = "Bing"; //Generate this line with python sitenames[2] = "Yahoo"; //Generate this line with python function changeLink(){ var index = document.getElementById("theselect").selectedIndex document.getElementById("thelink").innerHTML=index; var newlink = mysites[index]; var newstring = sitenames[index]; document.getElementById("thelink").href=newlink; document.getElementById("thelink").innerHTML=sitenames[index]; } </script> <select id="theselect" onclick="changeLink()"> <option>Google</option> <option>Bing</option> <option>Yahoo</option> </select> <br /> <a id="thelink" href="http://www.google.com" > Google </a> </body> </html> Clicking on the option box calls the changeLink() function, which then changes the link and the inner html of the tag.
HTML drop-down box with Google App Engine
I am creating a Google App Engine web application written in Python, and I would like to create a drop down box that displays different values corresponding to pages of a book that a user could choose from. I would like the action of the drop down box to be to direct the user to the page that corresponds to this link: <a href='/viewpage/{{bookpage.key}}'>{{ bookpage.page }} </a> The "bookpage" entity is passed to the html Thank you! David
[ "Use a Jump Menu. Here is a pretty straight forward implementation.\nBasically you'll just add a bit of JavaScript, and instead of writing an a tag, you'll write an option:\n<option value='/viewpage/{{bookpage.key}}'>{{ bookpage.page }} </option>\n\n", "What about <option value='/viewpage/{{bookpage.key.id}}'>{{...
[ 1, 0, 0 ]
[]
[]
[ "google_app_engine", "html", "python" ]
stackoverflow_0004160401_google_app_engine_html_python.txt
Q: How to create dynamic fields in Google App Engine expando class? I have a db expando class called widget. I'm passing in a json string and converting it to a dict and then adding it to the datastore. My question is how can I loop through my dict to create dynamic fields. widget = Widget.get_by_key_name(key_name) widget.name = self.request.get('wname') fields = simplejson.loads(self.request.get('wcontents')) for k,v in fields.iteritems(): widget.k = v This renders "k" as my field name as oppose to the k value in the dict. A: The syntax widget.k references the attribute k on object widget. To dynamically choose which attribute you set, use the built-in setattr method: setattr(widget, k, v) Dynamically setting an attribute like this will create the field on that particular entity.
How to create dynamic fields in Google App Engine expando class?
I have a db expando class called widget. I'm passing in a json string and converting it to a dict and then adding it to the datastore. My question is how can I loop through my dict to create dynamic fields. widget = Widget.get_by_key_name(key_name) widget.name = self.request.get('wname') fields = simplejson.loads(self.request.get('wcontents')) for k,v in fields.iteritems(): widget.k = v This renders "k" as my field name as oppose to the k value in the dict.
[ "The syntax widget.k references the attribute k on object widget. To dynamically choose which attribute you set, use the built-in setattr method:\nsetattr(widget, k, v)\n\nDynamically setting an attribute like this will create the field on that particular entity.\n" ]
[ 4 ]
[ "Try:\nfor k, v in fields.items()\n\n" ]
[ -3 ]
[ "datastore", "dynamic_variables", "expando", "google_app_engine", "python" ]
stackoverflow_0004160752_datastore_dynamic_variables_expando_google_app_engine_python.txt