title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Python element-wise tuple operations like sum
497,885
52
2009-01-31T00:51:48Z
497,931
18
2009-01-31T01:10:18Z
[ "python", "tuples" ]
Is there anyway to get tuple operations in Python to work like this: ``` >>> a = (1,2,3) >>> b = (3,2,1) >>> a + b (4,4,4) ``` instead of: ``` >>> a = (1,2,3) >>> b = (3,2,1) >>> a + b (1,2,3,3,2,1) ``` I know it works like that because the `__add__` and `__mul__` methods are defined to work like that. So the only way would be to redefine them?
Sort of combined the first two answers, with a tweak to ironfroggy's code so that it returns a tuple: ``` import operator class stuple(tuple): def __add__(self, other): return self.__class__(map(operator.add, self, other)) # obviously leaving out checking lengths >>> a = stuple([1,2,3]) >>> b = stuple([3,2,1]) >>> a + b (4, 4, 4) ``` Note: using `self.__class__` instead of `stuple` to ease subclassing.
Python element-wise tuple operations like sum
497,885
52
2009-01-31T00:51:48Z
498,103
58
2009-01-31T02:49:16Z
[ "python", "tuples" ]
Is there anyway to get tuple operations in Python to work like this: ``` >>> a = (1,2,3) >>> b = (3,2,1) >>> a + b (4,4,4) ``` instead of: ``` >>> a = (1,2,3) >>> b = (3,2,1) >>> a + b (1,2,3,3,2,1) ``` I know it works like that because the `__add__` and `__mul__` methods are defined to work like that. So the only way would be to redefine them?
Using all built-ins.. ``` tuple(map(sum, zip(a, b)) ```
Python element-wise tuple operations like sum
497,885
52
2009-01-31T00:51:48Z
499,696
13
2009-01-31T22:25:06Z
[ "python", "tuples" ]
Is there anyway to get tuple operations in Python to work like this: ``` >>> a = (1,2,3) >>> b = (3,2,1) >>> a + b (4,4,4) ``` instead of: ``` >>> a = (1,2,3) >>> b = (3,2,1) >>> a + b (1,2,3,3,2,1) ``` I know it works like that because the `__add__` and `__mul__` methods are defined to work like that. So the only way would be to redefine them?
``` from numpy import * a = array( [1,2,3] ) b = array( [3,2,1] ) print a + b ``` gives `array([4,4,4])`. See <http://www.scipy.org/Tentative_NumPy_Tutorial>
Python element-wise tuple operations like sum
497,885
52
2009-01-31T00:51:48Z
12,702,871
23
2012-10-03T06:20:20Z
[ "python", "tuples" ]
Is there anyway to get tuple operations in Python to work like this: ``` >>> a = (1,2,3) >>> b = (3,2,1) >>> a + b (4,4,4) ``` instead of: ``` >>> a = (1,2,3) >>> b = (3,2,1) >>> a + b (1,2,3,3,2,1) ``` I know it works like that because the `__add__` and `__mul__` methods are defined to work like that. So the only way would be to redefine them?
This solution doesn't require an import: ``` tuple(map(lambda x, y: x + y, tuple1, tuple2)) ```
How to make python gracefully fail?
497,952
13
2009-01-31T01:22:08Z
497,960
8
2009-01-31T01:26:01Z
[ "python" ]
I was just wondering how do you make python fail in a user defined way in all possible errors. For example, I'm writing a program that processes a (large) list of items, and some of the items may not be in the format I defined. If python detects an error, it currently just spits out an ugly error message and stop the whole process. However, I want it to just outputs the error to somewhere together with some context and then move on to the next item. If anyone can help me with this it would be greatly appreciated! Thanks a lot! Jason
The ugly error message means that an exception is raised. You need to catch the exception. A good place to start is the [Python tutorial's section on exceptions.](http://docs.python.org/tutorial/errors.html) Basically you need to wrap your code in a `try...except` block like this: ``` try: do_something_dangerous() except SomeException: handle_the_error() ```
How to make python gracefully fail?
497,952
13
2009-01-31T01:22:08Z
498,038
23
2009-01-31T02:01:10Z
[ "python" ]
I was just wondering how do you make python fail in a user defined way in all possible errors. For example, I'm writing a program that processes a (large) list of items, and some of the items may not be in the format I defined. If python detects an error, it currently just spits out an ugly error message and stop the whole process. However, I want it to just outputs the error to somewhere together with some context and then move on to the next item. If anyone can help me with this it would be greatly appreciated! Thanks a lot! Jason
The following are a few basic strategies I regularly use in my more-than-trivial scripts and medium-size applications. Tip 1: Trap the error at every level where it makes sense to continue processing. In your case it may be in the inside the loop. You don't have to protect every single line or every single function call, but only the places where it makes a difference to survive the error. Tip 2: Use the logging module to report what happened in a way that is configurable independently from how you compose the module with other modules in a larger applications. Start importing the root logger in your module, then, using it in a few different places, you may eventually figure out a more sensible logging hierarchy. ``` import logging logger = logging.getLogger() for item in items: try: process(item) except Exception, exc: logger.warn("error while processing item: %s", exc) ``` Tip 3: define an "application exception", eventually you may want to define a hierarchy of such exception but this is better discovered when the need arise. Use such exception(s) to "bubble out" when the data you are dealing with are not what you expected or to signal inconsistent situations, while separating them from the normal standard exception arising from regular bugs or problems outside the modeled domain (IO errors etc). ``` class DomainException(Exception): """Life is not what I expected""" def process(item): # There is no way that this item can be processed, so bail out quickly. # Here you are assuming that your caller will report this error but probably # it will be able to process the other items. if item.foo > item.bar: raise DomainException("bad news") # Everybody knows that every item has more that 10 wickets, so # the following instruction is assumed always being successful. # But even if luck is not on our side, our caller will be able to # cope with this situation and keep on working item.wickets[10] *= 2 ``` The main function is the outmost checkpoint: finally deal here with the possible ways your task finished. If this was not a shell script (but e.g. the processing beneath a dialog in an UI application or an operation after a POST in a web application) only the way you report the error changes (and the use of the logging method completely separates the implementation of the processing from its interface). ``` def main(): try: do_all_the_processing() return 0 except DomainException, exc: logger.error("I couldn't finish. The reason is: %s", exc) return 1 except Exception, exc: logger.error("Unexpected error: %s - %s", exc.__class__.__name__, exc) # In this case you may want to forward a stacktrace to the developers via e-mail return 1 except BaseException: logger.info("user stop") # this deals with a ctrl-c return 1 if __name__ == '__main__': sys.exit(main()) ```
How do I compile a Visual Studio project from the command-line?
498,106
76
2009-01-31T02:52:25Z
498,118
32
2009-01-31T02:58:27Z
[ "c++", "python", "visual-studio-2008", "command-line" ]
I'm scripting the checkout, build, distribution, test, and commit cycle for a large C++ solution that is using [Monotone](http://en.wikipedia.org/wiki/Monotone_%28software%29), [CMake](http://en.wikipedia.org/wiki/CMake), Visual Studio Express 2008, and custom tests. All of the other parts seem pretty straight-forward, but I don't see how to compile the Visual Studio solution without getting the GUI. The script is written in Python, but an answer that would allow me to just make a call to: os.system would do.
MSBuild usually works, but I've run into difficulties before. You may have better luck with ``` devenv YourSolution.sln /Build ```
How do I compile a Visual Studio project from the command-line?
498,106
76
2009-01-31T02:52:25Z
498,130
77
2009-01-31T03:04:10Z
[ "c++", "python", "visual-studio-2008", "command-line" ]
I'm scripting the checkout, build, distribution, test, and commit cycle for a large C++ solution that is using [Monotone](http://en.wikipedia.org/wiki/Monotone_%28software%29), [CMake](http://en.wikipedia.org/wiki/CMake), Visual Studio Express 2008, and custom tests. All of the other parts seem pretty straight-forward, but I don't see how to compile the Visual Studio solution without getting the GUI. The script is written in Python, but an answer that would allow me to just make a call to: os.system would do.
I know of two ways to do it. **Method 1** The first method (which I prefer) is to use [msbuild](http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx): ``` msbuild project.sln /Flags... ``` **Method 2** You can also run: ``` vcexpress project.sln /build /Flags... ``` The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script. Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue). So, the end result might be: ``` os.system("msbuild project.sln /p:Configuration=Debug") ``` You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with [os.putenv](http://docs.python.org/library/os.html#os.putenv)).
How do I compile a Visual Studio project from the command-line?
498,106
76
2009-01-31T02:52:25Z
17,867,663
11
2013-07-25T20:01:03Z
[ "c++", "python", "visual-studio-2008", "command-line" ]
I'm scripting the checkout, build, distribution, test, and commit cycle for a large C++ solution that is using [Monotone](http://en.wikipedia.org/wiki/Monotone_%28software%29), [CMake](http://en.wikipedia.org/wiki/CMake), Visual Studio Express 2008, and custom tests. All of the other parts seem pretty straight-forward, but I don't see how to compile the Visual Studio solution without getting the GUI. The script is written in Python, but an answer that would allow me to just make a call to: os.system would do.
To be honest I have to add my 2 cents. You can do it with **msbuild.exe**. There are many version of the **msbuild.exe**. > C:\Windows\Microsoft.NET\Framework64\v2.0.50727\msbuild.exe > C:\Windows\Microsoft.NET\Framework64\v3.5\msbuild.exe > C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe > C:\Windows\Microsoft.NET\Framework\v2.0.50727\msbuild.exe > C:\Windows\Microsoft.NET\Framework\v3.5\msbuild.exe > C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe Use version you need. Basically you have to use the last one. > C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe So how to do it. 1. Run the **COMMAND** window 2. Input the path to msbuild.exe > C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe 1. Input the path to the project solution like > "C:\Users\Clark.Kent\Documents\visual studio > 2012\Projects\WpfApplication1\WpfApplication1.sln" 1. Add any flags you need after the solution path. 2. Press **ENTER** Note you can get help about all possible flags like > C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe /help
Valid use case for django admin?
498,199
11
2009-01-31T03:56:54Z
498,288
17
2009-01-31T04:48:35Z
[ "python", "django", "django-admin" ]
I want to build a django site where a certain group of trusted users can edit their profile information. Does it make sense to have each trusted user go through the django admin interface? I'd only want them to be able to see and edit their own information (obviously). It doesn't seem like this fits the way the django people define "trust", especially the bolded bit... From [The Django Book, Chapter 18](http://74.125.95.132/search?q=cache:fw9E1c2Oa7AJ:www.djangobook.com/en/beta/chapter18/+django+admin+use+cases&hl=en&ct=clnk&cd=2&gl=ca&client=firefox-a): > The admin is designed to be used by > people who you, the developer, trust. > This doesn’t just mean “people who > have been authenticated;” it means > that Django assumes that your content > editors can be trusted to do the right > thing. > > This means that there’s no “approval” > process for editing content — if you > trust your users, nobody needs to > approve of their edits. It also means > that the permission system, while > powerful, has no support for limiting > access on a per-object basis. **If you > trust someone to edit their own > stories, you trust them not to edit > anyone else’s without permission.** Is this one of those use cases that fits with django's admin module, or is it just a specialized view for a non-trusted user?
No, the Django admin is not suited for individual user profiles, each user would be able to see, and edit, all other user profiles. This is suited more to an administrator who has to manage all the users at once. What you need to build is a user profile page. Django already has a nice login system courtesy of the django.contrib.auth module. You can easily integrate this into your pages, and its exactly what the Django admin uses to authenticate users. Next you'll have to build a simple page that exposes that specific user's profile information based on their User model. This should be relatively painless as it will only require one view and one template, and the template can take advantage of ModelForms.
Is Django a good choice for a security critical application?
498,630
22
2009-01-31T10:46:37Z
498,707
17
2009-01-31T11:56:17Z
[ "python", "django", "security" ]
Is Django a good choice for a security critical application? I am asking this because most of the online banking software is built using Java. Is there any real reason for this?
Probably the reason behind Java is not in the in the security. I think Java is more used in large development companies and banks usually resort to them for their development needs (which probably are not only related to the web site but creep deeper in the backend). So, I see no security reasons, mostly cultural ones.
Is Django a good choice for a security critical application?
498,630
22
2009-01-31T10:46:37Z
498,798
30
2009-01-31T13:08:04Z
[ "python", "django", "security" ]
Is Django a good choice for a security critical application? I am asking this because most of the online banking software is built using Java. Is there any real reason for this?
Actually, the security in Java and Python is the same. Digest-only password handling, cookies that timeout rapidly, careful deletion of sessions, multi-factor authentication. None of this is unique to a Java framework or a Python framework like Django. Django, indeed, has a security backend architecture that allows you to add your own LDAP (or AD) connection, possibly changing the digest technique used. Django has a Profile model where you can keep additional authentication factors. Django offers a few standard decorators for view function authorization checking. Since Python is so flexible, you can trivially write your own decorator functions to layer in different or additional authentication checking. Security is a number of first-class features in Django.
Is Django a good choice for a security critical application?
498,630
22
2009-01-31T10:46:37Z
499,599
8
2009-01-31T21:18:49Z
[ "python", "django", "security" ]
Is Django a good choice for a security critical application? I am asking this because most of the online banking software is built using Java. Is there any real reason for this?
The reasons for building banking apps in Java are not related to security, at least IMHO. They are related to: 1. Java is the COBOL of the 21st century, so there is a lot of legacy code that would have to be rewritten and that takes time. Basically banking apps are old apps, they were built in java some ten years ago and nobody wants to throw all the old code away (which BTW is almost always a bad decision), 2. some people believe that a static typed language is somewhat "safer" than the dynamic typed language. This is, IMHO, not true (take for instance collections prior to Java 5).
Regular expression to extract URL from an HTML link
499,345
22
2009-01-31T19:02:34Z
499,364
13
2009-01-31T19:13:16Z
[ "python", "regex" ]
I’m a newbie in Python. I’m learning regexes, but I need help here. Here comes the HTML source: ``` <a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a> ``` I’m trying to code a tool that only prints out `http://ptop.se`. Can you help me please?
Don't use regexes, use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/). That, or be so crufty as to spawn it out to, say, w3m/lynx and pull back in what w3m/lynx renders. First is more elegant probably, second just worked a heck of a lot faster on some unoptimized code I wrote a while back.
Regular expression to extract URL from an HTML link
499,345
22
2009-01-31T19:02:34Z
499,366
10
2009-01-31T19:16:03Z
[ "python", "regex" ]
I’m a newbie in Python. I’m learning regexes, but I need help here. Here comes the HTML source: ``` <a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a> ``` I’m trying to code a tool that only prints out `http://ptop.se`. Can you help me please?
this should work, although there might be more elegant ways. ``` import re url='<a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>' r = re.compile('(?<=href=").*?(?=")') r.findall(url) ```
Regular expression to extract URL from an HTML link
499,345
22
2009-01-31T19:02:34Z
499,371
50
2009-01-31T19:17:06Z
[ "python", "regex" ]
I’m a newbie in Python. I’m learning regexes, but I need help here. Here comes the HTML source: ``` <a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a> ``` I’m trying to code a tool that only prints out `http://ptop.se`. Can you help me please?
If you're only looking for one: ``` import re match = re.search(r'href=[\'"]?([^\'" >]+)', s) if match: print match.group(0) ``` If you have a long string, and want every instance of the pattern in it: ``` import re urls = re.findall(r'href=[\'"]?([^\'" >]+)', s) print ', '.join(urls) ``` Where `s` is the string that you're looking for matches in. *Quick explanation of the regexp bits:* > `r'...'` is a "raw" string. It stops you having to worry about escaping characters quite as much as you normally would. (`\` especially -- in a raw string a `\` is just a `\`. In a regular string you'd have to do `\\` every time, and that gets *old* in regexps.) > > "`href=[\'"]?`" says to match "href=", possibly followed by a `'` or `"`. "Possibly" because it's hard to say how horrible the HTML you're looking at is, and the quotes aren't strictly required. > > Enclosing the next bit in "`()`" says to make it a "group", which means to split it out and return it separately to us. It's just a way to say "this is the part of the pattern I'm interested in." > > "`[^\'" >]+`" says to match any characters that *aren't* `'`, `"`, `>`, or a space. Essentially this is a list of characters that are an end to the URL. It lets us avoid trying to write a regexp that reliably matches a full URL, which can be a bit complicated. The suggestion in another answer to use BeautifulSoup isn't bad, but it does introduce a higher level of external requirements. Plus it doesn't help you in your stated goal of learning regexps, which I'd assume this specific html-parsing project is just a part of. It's pretty easy to do: ``` from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(html_to_parse) for tag in soup.findAll('a', href=True): print tag['href'] ``` Once you've installed BeautifulSoup, anyway.
Regular expression to extract URL from an HTML link
499,345
22
2009-01-31T19:02:34Z
1,811,011
8
2009-11-27T23:37:54Z
[ "python", "regex" ]
I’m a newbie in Python. I’m learning regexes, but I need help here. Here comes the HTML source: ``` <a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a> ``` I’m trying to code a tool that only prints out `http://ptop.se`. Can you help me please?
John Gruber (who wrote Markdown, which is made of regular expressions and is used right here on Stack Overflow) had a go at producing a regular expression that recognises URLs in text: [http://daringfireball.net/2009/11/liberal\_regex\_for\_matching\_urls](http://daringfireball.net/2009/11/liberal%5Fregex%5Ffor%5Fmatching%5Furls) If you just want to grab the URL (i.e. you’re not really trying to parse the HTML), this might be more lightweight than an HTML parser.
What's the best serialization method for objects in memcached?
499,593
23
2009-01-31T21:17:24Z
600,483
7
2009-03-01T20:47:27Z
[ "python", "serialization", "xml-serialization", "memcached", "protocol-buffers" ]
My Python application currently uses the [python-memcached API](http://www.tummy.com/Community/software/python-memcached/) to set and get objects in memcached. This API uses Python's native [pickle module](http://docs.python.org/library/pickle.html) to serialize and de-serialize Python objects. This API makes it simple and fast to store nested Python lists, dictionaries and tuples in memcached, and reading these objects back into the application is completely transparent -- it just works. But I don't want to be limited to using Python exclusively, and if all the memcached objects are serialized with pickle, then clients written in other languages won't work. Here are the cross-platform serialization options I've considered: 1. XML - the main benefit is that it's human-readable, but that's not important in this application. XML also takes a lot space, and it's expensive to parse. 2. JSON - seems like a good cross-platform standard, but I'm not sure it retains the character of object types when read back from memcached. For example, according to [this post](http://stackoverflow.com/questions/408866/python-human-readable-object-serialization) tuples are transformed into lists when using [simplejson](http://pypi.python.org/pypi/simplejson/); also, it seems like adding elements to the JSON structure could break code written to the old structure 3. [Google Protocol Buffers](http://code.google.com/apis/protocolbuffers/docs/overview.html) - I'm really interested in this because it seems very fast and compact -- at least 10 times smaller and faster than XML; it's not human-readable, but that's not important for this app; and it seems designed to support growing the structure without breaking old code Considering the priorities for this app, what's the ideal object serialization method for memcached? 1. Cross-platform support (Python, Java, C#, C++, Ruby, Perl) 2. Handling nested data structures 3. Fast serialization/de-serialization 4. Minimum memory footprint 5. Flexibility to change structure without breaking old code
I tried several methods and settled on compressed JSON as the best balance between speed and memory footprint. Python's native Pickle function is slightly faster, but the resulting objects can't be used with non-Python clients. I'm seeing 3:1 compression so all the data fits in memcache and the app gets sub-10ms response times including page rendering. Here's a comparison of JSON, Thrift, Protocol Buffers and YAML, with and without compression: [http://bouncybouncy.net/ramblings/posts/more\_on\_json\_vs\_thrift\_and\_protocol\_buffers/](http://bouncybouncy.net/ramblings/posts/more%5Fon%5Fjson%5Fvs%5Fthrift%5Fand%5Fprotocol%5Fbuffers/) Looks like this test got the same results I did with compressed JSON. Since I don't need to pre-define each structure, this seems like the fastest and smallest cross-platform answer.
Can I use IPython in an embedded interactive Python console?
499,705
7
2009-01-31T22:29:21Z
19,891,856
13
2013-11-10T16:04:12Z
[ "python", "console" ]
I use the following snippet to drop into a Python shell mid-program. This works fine, but I only get the standard console. Is there a way to do the same but using the [IPython](http://ipython.scipy.org/) shell? ``` import code class EmbeddedConsole(code.InteractiveConsole): def start(self): try: self.interact("Debug console starting...") except: print("Debug console closing...") def print_names(): print(adam) print(bob) adam = "I am Adam" bob = "I am Bob" print_names() console = EmbeddedConsole(locals()) console.start() print_names() ```
The answer by f3lix is no longer valid it seems, I was able to find this however: At the top of your python script: ``` from IPython import embed ``` Wherever you want to spin up a console: ``` embed() ```
Python's timedelta: can't I just get in whatever time unit I want the value of the entire difference?
500,168
14
2009-02-01T03:59:27Z
500,195
15
2009-02-01T04:17:58Z
[ "python", "datetime", "timedelta" ]
I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the database for a post. Looks like, according to the docs, I have to use the days attribute AND the seconds attribute, to get the fancy date strings I want. Can't I just get in whatever time unit I want the value of the entire difference? Am I missing something? It would be perfect if I could just get the entire difference in seconds.
You can compute the difference in seconds. ``` total_seconds = delta.days * 86400 + delta.seconds ``` No, you're no "missing something". It doesn't provide deltas in seconds.
Python's timedelta: can't I just get in whatever time unit I want the value of the entire difference?
500,168
14
2009-02-01T03:59:27Z
3,471,718
21
2010-08-12T20:22:47Z
[ "python", "datetime", "timedelta" ]
I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the database for a post. Looks like, according to the docs, I have to use the days attribute AND the seconds attribute, to get the fancy date strings I want. Can't I just get in whatever time unit I want the value of the entire difference? Am I missing something? It would be perfect if I could just get the entire difference in seconds.
It seems that Python 2.7 has introduced a [total\_seconds()](http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds) method, which is what you were looking for, I believe!
Identifying numeric and array types in numpy
500,328
11
2009-02-01T06:17:38Z
500,908
16
2009-02-01T14:22:55Z
[ "python", "numpy" ]
Is there an existing function in numpy that will tell me if a value is either a numeric type or a numpy array? I'm writing some data-processing code which needs to handle numbers in several different representations (by "number" I mean any representation of a numeric quantity which can be manipulated using the standard arithmetic operators, +, -, \*, /, \*\*). Some examples of the behavior I'm looking for ``` >>> is_numeric(5) True >>> is_numeric(123.345) True >>> is_numeric('123.345') False >>> is_numeric(decimal.Decimal('123.345')) True >>> is_numeric(True) False >>> is_numeric([1, 2, 3]) False >>> is_numeric([1, '2', 3]) False >>> a = numpy.array([1, 2.3, 4.5, 6.7, 8.9]) >>> is_numeric(a) True >>> is_numeric(a[0]) True >>> is_numeric(a[1]) True >>> is_numeric(numpy.array([numpy.array([1]), numpy.array([2])]) True >>> is_numeric(numpy.array(['1']) False ``` If no such function exists, I know it shouldn't be hard to write one, something like ``` isinstance(n, (int, float, decimal.Decimal, numpy.number, numpy.ndarray)) ``` but are there other numeric types I should include in the list?
As others have answered, there could be other numeric types besides the ones you mention. One approach would be to check explicitly for the capabilities you want, with something like ``` # Python 2 def is_numeric(obj): attrs = ['__add__', '__sub__', '__mul__', '__div__', '__pow__'] return all(hasattr(obj, attr) for attr in attrs) # Python 3 def is_numeric(obj): attrs = ['__add__', '__sub__', '__mul__', '__truediv__', '__pow__'] return all(hasattr(obj, attr) for attr in attrs) ``` This works for all your examples except the last one, `numpy.array(['1'])`. That's because `numpy.ndarray` has the special methods for numeric operations but raises TypeError if you try to use them inappropriately with string or object arrays. You could add an explicit check for this like ``` ... and not (isinstance(obj, ndarray) and obj.dtype.kind in 'OSU') ``` This may be good enough. But... you can never be *100%* sure that somebody won't define another type with the same behavior, so a more foolproof way is to actually try to do a calculation and catch the exception, something like ``` def is_numeric_paranoid(obj): try: obj+obj, obj-obj, obj*obj, obj**obj, obj/obj except ZeroDivisionError: return True except Exception: return False else: return True ``` but depending on how often you plan to call use it and with what arguments, this may not be practical (it can be potentially slow, e.g. with large arrays).
How to vertically align Paragraphs within a Table using Reportlab?
500,406
3
2009-02-01T07:55:43Z
516,531
8
2009-02-05T16:01:15Z
[ "python", "pdf", "alignment", "reportlab" ]
I'm using Reportlab to generate report cards. The report cards are basically one big Table object. Some of the content in the table cells needs to wrap, specifically titles and comments, and I also need to bold certain elements. To accomplish both the wrapping and ability to bold, I'm using Paragraph objects within the Table. My table needs several of these elements vertically aligned to 'middle' but the Paragraph alignment and snaps my text to the bottom of the cell. How can I vertically align my Paragraph within a Table cell?
I have to ask: have you tried the tablestyle VALIGN:MIDDLE? something like: ``` t=Table(data) t.setStyle(TableStyle([('VALIGN',(-1,-1),(-1,-1),'MIDDLE')])) ``` (more details in section 7.2 of the ReportLab user guide) If that doesn't do it, then your paragraph object must be the full height of the cell, and internally aligned to the bottom. Could you please post a small sample that reproduces the problem?
using django-rest-interface with http put
500,434
9
2009-02-01T08:29:44Z
501,337
13
2009-02-01T18:41:22Z
[ "python", "django" ]
I'm trying to figure out how to implement my first RESTful interface using Django and django-rest-interface. I'm having problems with the HTTP PUT requests. How do I access the parameters of the PUT request? I thought they would be in the request.POST array, as PUT is somewhat similar to POST in my understanding, but that array is always empty. What am I doing wrong? Thanks for the help
request.POST processes form-encoded data into a dictionary, which only makes sense for web browser form submissions. There is no equivalent for PUT, as web browsers don't PUT forms; the data submitted could have any content type. You'll need to get the raw data out of request.raw\_post\_data, possibly check the content type, and process it however makes sense for your application. More information in [this thread](http://groups.google.com/group/django-developers/browse_thread/thread/771238a95ceb058e).
In Python - how to execute system command with no output
500,477
8
2009-02-01T09:20:45Z
500,512
17
2009-02-01T09:50:37Z
[ "python" ]
Is there a built-in method in Python to execute a system command without displaying the output? I only want to grab the return value. It is important that it be cross-platform, so just redirecting the output to /dev/null won't work on Windows, and the other way around. I know I can just check os.platform and build the redirection myself, but I'm hoping for a built-in solution.
``` import os import subprocess subprocess.call(["ls", "-l"], stdout=open(os.devnull, "w"), stderr=subprocess.STDOUT) ```
is there an alternative way of calling next on python generators?
500,578
3
2009-02-01T10:48:46Z
500,609
15
2009-02-01T11:12:53Z
[ "python", "language-features" ]
I have a generator and I would like to know if I can use it without having to worry about StopIteration , and I would like to use it without the **`for item in generator`** . I would like to use it with a while statement for example ( or other constructs ). How could I do that ?
built-in function > next(iterator[, default]) > Retrieve the next item from the iterator by calling its `__next__()` method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised. In Python 2.5 and older: ``` raiseStopIteration = object() def next(iterator, default=raiseStopIteration): if not hasattr(iterator, 'next'): raise TypeError("not an iterator") try: return iterator.next() except StopIteration: if default is raiseStopIteration: raise else: return default ```
How do Django model fields work?
500,650
9
2009-02-01T11:43:27Z
501,362
19
2009-02-01T18:56:40Z
[ "python", "django", "django-models" ]
First of all,I'm not into web programming. I bumped into django and read a bit about models. I was intrigued by the following code ( from djangoproject.com ) : ``` class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): # Note use of django.utils.encoding.smart_str() here because # first_name and last_name will be unicode strings. return smart_str('%s %s' % (self.first_name, self.last_name)) ``` By my understanding of python , first\_name and last\_name are class variables , right ? How is that used in code ( because I guess that setting Person.first\_name or Person.last\_name will affect all Person instances ) ? Why is it used that way ?
The essence of your question is "how come these class variables (which I assign Field objects to) suddenly become instance variables (which I assign data to) in Django's ORM"? The answer to that is the magic of Python [metaclasses](http://docs.python.org/reference/datamodel.html). A metaclass allows you to hook into and modify the process of creating a Python class (not the creation of an instance of that class, the creation of the class itself). Django's Model object (and thus also your models, which are subclasses) has a [ModelBase metaclass](http://code.djangoproject.com/browser/django/trunk/django/db/models/base.py). It looks through all the class attributes of your model, and any that are instances of a Field subclass it moves into a fields list. That list is assigned as an attribute of the `_meta` object, which is a class attribute of the model. Thus you can always get to the actual Field objects via `MyModel._meta.fields`, or `MyModel._meta.get_field('field_name')`. The `Model.__init__` method is then able to use the `_meta.fields` list to determine what instance attributes should be initialized when a model instance is created. Don't be afraid to dive into the Django source code; it's a great source of education!
Case insensitive Python regular expression without re.compile
500,864
132
2009-02-01T13:56:14Z
500,870
206
2009-02-01T14:01:10Z
[ "python", "regex", "case-sensitive", "case-insensitive" ]
In Python, I can compile a regular expression to be case-insensitive using `re.compile`: ``` >>> s = 'TeSt' >>> casesensitive = re.compile('test') >>> ignorecase = re.compile('test', re.IGNORECASE) >>> >>> print casesensitive.match(s) None >>> print ignorecase.match(s) <_sre.SRE_Match object at 0x02F0B608> ``` Is there a way to do the same, but without using `re.compile`. I can't find anything like Perl's `i` suffix (e.g. `m/test/i`) in the documentation.
Pass `re.IGNORECASE` to the `flags` param of [`search`](https://docs.python.org/library/re.html#re.search), [`match`](https://docs.python.org/library/re.html#re.match), or [`sub`](https://docs.python.org/library/re.html#re.sub): ``` re.search('test', 'TeSt', re.IGNORECASE) re.match('test', 'TeSt', re.IGNORECASE) re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE) ```
Case insensitive Python regular expression without re.compile
500,864
132
2009-02-01T13:56:14Z
10,444,271
31
2012-05-04T07:05:38Z
[ "python", "regex", "case-sensitive", "case-insensitive" ]
In Python, I can compile a regular expression to be case-insensitive using `re.compile`: ``` >>> s = 'TeSt' >>> casesensitive = re.compile('test') >>> ignorecase = re.compile('test', re.IGNORECASE) >>> >>> print casesensitive.match(s) None >>> print ignorecase.match(s) <_sre.SRE_Match object at 0x02F0B608> ``` Is there a way to do the same, but without using `re.compile`. I can't find anything like Perl's `i` suffix (e.g. `m/test/i`) in the documentation.
You can also perform case insensitive searches using search/match without the IGNORECASE flag (tested in Python 2.7.3): ``` re.search(r'(?i)test', 'TeSt').group() ## returns 'TeSt' re.match(r'(?i)test', 'TeSt').group() ## returns 'TeSt' ```
Problem in understanding Python list comprehensions
501,308
4
2009-02-01T18:22:26Z
501,323
18
2009-02-01T18:34:33Z
[ "python", "list-comprehension" ]
What does the last line mean in the following code? ``` import pickle, urllib handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p") data = pickle.load(handle) handle.close() for elt in data: print "".join([e[1] * e[0] for e in elt]) ``` My attempt to the problem: * "".join... uses join -method to empty text * e[1] \* e[0] multiplies two subsequent values in the sequence, e * I am not sure what is e * I am not sure, what it means, when you have something before for -loop, like: `e[1] * e[0] for e in elt`
Maybe best explained with an example: ``` print "".join([e[1] * e[0] for e in elt]) ``` is the short form of ``` x = [] for e in elt: x.append(e[1] * e[0]) print "".join(x) ``` List comprehensions are simply syntactic sugar for `for` loops, which make an expression out of a sequence of statements. `elt` can be an arbitrary object, since you load it from pickles, and `e` likewise. The usage suggests that is it a [sequence](http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange) type, but it could just be anything that implements the sequence protocol.
How can you use Python in Vim?
501,585
50
2009-02-01T21:10:02Z
501,698
155
2009-02-01T22:17:12Z
[ "python", "vim" ]
I waste a lot of time between Vim and Python. I find it too slow to manually copy-paste from Python to Vim and vice versa. A good broken example is: > %!python for i in xrange(25); print 6\*i \n How can you do such tweaks direcly in Vim? **[Solved]** **[Clarification]** I need things to Vim, like printing sequences, arithmetics... - things I cannot do in Vim. **[?]** Can someone elaborate this point: "your script can read from stdin to operate directly on the lines given *(., %, ...).*" **[Further Clarification]** If I want to print 'Hello' to lines 4,5, 6 and 7, what is wrong: > :4-7!python -c "print 'hello'" The dot . modifies the current line. Can I print on multiple lines 7, 32 and 99: > :7,32,99!python -c "print 'hello'" Clearly not working. How?
In any of your vim windows, type something like this: ``` for x in range(1,10): print '-> %d' % x ``` Visually select both of those lines (V to start visual mode), and type the following: ``` :!python ``` Because you pressed ':' in visual mode, that will end up looking like: ``` :'<,'>!python ``` Hit enter and the selection is replaced by the output of the `print` statements. You could easily turn it into a mapping: ``` :vnoremap <f5> :!python<CR> ```
Both Python 2 and 3 in Emacs
501,626
16
2009-02-01T21:32:47Z
502,422
10
2009-02-02T07:14:45Z
[ "python", "emacs", "python-3.x" ]
I have been using Emacs to write Python 2 code. Now I have both Python 2.6 and 3.0 installed on my system, and I need to write Python 3 code as well. Here is how the different versions are set up in /usr/bin: ``` python -> python2.6* python2 -> python2.6* python2.6* python3 -> python3.0* python3.0* ``` Is there any way to set this up so that Emacs uses the correct version of Python, depending on which language I am using? For instance, C-c C-c currently runs the buffer, but it always calls python2.6, even if I am writing Python 3 code.
If you are using python-mode.el you can try to change `py-which-shell`. In order to do this on a per-file basis you can put ``` # -*- py-which-shell: "python3"; -*- ``` at the first line of your file - or at the second line if the first line starts with `#!`. Another choice is to put ``` # Local Variables: # py-which-shell: "python3" # End: ``` at the end of your file. Perhaps you should give the full path to python3 instead of just "python3".
Simple simulations for Physics in Python?
501,940
7
2009-02-02T00:55:03Z
502,627
10
2009-02-02T09:06:01Z
[ "python", "modeling", "simulation" ]
I would like to know similar, concrete simulations, as the simulation about watering a field [here](http://stackoverflow.com/questions/494184/simulation-problem-with-mouse-in-pygame). What is your favorite library/internet page for such simulations in Python? I know little Simpy, Numpy and Pygame. I would like to get examples about them.
If you are looking for some *game* physics (collisions, deformations, gravity, etc.) which *looks* real and is reasonably *fast* consider re-using some *physics engine* libraries. As a first reference, you may want to look into [pymunk](http://www.pymunk.org/), a Python wrapper of [Chipmunk](http://wiki.slembcke.net/main/published/Chipmunk) 2D physics library. You can find a list of various Open Source physics engines (2D and 3D) in Wikipedia. If you are looking for *physically correct* simulations, no matter what language you want to use, it will be much *slower* (almost never real-time), and you need to use some *numerical analysis* software (and probably to write something yourself). Exact answer depends on the problem you want to solve. It is a fairly complicated field (of math). For example, if you need to do simulations in continuum mechanics or electromagnetism, you probably need Finite Difference, Finite Volume or Finite Element methods. For Python, there are some ready-to-use libraries, for example: [FiPy](http://www.ctcms.nist.gov/fipy/) (FVM), [GetFem++](http://home.gna.org/getfem/) (FEM), [FEniCS/DOLFIN](http://www.fenics.org/wiki/FEniCS_Project) (FEM), and some other.
How to modularize a Python application
501,945
5
2009-02-02T00:59:26Z
502,014
8
2009-02-02T02:00:33Z
[ "python" ]
I've got a number of scripts that use common definitions. How do I split them in multiple files? Furthermore, the application can not be installed in any way in my scenario; it must be possible to have an arbitrary number of versions concurrently running and it must work without superuser rights. Solutions I've come up with are: * **Duplicate code** in every script. Messy, and probably the worst scheme. * **Put all scripts and common code in a single directory,** and use `from . import` to load them. The downside of this approach is that I'd like to put my libraries in other directory than the applications. * **Put common code in its own directory**, write a `__init__.py` that imports all submodules and finally use `from . import` to load them. Keeps code organized, but it's a little bit of overhead to maintain `__init__.py` and qualify names. * **Add the library directory to `sys.path` and `import`.** I tend to this, but I'm not sure whether fiddling with `sys.path` is nice code. * **Load using `execfile`** (`exec` in Python 3). Combines the advantages of the previous two approaches: Only one line per module needed, and I can use a dedicated. On the other hand, this evades the python module concept and polutes the global namespace. * **Write and install a module using `distutils`.** This installs the library for all python scripts and needs superuser rights and impacts other applications and is hence not applicable in my case. What is the best method?
Adding to sys.path (usually using site.addsitedir) is quite common and not particularly frowned upon. Certainly you will want your common working shared stuff to be in modules somewhere convenient. If you are using Python 2.6+ there's already a user-level modules folder you can use without having to add to sys.path or PYTHONPATH. It's ~/.local/lib/python2.6/site-packages on Unix-likes - see [PEP 370](http://www.python.org/dev/peps/pep-0370/) for more information.
Finding the workspace size (screen size less the taskbar) using GTK
502,282
5
2009-02-02T05:38:09Z
508,251
9
2009-02-03T18:09:21Z
[ "python", "gtk", "pygtk" ]
How do you create a main window that fills the entire desktop **without covering (or being covered by) the task bar** and **without being maximized**? I can find the entire screen size with and set the main window accordingly with this: ``` window = gtk.Window() screen = window.get_screen() window.resize(screen.get_width(), screen.get_height()) ``` but the bottom of the window is covered by the task bar.
You are totally at the mercy of your window manager for this, and the key issue here is: > **without being maximized** So we are left with a number of hacks, because basically maximization and resizing are two separate things, in order that you might be able to remember where it was when it is unmaximized. So before I show you this hideous hack, I urge you to consider using proper maximization and just be happy with it. So here goes: ``` import gtk # Even I am ashamed by this # Set up a one-time signal handler to detect size changes def _on_size_req(win, req): x, y, w, h = win.get_allocation() print x, y, w, h # just to prove to you its working win.disconnect(win.connection_id) win.unmaximize() win.window.move_resize(x, y, w, h) # Create the window, connect the signal, then maximise it w = gtk.Window() w.show_all() w.connection_id = w.connect('size-request', _on_size_req) # Maximizing will fire the signal handler just once, # unmaximize, and then resize to the previously set size for maximization. w.maximize() # run this monstrosity gtk.main() ```
Converting date between DD/MM/YYYY and YYYY-MM-DD?
502,726
12
2009-02-02T10:01:49Z
502,737
8
2009-02-02T10:07:57Z
[ "python", "date" ]
Using a Python script, I need to read a CVS file where dates are formated as DD/MM/YYYY, and convert them to YYYY-MM-DD before saving this into a SQLite database. This almost works, but fails because I don't provide time: ``` from datetime import datetime lastconnection = datetime.strptime("21/12/2008", "%Y-%m-%d") #ValueError: time data did not match format: data=21/12/2008 fmt=%Y-%m-%d print lastconnection ``` I assume there's a method in the datetime object to perform this conversion very easily, but I can't find an example of how to do it. Thank you.
you first would need to convert string into datetime tuple, and then convert that datetime tuple to string, it would go like this: ``` lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime('%Y-%m-%d') ```
Converting date between DD/MM/YYYY and YYYY-MM-DD?
502,726
12
2009-02-02T10:01:49Z
502,738
33
2009-02-02T10:09:22Z
[ "python", "date" ]
Using a Python script, I need to read a CVS file where dates are formated as DD/MM/YYYY, and convert them to YYYY-MM-DD before saving this into a SQLite database. This almost works, but fails because I don't provide time: ``` from datetime import datetime lastconnection = datetime.strptime("21/12/2008", "%Y-%m-%d") #ValueError: time data did not match format: data=21/12/2008 fmt=%Y-%m-%d print lastconnection ``` I assume there's a method in the datetime object to perform this conversion very easily, but I can't find an example of how to do it. Thank you.
Your example code is wrong. This works: ``` import datetime datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d") ``` The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.
Django: How to create a model dynamically just for testing
502,916
41
2009-02-02T11:35:52Z
503,435
39
2009-02-02T14:49:31Z
[ "python", "django", "unit-testing", "django-models", "mocking" ]
I have a Django app that requires a `settings` attribute in the form of: ``` RELATED_MODELS = ('appname1.modelname1.attribute1', 'appname1.modelname2.attribute2', 'appname2.modelname3.attribute3', ...) ``` Then hooks their post\_save signal to update some other fixed model depending on the `attributeN` defined. I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?) Solutions that allow me to use test fixtures would be great.
You can put your tests in a `tests/` subdirectory of the app (rather than a `tests.py` file), and include a `tests/models.py` with the test-only models. Then provide a test-running script ([example](https://github.com/carljm/django-model-utils/blob/master/runtests.py)) that includes your `tests/` "app" in `INSTALLED_APPS`. (This doesn't work when running app tests from a real project, which won't have the tests app in `INSTALLED_APPS`, but I rarely find it useful to run reusable app tests from a project, and Django 1.6+ doesn't by default.) (**NOTE**: The alternative dynamic method described below only works in Django 1.1+ if your test case subclasses `TransactionTestCase` - which slows down your tests significantly - and no longer works at all in Django 1.7+. It's left here only for historical interest; don't use it.) At the beginning of your tests (i.e. in a setUp method, or at the beginning of a set of doctests), you can dynamically add `"myapp.tests"` to the INSTALLED\_APPS setting, and then do this: ``` from django.core.management import call_command from django.db.models import loading loading.cache.loaded = False call_command('syncdb', verbosity=0) ``` Then at the end of your tests, you should clean up by restoring the old version of INSTALLED\_APPS and clearing the app cache again. [This class](http://www.djangosnippets.org/snippets/1011/) encapsulates the pattern so it doesn't clutter up your test code quite as much.
Django: How to create a model dynamically just for testing
502,916
41
2009-02-02T11:35:52Z
1,827,272
10
2009-12-01T16:24:59Z
[ "python", "django", "unit-testing", "django-models", "mocking" ]
I have a Django app that requires a `settings` attribute in the form of: ``` RELATED_MODELS = ('appname1.modelname1.attribute1', 'appname1.modelname2.attribute2', 'appname2.modelname3.attribute3', ...) ``` Then hooks their post\_save signal to update some other fixed model depending on the `attributeN` defined. I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?) Solutions that allow me to use test fixtures would be great.
This solution works only for earlier versions of `django` (before `1.7`). You can check your version easily: ``` import django django.VERSION < (1, 7) ``` Original response: It's quite strange but form me works very simple pattern: 1. add tests.py to app which you are going to test, 2. in this file just define testing models, 3. below put your testing code (doctest or TestCase definition), Below I've put some code which defines Article model which is needed only for tests (it exists in someapp/tests.py and I can test it just with: *./manage.py test someapp* ): ``` class Article(models.Model): title = models.CharField(max_length=128) description = models.TextField() document = DocumentTextField(template=lambda i: i.description) def __unicode__(self): return self.title __test__ = {"doctest": """ #smuggling model for tests >>> from .tests import Article #testing data >>> by_two = Article.objects.create(title="divisible by two", description="two four six eight") >>> by_three = Article.objects.create(title="divisible by three", description="three six nine") >>> by_four = Article.objects.create(title="divisible by four", description="four four eight") >>> Article.objects.all().search(document='four') [<Article: divisible by two>, <Article: divisible by four>] >>> Article.objects.all().search(document='three') [<Article: divisible by three>] """} ``` Unit tests also working with such model definition.
Django: How to create a model dynamically just for testing
502,916
41
2009-02-02T11:35:52Z
2,672,444
17
2010-04-20T04:00:49Z
[ "python", "django", "unit-testing", "django-models", "mocking" ]
I have a Django app that requires a `settings` attribute in the form of: ``` RELATED_MODELS = ('appname1.modelname1.attribute1', 'appname1.modelname2.attribute2', 'appname2.modelname3.attribute3', ...) ``` Then hooks their post\_save signal to update some other fixed model depending on the `attributeN` defined. I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?) Solutions that allow me to use test fixtures would be great.
@paluh's answer requires adding unwanted code to a non-test file and in my experience, @carl's solution does not work with django.test.TestCase which is needed to use fixtures. If you want to use django.test.TestCase, you need to make sure you call syncdb before the fixtures get loaded. This requires overriding the \_pre\_setup method (putting the code in the setUp method is not sufficient). I use my own version of TestCase that let's me add apps with test models. It is defined as follows: ``` from django.conf import settings from django.core.management import call_command from django.db.models import loading from django import test class TestCase(test.TestCase): apps = () def _pre_setup(self): # Add the models to the db. self._original_installed_apps = list(settings.INSTALLED_APPS) for app in self.apps: settings.INSTALLED_APPS.append(app) loading.cache.loaded = False call_command('syncdb', interactive=False, verbosity=0) # Call the original method that does the fixtures etc. super(TestCase, self)._pre_setup() def _post_teardown(self): # Call the original method. super(TestCase, self)._post_teardown() # Restore the settings. settings.INSTALLED_APPS = self._original_installed_apps loading.cache.loaded = False ```
Django: How to create a model dynamically just for testing
502,916
41
2009-02-02T11:35:52Z
15,460,736
8
2013-03-17T12:34:18Z
[ "python", "django", "unit-testing", "django-models", "mocking" ]
I have a Django app that requires a `settings` attribute in the form of: ``` RELATED_MODELS = ('appname1.modelname1.attribute1', 'appname1.modelname2.attribute2', 'appname2.modelname3.attribute3', ...) ``` Then hooks their post\_save signal to update some other fixed model depending on the `attributeN` defined. I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?) Solutions that allow me to use test fixtures would be great.
Quoting from [a related answer](http://stackoverflow.com/a/6960879/2179211): > If you want models defined for testing only then you should check out > [Django ticket #7835](https://code.djangoproject.com/ticket/7835) in particular [comment #24](https://code.djangoproject.com/ticket/7835#comment:24) part of which > is given below: > > > Apparently you can simply define models directly in your tests.py. > > Syncdb never imports tests.py, so those models won't get synced to the > > normal db, but they will get synced to the test database, and can be > > used in tests.
How to parse nagios status.dat file?
503,148
4
2009-02-02T13:11:09Z
2,570,062
9
2010-04-03T02:46:05Z
[ "python", "parsing", "nagios" ]
I'd like to parse status.dat file for nagios3 and output as xml with a python script. The xml part is the easy one but how do I go about parsing the file? Use multi line regex? It's possible the file will be large as many hosts and services are monitored, will loading the whole file in memory be wise? I only need to extract services that have critical state and host they belong to. Any help and pointing in the right direction will be highly appreciated. **LE** Here's how the file looks: ``` ######################################## # NAGIOS STATUS FILE # # THIS FILE IS AUTOMATICALLY GENERATED # BY NAGIOS. DO NOT MODIFY THIS FILE! ######################################## info { created=1233491098 version=2.11 } program { modified_host_attributes=0 modified_service_attributes=0 nagios_pid=15015 daemon_mode=1 program_start=1233490393 last_command_check=0 last_log_rotation=0 enable_notifications=1 active_service_checks_enabled=1 passive_service_checks_enabled=1 active_host_checks_enabled=1 passive_host_checks_enabled=1 enable_event_handlers=1 obsess_over_services=0 obsess_over_hosts=0 check_service_freshness=1 check_host_freshness=0 enable_flap_detection=0 enable_failure_prediction=1 process_performance_data=0 global_host_event_handler= global_service_event_handler= total_external_command_buffer_slots=4096 used_external_command_buffer_slots=0 high_external_command_buffer_slots=0 total_check_result_buffer_slots=4096 used_check_result_buffer_slots=0 high_check_result_buffer_slots=2 } host { host_name=localhost modified_attributes=0 check_command=check-host-alive event_handler= has_been_checked=1 should_be_scheduled=0 check_execution_time=0.019 check_latency=0.000 check_type=0 current_state=0 last_hard_state=0 plugin_output=PING OK - Packet loss = 0%, RTA = 3.57 ms performance_data= last_check=1233490883 next_check=0 current_attempt=1 max_attempts=10 state_type=1 last_state_change=1233489475 last_hard_state_change=1233489475 last_time_up=1233490883 last_time_down=0 last_time_unreachable=0 last_notification=0 next_notification=0 no_more_notifications=0 current_notification_number=0 notifications_enabled=1 problem_has_been_acknowledged=0 acknowledgement_type=0 active_checks_enabled=1 passive_checks_enabled=1 event_handler_enabled=1 flap_detection_enabled=1 failure_prediction_enabled=1 process_performance_data=1 obsess_over_host=1 last_update=1233491098 is_flapping=0 percent_state_change=0.00 scheduled_downtime_depth=0 } service { host_name=gateway service_description=PING modified_attributes=0 check_command=check_ping!100.0,20%!500.0,60% event_handler= has_been_checked=1 should_be_scheduled=1 check_execution_time=4.017 check_latency=0.210 check_type=0 current_state=0 last_hard_state=0 current_attempt=1 max_attempts=4 state_type=1 last_state_change=1233489432 last_hard_state_change=1233489432 last_time_ok=1233491078 last_time_warning=0 last_time_unknown=0 last_time_critical=0 plugin_output=PING OK - Packet loss = 0%, RTA = 2.98 ms performance_data= last_check=1233491078 next_check=1233491378 current_notification_number=0 last_notification=0 next_notification=0 no_more_notifications=0 notifications_enabled=1 active_checks_enabled=1 passive_checks_enabled=1 event_handler_enabled=1 problem_has_been_acknowledged=0 acknowledgement_type=0 flap_detection_enabled=1 failure_prediction_enabled=1 process_performance_data=1 obsess_over_service=1 last_update=1233491098 is_flapping=0 percent_state_change=0.00 scheduled_downtime_depth=0 } ``` It can have any number of hosts and a host can have any number of services.
Pfft, get yerself mk\_livestatus. <http://mathias-kettner.de/checkmk_livestatus.html>
Why is IronPython faster than the Official Python Interpreter
504,716
8
2009-02-02T20:21:28Z
504,725
37
2009-02-02T20:23:27Z
[ "python", "performance", "ironpython" ]
According to this: <http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&referringTitle=IronPython%20Performance> IronPython (Python for .Net) is faster than regular Python (cPython) on the same machine. Why is this? I would think compiled C code would always be faster than the equivalent CLI bytecode.
Python code doesn't get compiled to C, Python itself is written in C and interprets Python bytecode. CIL gets compiled to machine code, which is why you see better performance when using IronPython.
Why is IronPython faster than the Official Python Interpreter
504,716
8
2009-02-02T20:21:28Z
506,956
8
2009-02-03T12:49:08Z
[ "python", "performance", "ironpython" ]
According to this: <http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&referringTitle=IronPython%20Performance> IronPython (Python for .Net) is faster than regular Python (cPython) on the same machine. Why is this? I would think compiled C code would always be faster than the equivalent CLI bytecode.
You're right, C is a lot faster. That's why in those results CPython is twice as fast when it comes to dictionaries, which are almost pure C. On the other hand, Python code is not compiled, it's interpreted. Function calls in CPython are terribly slow. But on the other hand: ``` TryRaiseExcept: +4478.9% ``` Now, there's where IronPython get is horribly wrong. And then, there is this PyPy project, with one of the objectives being Just-In-Time compiler. There is even subset of Python, called RPython (Reduced Python) which can be statically compiled. Which of course is a **lot** faster.
Py2exe for Python 3.0
505,230
28
2009-02-02T22:28:40Z
506,005
7
2009-02-03T04:24:49Z
[ "python", "python-3.x", "py2exe" ]
I am looking for a Python3.0 version of "py2exe". I tried running 2to3 on the source for py2exe but the code remained broken. Any ideas?
The `py2exe` and `2to3` programs serve completely different purposes, so I'm not sure what your ultimate goal is. If you want to build an executable from a working Python program, use the version of `py2exe` that is suitable for whichever Python you are using (version 2 or version 3). If you want to convert an existing Python 2 program to Python 3, use `2to3` plus any additional editing as necessary. The Python 3 documentation describes [the conversion process in more detail](http://docs.python.org/3.0/whatsnew/3.0.html#porting-to-python-3-0). **Update**: I now understand that you might have been trying to run `2to3` against `py2exe` itself to try to make a Python 3 compatible version. Unfortunately, this is definitely beyond the capabilities of `2to3`. You will probably have to wait for the [py2exe project](http://www.py2exe.org/) to release a Python 3 compatible version.
Py2exe for Python 3.0
505,230
28
2009-02-02T22:28:40Z
633,648
27
2009-03-11T07:33:42Z
[ "python", "python-3.x", "py2exe" ]
I am looking for a Python3.0 version of "py2exe". I tried running 2to3 on the source for py2exe but the code remained broken. Any ideas?
### Update 2014-05-15 py2exe for Python 3.x is now released! [Get it on PyPI](https://pypi.python.org/pypi/py2exe). ### Old information Have a look at the py2exe SourceForge project SVN repository at: <http://py2exe.svn.sourceforge.net/> The last I looked at it, it said the last update was August 2009. But keep an eye on that to see if there's any Python 3 work in-progress. I've also submitted two feature requests on the py2exe tracker. So far, no feedback on them: * [Support Python 3.x](http://sourceforge.net/tracker/?func=detail&aid=3011276&group_id=15583&atid=365583) * [Project roadmap](http://sourceforge.net/tracker/?func=detail&aid=3031912&group_id=15583&atid=365583)
Py2exe for Python 3.0
505,230
28
2009-02-02T22:28:40Z
1,263,200
27
2009-08-11T22:00:16Z
[ "python", "python-3.x", "py2exe" ]
I am looking for a Python3.0 version of "py2exe". I tried running 2to3 on the source for py2exe but the code remained broken. Any ideas?
Did you check out [cx\_Freeze](http://cx-freeze.sourceforge.net/)? It seems to create standalone executables from your Python scripts, including support for Python 3.0 and 3.1
Py2exe for Python 3.0
505,230
28
2009-02-02T22:28:40Z
23,638,686
8
2014-05-13T18:15:48Z
[ "python", "python-3.x", "py2exe" ]
I am looking for a Python3.0 version of "py2exe". I tried running 2to3 on the source for py2exe but the code remained broken. Any ideas?
# py2exe for Python3 is out! Here is the original bug report: <http://sourceforge.net/projects/py2exe/> Here is the comment mentioning the release: <http://sourceforge.net/projects/py2exe/> Here is the package on pypi: <https://pypi.python.org/pypi/py2exe/0.9.2.0> **Note that py2exe for Python 3 only supports Python 3.3 and above!** **A huge thank you to the py2exe development team!**
Closures in Python
505,559
6
2009-02-03T00:13:06Z
505,596
7
2009-02-03T00:26:25Z
[ "python", "closures", "lexical-scope" ]
I've been trying to learn Python, and while I'm enthusiastic about using closures in Python, I've been having trouble getting some code to work properly: ``` def memoize(fn): def get(key): return (False,) def vset(key, value): global get oldget = get def newget(ky): if key==ky: return (True, value) return oldget(ky) get = newget def mfun(*args): cache = get(args) if (cache[0]): return cache[1] val = apply(fn, args) vset(args, val) return val return mfun def fib(x): if x<2: return x return fib(x-1)+fib(x-2) def fibm(x): if x<2: return x return fibm(x-1)+fibm(x-2) fibm = memoize(fibm) ``` Basically, what this is supposed to do is use closures to maintain the memoized state of the function. I realize there are probably many faster, easier to read, and in general more 'Pythonic' ways to implement this; however, my goal is to understand exactly how closures work in Python, and how they differ from Lisp, so I'm not interested in alternative solutions, just why my code doesn't work and what I can do (if anything) to fix it. The problem I'm running into is when I try to use `fibm` - Python insists that `get` isn't defined: ``` Python 2.6.1 (r261:67515, Feb 1 2009, 11:39:55) [GCC 4.0.1 (Apple Inc. build 5488)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import memoize >>> memoize.fibm(35) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "memoize.py", line 14, in mfun cache = get(args) NameError: global name 'get' is not defined >>> ``` Seeing as I'm new to Python, I don't know if I've done something wrong, or if this is just a limitation of the language. I'm hoping it's the former. :-)
The problem is in your scoping, not in your closures. If you're up for some heavy reading, then you can try <http://www.python.org/dev/peps/pep-3104/>. If that's not the case, here's the simple explanation: The problem is in the statement `global get` . `global` refers to the outermost scope, and since there isn't any global function `get`, it throws. What you need, is an access specifier for variables in the enclosing scope, and not the global scope. In python 3.0, as I've tested, the `nonlocal` keyword is exactly what you need, in the place of `global`. ``` nonlocal get ... ``` In python 2.x, I just removed the `global get` and the `oldget` references and it works properly.
Closures in Python
505,559
6
2009-02-03T00:13:06Z
505,663
7
2009-02-03T00:57:24Z
[ "python", "closures", "lexical-scope" ]
I've been trying to learn Python, and while I'm enthusiastic about using closures in Python, I've been having trouble getting some code to work properly: ``` def memoize(fn): def get(key): return (False,) def vset(key, value): global get oldget = get def newget(ky): if key==ky: return (True, value) return oldget(ky) get = newget def mfun(*args): cache = get(args) if (cache[0]): return cache[1] val = apply(fn, args) vset(args, val) return val return mfun def fib(x): if x<2: return x return fib(x-1)+fib(x-2) def fibm(x): if x<2: return x return fibm(x-1)+fibm(x-2) fibm = memoize(fibm) ``` Basically, what this is supposed to do is use closures to maintain the memoized state of the function. I realize there are probably many faster, easier to read, and in general more 'Pythonic' ways to implement this; however, my goal is to understand exactly how closures work in Python, and how they differ from Lisp, so I'm not interested in alternative solutions, just why my code doesn't work and what I can do (if anything) to fix it. The problem I'm running into is when I try to use `fibm` - Python insists that `get` isn't defined: ``` Python 2.6.1 (r261:67515, Feb 1 2009, 11:39:55) [GCC 4.0.1 (Apple Inc. build 5488)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import memoize >>> memoize.fibm(35) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "memoize.py", line 14, in mfun cache = get(args) NameError: global name 'get' is not defined >>> ``` Seeing as I'm new to Python, I don't know if I've done something wrong, or if this is just a limitation of the language. I'm hoping it's the former. :-)
``` def memoize(fn): get = [lambda key: (False, None)] def vset(args): value = fn(*args) oldget = get[0] def newget(key): if args == key: return (True, value) return oldget(key) get[0] = newget return value def mfun(*args): found, value = get[0](args) if found: return value return vset(args) return mfun CALLS = 0 def fib(x): global CALLS CALLS += 1 if x<2: return x return fib(x-1)+fib(x-2) @memoize def fibm(x): global CALLS CALLS += 1 if x<2: return x return fibm(x-1)+fibm(x-2) CALLS = 0 print "fib(35) is", fib(35), "and took", CALLS, "calls" CALLS = 0 print "fibm(35) is", fibm(35), "and took", CALLS, "calls" ``` Output is: ``` fib(35) is 9227465 and took 29860703 calls fibm(35) is 9227465 and took 36 calls ``` Similar to other answers, however this one works. :) The important change from the code in the question is assigning to a non-global non-local (get); however, I also made some improvements while trying to maintain your `*`cough`*`*broken*`*`cough`*` closure use. Usually the cache is a dict instead of a linked list of closures.
Is there a widely used STOMP adapter for Twisted?
506,594
2
2009-02-03T10:12:30Z
561,901
7
2009-02-18T16:45:59Z
[ "python", "twisted", "activemq", "stomp" ]
I checked out stomper and it didn't look complete. (I'm very new to Python) Is anybody out there using stomper in a production environment? If not, I guess I'll have to roll out my own Twisted Stomp adapter. Thanks in advance!
There is a python library called [stomper](https://github.com/oisinmulvihill/stomper) which I've used in the past with twisted (it comes with twisted example code). Disclaimer, I've worked on the code for stomper so I like it :) These days I've moved away from stomp/ActiveMQ towards AMQP + [RabbitMQ](http://www.rabbitmq.com/), using the [txAMQP](https://launchpad.net/txamqp) and [py-amqplib](http://barryp.org/software/py-amqplib/) libraries. I've found rabbit more reliable and the AMQP protocol quite good. See [this article](http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/) for a very good overview. A big bonus is good java and .net library support too.
Python xml minidom. generate <text>Some text</text> element
507,405
10
2009-02-03T14:59:17Z
507,555
8
2009-02-03T15:30:32Z
[ "python", "xml", "minidom" ]
I have the following code. ``` from xml.dom.minidom import Document doc = Document() root = doc.createElement('root') doc.appendChild(root) main = doc.createElement('Text') root.appendChild(main) text = doc.createTextNode('Some text here') main.appendChild(text) print doc.toprettyxml(indent='\t') ``` The result is: ``` <?xml version="1.0" ?> <root> <Text> Some text here </Text> </root> ``` This is all fine and dandy, but what if I want the output to look like this? ``` <?xml version="1.0" ?> <root> <Text>Some text here</Text> </root> ``` Can this easily be done? Orjanp...
> Can this easily be done? It depends what exact rule you want, but generally no, you get little control over pretty-printing. If you want a specific format you'll usually have to write your own walker. The DOM Level 3 LS parameter format-pretty-print in [pxdom](http://www.doxdesk.com/software/py/pxdom.html) comes pretty close to your example. Its rule is that if an element contains only a single TextNode, no extra whitespace will be added. However it (currently) uses two spaces for an indent rather than four. ``` >>> doc= pxdom.parseString('<a><b>c</b></a>') >>> doc.domConfig.setParameter('format-pretty-print', True) >>> print doc.pxdomContent <?xml version="1.0" encoding="utf-16"?> <a> <b>c</b> </a> ``` (Adjust encoding and output format for whatever type of serialisation you're doing.) If that's the rule you want, and you can get away with it, you might also be able to monkey-patch minidom's Element.writexml, eg.: ``` >>> from xml.dom import minidom >>> def newwritexml(self, writer, indent= '', addindent= '', newl= ''): ... if len(self.childNodes)==1 and self.firstChild.nodeType==3: ... writer.write(indent) ... self.oldwritexml(writer) # cancel extra whitespace ... writer.write(newl) ... else: ... self.oldwritexml(writer, indent, addindent, newl) ... >>> minidom.Element.oldwritexml= minidom.Element.writexml >>> minidom.Element.writexml= newwritexml ``` All the usual caveats about the badness of monkey-patching apply.
How do i install pyCurl?
507,927
22
2009-02-03T16:50:24Z
507,955
7
2009-02-03T16:56:48Z
[ "python", "libcurl", "pycurl", "installation" ]
I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine. i'm on windows, i tried DLing the sources and use pycurl setup script, i had no luck.
Depends on platform. Here on ubuntu it's as simple as: ``` sudo aptitude install python-pycurl ``` It's common enough a package to think that most major Linux distributions will have it in their sources. If you're on windows, you'll need [cURL](http://curl.haxx.se/download.html) too. Then you can install [pycurl](http://pycurl.sourceforge.net/download/) which comes wrapped in an installer.
How do i install pyCurl?
507,927
22
2009-02-03T16:50:24Z
508,143
7
2009-02-03T17:42:26Z
[ "python", "libcurl", "pycurl", "installation" ]
I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine. i'm on windows, i tried DLing the sources and use pycurl setup script, i had no luck.
As it has been said already, it depends on the platform. In general, I prefer to use only the Python interpreter itself that is packaged for my OS and install everything else in a [virtual environment](http://pypi.python.org/pypi/virtualenv), but this is a whole different story... If you've got [setuptools](http://pypi.python.org/pypi/setuptools/) installed, installing most Python packages is as simple as: ``` easy_install pycurl ```
How do i install pyCurl?
507,927
22
2009-02-03T16:50:24Z
551,418
11
2009-02-15T19:07:16Z
[ "python", "libcurl", "pycurl", "installation" ]
I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine. i'm on windows, i tried DLing the sources and use pycurl setup script, i had no luck.
According to <http://bazaar-vcs.org/PyCurl> > Since Windows does not come with > neither cURL or pycURL, Windows users > will have to install both. > > cURL downloads: > <http://curl.haxx.se/download.html>. > > pycURL downloads: > <http://pycurl.sourceforge.net/download/>. > > Both links contain Linux (and other > \*Nix) tarballs/packages and Windows installer files. There are windows installers at both links, hopefully they will work for you.
How do i install pyCurl?
507,927
22
2009-02-03T16:50:24Z
5,385,014
12
2011-03-21T23:35:40Z
[ "python", "libcurl", "pycurl", "installation" ]
I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine. i'm on windows, i tried DLing the sources and use pycurl setup script, i had no luck.
You can try to download pycurl from here <http://www.lfd.uci.edu/~gohlke/pythonlibs/> > PycURL is a interface to the libcurl library. > pycurl-7.19.0.win-amd64-py2.6.‌exe [863 KB] [Python 2.6] [64 bit] [Dec 09, 2010] > pycurl-7.19.0.win-amd64-py2.7.‌exe [863 KB] [Python 2.7] [64 bit] [Dec 09, 2010] > pycurl-7.19.0.win32-py2.6.‌exe [764 KB] [Python 2.6] [32 bit] [Dec 09, 2010] > pycurl-7.19.0.win32-py2.7.‌exe [764 KB] [Python 2.7] [32 bit] [Dec 09, 2010] or here <http://pycurl.sourceforge.net/download/> > pycurl-ssl-7.15.5.1.win32-py2.4.exe 02-Oct-2006 10:10 534K precompiled win32 installer (with openssl-0.9.8c, zlib-1.2.3, c-ares-1.3.1) > pycurl-ssl-7.15.5.1.win32-py2.5.exe 02-Oct-2006 10:10 534K precompiled win32 installer (with openssl-0.9.8c, zlib-1.2.3, c-ares-1.3.1) > pycurl-ssl-7.16.4.win32-py2.4.exe 05-Sep-2007 19:28 546K precompiled win32 installer (with openssl-0.9.8e, zlib-1.2.3, c-ares-1.4.0) > pycurl-ssl-7.16.4.win32-py2.5.exe 05-Sep-2007 19:27 546K precompiled win32 installer (with openssl-0.9.8e, zlib-1.2.3, c-ares-1.4.0) > pycurl-ssl-7.18.2.win32-py2.5.exe 17-Jun-2008 20:43 540K precompiled win32 installer (with openssl-0.9.8h, zlib-1.2.3)
How do i install pyCurl?
507,927
22
2009-02-03T16:50:24Z
10,699,666
14
2012-05-22T09:52:55Z
[ "python", "libcurl", "pycurl", "installation" ]
I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine. i'm on windows, i tried DLing the sources and use pycurl setup script, i had no luck.
**TL,DR** Get a binary from this website: <http://www.lfd.uci.edu/~gohlke/pythonlibs/> Direct links: [`2.6 32bit`](http://www.lfd.uci.edu/~gohlke/pythonlibs/qjbh48zu/pycurl-7.19.0.win32-py2.6.exe), [`2.7 32bit`](http://www.lfd.uci.edu/~gohlke/pythonlibs/qjbh48zu/pycurl-7.19.0.win32-py2.7.exe),[`2.6 64bit`](http://www.lfd.uci.edu/~gohlke/pythonlibs/qjbh48zu/pycurl-7.19.0.win-amd64-py2.6.exe), [`2.7 64bit`](http://www.lfd.uci.edu/~gohlke/pythonlibs/qjbh48zu/pycurl-7.19.0.win-amd64-py2.7.exe) --- For pycURL, both `pip` and `easy_install` will fail on Windows. I also tried to download and install the pycURL package manually, after downloading cURL, but that didn't work either, even if specifying the `CURL_DIR` ( it complained that it cannot find 'lib\libcurl.lib' ). From what I can gather from the README, what it needs in the `CURL_DIR` is the source distribution of cURL, not the executable. Downloading the precompiled version from the official [pycURL repository](http://pycurl.sourceforge.net/download/) will probably get you nowhere, because it requires Python 2.5. It will *not* work with 2.6. The only easy way at the moment seems to be [this](http://www.lfd.uci.edu/~gohlke/pythonlibs/5kq9gygp/pycurl-7.19.0.win32-py2.6.exe) unofficial release. It an executable installer, and I have used it without any issues with Python 2.6. A [version for Python 2.7](http://www.lfd.uci.edu/~gohlke/pythonlibs/5kq9gygp/pycurl-7.19.0.win32-py2.7.exe) is available from [the same site](http://www.lfd.uci.edu/~gohlke/pythonlibs/). --- You might also want to consider using [`requests`](http://docs.python-requests.org/en/latest/), a popular alternative to pycURL. It's a pleasure to use, and is actively developed.
Is there a good dependency analysis tool for Python?
508,277
23
2009-02-03T18:18:07Z
509,194
24
2009-02-03T22:26:13Z
[ "python", "dependencies" ]
Dependency analysis programs help us organize code by controlling the dependencies between modules in our code. When one module is a circular dependency of another module, it is a clue to find a way to turn that into a unidirectional dependency or merge two modules into one module. What is the best dependency analysis tool for Python code?
I recommend using [snakefood](http://furius.ca/snakefood/) for creating graphical dependency graphs of Python projects. It detects dependencies nicely enough to immediately see areas for refactorisation. Its usage is pretty straightforward if you read a little bit of documentation. Of course, you can omit the graph-creation step and receive a dependency dictionary in a file instead.
AUTO_INCREMENT in sqlite problem with python
508,627
8
2009-02-03T19:49:59Z
508,664
34
2009-02-03T19:56:53Z
[ "python", "sqlite" ]
I am using sqlite with python 2.5. I get a sqlite error with the syntax below. I looked around and saw AUTOINCREMENT on this page <http://www.sqlite.org/syntaxdiagrams.html#column-constraint> but that did not work either. Without AUTO\_INCREMENT my table can be created. ``` An error occurred: near "AUTO_INCREMENT": syntax error CREATE TABLE fileInfo ( fileId int NOT NULL AUTO_INCREMENT, name varchar(255), status int NOT NULL, PRIMARY KEY (fileId) ); ```
This is addressed in the [SQLite FAQ](http://www.sqlite.org/faq.html). [Question #1](http://www.sqlite.org/faq.html#q1). Which states: > How do I create an AUTOINCREMENT > field? > > Short answer: A column declared > INTEGER PRIMARY KEY will > autoincrement. > > Here is the long answer: If you > declare a column of a table to be > INTEGER PRIMARY KEY, then whenever you > insert a NULL into that column of the > table, the NULL is automatically > converted into an integer which is one > greater than the largest value of that > column over all other rows in the > table, or 1 if the table is empty. (If > the largest possible integer key, > 9223372036854775807, then an unused > key value is chosen at random.) For > example, suppose you have a table like > this: > > `CREATE TABLE t1( a INTEGER PRIMARY` > `KEY, b INTEGER );` With this table, > the statement > > `INSERT INTO t1 VALUES(NULL,123);` is > logically equivalent to saying: > > `INSERT INTO t1 VALUES((SELECT max(a) > FROM t1)+1,123);` There is a function > named `sqlite3_last_insert_rowid()` > which will return the integer key for > the most recent insert operation. > > Note that the integer key is one > greater than the largest key that was > in the table just prior to the insert. > The new key will be unique over all > keys currently in the table, but it > might overlap with keys that have been > previously deleted from the table. To > create keys that are unique over the > lifetime of the table, add the > AUTOINCREMENT keyword to the INTEGER > PRIMARY KEY declaration. Then the key > chosen will be one more than than the > largest key that has ever existed in > that table. If the largest possible > key has previously existed in that > table, then the INSERT will fail with > an SQLITE\_FULL error code.
AUTO_INCREMENT in sqlite problem with python
508,627
8
2009-02-03T19:49:59Z
508,667
10
2009-02-03T19:57:06Z
[ "python", "sqlite" ]
I am using sqlite with python 2.5. I get a sqlite error with the syntax below. I looked around and saw AUTOINCREMENT on this page <http://www.sqlite.org/syntaxdiagrams.html#column-constraint> but that did not work either. Without AUTO\_INCREMENT my table can be created. ``` An error occurred: near "AUTO_INCREMENT": syntax error CREATE TABLE fileInfo ( fileId int NOT NULL AUTO_INCREMENT, name varchar(255), status int NOT NULL, PRIMARY KEY (fileId) ); ```
It looks like AUTO\_INCREMENT should be AUTOINCREMENT see <http://www.sqlite.org/syntaxdiagrams.html#column-constraint>
Multidimensional array in Python
508,657
8
2009-02-03T19:54:37Z
261,084
18
2008-11-04T06:37:50Z
[ "java", "python", "arrays" ]
I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like: ``` double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3]; dArray[0][0][0] = 0; dArray[0][0][1] = POSITIVE_INFINITY; ``` Further values will be created bei loops and written into the array. How do I instantiate the array? PS: There is no matrix multiplication involved...
If you restrict yourself to the Python standard library, then a list of lists is the closest construct: ``` arr = [[1,2],[3,4]] ``` gives a 2d-like array. The rows can be accessed as `arr[i]` for `i` in `{0,..,len(arr}`, but column access is difficult. If you are willing to add a library dependency, the [NumPy](http://numpy.scipy.org) package is what you really want. You can create a fixed-length array from a list of lists using: ``` import numpy arr = numpy.array([[1,2],[3,4]]) ``` Column access is the same as for the list-of-lists, but column access is easy: `arr[:,i]` for `i` in `{0,..,arr.shape[1]}` (the number of columns). In fact NumPy arrays can be n-dimensional. Empty arrays can be created with ``` numpy.empty(shape) ``` where `shape` is a tuple of size in each dimension; `shape=(1,3,2)` gives a 3-d array with size 1 in the first dimension, size 3 in the second dimension and 2 in the 3rd dimension. If you want to store objects in a NumPy array, you can do that as well: ``` arr = numpy.empty((1,), dtype=numpy.object) arr[0] = 'abc' ``` For more info on the NumPy project, check out the [NumPy homepage](http://numpy.scipy.org).
Multidimensional array in Python
508,657
8
2009-02-03T19:54:37Z
261,340
13
2008-11-04T09:34:25Z
[ "java", "python", "arrays" ]
I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like: ``` double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3]; dArray[0][0][0] = 0; dArray[0][0][1] = POSITIVE_INFINITY; ``` Further values will be created bei loops and written into the array. How do I instantiate the array? PS: There is no matrix multiplication involved...
To create a standard python array of arrays of arbitrary size: ``` a = [[0]*cols for _ in [0]*rows] ``` It is accessed like this: ``` a[0][1] = 5 # set cell at row 0, col 1 to 5 ``` A small python gotcha that's worth mentioning: It is tempting to just type ``` a = [[0]*cols]*rows ``` but that'll copy the *same* column array to each row, resulting in unwanted behaviour. Namely: ``` >>> a[0][0] = 5 >>> print a[1][0] 5 ```
Multidimensional array in Python
508,657
8
2009-02-03T19:54:37Z
261,656
10
2008-11-04T12:04:00Z
[ "java", "python", "arrays" ]
I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like: ``` double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3]; dArray[0][0][0] = 0; dArray[0][0][1] = POSITIVE_INFINITY; ``` Further values will be created bei loops and written into the array. How do I instantiate the array? PS: There is no matrix multiplication involved...
Multidimensional arrays are a little murky. There are few reasons for using them and many reasons for thinking twice and using something else that more properly reflects what you're doing. [Hint. your question was thin on context ;-) ] If you're doing matrix math, then use `numpy`. However, some folks have worked with languages that force them to use multi-dimensional arrays because it's all they've got. If your as old as I am (I started programming in the 70's) then you may remember the days when multidimensional arrays were the only data structure you had. Or, your experience may have limited you to languages where you had to morph your problem into multi-dimensional arrays. Say you have a collection *n* 3D points. Each point has an x, y, z, and time value. Is this an *n* x 4 array? Or a 4 \* *n* array? Not really. Since each point has 4 fixed values, this is more properly a list of tuples. ``` a = [ ( x, y, z, t ), ( x, y, z, t ), ... ] ``` Better still, we could represent this as a list of objects. ``` class Point( object ): def __init__( self, x, y, z, t ): self.x, self.y, self.z, self.t = x, y, z, t a = [ Point(x,y,x,t), Point(x,y,z,t), ... ] ```
Multidimensional array in Python
508,657
8
2009-02-03T19:54:37Z
508,677
11
2009-02-03T19:59:02Z
[ "java", "python", "arrays" ]
I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like: ``` double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3]; dArray[0][0][0] = 0; dArray[0][0][1] = POSITIVE_INFINITY; ``` Further values will be created bei loops and written into the array. How do I instantiate the array? PS: There is no matrix multiplication involved...
You can create it using nested lists: ``` matrix = [[a,b],[c,d],[e,f]] ``` If it has to be dynamic it's more complicated, why not write a small class yourself? ``` class Matrix(object): def __init__(self, rows, columns, default=0): self.m = [] for i in range(rows): self.m.append([default for j in range(columns)]) def __getitem__(self, index): return self.m[index] ``` This can be used like this: ``` m = Matrix(10,5) m[3][6] = 7 print m[3][6] // -> 7 ``` I'm sure one could implement it much more efficient. :) If you need multidimensional arrays you can either create an array and calculate the offset or you'd use arrays in arrays in arrays, which can be pretty bad for memory. (Could be faster though…) I've implemented the first idea like this: ``` class Matrix(object): def __init__(self, *dims): self._shortcuts = [i for i in self._create_shortcuts(dims)] self._li = [None] * (self._shortcuts.pop()) self._shortcuts.reverse() def _create_shortcuts(self, dims): dimList = list(dims) dimList.reverse() number = 1 yield 1 for i in dimList: number *= i yield number def _flat_index(self, index): if len(index) != len(self._shortcuts): raise TypeError() flatIndex = 0 for i, num in enumerate(index): flatIndex += num * self._shortcuts[i] return flatIndex def __getitem__(self, index): return self._li[self._flat_index(index)] def __setitem__(self, index, value): self._li[self._flat_index(index)] = value ``` Can be used like this: ``` m = Matrix(4,5,2,6) m[2,3,1,3] = 'x' m[2,3,1,3] // -> 'x' ```
Multidimensional array in Python
508,657
8
2009-02-03T19:54:37Z
508,679
11
2009-02-03T20:00:21Z
[ "java", "python", "arrays" ]
I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like: ``` double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3]; dArray[0][0][0] = 0; dArray[0][0][1] = POSITIVE_INFINITY; ``` Further values will be created bei loops and written into the array. How do I instantiate the array? PS: There is no matrix multiplication involved...
Take a look at [numpy](http://numpy.scipy.org//) here's a code snippet for you ``` import numpy as npy d = npy.zeros((len(x)+1, len(y)+1, len(x)+len(y)+3)) d[0][0][0] = 0 # although this is unnecessary since zeros initialises to zero d[i][j][k] = npy.inf ``` I don't think you need to be implementing a scientific application to justify the use of numpy. It is faster and more flexible and you can store pretty much anything. Given that I think it is probably better to try and justify *not* using it. There are legitimate reasons, but it adds a great deal and costs very little so it deserves consideration. P.S. Are your array lengths right? It looks like a pretty peculiar shaped matrix...
Python time to age
508,727
2
2009-02-03T20:12:06Z
508,742
16
2009-02-03T20:16:48Z
[ "python", "datetime" ]
I'm trying to convert a date string into an age. The string is like: "Mon, 17 Nov 2008 01:45:32 +0200" and I need to work out how many days old it is. I have sucessfully converted the date using: ``` >>> time.strptime("Mon, 17 Nov 2008 01:45:32 +0200","%a, %d %b %Y %H:%M:%S +0200") (2008, 11, 17, 1, 45, 32, 0, 322, -1) ``` For some reason %z gives me an error for the +0200 but it doesn't matter that much. I can get the current time using: ``` >>> time.localtime() (2009, 2, 3, 19, 55, 32, 1, 34, 0) ``` but how can I subtract one from the other without going though each item in the list and doing it manually?
You need to use the module `datetime` and the object [`datetime.timedelta`](http://docs.python.org/library/datetime.html#datetime.timedelta) ``` from datetime import datetime t1 = datetime.strptime("Mon, 17 Nov 2008 01:45:32 +0200","%a, %d %b %Y %H:%M:%S +0200") t2 = datetime.now() tdelta = t2 - t1 # actually a datetime.timedelta object print tdelta.days ```
A replacement for python's httplib?
508,817
9
2009-02-03T20:36:21Z
508,840
21
2009-02-03T20:44:37Z
[ "python", "http", "curl", "twisted" ]
I have a python client which pushes a great deal of data through the standard library's httlib. Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using. Could I improve performance by replacing httplib with something else? I've seen that twisted offers a HTTP client. It seems to be very basic compared to their other protocol offerings. PyCurl might be a valid alternative, however it's use seems to be very un-pythonic, on the other hand if it's performance is really good then I can put up with a bit of un-pythonic code. So if you have experience of better HTTP client libraries of python please tell me about it. I'd like to know what you thought of the performance relative to httplib and what you thought of the quality of implementation. UPDATE 0: My use of httplib is actually very limited - the replacement needs to do the following: ``` conn = httplib.HTTPConnection(host, port) conn.request("POST", url, params, headers) compressedstream = StringIO.StringIO(conn.getresponse().read()) ``` That's all: No proxies, redirection or any fancy stuff. It's plain-old HTTP. I just need to be able to do it as fast as possible. UPDATE 1: I'm stuck with Python2.4 and I'm working on Windows 32. Please do not tell me about better ways to use httplib - I want to know about some of the alternatives to httplib.
Often when I've had performance problems with httplib, the problem hasn't been with the httplib itself, but with how I'm using it. Here are a few common pitfalls: (1) Don't make a new TCP connection for every web request. If you are making lots of request to the same server, instead of this pattern: ``` conn = httplib.HTTPConnection("www.somewhere.com") conn.request("GET", '/foo') conn = httplib.HTTPConnection("www.somewhere.com") conn.request("GET", '/bar') conn = httplib.HTTPConnection("www.somewhere.com") conn.request("GET", '/baz') ``` Do this instead: ``` conn = httplib.HTTPConnection("www.somewhere.com") conn.request("GET", '/foo') conn.request("GET", '/bar') conn.request("GET", '/baz') ``` (2) Don't serialize your requests. You can use threads or asynccore or whatever you like, but if you are making multiple requests from different servers, you can improve performance by running them in parallel.
A replacement for python's httplib?
508,817
9
2009-02-03T20:36:21Z
508,858
18
2009-02-03T20:53:12Z
[ "python", "http", "curl", "twisted" ]
I have a python client which pushes a great deal of data through the standard library's httlib. Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using. Could I improve performance by replacing httplib with something else? I've seen that twisted offers a HTTP client. It seems to be very basic compared to their other protocol offerings. PyCurl might be a valid alternative, however it's use seems to be very un-pythonic, on the other hand if it's performance is really good then I can put up with a bit of un-pythonic code. So if you have experience of better HTTP client libraries of python please tell me about it. I'd like to know what you thought of the performance relative to httplib and what you thought of the quality of implementation. UPDATE 0: My use of httplib is actually very limited - the replacement needs to do the following: ``` conn = httplib.HTTPConnection(host, port) conn.request("POST", url, params, headers) compressedstream = StringIO.StringIO(conn.getresponse().read()) ``` That's all: No proxies, redirection or any fancy stuff. It's plain-old HTTP. I just need to be able to do it as fast as possible. UPDATE 1: I'm stuck with Python2.4 and I'm working on Windows 32. Please do not tell me about better ways to use httplib - I want to know about some of the alternatives to httplib.
> Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using. > > Could I improve performance by replacing httplib with something else? Do you *suspect* it or are you *sure* that that it's `httplib`? Profile before you do anything to improve the performance of your app. I've found my own intuition on where time is spent is often pretty bad (given that there isn't some code kernel executed millions of times). It's really disappointing to implement something to improve performance then pull up the app and see that it made no difference. If you're not profiling, you're shooting in the dark!
How to overwrite some bytes in the middle of a file with Python?
508,983
11
2009-02-03T21:31:53Z
509,014
18
2009-02-03T21:39:57Z
[ "python", "file", "patching" ]
I'd like to be able to overwrite some bytes at a given offset in a file using Python. My attempts have failed miserably and resulted in: * overwriting the bytes at the offset but also truncating the file just after (file mode = "w" or "w+") * appending the bytes at the end of the file (file mode = "a" or "a+") Is it possible to achieve this with Python in a portable way?
Try this: ``` fh = open("filename.ext", "r+b") fh.seek(offset) fh.write(bytes) fh.close() ```
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
509,295
1,891
2009-02-03T22:48:24Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
It's pretty simple really: ``` a[start:end] # items start through end-1 a[start:] # items start through the rest of the array a[:end] # items from the beginning through end-1 a[:] # a copy of the whole array ``` There is also the `step` value, which can be used with any of the above: ``` a[start:end:step] # start through not past end, by step ``` The key point to remember is that the `:end` value represents the first value that is *not* in the selected slice. So, the difference beween `end` and `start` is the number of elements selected (if `step` is 1, the default). The other feature is that `start` or `end` may be a *negative* number, which means it counts from the end of the array instead of the beginning. So: ``` a[-1] # last item in the array a[-2:] # last two items in the array a[:-2] # everything except the last two items ``` Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for `a[:-2]` and `a` only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
509,297
245
2009-02-03T22:49:04Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
The tutorial talks about it: <http://docs.python.org/tutorial/introduction.html#strings> (Scroll down a bit until you get to the part about slicing.) The ASCII art diagram is helpful too for remembering how slices work: ``` +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1 ``` > "One way to remember how slices work > is to think of the indices as pointing > *between* characters, with the left edge of the first character numbered > 0."
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
509,377
180
2009-02-03T23:08:22Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
Enumerating the possibilities allowed by the grammar: ``` >>> seq[:] # [seq[0], seq[1], ..., seq[-1] ] >>> seq[low:] # [seq[low], seq[low+1], ..., seq[-1] ] >>> seq[:high] # [seq[0], seq[1], ..., seq[high-1]] >>> seq[low:high] # [seq[low], seq[low+1], ..., seq[high-1]] >>> seq[::stride] # [seq[0], seq[stride], ..., seq[-1] ] >>> seq[low::stride] # [seq[low], seq[low+stride], ..., seq[-1] ] >>> seq[:high:stride] # [seq[0], seq[stride], ..., seq[high-1]] >>> seq[low:high:stride] # [seq[low], seq[low+stride], ..., seq[high-1]] ``` Of course, if `(high-low)%stride != 0`, then the end point will be a little lower than `high-1`. Extended slicing (with commas and ellipses) are mostly used only by special data structures (like Numpy); the basic sequences don't support them. ``` >>> class slicee: ... def __getitem__(self, item): ... return `item` ... >>> slicee()[0, 1:2, ::5, ...] '(0, slice(1, 2, None), slice(None, None, 5), Ellipsis)' ```
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
509,415
82
2009-02-03T23:15:02Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
And a couple of things that weren't immediately obvious to me when I first saw the slicing syntax: ``` >>> x = [1,2,3,4,5,6] >>> x[::-1] [6,5,4,3,2,1] ``` Easy way to reverse sequences! And if you wanted, for some reason, every second item in the reversed sequence: ``` >>> x = [1,2,3,4,5,6] >>> x[::-2] [6,4,2] ```
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
522,212
20
2009-02-06T21:16:28Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
I use the "an index points between elements" method of thinking about it myself, but one way of describing it which sometimes helps others get it is this: ``` mylist[X:Y] ``` X is the index of the first element you want. Y is the index of the first element you *don't* want.
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
567,094
33
2009-02-19T20:52:44Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
After using it a bit I realise that the simplest description is that it is exactly the same as the arguments in a for loop... ``` (from:to:step) ``` any of them are optional ``` (:to:step) (from::step) (from:to) ``` then the negative indexing just needs you to add the length of the string to the negative indices to understand it. This works for me anyway...
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
4,729,334
119
2011-01-18T21:37:57Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
The answers above don't discuss slice assignment: ``` >>> r=[1,2,3,4] >>> r[1:1] [] >>> r[1:1]=[9,8] >>> r [1, 9, 8, 2, 3, 4] >>> r[1:1]=['blah'] >>> r [1, 'blah', 9, 8, 2, 3, 4] ``` This may also clarify the difference between slicing and indexing.
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
7,315,935
64
2011-09-06T06:50:08Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
Found this great table at <http://wiki.python.org/moin/MovingToPythonFromOtherLanguages> ``` Python indexes and slices for a six-element list. Indexes enumerate the elements, slices enumerate the spaces between the elements. Index from rear: -6 -5 -4 -3 -2 -1 a=[0,1,2,3,4,5] a[1:]==[1,2,3,4,5] Index from front: 0 1 2 3 4 5 len(a)==6 a[:5]==[0,1,2,3,4] +---+---+---+---+---+---+ a[0]==0 a[:-2]==[0,1,2,3] | a | b | c | d | e | f | a[5]==5 a[1:2]==[1] +---+---+---+---+---+---+ a[-1]==5 a[1:-1]==[1,2,3,4] Slice from front: : 1 2 3 4 5 : a[-2]==4 Slice from rear: : -5 -4 -3 -2 -1 : b=a[:] b==[0,1,2,3,4,5] (shallow copy of a) ```
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
9,827,284
16
2012-03-22T17:20:59Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
This is just for some extra info... Consider the list below ``` >>> l=[12,23,345,456,67,7,945,467] ``` Few other tricks for reversing the list: ``` >>> l[len(l):-len(l)-1:-1] [467, 945, 7, 67, 456, 345, 23, 12] >>> l[:-len(l)-1:-1] [467, 945, 7, 67, 456, 345, 23, 12] >>> l[len(l)::-1] [467, 945, 7, 67, 456, 345, 23, 12] >>> l[::-1] [467, 945, 7, 67, 456, 345, 23, 12] >>> l[-1:-len(l)-1:-1] [467, 945, 7, 67, 456, 345, 23, 12] ``` See abc's answer above
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
9,923,354
21
2012-03-29T10:15:12Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
I find it easier to remember how it's works, then I can figure out any specific start/stop/step combination. It's instructive to understand `range()` first: ``` def range(start=0, stop, step=1): # illegal syntax, but that's the effect i = start while (i < stop if step > 0 else i > stop): yield i i += step ``` Begin from `start`, increment by `step`, do not reach `stop`. Very simple. The thing to remember about negative step is that `stop` is always the excluded end, whether it's higher or lower. If you want same slice in opposite order, it's much cleaner to do the reversal separately: e.g. `'abcde'[1:-2][::-1]` slices off one char from left, two from right, then reverses. (See also [`reversed()`](http://www.python.org/dev/peps/pep-0322/).) Sequence slicing is same, except it first normalizes negative indexes, and can never go outside the sequence: ``` def this_is_how_slicing_works(seq, start=None, stop=None, step=1): if start is None: start = (0 if step > 0 else len(seq)-1) elif start < 0: start += len(seq) if stop is None: stop = (len(seq) if step > 0 else -1) # really -1, not last element elif stop < 0: stop += len(seq) for i in range(start, stop, step): if 0 <= i < len(seq): yield seq[i] ``` Don't worry about the `is None` details - just remember that omitting `start` and/or `stop` always does the right thing to give you the whole sequence. Normalizing negative indexes first allows start and/or stop to be counted from the end independently: `'abcde'[1:-2] == 'abcde'[1:3] == 'bc'` despite `range(1,-2) == []`. The normalization is sometimes thought of as "modulo the length" but note it adds the length just once: e.g. `'abcde'[-53:42]` is just the whole string.
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
13,005,464
51
2012-10-22T05:33:39Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
In python 2.7 Slicing in python ``` [a:b:c] len = length of string, tuple or list c -- default is +1. sign of c indicates forward or backward, absolute value of c indicates steps. Default is forward with step size 1. Positive means forward, negative means backward. a -- when c is positive or blank, default is 0. when c is negative, default is -1. b -- when c is positive or blank, default is len. when c is negative, default is -(len+1). ``` Understanding index assignment is very important. ``` In forward direction, starts at 0 and ends at len-1 In backward direction, starts at -1 and ends at -len ``` when you say [a:b:c] you are saying depending on sign of c (forward or backward), start at a and end at b ( excluding element at bth index). Use the indexing rule above and remember you will only find elements in this range ``` -len, -len+1, -len+2, ..., 0, 1, 2,3,4 , len -1 ``` but this range continues in both directions infinitely ``` ...,-len -2 ,-len-1,-len, -len+1, -len+2, ..., 0, 1, 2,3,4 , len -1, len, len +1, len+2 , .... ``` e.g. ``` 0 1 2 3 4 5 6 7 8 9 10 11 a s t r i n g -9 -8 -7 -6 -5 -4 -3 -2 -1 ``` if your choice of a , b and c allows overlap with the range above as you traverse using rules for a,b,c above you will either get a list with elements (touched during traversal) or you will get an empty list. One last thing: if a and b are equal , then also you get an empty list ``` >>> l1 [2, 3, 4] >>> l1[:] [2, 3, 4] >>> l1[::-1] # a default is -1 , b default is -(len+1) [4, 3, 2] >>> l1[:-4:-1] # a default is -1 [4, 3, 2] >>> l1[:-3:-1] # a default is -1 [4, 3] >>> l1[::] # c default is +1, so a default is 0, b default is len [2, 3, 4] >>> l1[::-1] # c is -1 , so a default is -1 and b default is -(len+1) [4, 3, 2] >>> l1[-100:-200:-1] # interesting [] >>> l1[-1:-200:-1] # interesting [4, 3, 2] >>> l1[-1:-1:1] [] >>> l1[-1:5:1] # interesting [4] >>> l1[1:-7:1] [] >>> l1[1:-7:-1] # interesting [3, 2] ```
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
14,682,039
13
2013-02-04T07:20:03Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
``` index: ------------> 0 1 2 3 4 +---+---+---+---+---+ | a | b | c | d | e | +---+---+---+---+---+ 0 -4 -3 -2 -1 <------------ slice: <---------------| |---------------> : 1 2 3 4 : +---+---+---+---+---+ | a | b | c | d | e | +---+---+---+---+---+ : -4 -3 -2 -1 : |---------------> <---------------| ``` hope this will help you to model the list in Python reference:<http://wiki.python.org/moin/MovingToPythonFromOtherLanguages>
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
15,824,717
16
2013-04-05T01:59:41Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
You can also use slice assignment to remove one or more elements from a list: ``` r = [1, 'blah', 9, 8, 2, 3, 4] >>> r[1:4] = [] >>> r [1, 2, 3, 4] ```
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
16,267,103
19
2013-04-28T19:49:39Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
Python slicing notation: ``` a[start:end:step] ``` * For `start` and `end`, negative values are interpreted as being relative to the end of the sequence. * Positive indices for `end` indicate the position *after* the last element to be included. * Blank values are defaulted as follows: `[+0:-0:1]`. * Using a negative step reverses the interpretation of `start` and `end` The notation extends to (numpy) matrices and multidimensional arrays. For example, to slice entire columns you can use: ``` m[::,0:2:] ## slice the first two columns ``` Slices hold references, not copies, of the array elements. If you want to make a separate copy an array, you can use [`deepcopy()`](http://stackoverflow.com/questions/6532881/how-to-make-a-copy-of-a-2d-array-in-python).
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
20,443,928
15
2013-12-07T16:52:45Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
As a general rule, writing code with a lot of hardcoded index values leads to a readability and maintenance mess. For example, if you come back to the code a year later, you’ll look at it and wonder what you were thinking when you wrote it. The solution shown is simply a way of more clearly stating what your code is actually doing. In general, the built-in slice() creates a slice object that can be used anywhere a slice is allowed. For example: ``` >>> items = [0, 1, 2, 3, 4, 5, 6] >>> a = slice(2, 4) >>> items[2:4] [2, 3] >>> items[a] [2, 3] >>> items[a] = [10,11] >>> items [0, 1, 10, 11, 4, 5, 6] >>> del items[a] >>> items [0, 1, 4, 5, 6] ``` If you have a slice instance s, you can get more information about it by looking at its s.start, s.stop, and s.step attributes, respectively. For example: > ``` > >>> a = slice(10, 50, 2) > >>> a.start > 10 > >>> a.stop > 50 > >>> a.step > 2 > >>> > ```
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
24,713,353
62
2014-07-12T13:19:03Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
> # Explain Python's slice notation In short, the colons (`:`) in subscript notation (`subscriptable[subscriptarg]`) make slice notation - which has the optional arguments, `start`, `stop`, `step`: ``` sliceable[start:stop:step] ``` Python slicing is a computationally fast way to methodically access parts of your data. In my opinion, to be even an intermediate Python programmer, it's one aspect of the language that it is necessary to be familiar with. # Important Definitions To begin with, let's define a few terms: > **start:** the beginning index of the slice, it will include the element at this index unless it is the same as *stop*, defaults to 0, i.e. the first index. If it's negative, it means to start `n` items from the end. > > **stop:** the ending index of the slice, it does *not* include the element at this index, defaults to length of the sequence being sliced, that is, up to and including the end. > > **step:** the amount by which the index increases, defaults to 1. If it's negative, you're slicing over the iterable in reverse. # How Indexing Works You can make any of these positive or negative numbers. The meaning of the positive numbers is straightforward, but for negative numbers, just like indexes in Python, you count backwards from the end for the *start* and *stop*, and for the *step*, you simply decrement your index. This example is [from the documentation's tutorial](https://docs.python.org/2/tutorial/introduction.html), but I've modified it slightly to indicate which item in a sequence each index references: ``` +---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 -6 -5 -4 -3 -2 -1 ``` # How Slicing Works To use slice notation with a sequence that supports it, you must include at least one colon in the square brackets that follow the sequence (which actually [implement the `__getitem__` method of the sequence, according to the Python data model](https://docs.python.org/2/reference/datamodel.html#object.__getitem__).) Slice notation works like this: ``` sequence[start:stop:step] ``` And recall that there are defaults for *start*, *stop*, and *step*, so to access the defaults, simply leave out the argument. Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this: ``` my_list[-9:] ``` When I see this, I read the part in the brackets as "9th from the end, to the end." (Actually, I abbreviate it mentally as "-9, on") # Explanation: The full notation is ``` my_list[-9:None:None] ``` and to substitute the defaults (actually when `step` is negative, `stop`'s default is `-len(my_list) - 1`), so `None` for stop really just means it goes to whichever end step takes it to): ``` my_list[-9:len(my_list):1] ``` The **colon**, `:`, is what tells Python you're giving it a slice and not a regular index. That's why the idiomatic way of making a shallow copy of lists in Python 2 is ``` list_copy = sequence[:] ``` And clearing them is with: ``` del my_list[:] ``` (Python 3 gets a `list.copy` and `list.clear` method.) # Give your slices a descriptive name! You may find it useful to separate forming the slice from passing it to the `list.__getitem__` method ([that's what the square brackets do](https://docs.python.org/2/reference/datamodel.html#object.__getitem__)). Even if you're not new to it, it keeps your code more readable so that others that may have to read your code can more readily understand what you're doing. However, you can't just assign some integers separated by colons to a variable. You need to use the slice object: ``` last_nine_slice = slice(-9, None) ``` The second argument, `None`, is required, so that the first argument is interpreted as the `start` argument [otherwise it would be the `stop` argument](https://docs.python.org/2/library/functions.html#slice). You can then pass the slice object to your sequence: ``` >>> list(range(100))[last_nine_slice] [91, 92, 93, 94, 95, 96, 97, 98, 99] ``` # Memory Considerations: Since slices of Python lists create new objects in memory, another important function to be aware of is `itertools.islice`. Typically you'll want to iterate over a slice, not just have it created statically in memory. `islice` is perfect for this. A caveat, it doesn't support negative arguments to `start`, `stop`, or `step`, so if that's an issue you may need to calculate indices or reverse the iterable in advance. ``` >>> length = 100 >>> last_nine_iter = itertools.islice(list(range(length)), length-9, None, 1) >>> list_last_nine = list(last_nine) >>> list_last_nine [91, 92, 93, 94, 95, 96, 97, 98, 99] ``` The fact that list slices make a copy is a feature of lists themselves. If you're slicing advanced objects like a Pandas DataFrame, it may return a view on the original, and not a copy.
Explain Python's slice notation
509,211
1,331
2009-02-03T22:31:02Z
29,237,560
11
2015-03-24T16:08:36Z
[ "python", "list", "slice" ]
I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it.
This is how I teach slices to newbies: **Understanding difference between indexing and slicing:** Wiki Python has this amazing picture which clearly distinguishes indexing and slicing. ![enter image description here](http://i.stack.imgur.com/o99aU.png) It is a list with 6 elements in it. To understand slicing better, consider that list as a set of six boxes placed together. Each box has an alphabet in it. Indexing is like dealing with the contents of box. You can check contents of any box. But You can't check contents of multiple boxes at once. You can even replace contents of the box. But You can't place 2 balls in 1 box or replace 2 balls at a time. ``` In [122]: alpha = ['a', 'b', 'c', 'd', 'e', 'f'] In [123]: alpha Out[123]: ['a', 'b', 'c', 'd', 'e', 'f'] In [124]: alpha[0] Out[124]: 'a' In [127]: alpha[0] = 'A' In [128]: alpha Out[128]: ['A', 'b', 'c', 'd', 'e', 'f'] In [129]: alpha[0,1] --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-129-c7eb16585371> in <module>() ----> 1 alpha[0,1] TypeError: list indices must be integers, not tuple ``` Slicing is like dealing with boxes itself. You can pickup first box and place it on another table. To pickup the box all You need to know is the position of beginning & ending of the box. You can even pickup first 3 boxes or last 2 boxes or all boxes between 1 & 4. So, You can pick any set of boxes if You know beginning & ending. This positions are called start & stop positions. The interesting thing is that You can replace multiple boxes at once. Also You can place multiple boxes where ever You like. ``` In [130]: alpha[0:1] Out[130]: ['A'] In [131]: alpha[0:1] = 'a' In [132]: alpha Out[132]: ['a', 'b', 'c', 'd', 'e', 'f'] In [133]: alpha[0:2] = ['A', 'B'] In [134]: alpha Out[134]: ['A', 'B', 'c', 'd', 'e', 'f'] In [135]: alpha[2:2] = ['x', 'xx'] In [136]: alpha Out[136]: ['A', 'B', 'x', 'xx', 'c', 'd', 'e', 'f'] ``` **Slicing With Step:** Till now You have picked boxes continuously. But some times You need to pickup discretely. For example You can pickup every second box. You can even pickup every third box from the end. This value is called step size. This represents the gap between Your successive pickups. The step size should be positive if You are picking boxes from the beginning to end and vice versa. ``` In [137]: alpha = ['a', 'b', 'c', 'd', 'e', 'f'] In [142]: alpha[1:5:2] Out[142]: ['b', 'd'] In [143]: alpha[-1:-5:-2] Out[143]: ['f', 'd'] In [144]: alpha[1:5:-2] Out[144]: [] In [145]: alpha[-1:-5:2] Out[145]: [] ``` **How Python Figures Out Missing Parameters:** When slicing if You leave out any parameter, Python tries to figure it out automatically. If You check source code of CPython, You will find a function called PySlice\_GetIndicesEx which figures out indices to a slice for any given parameters. Here is the logical equivalent code in Python. This function takes a Python object & optional parameters for slicing and returns start, stop, step & slice length for the requested slice. ``` def py_slice_get_indices_ex(obj, start=None, stop=None, step=None): length = len(obj) if step is None: step = 1 if step == 0: raise Exception("Step cannot be zero.") if start is None: start = 0 if step > 0 else length - 1 else: if start < 0: start += length if start < 0: start = 0 if step > 0 else -1 if start >= length: start = length if step > 0 else length - 1 if stop is None: stop = length if step > 0 else -1 else: if stop < 0: stop += length if stop < 0: stop = 0 if step > 0 else -1 if stop >= length: stop = length if step > 0 else length - 1 if (step < 0 and stop >= start) or (step > 0 and start >= stop): slice_length = 0 elif step < 0: slice_length = (stop - start + 1)/(step) + 1 else: slice_length = (stop - start - 1)/(step) + 1 return (start, stop, step, slice_length) ``` This is the intelligence that is present behind slices. Since Python has inbuilt function called slice, You can pass some parameters & check how smartly it calculates missing parameters. ``` In [21]: alpha = ['a', 'b', 'c', 'd', 'e', 'f'] In [22]: s = slice(None, None, None) In [23]: s Out[23]: slice(None, None, None) In [24]: s.indices(len(alpha)) Out[24]: (0, 6, 1) In [25]: range(*s.indices(len(alpha))) Out[25]: [0, 1, 2, 3, 4, 5] In [26]: s = slice(None, None, -1) In [27]: range(*s.indices(len(alpha))) Out[27]: [5, 4, 3, 2, 1, 0] In [28]: s = slice(None, 3, -1) In [29]: range(*s.indices(len(alpha))) Out[29]: [5, 4] ``` **Note:** This post is originally written in my blog <http://www.avilpage.com/2015/03/a-slice-of-python-intelligence-behind.html>
python reading lines w/o \n?
509,446
3
2009-02-03T23:23:57Z
509,482
13
2009-02-03T23:34:39Z
[ "python", "file", "newline" ]
Would this work on all platforms? i know windows does \r\n, and remember hearing mac does \r while linux did \n. I ran this code on windows so it seems fine, but do any of you know if its cross platform? ``` while 1: line = f.readline() if line == "": break line = line[:-1] print "\"" + line + "\"" ```
First of all, there is [universal newline support](https://www.python.org/dev/peps/pep-0278/) Second: just use `line.strip()`. Use `line.rstrip('\r\n')`, if you want to preserve any whitespace at the beginning or end of the line. Oh, and ``` print '"%s"' % line ``` or at least ``` print '"' + line + '"' ``` might look a bit nicer. You can iterate over the lines in a file like this (this will not break on empty lines in the middle of the file like your code): ``` for line in f: print '"' + line.strip('\r\n') + '"' ``` If your input file is short enough, you can use the fact that `str.splitlines` throws away the line endings by default: ``` with open('input.txt', 'rU') as f: for line in f.read().splitlines(): print '"%s"' % line ```
Python M2Crypto - generating a DSA key pair and separating public/private components
509,449
2
2009-02-03T23:25:04Z
509,633
7
2009-02-04T00:35:25Z
[ "python", "cryptography", "rsa", "m2crypto" ]
Could anybody explain what is the cause of the following: ``` >>> from M2Crypto import DSA, BIO >>> dsa = DSA.gen_params(1024) ..+........+++++++++++++++++++++++++++++++++++++++++++++++++++* ............+.+.+..+.........+.............+.....................+. ...+.............+...........+......................................... +.........+................+..........+......+..+.+...+..........+..+.. ..+...+......+....+.............+.................+.......+.........+.. ....+......+.+..+..........+........+.+...+..+...............+......... ..+.....+........+..........+++++++++++++++++++++++++++++++++++++++++++ ++++++++* >>> mem = BIO.MemoryBuffer() >>> dsa.save_key_bio(mem, cipher=None) 1 >>> dsa.save_pub_key_bio(mem) 0 >>> print mem.getvalue() -----BEGIN DSA PRIVATE KEY----- MIIBIgIBAAKBgQDPGRFSTqqx8vet5kaW5m99A83REotTcX9HOv+zrqMxQpaTlinS MDz49I4psDPJ+bWH7vySEdOYO2JGUj6kYZdz/ZwyNjphWNjQkaUrmfaVLzS3PHpW aMrPEweLesf/PT4KXm2HaDbaW/g2Ds5h+Zlq9LDKcN2vfvyeiTCmf1esyQIVAO9I ippU4PIdvJVO9HQRkqrD2bxPAoGBAIwVgM7dgNVwihJva6qeeh7ypy3ESNB9k8nY fOnES+SqZGQbkPrJIusRCJNKERiMATJXNRMfBeWD8htNRezbgtr0OpuYSBurAQjp hKKVI3DHSv7XT49BQ3tdJww8lQfkOhHOfFTG6U1dJhWdggp0WN3EjYlt77agRsjR 4t5sD1f3 -----END DSA PRIVATE KEY----- -----BEGIN PUBLIC KEY----- -----END PUBLIC KEY----- >>> ``` clearly I'm missing something. M2Crypto nonexistant docs don't help.
Call dsa.gen\_key(), then save. You aren't actually generating the public key. ``` >>> from M2Crypto import DSA, BIO >>> dsa = DSA.gen_params(1024) ..+..etc >>> mem = BIO.MemoryBuffer() >>> dsa.gen_key() >>> dsa.save_key_bio(mem, cipher=None) 1 >>> dsa.save_pub_key_bio(mem) 1 >>> print mem.getvalue() -----BEGIN DSA PRIVATE KEY----- MIIBuwIBAAKBgQDowiLFDXGwaWIOkZybeeqSXYZ8KCLmXg5XfnAtDBlVOokB91Rj etc. -----END DSA PRIVATE KEY----- -----BEGIN PUBLIC KEY----- MIIBtzCCASsGByqGSM44BAEwggEeAoGBAOjCIsUNcbBpYg6RnJt56pJdhnwoIuZe Dld+cC0MGVU6iQH3VGNEzKycBVQeVYke3itZwQALSlT2JfUsmOjeZYIkc9l2YYob rixObXfQyc0AOBM/J53F0F6R8+xvEwN/Hmdd9SjjbdZi8gve+dr9UfnKHXi0KPUF s2ougGhXeEjTAhUAiW5bMzG8nCVjXErgwaDEx+JEdtECgYACba2quw3xibhT3JNd sDh0gIRpHPQgIgxgzGv6A09Vdb4VgtWf0MYAo6gAhxsZIWWKzQ94Oe1nf7OhC+B+ VjT+PW+ExSrbJVONTN5ycE64O7+2L+q/hZSjjkxXgfcApqeVtZp4wKqbS976Kpch WgNl0zdkvV8JddRs0oKQ0Bl7dwOBhQACgYEAgkdF/+ncobVcYXfXHBUH3H5SLD3y u2zUWGhXM4/MUTwPromDOQ8Zd0H7myYhmQvVUb+J9mJHMIn7Guf4JDH+8d6rBpzo U5yEGqgsSqYqgtStzDvsKHfqw3mvjvsktm66N/vm36eai2I6J15QibdtP0lb1Um8 EeECDTxWUWT93rs= -----END PUBLIC KEY----- >>> ```
Change directory to the directory of a Python script
509,742
4
2009-02-04T01:24:43Z
509,754
14
2009-02-04T01:30:18Z
[ "python", "scripting", "directory" ]
How do i change directory to the directory with my python script in? So far I figured out I should use `os.chdir` and `sys.argv[0]`. I'm sure there is a better way then to write my own function to parse argv[0].
``` os.chdir(os.path.dirname(__file__)) ```
Best way to write a Python function that integrates a gaussian?
509,994
6
2009-02-04T03:49:20Z
510,040
12
2009-02-04T04:11:03Z
[ "python", "scipy", "gaussian", "integral" ]
In attempting to use scipy's quad method to integrate a gaussian (lets say there's a gaussian method named gauss), I was having problems passing needed parameters to gauss and leaving quad to do the integration over the correct variable. Does anyone have a good example of how to use quad w/ a multidimensional function? But this led me to a more grand question about the best way to integrate a gaussian in general. I didn't find a gaussian integrate in scipy (to my surprise). My plan was to write a simple gaussian function and pass it to quad (or maybe now a fixed width integrator). What would you do? Edit: Fixed-width meaning something like trapz that uses a fixed dx to calculate areas under a curve. What I've come to so far is a method make\_\_\_gauss that returns a lambda function that can then go into quad. This way I can make a normal function with the average and variance I need before integrating. ``` def make_gauss(N, sigma, mu): return (lambda x: N/(sigma * (2*numpy.pi)**.5) * numpy.e ** (-(x-mu)**2/(2 * sigma**2))) quad(make_gauss(N=10, sigma=2, mu=0), -inf, inf) ``` When I tried passing a general gaussian function (that needs to be called with x, N, mu, and sigma) and filling in some of the values using quad like ``` quad(gen_gauss, -inf, inf, (10,2,0)) ``` the parameters 10, 2, and 0 did NOT necessarily match N=10, sigma=2, mu=0, which prompted the more extended definition. The erf(z) in scipy.special would require me to define exactly what t is initially, but it nice to know it is there.
scipy ships with the "error function", aka Gaussian integral: ``` import scipy.special help(scipy.special.erf) ```
Best way to write a Python function that integrates a gaussian?
509,994
6
2009-02-04T03:49:20Z
511,155
27
2009-02-04T12:32:51Z
[ "python", "scipy", "gaussian", "integral" ]
In attempting to use scipy's quad method to integrate a gaussian (lets say there's a gaussian method named gauss), I was having problems passing needed parameters to gauss and leaving quad to do the integration over the correct variable. Does anyone have a good example of how to use quad w/ a multidimensional function? But this led me to a more grand question about the best way to integrate a gaussian in general. I didn't find a gaussian integrate in scipy (to my surprise). My plan was to write a simple gaussian function and pass it to quad (or maybe now a fixed width integrator). What would you do? Edit: Fixed-width meaning something like trapz that uses a fixed dx to calculate areas under a curve. What I've come to so far is a method make\_\_\_gauss that returns a lambda function that can then go into quad. This way I can make a normal function with the average and variance I need before integrating. ``` def make_gauss(N, sigma, mu): return (lambda x: N/(sigma * (2*numpy.pi)**.5) * numpy.e ** (-(x-mu)**2/(2 * sigma**2))) quad(make_gauss(N=10, sigma=2, mu=0), -inf, inf) ``` When I tried passing a general gaussian function (that needs to be called with x, N, mu, and sigma) and filling in some of the values using quad like ``` quad(gen_gauss, -inf, inf, (10,2,0)) ``` the parameters 10, 2, and 0 did NOT necessarily match N=10, sigma=2, mu=0, which prompted the more extended definition. The erf(z) in scipy.special would require me to define exactly what t is initially, but it nice to know it is there.
Okay, you appear to be pretty confused about several things. Let's start at the beginning: you mentioned a "multidimensional function", but then go on to discuss the usual one-variable Gaussian curve. This is *not* a multidimensional function: when you integrate it, you only integrate one variable (x). The distinction is important to make, because there *is* a monster called a "multivariate Gaussian distribution" which is a true multidimensional function and, if integrated, requires integrating over two or more variables (which uses the expensive Monte Carlo technique I mentioned before). But you seem to just be talking about the regular one-variable Gaussian, which is much easier to work with, integrate, and all that. The one-variable Gaussian distribution has two parameters, `sigma` and `mu`, and is a function of a single variable we'll denote `x`. You also appear to be carrying around a normalization parameter `n` (which is useful in a couple of applications). Normalization parameters are usually *not* included in calculations, since you can just tack them back on at the end (remember, integration is a linear operator: `int(n*f(x), x) = n*int(f(x), x)` ). But we can carry it around if you like; the notation I like for a normal distribution is then `N(x | mu, sigma, n) := (n/(sigma*sqrt(2*pi))) * exp((-(x-mu)^2)/(2*sigma^2))` (read that as "the normal distribution of `x` given `sigma`, `mu`, and `n` is given by...") So far, so good; this matches the function you've got. Notice that the only *true variable* here is `x`: the other three parameters are *fixed* for any particular Gaussian. Now for a mathematical fact: it is provably true that all Gaussian curves have the same shape, they're just shifted around a little bit. So we can work with `N(x|0,1,1)`, called the "standard normal distribution", and just translate our results back to the general Gaussian curve. So if you have the integral of `N(x|0,1,1)`, you can trivially calculate the integral of any Gaussian. This integral appears so frequently that it has a special name: the *error function* `erf`. Because of some old conventions, it's not *exactly* `erf`; there are a couple additive and multiplicative factors also being carried around. If `Phi(z) = integral(N(x|0,1,1), -inf, z)`; that is, `Phi(z)` is the integral of the standard normal distribution from minus infinity up to `z`, then it's true by the definition of the error function that `Phi(z) = 0.5 + 0.5 * erf(z / sqrt(2))`. Likewise, if `Phi(z | mu, sigma, n) = integral( N(x|sigma, mu, n), -inf, z)`; that is, `Phi(z | mu, sigma, n)` is the integral of the normal distribution given parameters `mu`, `sigma`, and `n` from minus infinity up to `z`, then it's true by the definition of the error function that `Phi(z | mu, sigma, n) = (n/2) * (1 + erf((x - mu) / (sigma * sqrt(2))))`. Take a look at [the Wikipedia article on the normal CDF](http://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function) if you want more detail or a proof of this fact. Okay, that should be enough background explanation. Back to your (edited) post. You say "The erf(z) in scipy.special would require me to define exactly what t is initially". I have no idea what you mean by this; where does `t` (time?) enter into this at all? Hopefully the explanation above has demystified the error function a bit and it's clearer now as to why the error function is the right function for the job. Your Python code is OK, but I would prefer a closure over a lambda: ``` def make_gauss(N, sigma, mu): k = N / (sigma * math.sqrt(2*math.pi)) s = -1.0 / (2 * sigma * sigma) def f(x): return k * math.exp(s * (x - mu)*(x - mu)) return f ``` Using a closure enables precomputation of constants `k` and `s`, so the returned function will need to do less work each time it's called (which can be important if you're integrating it, which means it'll be called many times). Also, I have avoided any use of the exponentiation operator `**`, which is slower than just writing the squaring out, and hoisted the divide out of the inner loop and replaced it with a multiply. I haven't looked at all at their implementation in Python, but from my last time tuning an inner loop for pure speed using raw x87 assembly, I seem to remember that adds, subtracts, or multiplies take about 4 CPU cycles each, divides about 36, and exponentiation about 200. That was a couple years ago, so take those numbers with a grain of salt; still, it illustrates their relative complexity. As well, calculating `exp(x)` the brute-force way is a very bad idea; there are tricks you can take when writing a good implementation of `exp(x)` that make it significantly faster and more accurate than a general `a**b` style exponentiation. I've never used the numpy version of the constants pi and e; I've always stuck with the plain old math module's versions. I don't know why you might prefer either one. I'm not sure what you're going for with the `quad()` call. `quad(gen_gauss, -inf, inf, (10,2,0))` ought to integrate a renormalized Gaussian from minus infinity to plus infinity, and should always spit out 10 (your normalization factor), since the Gaussian integrates to 1 over the real line. Any answer far from 10 (I wouldn't expect *exactly* 10 since `quad()` is only an approximation, after all) means something is screwed up somewhere... hard to say what's screwed up without knowing the actual return value and possibly the inner workings of `quad()`. Hopefully that has demystified some of the confusion, and explained why the error function is the right answer to your problem, as well as how to do it all yourself if you're curious. If any of my explanation wasn't clear, I suggest taking a quick look at Wikipedia first; if you still have questions, don't hesitate to ask.
creating blank field and receving the INTEGER PRIMARY KEY with sqlite, python
510,135
3
2009-02-04T05:06:34Z
510,182
7
2009-02-04T05:34:27Z
[ "python", "sqlite" ]
I am using sqlite with python. When i insert into table A i need to feed it an ID from table B. So what i wanted to do is insert default data into B, grab the id (which is auto increment) and use it in table A. Whats the best way receive the key from the table i just inserted into?
As Christian said, `sqlite3_last_insert_rowid()` is what you want... but that's the C level API, and you're using the Python DB-API bindings for SQLite. It looks like the cursor method `lastrowid` will do what you want [(search for 'lastrowid' in the documentation for more information)](http://docs.python.org/library/sqlite3.html). Insert your row with `cursor.execute( ... )`, then do something like `lastid = cursor.lastrowid` to check the last ID inserted. That you say you need "an" ID worries me, though... it doesn't matter *which* ID you have? Unless you are using the data just inserted into B for something, in which case you need *that* row ID, your database structure is seriously screwed up if you just need any old row ID for table B.
How can I make a time delay in Python?
510,348
1,061
2009-02-04T07:04:09Z
64,486
330
2008-09-15T16:34:29Z
[ "python", "sleep", "timedelay" ]
I would like to know how to put a time delay in a Python script.
You can use the sleep() function in the time module. It can take a float argument for sub second resolution. ``` from time import sleep sleep(0.1) # Time in seconds. ```
How can I make a time delay in Python?
510,348
1,061
2009-02-04T07:04:09Z
510,351
1,176
2009-02-04T07:05:59Z
[ "python", "sleep", "timedelay" ]
I would like to know how to put a time delay in a Python script.
``` import time time.sleep(5) # delays for 5 seconds ``` Here is another example where something is run once a minute: ``` import time while True: print "This prints once a minute." time.sleep(60) # Delay for 1 minute (60 seconds) ```
How can I make a time delay in Python?
510,348
1,061
2009-02-04T07:04:09Z
510,356
40
2009-02-04T07:07:32Z
[ "python", "sleep", "timedelay" ]
I would like to know how to put a time delay in a Python script.
Please read <http://www.faqts.com/knowledge_base/view.phtml/aid/2609/fid/378>, which can help you further: > Try the sleep function in the time module. > > ``` > import time > time.sleep(60) > ``` > > And put this in a while loop and a statement will only execute on the > minute... That allows you to run a statement at predefined intervals > regardless of how long the command takes (as long as it takes less than > a minute or 5 or 60 or whatever you set it to) For example, I wanted to > run a ping once a minute. If I just time.sleep(60) or time.sleep(45) > even, the ping will not always take the same amount of time. Here's the > code :) > > ``` > time.sleep(time.localtime(time.time())[5]) > ``` > > The [5] just pulls the seconds out of the time.localtime()'s return > value. > > The great thing about time.sleep is that it supports floating point > numbers! > > ``` > import time > time.sleep(0.1) > ``` > > <http://python.org/doc/current/lib/module-time.html>
How can I make a time delay in Python?
510,348
1,061
2009-02-04T07:04:09Z
6,234,820
57
2011-06-04T05:03:16Z
[ "python", "sleep", "timedelay" ]
I would like to know how to put a time delay in a Python script.
What You Need Is `time.sleep(sec)` where sec is how many seconds delay you add there you also need to `import time`
How can I make a time delay in Python?
510,348
1,061
2009-02-04T07:04:09Z
22,583,596
153
2014-03-22T21:06:10Z
[ "python", "sleep", "timedelay" ]
I would like to know how to put a time delay in a Python script.
There is a built-in Python module called `time`. Use it like this: ``` import time time.sleep(5) ``` This will make the script wait for 5 seconds.
How can I make a time delay in Python?
510,348
1,061
2009-02-04T07:04:09Z
23,131,522
19
2014-04-17T11:08:36Z
[ "python", "sleep", "timedelay" ]
I would like to know how to put a time delay in a Python script.
There is a built in python module named time. The 2 examples are identical but differ only in the way the method is imported from the module: 1 Use This: ``` import time time.sleep(Num of seconds to sleep) ``` 2 Use this: ``` from time import sleep sleep(Num of seconds to sleep) ```
How can I make a time delay in Python?
510,348
1,061
2009-02-04T07:04:09Z
23,665,492
18
2014-05-14T21:30:35Z
[ "python", "sleep", "timedelay" ]
I would like to know how to put a time delay in a Python script.
A bit of fun with sleepy generator. The question is about time delay. It can be fixed time, but in some cases we might need a delay measured since last time. Here is one possible solutions: # Delay measured since last time (waking up regularly) The situation can be, we want to do something as regularly as possible and we do not want to bother with all the `last_time`, `next_time` stuff all around our code. ## buzzer generator Following code (**sleepy.py**) defines `buzzergen` gerenarator ``` import time from itertools import count def buzzergen(period): nexttime = time.time() + period for i in count(): now = time.time() tosleep = nexttime - now if tosleep > 0: time.sleep(tosleep) nexttime += period else: nexttime = now + period yield i, nexttime ``` ## Invoking regular buzzergen ``` from sleepy import buzzergen import time buzzer = buzzergen(3) # planning to wake up each 3 seconds print time.time() buzzer.next() print time.time() time.sleep(2) buzzer.next() print time.time() time.sleep(5) # sleeping a bit longer than usually buzzer.next() print time.time() buzzer.next() print time.time() ``` and running it we see: ``` 1400102636.46 1400102639.46 1400102642.46 1400102647.47 1400102650.47 ``` We can also use it directly in a loop: ``` import random for ring in buzzergen(3): print "now", time.time() print "ring", ring time.sleep(random.choice([0, 2, 4, 6])) ``` and running it we might see: ``` now 1400102751.46 ring (0, 1400102754.461676) now 1400102754.46 ring (1, 1400102757.461676) now 1400102757.46 ring (2, 1400102760.461676) now 1400102760.46 ring (3, 1400102763.461676) now 1400102766.47 ring (4, 1400102769.47115) now 1400102769.47 ring (5, 1400102772.47115) now 1400102772.47 ring (6, 1400102775.47115) now 1400102775.47 ring (7, 1400102778.47115) ``` As we see, this buzzer is not too rigid and allow us to catch up regular sleepy intervals even if we oversleep and get out of regular schedule.
How can I make a time delay in Python?
510,348
1,061
2009-02-04T07:04:09Z
28,965,832
18
2015-03-10T14:04:40Z
[ "python", "sleep", "timedelay" ]
I would like to know how to put a time delay in a Python script.
to halt further execution for defined time, sleep method is available in time package. it easy all you have to do is at the top of your code type in `from time import sleep` then use sleep in your desired code let say 5 seconds: `sleep(5)` alternatively you can import time and then use time.sleep(5) `import time` then go to the line where you want it to wait and type in `time.sleep(5)`