title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Is there a more pythonic way to build this dictionary? | 753,986 | <p>What is the "most pythonic" way to build a dictionary where I have the values in a sequence and each key will be a function of its value? I'm currently using the following, but I feel like I'm just missing a cleaner way. NOTE: <code>values</code> is a list that is not related to any dictionary.</p>
<pre><code>for v... | 6 | 2009-04-15T22:26:44Z | 754,154 | <p>This method avoids the list comprehension syntax:</p>
<pre><code>dict(zip(map(key_from_value, values), values))
</code></pre>
<p>I will never claim to be an authority on "Pythonic", but this way feels like a good way.</p>
| 0 | 2009-04-15T23:26:40Z | [
"python"
] |
Is there a more pythonic way to build this dictionary? | 753,986 | <p>What is the "most pythonic" way to build a dictionary where I have the values in a sequence and each key will be a function of its value? I'm currently using the following, but I feel like I'm just missing a cleaner way. NOTE: <code>values</code> is a list that is not related to any dictionary.</p>
<pre><code>for v... | 6 | 2009-04-15T22:26:44Z | 755,252 | <p>Py3K:</p>
<pre><code>{ key_for_value(value) : value for value in values }
</code></pre>
| 5 | 2009-04-16T08:42:09Z | [
"python"
] |
Python: Read a file (from an external server) | 754,170 | <p>Can you tell me how to code a Python script which reads a file from an external server? I look for something similar to PHP's file_get_contents() or file() function.</p>
<p>It would be great if someone could post the entire code for such a script.</p>
<p>Thanks in advance!</p>
| 0 | 2009-04-15T23:33:46Z | 754,175 | <p>The entire script is:</p>
<pre><code>import urllib
content = urllib.urlopen('http://www.google.com/').read()
</code></pre>
| 12 | 2009-04-15T23:35:55Z | [
"python",
"file"
] |
Python: Read a file (from an external server) | 754,170 | <p>Can you tell me how to code a Python script which reads a file from an external server? I look for something similar to PHP's file_get_contents() or file() function.</p>
<p>It would be great if someone could post the entire code for such a script.</p>
<p>Thanks in advance!</p>
| 0 | 2009-04-15T23:33:46Z | 754,501 | <p>better would be the same as Jarret's code, but using urllib2:</p>
<pre><code>import urllib2
content = urllib2.urlopen('http://google.com').read()
</code></pre>
<p>urllib2 is a bit newer and more modern. Doesn't matter too much in your case, but it's good practice to use it.</p>
| 5 | 2009-04-16T02:10:18Z | [
"python",
"file"
] |
How to know when to manage resources in Python | 754,187 | <p>I hope I framed the question right. I am trying to force myself to be a better programmer. By better I mean efficient. I want to write a program to identify the files in a directory and read each file for further processing. After some shuffling I got to this:</p>
<pre><code>for file in os.listdir(dir):
y=o... | 4 | 2009-04-15T23:39:48Z | 754,215 | <p>Python will close open files when they get garbage-collected, so generally you can forget about it -- particularly when reading.</p>
<p>That said, if you want to close explicitely, you could do this:</p>
<pre><code>for file in os.listdir(dir):
f = open(dir+'\\'+file,'r')
y = f.readlines()
for line in y... | 11 | 2009-04-15T23:47:26Z | [
"python",
"garbage-collection"
] |
How to know when to manage resources in Python | 754,187 | <p>I hope I framed the question right. I am trying to force myself to be a better programmer. By better I mean efficient. I want to write a program to identify the files in a directory and read each file for further processing. After some shuffling I got to this:</p>
<pre><code>for file in os.listdir(dir):
y=o... | 4 | 2009-04-15T23:39:48Z | 754,275 | <p>Don't worry about it. Python's garbage collector is good, and I've never had a problem with not closing file-pointers (for read operations at least)</p>
<p>If you did want to explicitly close the file, just store the <code>open()</code> in one variable, then call <code>readlines()</code> on that, for example..</p>
... | 3 | 2009-04-16T00:13:07Z | [
"python",
"garbage-collection"
] |
How is this "referenced before assignment"? | 754,421 | <p>I have a bit of Python to connect to a database with a switch throw in for local versus live. </p>
<pre><code> LOCAL_CONNECTION = {"server": "127.0.0.1", "user": "root", "password": "", "database": "testing"}
LIVE_CONNECTION = {"server": "10.1.1.1", "user": "x", "password": "y", "database": "nottesting"}
if d... | 1 | 2009-04-16T01:17:43Z | 754,428 | <p>The second assignement is misspelled.</p>
<p>You wrote <code>connnection_info = LIVE_CONNECTION</code> with 3 n's.</p>
| 16 | 2009-04-16T01:19:32Z | [
"python"
] |
How is this "referenced before assignment"? | 754,421 | <p>I have a bit of Python to connect to a database with a switch throw in for local versus live. </p>
<pre><code> LOCAL_CONNECTION = {"server": "127.0.0.1", "user": "root", "password": "", "database": "testing"}
LIVE_CONNECTION = {"server": "10.1.1.1", "user": "x", "password": "y", "database": "nottesting"}
if d... | 1 | 2009-04-16T01:17:43Z | 754,429 | <p>Typo: connnection_info = LIVE_CONNECTION</p>
| 4 | 2009-04-16T01:19:58Z | [
"python"
] |
Some Basic Python Questions | 754,468 | <p>I'm a total python noob so please bear with me. I want to have python scan a page of html and replace instances of Microsoft Word entities with something UTF-8 compatible. </p>
<p>My question is, how do you do that in Python (I've Googled this but haven't found a clear answer so far)? I want to dip my toe in the Py... | 5 | 2009-04-16T01:41:41Z | 754,473 | <p>The Python code has the same outline.</p>
<p>Just replace all of the PHP-isms with Python-isms.</p>
<p>Start by creating a <a href="http://docs.python.org/library/stdtypes.html#file-objects" rel="nofollow">File</a> object. The result of a file.read() is a <a href="http://docs.python.org/library/stdtypes.html#stri... | 3 | 2009-04-16T01:47:24Z | [
"php",
"python",
"unicode",
"replace",
"html-entities"
] |
Some Basic Python Questions | 754,468 | <p>I'm a total python noob so please bear with me. I want to have python scan a page of html and replace instances of Microsoft Word entities with something UTF-8 compatible. </p>
<p>My question is, how do you do that in Python (I've Googled this but haven't found a clear answer so far)? I want to dip my toe in the Py... | 5 | 2009-04-16T01:41:41Z | 754,480 | <p>Your best bet for cleaning Word HTML is using <a href="http://tidy.sourceforge.net/" rel="nofollow">HTML Tidy</a> which has a mode just for that. There are <a href="http://pypi.python.org/pypi?%3Aaction=search&term=tidy&submit=search" rel="nofollow">a few Python wrappers</a> you can use if you need to do it... | 2 | 2009-04-16T01:53:12Z | [
"php",
"python",
"unicode",
"replace",
"html-entities"
] |
Some Basic Python Questions | 754,468 | <p>I'm a total python noob so please bear with me. I want to have python scan a page of html and replace instances of Microsoft Word entities with something UTF-8 compatible. </p>
<p>My question is, how do you do that in Python (I've Googled this but haven't found a clear answer so far)? I want to dip my toe in the Py... | 5 | 2009-04-16T01:41:41Z | 754,484 | <p>As S.Lott said, the Python code would be very, very similarâthe only differences would essentially be the function calls/statements.</p>
<p>I don't think Python has a direct equivalent to <code>file_get_contents()</code>, but since you can obtain an array of the lines in the file, you can then join them by newlin... | 1 | 2009-04-16T01:54:55Z | [
"php",
"python",
"unicode",
"replace",
"html-entities"
] |
Some Basic Python Questions | 754,468 | <p>I'm a total python noob so please bear with me. I want to have python scan a page of html and replace instances of Microsoft Word entities with something UTF-8 compatible. </p>
<p>My question is, how do you do that in Python (I've Googled this but haven't found a clear answer so far)? I want to dip my toe in the Py... | 5 | 2009-04-16T01:41:41Z | 754,503 | <p>First of all, those aren't Microsoft Word entitiesâthey <strong>are</strong> UTF-8. You're converting them to HTML entities.</p>
<p>The Pythonic way to write something like:</p>
<pre><code>chr(0xe2) . chr(0x80) . chr(0x98)
</code></pre>
<p>would be:</p>
<pre><code>'\xe2\x80\x98'
</code></pre>
<p>But Python a... | 20 | 2009-04-16T02:10:31Z | [
"php",
"python",
"unicode",
"replace",
"html-entities"
] |
How do you Debug/Take Apart/Learn from someone else's Python code (web-based)? | 754,481 | <p>A good example of this is: <a href="http://github.com/tav/tweetapp/blob/a711404f2935c3689457c61e073105c1756b62af/app/root.py" rel="nofollow">http://github.com/tav/tweetapp/blob/a711404f2935c3689457c61e073105c1756b62af/app/root.py</a></p>
<p>In Visual Studio (ASP.net C#) where I come from, the classes are usually sp... | 1 | 2009-04-16T01:53:33Z | 754,500 | <p>You've run into a pretty specific case of code that will be hard to understand. They probably did that for the convenience of having all the code in one file.</p>
<p>I would recommend letting epydoc have a pass at it. It will create HTML documentation of the program. This will show you the class structure and you c... | 3 | 2009-04-16T02:10:01Z | [
"python",
"google-app-engine"
] |
How do you Debug/Take Apart/Learn from someone else's Python code (web-based)? | 754,481 | <p>A good example of this is: <a href="http://github.com/tav/tweetapp/blob/a711404f2935c3689457c61e073105c1756b62af/app/root.py" rel="nofollow">http://github.com/tav/tweetapp/blob/a711404f2935c3689457c61e073105c1756b62af/app/root.py</a></p>
<p>In Visual Studio (ASP.net C#) where I come from, the classes are usually sp... | 1 | 2009-04-16T01:53:33Z | 755,218 | <p>If you install <a href="http://www.eclipse.org" rel="nofollow">Eclipse</a> and <a href="http://pydev.sourceforge.net/" rel="nofollow">PyDev</a> you can set breakpoints in the same way you can in visual studio.</p>
<p>Failing that, printing out information at cucial points is often a good way to see what's going on.... | 0 | 2009-04-16T08:28:09Z | [
"python",
"google-app-engine"
] |
What is the purpose of the sub-interpreter API in CPython? | 755,070 | <p>I'm unclear on why the sub-interpreter API exists and why it's used in modules such as the mod_wsgi apache module. Is it mainly used for creating a security sandbox for different applications running within the same process, or is it a way to allow concurrency with multiple threads? Maybe both? Are there other pur... | 14 | 2009-04-16T07:20:45Z | 755,125 | <p>I imagine the purpose is to create separate python execution environments. For instance, <a href="https://code.google.com/p/modwsgi/">mod_wsgi</a> (Apache Python module) hosts a single python interpreter and then hosts multiple applications within sub-interpreters (in the default configuration).</p>
<p>Some key poi... | 14 | 2009-04-16T07:45:18Z | [
"mod-wsgi",
"python"
] |
What is the purpose of the sub-interpreter API in CPython? | 755,070 | <p>I'm unclear on why the sub-interpreter API exists and why it's used in modules such as the mod_wsgi apache module. Is it mainly used for creating a security sandbox for different applications running within the same process, or is it a way to allow concurrency with multiple threads? Maybe both? Are there other pur... | 14 | 2009-04-16T07:20:45Z | 19,104,744 | <p>As I understood it last, the idea was to be able to execute multiple applications as well as <em>multiple copies of the same application</em> within the same process. </p>
<p>This is a feature found in other scripting languages (e.g. TCL), and is of particular use to gui builders, web servers, etc.</p>
<p>It break... | 0 | 2013-09-30T22:08:59Z | [
"mod-wsgi",
"python"
] |
finditer hangs when matching against long string | 755,332 | <p>I have a somewhat complex regular expression which I'm trying to match against a long string (65,535 characters). I'm looking for multiple occurrences of the re in the string, and so am using finditer. It works, but for some reason it hangs after identifying the first few occurrences. Does anyone know why this might... | 2 | 2009-04-16T09:14:26Z | 755,351 | <p>Could it be that your expression triggers exponential behavior in the Python RE engine?</p>
<p><a href="http://swtch.com/~rsc/regexp/regexp1.html" rel="nofollow">This article</a> deals with the problem. If you have the time, you might want to try running your expression in an RE engine developed using those ideas.<... | 5 | 2009-04-16T09:22:12Z | [
"python",
"regex",
"performance"
] |
finditer hangs when matching against long string | 755,332 | <p>I have a somewhat complex regular expression which I'm trying to match against a long string (65,535 characters). I'm looking for multiple occurrences of the re in the string, and so am using finditer. It works, but for some reason it hangs after identifying the first few occurrences. Does anyone know why this might... | 2 | 2009-04-16T09:14:26Z | 755,358 | <p>You already gave yourself the answer: The regular expression is to complex and ambiguous.</p>
<p>You should try to find a less complex and more distinct expression that is easier to process. Or tell us what you want to accomplish and we could try to help you to find one.</p>
<p><hr /></p>
<p><strong>Edit</strong>... | 1 | 2009-04-16T09:24:38Z | [
"python",
"regex",
"performance"
] |
finditer hangs when matching against long string | 755,332 | <p>I have a somewhat complex regular expression which I'm trying to match against a long string (65,535 characters). I'm looking for multiple occurrences of the re in the string, and so am using finditer. It works, but for some reason it hangs after identifying the first few occurrences. Does anyone know why this might... | 2 | 2009-04-16T09:14:26Z | 755,362 | <p>I think you experience what is known as "catastrophic backtracking".</p>
<p>Your regex has many optional/alternative parts, all of which still try to match, so previous sub-expressions give back characters to the following expression on local failure. This leads to a back-and-fourth behavior within the regex and ex... | 2 | 2009-04-16T09:28:34Z | [
"python",
"regex",
"performance"
] |
finditer hangs when matching against long string | 755,332 | <p>I have a somewhat complex regular expression which I'm trying to match against a long string (65,535 characters). I'm looking for multiple occurrences of the re in the string, and so am using finditer. It works, but for some reason it hangs after identifying the first few occurrences. Does anyone know why this might... | 2 | 2009-04-16T09:14:26Z | 755,369 | <p>catastrophic backtracking!</p>
<blockquote>
<p>Regular Expressions can be very expensive. Certain (unintended and intended) strings may cause RegExes to exhibit exponential behavior. We've taken several hotfixes for this. RegExes are so handy, but devs really need to understand how they work; we've gotten bitten ... | 2 | 2009-04-16T09:31:19Z | [
"python",
"regex",
"performance"
] |
finditer hangs when matching against long string | 755,332 | <p>I have a somewhat complex regular expression which I'm trying to match against a long string (65,535 characters). I'm looking for multiple occurrences of the re in the string, and so am using finditer. It works, but for some reason it hangs after identifying the first few occurrences. Does anyone know why this might... | 2 | 2009-04-16T09:14:26Z | 755,378 | <p>Definitely exponential behaviour. You've got so many <code>d*</code> parts to your regexp that it'll be backtracking like crazy when it gets to the long string of d's, but fails to match something earlier. You need to rethink the regexp, so it has less possible paths to try.</p>
<p>In particular I think:</p>
<pr... | 4 | 2009-04-16T09:35:45Z | [
"python",
"regex",
"performance"
] |
finditer hangs when matching against long string | 755,332 | <p>I have a somewhat complex regular expression which I'm trying to match against a long string (65,535 characters). I'm looking for multiple occurrences of the re in the string, and so am using finditer. It works, but for some reason it hangs after identifying the first few occurrences. Does anyone know why this might... | 2 | 2009-04-16T09:14:26Z | 755,436 | <p>Thanks to all the responses, which were very helpful. In the end, surprisingly, it was easy to speed it up. Here's the original regex:</p>
<pre><code>(([ef]|([gh]d*(ad*[gh]d)*b))d*b([ef]d*b|d*)*c)
</code></pre>
<p>I noticed that the |d* near the end was not really what I needed, so I modified it as follows:</p>
<... | 2 | 2009-04-16T09:56:54Z | [
"python",
"regex",
"performance"
] |
delete *.pyc | 755,694 | <p>I have three modules as:</p>
<p><strong><code>one.py</code>:</strong></p>
<pre><code>def abc():
print "Heeeeeeeeeeeiiiiiioooooooooo"
</code></pre>
<p><strong><code>two.py</code>:</strong></p>
<pre><code>import one
def defg():
one.abc()
</code></pre>
<p><strong><code>three.py</code>:</strong></p>
<pre>... | 1 | 2009-04-16T11:24:38Z | 755,739 | <p>I think that IDLE is caching the bytecode within its own Python process, so it doesn't need to regenerate the it each time the file is run.</p>
| 1 | 2009-04-16T11:37:55Z | [
"python",
"caching"
] |
delete *.pyc | 755,694 | <p>I have three modules as:</p>
<p><strong><code>one.py</code>:</strong></p>
<pre><code>def abc():
print "Heeeeeeeeeeeiiiiiioooooooooo"
</code></pre>
<p><strong><code>two.py</code>:</strong></p>
<pre><code>import one
def defg():
one.abc()
</code></pre>
<p><strong><code>three.py</code>:</strong></p>
<pre>... | 1 | 2009-04-16T11:24:38Z | 755,740 | <p>The .pyc isnt getting created again because there is a refernce to your imported module in code. When it is re-run, this reference is used.</p>
<p>This is why the .pyc isnt generated again, and also why the extra changes you make arent getting run.</p>
<p>You can either remove all references and call a garbage col... | 8 | 2009-04-16T11:37:58Z | [
"python",
"caching"
] |
delete *.pyc | 755,694 | <p>I have three modules as:</p>
<p><strong><code>one.py</code>:</strong></p>
<pre><code>def abc():
print "Heeeeeeeeeeeiiiiiioooooooooo"
</code></pre>
<p><strong><code>two.py</code>:</strong></p>
<pre><code>import one
def defg():
one.abc()
</code></pre>
<p><strong><code>three.py</code>:</strong></p>
<pre>... | 1 | 2009-04-16T11:24:38Z | 27,978,761 | <blockquote>
<p>Edit ~/.bashrc and add this shell function to it</p>
<blockquote>
<p>$ cd ; pyclean</p>
</blockquote>
</blockquote>
<pre><code>pyclean () {
find . -type f -name "*.py[co]" -delete
find . -type d -name "__pycache__" -delete
}
</code></pre>
| 0 | 2015-01-16T06:56:36Z | [
"python",
"caching"
] |
Google App Engine for pseudo-cronjobs? | 755,777 | <p>I look for a possibility to create pseudo-cronjobs as I cannot use the real jobs on UNIX.</p>
<p>Since Python scripts can run for an unlimited period, I thought Python would be a great solution.</p>
<p>On Google App Engine you can set up Python scripts and it's free. So I should use the App Engine.</p>
<p>The App... | 3 | 2009-04-16T11:48:33Z | 755,792 | <p>Duplicate, see <a href="http://stackoverflow.com/questions/145651/cron-jobs-on-google-appengine">http://stackoverflow.com/questions/145651/cron-jobs-on-google-appengine</a></p>
<p>Cron jobs are now officaly supported on GAE:
<a href="http://code.google.com/appengine/docs/python/config/cron.html" rel="nofollow">http... | 1 | 2009-04-16T11:52:31Z | [
"python",
"google-app-engine",
"cron"
] |
Google App Engine for pseudo-cronjobs? | 755,777 | <p>I look for a possibility to create pseudo-cronjobs as I cannot use the real jobs on UNIX.</p>
<p>Since Python scripts can run for an unlimited period, I thought Python would be a great solution.</p>
<p>On Google App Engine you can set up Python scripts and it's free. So I should use the App Engine.</p>
<p>The App... | 3 | 2009-04-16T11:48:33Z | 755,976 | <p>Maybe I'm misunderstanding you, but the cron config files will let you do this (without Python).
You can add something like this to you cron.yaml file:</p>
<pre><code>cron:
- description: job that runs every minute
url: /cronjobs/job1
schedule: every minute
</code></pre>
<p>See <a href="http://code.google.com/... | 6 | 2009-04-16T12:48:53Z | [
"python",
"google-app-engine",
"cron"
] |
Google App Engine for pseudo-cronjobs? | 755,777 | <p>I look for a possibility to create pseudo-cronjobs as I cannot use the real jobs on UNIX.</p>
<p>Since Python scripts can run for an unlimited period, I thought Python would be a great solution.</p>
<p>On Google App Engine you can set up Python scripts and it's free. So I should use the App Engine.</p>
<p>The App... | 3 | 2009-04-16T11:48:33Z | 757,914 | <p>Google has some limits on how long a task can run. </p>
<p>URLFetch calls made in the SDK now have a 5 second timeout, <a href="http://googleappengine.blogspot.com/2008/11/sdk-116-released.html" rel="nofollow">here</a></p>
<p>They allow you to schedule up to 20 cron tasks in any given day. <a href="http://code.go... | 2 | 2009-04-16T20:28:05Z | [
"python",
"google-app-engine",
"cron"
] |
Google App Engine for pseudo-cronjobs? | 755,777 | <p>I look for a possibility to create pseudo-cronjobs as I cannot use the real jobs on UNIX.</p>
<p>Since Python scripts can run for an unlimited period, I thought Python would be a great solution.</p>
<p>On Google App Engine you can set up Python scripts and it's free. So I should use the App Engine.</p>
<p>The App... | 3 | 2009-04-16T11:48:33Z | 757,986 | <p>You may want to clarify which way around you want to do it</p>
<p>Do you want to use appengine to RUN the job? Ie, the job runs on google's server?</p>
<p>or</p>
<p>Do you want to use your OWN code on your server, and trigger it by using google app engine?</p>
<p>If it's the former: google does cron now. Use tha... | 1 | 2009-04-16T20:47:24Z | [
"python",
"google-app-engine",
"cron"
] |
Google App Engine for pseudo-cronjobs? | 755,777 | <p>I look for a possibility to create pseudo-cronjobs as I cannot use the real jobs on UNIX.</p>
<p>Since Python scripts can run for an unlimited period, I thought Python would be a great solution.</p>
<p>On Google App Engine you can set up Python scripts and it's free. So I should use the App Engine.</p>
<p>The App... | 3 | 2009-04-16T11:48:33Z | 30,807,464 | <p>Do what Nic Wise said or also outsource the cronjob using a service like www.guardiano.pm so you can actually call www.yoursite.com/myjob.php and every time you call that url something you want will be executed. </p>
<p>Ps is free
Pss is my pet project and is in beta</p>
| 0 | 2015-06-12T16:00:21Z | [
"python",
"google-app-engine",
"cron"
] |
Default value for field in Django model | 755,857 | <p>Suppose I have a model:</p>
<pre><code>class SomeModel(models.Model):
id = models.AutoField(primary_key=True)
a = models.CharField(max_length=10)
b = models.CharField(max_length=7)
</code></pre>
<p>Currently I am using the default admin to create/edit objects of this type.
How do I remove the field <st... | 57 | 2009-04-16T12:13:34Z | 755,863 | <p>Set <code>editable</code> to <code>False</code> and <code>default</code> to your default value.</p>
<p><a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#editable">http://docs.djangoproject.com/en/dev/ref/models/fields/#editable</a></p>
<pre><code>b = models.CharField(max_length=7, default='0000000',... | 84 | 2009-04-16T12:16:41Z | [
"python",
"django",
"django-models",
"django-admin"
] |
Default value for field in Django model | 755,857 | <p>Suppose I have a model:</p>
<pre><code>class SomeModel(models.Model):
id = models.AutoField(primary_key=True)
a = models.CharField(max_length=10)
b = models.CharField(max_length=7)
</code></pre>
<p>Currently I am using the default admin to create/edit objects of this type.
How do I remove the field <st... | 57 | 2009-04-16T12:13:34Z | 755,872 | <p>You can set the default like this:</p>
<pre><code>b = models.CharField(max_length=7,default="foobar")
</code></pre>
<p>and then you can hide the field with your model's Admin class like this:</p>
<pre><code>class SomeModelAdmin(admin.ModelAdmin):
exclude = ("b")
</code></pre>
| 17 | 2009-04-16T12:20:38Z | [
"python",
"django",
"django-models",
"django-admin"
] |
Default value for field in Django model | 755,857 | <p>Suppose I have a model:</p>
<pre><code>class SomeModel(models.Model):
id = models.AutoField(primary_key=True)
a = models.CharField(max_length=10)
b = models.CharField(max_length=7)
</code></pre>
<p>Currently I am using the default admin to create/edit objects of this type.
How do I remove the field <st... | 57 | 2009-04-16T12:13:34Z | 7,969,092 | <p>You can also use a callable in the default field, such as:</p>
<pre><code>b = models.CharField(max_length=7, default=foo)
</code></pre>
<p>And then define the callable:</p>
<pre><code>def foo():
return 'bar'
</code></pre>
| 12 | 2011-11-01T15:53:42Z | [
"python",
"django",
"django-models",
"django-admin"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 756,083 | <p>First of all: it smells like <em>recursion</em> of course!</p>
<p>Since you also wanted to know the principle, I did my best to explain it human language. I think recursion is very easy most of the times. You only have to grasp two steps:</p>
<ol>
<li>The first step</li>
<li>All the other steps (all with the same ... | 106 | 2009-04-16T13:22:28Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 756,102 | <p>First of all, sets have permutations, not strings or integers, so I'll just assume you mean "the set of characters in a string."</p>
<p>Note that a set of size n has n! n-permutations.</p>
<p>The following pseudocode (from Wikipedia), called with k = 1...n! will give all the permutations:</p>
<pre><code>function ... | 9 | 2009-04-16T13:25:08Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 756,145 | <p>Here's a good article covering three algorithms for finding all permutations, including one to find the next permutation.</p>
<p><a href="http://www.cut-the-knot.org/do_you_know/AllPerm.shtml">http://www.cut-the-knot.org/do_you_know/AllPerm.shtml</a></p>
<p>C++ and Python have built-in <a href="http://www.cplusplu... | 5 | 2009-04-16T13:34:49Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 756,467 | <p>Here's a purely functional F# implementation:</p>
<pre>
<code>
let factorial i =
let rec fact n x =
match n with
| 0 -> 1
| 1 -> x
| _ -> fact (n-1) (x*n)
fact i 1
let swap (arr:'a array) i j = [| for k in 0..(arr.Length-1) -> if k = i then arr.[j] elif k = j then arr.[i] el... | 5 | 2009-04-16T14:46:52Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 1,447,183 | <pre><code>void permute (char *str, int ptr) {
int i, len;
len = strlen(str);
if (ptr == len) {
printf ("%s\n", str);
return;
}
for (i = ptr ; i < len ; i++) {
swap (&str[ptr], &str[i]);
permute (str, ptr + 1);
swap (&str[ptr], &str[i]);
}
}
</code></pre>
<p>You can ... | 11 | 2009-09-18T23:08:27Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 8,566,913 | <p>Here is the function which will print all permutaion.
This function implements logic Explained by peter.</p>
<pre><code>public class Permutation
{
//http://www.java2s.com/Tutorial/Java/0100__Class-Definition/RecursivemethodtofindallpermutationsofaString.htm
public static void permuteString(String beginning... | 2 | 2011-12-19T20:09:19Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 10,630,026 | <p>It's just two lines of code if LINQ is allowed to use. Please see my answer <a href="http://stackoverflow.com/a/10629938/1251423">here</a>.</p>
<p><strong>EDIT</strong></p>
<p>Here is my generic function which can return all the permutations (not combinations) from a list of T:</p>
<pre><code>static IEnumerable&l... | 40 | 2012-05-17T04:54:32Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 12,542,156 | <p>The below is my implementation of permutation . Don't mind the variable names, as i was doing it for fun :) </p>
<pre><code>class combinations
{
static void Main()
{
string choice = "y";
do
{
try
{
Console.WriteLine("Enter word :");
... | 2 | 2012-09-22T08:29:58Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 13,022,090 | <p>Slightly modified version in C# that yields needed permutations in an array of ANY type.</p>
<pre><code> // USAGE: create an array of any type, and call Permutations()
var vals = new[] {"a", "bb", "ccc"};
foreach (var v in Permutations(vals))
Console.WriteLine(string.Join(",", v)); // Print value... | 5 | 2012-10-23T00:44:50Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 18,181,573 | <p>Here is the function which will print all permutations recursively. </p>
<pre><code>public void Permutations(string input, StringBuilder sb)
{
if (sb.Length == input.Length)
{
Console.WriteLine(sb.ToString());
return;
}
char[] inChar = input.ToCharArray()... | 0 | 2013-08-12T07:28:53Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 21,843,611 | <p>Here I have found the solution. It was written in Java, but I have converted it to C#. I hope it will help you.</p>
<p><img src="http://i.stack.imgur.com/F0lDq.jpg" alt="Enter image description here"></p>
<p>Here's the code in C#:</p>
<pre><code>static void Main(string[] args)
{
string str = "ABC";
char[]... | 17 | 2014-02-18T03:11:27Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 21,963,875 | <pre><code>class Permutation
{
public static List<string> Permutate(string seed, List<string> lstsList)
{
loopCounter = 0;
// string s="\w{0,2}";
var lstStrs = PermuateRecursive(seed);
Trace.WriteLine("Loop counter :" + loopCounter);
return lstStrs;
}
... | -1 | 2014-02-23T03:35:51Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 23,147,324 | <p>Here is a C# answer which is a little simplified.</p>
<pre><code>public static void StringPermutationsDemo()
{
strBldr = new StringBuilder();
string result = Permute("ABCD".ToCharArray(), 0);
MessageBox.Show(result);
}
static string Permute(char[] elementsList, int startIndex)
{
if (startInde... | 0 | 2014-04-18T04:22:42Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 25,048,284 | <pre><code> /// <summary>
/// Print All the Permutations.
/// </summary>
/// <param name="inputStr">input string</param>
/// <param name="strLength">length of the string</param>
/// <param name="outputStr">output string</param>
private void Prin... | -1 | 2014-07-30T22:53:11Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 25,386,936 | <p>Here's a high level example I wrote which illustrates the <strong>human language</strong> explanation Peter gave:</p>
<pre><code> public List<string> FindPermutations(string input)
{
if (input.Length == 1)
return new List<string> { input };
var perms = new List<stri... | 2 | 2014-08-19T15:08:37Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 30,312,182 | <p>I liked <em>FBryant87</em> approach since it's simple. Unfortunately, it does like many other "solutions" not offer all permutations or of e.g. an integer if it contains the same digit more than once. Take 656123 as an example. The line:</p>
<pre><code>var tail = chars.Except(new List<char>(){c});
</code></pr... | 4 | 2015-05-18T20:23:29Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 32,037,976 | <p>This is my solution which it is easy for me to understand</p>
<pre><code>class ClassicPermutationProblem
{
ClassicPermutationProblem() { }
private static void PopulatePosition<T>(List<List<T>> finalList, List<T> list, List<T> temp, int position)
{
foreach (T eleme... | 0 | 2015-08-16T17:28:09Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 32,544,916 | <p><strong>Recursion</strong> is not necessary, <a href="http://stackoverflow.com/a/1506337/1486443">here</a> is good information about this solution.</p>
<pre><code>var values1 = new[] { 1, 2, 3, 4, 5 };
foreach (var permutation in values1.GetPermutations())
{
Console.WriteLine(string.Join(", ", permutation));
}... | 8 | 2015-09-12T23:47:19Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 36,634,228 | <p>If performance and memory is an issue, I suggest this very efficient implementation. According to <a href="https://en.wikipedia.org/wiki/Heap%27s_algorithm" rel="nofollow">Heap's algorithm in Wikipedia</a>, it should be the fastest. Hope it will fits your need :-) !</p>
<p>Just as comparison of this with a Linq imp... | 0 | 2016-04-14T21:20:51Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 38,175,625 | <p>Here is an easy to understand permutaion function for both string and integer as input. With this <strong>you can even set your output length</strong>(which in normal case it is equal to input length)</p>
<p><strong><em>String</em></strong></p>
<pre><code> static ICollection<string> result;
public st... | 1 | 2016-07-04T00:50:33Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
Listing all permutations of a string/integer | 756,055 | <p>A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.</p>
<p>Is there an example of how this is done and the logic behind solving such a problem?</p>
<p>I've seen a few code snippets but they weren't well comment... | 96 | 2009-04-16T13:13:39Z | 38,213,245 | <p>Here is one more implementation of the algo mentioned. </p>
<pre><code>public class Program
{
public static void Main(string[] args)
{
string str = "abcefgh";
var astr = new Permutation().GenerateFor(str);
Console.WriteLine(astr.Length);
foreach(var a in astr)
{
... | 0 | 2016-07-05T21:40:47Z | [
"c#",
"python",
"algorithm",
"f#",
"permutation"
] |
pylint warning on 'except Exception:' | 756,180 | <p>For a block like this:</p>
<pre><code>try:
#some stuff
except Exception:
pass
</code></pre>
<p>pylint raises warning W0703 'Catch "Exception"'. Why?</p>
| 10 | 2009-04-16T13:42:24Z | 756,183 | <p>It's considered good practice to not normally catch the root Exception object, but instead to catch more specific ones - for example IOException.</p>
<p>Consider if an out of memory exception occurred - simply using "pass" isn't going to leave your programme in a good state.</p>
<p>Pretty much the only time you sh... | 18 | 2009-04-16T13:44:45Z | [
"python",
"pylint"
] |
pylint warning on 'except Exception:' | 756,180 | <p>For a block like this:</p>
<pre><code>try:
#some stuff
except Exception:
pass
</code></pre>
<p>pylint raises warning W0703 'Catch "Exception"'. Why?</p>
| 10 | 2009-04-16T13:42:24Z | 756,187 | <p>because it thinks that you're catching too much. and it's right.</p>
| 3 | 2009-04-16T13:45:33Z | [
"python",
"pylint"
] |
pylint warning on 'except Exception:' | 756,180 | <p>For a block like this:</p>
<pre><code>try:
#some stuff
except Exception:
pass
</code></pre>
<p>pylint raises warning W0703 'Catch "Exception"'. Why?</p>
| 10 | 2009-04-16T13:42:24Z | 756,190 | <p>Exception are raised when something... exceptional occurs. It's generally a good thing that the program terminates.</p>
<p>You may want to ignore some exceptions, but IMO there's no good reason for catching a base-class like that.</p>
| 2 | 2009-04-16T13:46:09Z | [
"python",
"pylint"
] |
pylint warning on 'except Exception:' | 756,180 | <p>For a block like this:</p>
<pre><code>try:
#some stuff
except Exception:
pass
</code></pre>
<p>pylint raises warning W0703 'Catch "Exception"'. Why?</p>
| 10 | 2009-04-16T13:42:24Z | 816,524 | <p>Catching Exception (without re-raising) has 2 really bad side effects: errors get eaten, so you lose the stack trace, but also that ctrl-c (or whatever the break key is on your operating system) also gets handled here.</p>
<p>The typical behavior of programs like this is that either they can't be stopped, or that c... | -1 | 2009-05-03T07:37:11Z | [
"python",
"pylint"
] |
pylint warning on 'except Exception:' | 756,180 | <p>For a block like this:</p>
<pre><code>try:
#some stuff
except Exception:
pass
</code></pre>
<p>pylint raises warning W0703 'Catch "Exception"'. Why?</p>
| 10 | 2009-04-16T13:42:24Z | 1,114,833 | <p>It's good practice to catch only a very narrow range of types. 'Exception' is too general - you will end up catching not just the errors you planned for, but other errors too, which may mask bugs in your code that would be quicker to diagnose if they weren't caught at all, or possibly would be better dealt with by a... | 14 | 2009-07-11T22:37:07Z | [
"python",
"pylint"
] |
pylint warning on 'except Exception:' | 756,180 | <p>For a block like this:</p>
<pre><code>try:
#some stuff
except Exception:
pass
</code></pre>
<p>pylint raises warning W0703 'Catch "Exception"'. Why?</p>
| 10 | 2009-04-16T13:42:24Z | 6,714,306 | <p>like Greg's answer, 'Exception' is a base class and exceptions should be derived from this class, see also <a href="http://docs.python.org/library/exceptions.html#exceptions.Exception" rel="nofollow">exceptions.Exception</a>.</p>
<p>Here a very usefull <b> list of Errors in <a href="http://docs.python.org/c-api/exc... | 0 | 2011-07-15T23:51:56Z | [
"python",
"pylint"
] |
Can you write a permutation function just as elegantly in C#? | 756,223 | <p>I like this 6 line solution a lot and am trying to replicate it in C#. Basically, it permutes the elements of an array:</p>
<pre><code>def permute(xs, pre=[]):
if len(xs) == 0:
yield pre
for i, x in enumerate(xs):
for y in permute(xs[:i] + xs[i+1:], pre + [x]):
yield y
</code></pre>
| 5 | 2009-04-16T13:53:49Z | 756,262 | <p>Not entirely to the point I must admit after some comments, but the code below can be used to generate a random permutation of a finite sequence. It's a variation of the <a href="http://en.wikipedia.org/wiki/Fisher-Yates%5Fshuffle" rel="nofollow">Fisher-Yates shuffle algorithm</a>. The example uses a sequence of <co... | -6 | 2009-04-16T14:04:50Z | [
"c#",
"python",
"algorithm"
] |
Can you write a permutation function just as elegantly in C#? | 756,223 | <p>I like this 6 line solution a lot and am trying to replicate it in C#. Basically, it permutes the elements of an array:</p>
<pre><code>def permute(xs, pre=[]):
if len(xs) == 0:
yield pre
for i, x in enumerate(xs):
for y in permute(xs[:i] + xs[i+1:], pre + [x]):
yield y
</code></pre>
| 5 | 2009-04-16T13:53:49Z | 756,274 | <p>C# has a yield keyword that I imagine works pretty much the same as what your python code is doing, so it shouldn't be too hard to get a mostly direct translation.</p>
<p>However this is a recursive solution, so for all it's brevity it's sub-optimal. I don't personally understand all the math involved, but for goo... | 1 | 2009-04-16T14:06:45Z | [
"c#",
"python",
"algorithm"
] |
Can you write a permutation function just as elegantly in C#? | 756,223 | <p>I like this 6 line solution a lot and am trying to replicate it in C#. Basically, it permutes the elements of an array:</p>
<pre><code>def permute(xs, pre=[]):
if len(xs) == 0:
yield pre
for i, x in enumerate(xs):
for y in permute(xs[:i] + xs[i+1:], pre + [x]):
yield y
</code></pre>
| 5 | 2009-04-16T13:53:49Z | 756,308 | <p>Well, it probably isn't how I'd write it, but:</p>
<pre><code>static IEnumerable<T[]> Permute<T>(this T[] xs, params T[] pre) {
if (xs.Length == 0) yield return pre;
for (int i = 0; i < xs.Length; i++) {
foreach (T[] y in Permute(xs.Take(i).Union(xs.Skip(i+1)).ToArray(), pre.Union(new... | 12 | 2009-04-16T14:13:01Z | [
"c#",
"python",
"algorithm"
] |
Can you write a permutation function just as elegantly in C#? | 756,223 | <p>I like this 6 line solution a lot and am trying to replicate it in C#. Basically, it permutes the elements of an array:</p>
<pre><code>def permute(xs, pre=[]):
if len(xs) == 0:
yield pre
for i, x in enumerate(xs):
for y in permute(xs[:i] + xs[i+1:], pre + [x]):
yield y
</code></pre>
| 5 | 2009-04-16T13:53:49Z | 756,328 | <p>While you cannot port it while maintaining the brevity, you can get pretty close.</p>
<pre><code>public static class IEnumerableExtensions
{
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> source)
{
if (source == null)
throw new ArgumentNullExcepti... | 0 | 2009-04-16T14:18:06Z | [
"c#",
"python",
"algorithm"
] |
Elixir Event Handler | 756,529 | <p>I want to use the @after_insert decorator of Elixir, but i can't access the Session within the model. Since i have autocommit set to False, i can't commit any changes in the event handler. Is there any best practice how to deal with that?</p>
<p>The Code I used to build model, database connection etc. are mostly ta... | 0 | 2009-04-16T14:57:49Z | 759,908 | <p>Have you imported Session?</p>
<p><code>from packagename import Session</code></p>
<p>at the top of your model file should do the trick. Packagename is the directory name.</p>
| 0 | 2009-04-17T10:28:56Z | [
"python",
"pylons",
"python-elixir"
] |
Multiple Tuple to Two-Pair Tuple in Python? | 756,550 | <p>What is the nicest way of splitting this:</p>
<pre><code>tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
</code></pre>
<p>into this:</p>
<pre><code>tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
</code></pre>
<p>Assuming that the input always has an even number of values.</p>
| 11 | 2009-04-16T15:02:38Z | 756,580 | <pre><code>[(tuple[a], tuple[a+1]) for a in range(0,len(tuple),2)]
</code></pre>
| 15 | 2009-04-16T15:07:24Z | [
"python",
"data-structures",
"tuples"
] |
Multiple Tuple to Two-Pair Tuple in Python? | 756,550 | <p>What is the nicest way of splitting this:</p>
<pre><code>tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
</code></pre>
<p>into this:</p>
<pre><code>tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
</code></pre>
<p>Assuming that the input always has an even number of values.</p>
| 11 | 2009-04-16T15:02:38Z | 756,602 | <p><code>zip()</code> is your friend:</p>
<pre><code>t = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
zip(t[::2], t[1::2])
</code></pre>
| 36 | 2009-04-16T15:10:52Z | [
"python",
"data-structures",
"tuples"
] |
Multiple Tuple to Two-Pair Tuple in Python? | 756,550 | <p>What is the nicest way of splitting this:</p>
<pre><code>tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
</code></pre>
<p>into this:</p>
<pre><code>tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
</code></pre>
<p>Assuming that the input always has an even number of values.</p>
| 11 | 2009-04-16T15:02:38Z | 756,701 | <p>Here's a general recipe for any-size chunk, if it might not always be 2:</p>
<pre><code>def chunk(seq, n):
return [seq[i:i+n] for i in range(0, len(seq), n)]
chunks= chunk(tuples, 2)
</code></pre>
<p>Or, if you enjoy iterators:</p>
<pre><code>def iterchunk(iterable, n):
it= iter(iterable)
while True:... | -1 | 2009-04-16T15:35:14Z | [
"python",
"data-structures",
"tuples"
] |
Multiple Tuple to Two-Pair Tuple in Python? | 756,550 | <p>What is the nicest way of splitting this:</p>
<pre><code>tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
</code></pre>
<p>into this:</p>
<pre><code>tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
</code></pre>
<p>Assuming that the input always has an even number of values.</p>
| 11 | 2009-04-16T15:02:38Z | 756,704 | <p>Or, using <code>itertools</code> (see the <a href="http://docs.python.org/library/itertools.html#recipes">recipe</a> for <code>grouper</code>):</p>
<pre><code>from itertools import izip
def group2(iterable):
args = [iter(iterable)] * 2
return izip(*args)
tuples = [ab for ab in group2(tuple)]
</code></pre>
| 7 | 2009-04-16T15:36:04Z | [
"python",
"data-structures",
"tuples"
] |
Multiple Tuple to Two-Pair Tuple in Python? | 756,550 | <p>What is the nicest way of splitting this:</p>
<pre><code>tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
</code></pre>
<p>into this:</p>
<pre><code>tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
</code></pre>
<p>Assuming that the input always has an even number of values.</p>
| 11 | 2009-04-16T15:02:38Z | 17,899,786 | <p>I present this code based on <a href="http://stackoverflow.com/a/756580/117870">Peter Hoffmann's answer</a> as a response to <a href="http://stackoverflow.com/questions/756550/17899786#comment568676_756602">dfa's comment</a>. </p>
<p>It is guaranteed to work whether or not your tuple has an even number of elements... | 0 | 2013-07-27T16:05:25Z | [
"python",
"data-structures",
"tuples"
] |
How do you use Binary conversion in Python/Bash/AWK? | 756,630 | <p>I am new in binary conversion.
I use Python, Bash and AWK daily.</p>
<p>I would like to see binary conversion's applications in these languages.
For example, I am interested in problems which you solve by it at your work.</p>
<p><strong>Where do you use binary conversion in Python/Bash/AWK?</strong></p>
<p>I woul... | 1 | 2009-04-16T15:14:46Z | 756,705 | <p>Conversion of strings of binary digits to a number using Python on the commandline:</p>
<pre><code>binary=00001111
DECIMAL=$(python -c "print int('$BINARY', 2)")
echo $decimal
</code></pre>
<p>See the docs for the <a href="http://docs.python.org/library/functions.html#int" rel="nofollow">int function</a>.</p>
<p>... | 2 | 2009-04-16T15:36:17Z | [
"python",
"bash",
"binary",
"awk"
] |
How do you use Binary conversion in Python/Bash/AWK? | 756,630 | <p>I am new in binary conversion.
I use Python, Bash and AWK daily.</p>
<p>I would like to see binary conversion's applications in these languages.
For example, I am interested in problems which you solve by it at your work.</p>
<p><strong>Where do you use binary conversion in Python/Bash/AWK?</strong></p>
<p>I woul... | 1 | 2009-04-16T15:14:46Z | 756,745 | <p>In shell, a nice use of <a href="http://stackoverflow.com/questions/750606/what-technologies-are-you-using-even-though-they-are-embarassingly-out-of-date/750620#750620"><code>dc</code></a>:</p>
<pre><code>echo 2i 00001111 pq | dc
</code></pre>
<p>2i means: <em>base for input numbers is 2</em>.</p>
<p>pq means: <e... | 2 | 2009-04-16T15:45:12Z | [
"python",
"bash",
"binary",
"awk"
] |
How do you use Binary conversion in Python/Bash/AWK? | 756,630 | <p>I am new in binary conversion.
I use Python, Bash and AWK daily.</p>
<p>I would like to see binary conversion's applications in these languages.
For example, I am interested in problems which you solve by it at your work.</p>
<p><strong>Where do you use binary conversion in Python/Bash/AWK?</strong></p>
<p>I woul... | 1 | 2009-04-16T15:14:46Z | 6,600,616 | <p>In newer versions of Python there exists the <code>bin()</code> function which I believe takes an int and returns a binary literal, of form <code>0b011010</code> or whatever.</p>
| 0 | 2011-07-06T17:35:53Z | [
"python",
"bash",
"binary",
"awk"
] |
Using multiple listboxes in python tkinter | 756,662 | <pre><code>from Tkinter import *
master = Tk()
listbox = Listbox(master)
listbox.pack()
listbox.insert(END, "a list entry")
for item in ["one", "two", "three", "four"]:
listbox.insert(END, item)
listbox2 = Listbox(master)
listbox2.pack()
listbox2.insert(END, "a list entry")
for item in ["one", "two", "three"... | 12 | 2009-04-16T15:24:17Z | 756,831 | <p><code>exportselection=0</code> when defining a listbox seems to take care of this issue.</p>
| 2 | 2009-04-16T16:01:56Z | [
"python",
"listbox",
"tkinter"
] |
Using multiple listboxes in python tkinter | 756,662 | <pre><code>from Tkinter import *
master = Tk()
listbox = Listbox(master)
listbox.pack()
listbox.insert(END, "a list entry")
for item in ["one", "two", "three", "four"]:
listbox.insert(END, item)
listbox2 = Listbox(master)
listbox2.pack()
listbox2.insert(END, "a list entry")
for item in ["one", "two", "three"... | 12 | 2009-04-16T15:24:17Z | 756,875 | <p>Short answer: set the value of the <code>exportselection</code> attribute of all listbox widgets to False or zero.</p>
<p>From <a href="http://www-acc.kek.jp/WWW-ACC-exp/KEKB/control/Activity/Python/TkIntro/introduction/listbox.htm">a pythonware overview</a> of the listbox widget:</p>
<blockquote>
<p>By default,... | 19 | 2009-04-16T16:11:42Z | [
"python",
"listbox",
"tkinter"
] |
Matching a pair of comments in HTML using regular expressions | 756,898 | <p>I have a mako template that looks something like this:</p>
<pre><code>% if staff:
<!-- begin staff -->
...
<!-- end staff -->
% endif
</code></pre>
<p>That way if I pass the staff variable as being True, those comments should appear. I'm trying to test this by using a regular expression th... | 1 | 2009-04-16T16:17:03Z | 756,914 | <p>By default <code>.</code> doesn't match newlines - you need to add the <code>re.DOTALL</code> option.</p>
<pre><code>re.search('<!-- begin staff -->.*<!-- end staff -->', text, re.DOTALL)
</code></pre>
<p>If you have more than one staff section, you might also want to make the match ungreedy:</p>
<pre... | 9 | 2009-04-16T16:21:01Z | [
"python",
"regex",
"unit-testing",
"mako"
] |
Matching a pair of comments in HTML using regular expressions | 756,898 | <p>I have a mako template that looks something like this:</p>
<pre><code>% if staff:
<!-- begin staff -->
...
<!-- end staff -->
% endif
</code></pre>
<p>That way if I pass the staff variable as being True, those comments should appear. I'm trying to test this by using a regular expression th... | 1 | 2009-04-16T16:17:03Z | 756,919 | <p>Use an HTML Parser like <a href="http://docs.python.org/library/htmlparser.html" rel="nofollow">HTMLParser</a> instead. See <a href="http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-rege">Can you provide some examples of why it is hard to parse X... | 2 | 2009-04-16T16:22:47Z | [
"python",
"regex",
"unit-testing",
"mako"
] |
How do I send large amounts of data from a forked process? | 757,020 | <p>I have a ctypes wrapper for a library. Unfortunately, this library is not 100% reliable (occasional segfaults, etc.). Because of how it's used, I want the wrapper to be reasonably resilient to the library crashing.</p>
<p>The best way to do this seems to be forking a process and sending the results back from the ch... | 3 | 2009-04-16T16:47:21Z | 757,269 | <p>Probably you are trying to write more data than can fit into the pipe, so it is blocking until someone comes along and reads some of that info out of there. That will never happen, because the only reader is the parent process, which you appear to have written to wait until the child terminates before it reads anyth... | 4 | 2009-04-16T17:45:01Z | [
"python",
"fork",
"pipe"
] |
How do I send large amounts of data from a forked process? | 757,020 | <p>I have a ctypes wrapper for a library. Unfortunately, this library is not 100% reliable (occasional segfaults, etc.). Because of how it's used, I want the wrapper to be reasonably resilient to the library crashing.</p>
<p>The best way to do this seems to be forking a process and sending the results back from the ch... | 3 | 2009-04-16T16:47:21Z | 757,622 | <p>One solution to the deadlock that ted.dennison mentioned is the following pseudocode:</p>
<pre><code>#parent
while waitpid(pid, WNOHANG) == (0, 0):
result = os.read(r, 1024)
#sleep for a short time
#at this point the child process has ended
#and you need the last bit of data from the pipe
result = os.read(... | 0 | 2009-04-16T19:15:38Z | [
"python",
"fork",
"pipe"
] |
How do I send large amounts of data from a forked process? | 757,020 | <p>I have a ctypes wrapper for a library. Unfortunately, this library is not 100% reliable (occasional segfaults, etc.). Because of how it's used, I want the wrapper to be reasonably resilient to the library crashing.</p>
<p>The best way to do this seems to be forking a process and sending the results back from the ch... | 3 | 2009-04-16T16:47:21Z | 757,624 | <p>The basic problem is that there's a 64kB limit on the pipe. A few possible solutions, from the simple to the complex:</p>
<ol>
<li>Send less data. zlib.compress could help in getting under the limit.</li>
<li>Store the actual data somewhere else (file, mmap, memcache), only using the pipe to send control informatio... | 2 | 2009-04-16T19:15:57Z | [
"python",
"fork",
"pipe"
] |
How do you serialize a model instance in Django? | 757,022 | <p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
| 93 | 2009-04-16T16:47:31Z | 757,042 | <p>It doesn't seem you can serialize an instance, you'd have to serialize a QuerySet of one object.</p>
<pre><code>from django.core import serializers
from models import *
def getUser(request):
return HttpResponse(json(Users.objects.filter(id=88)))
</code></pre>
<p>I run out of the <code>svn</code> release of dj... | 1 | 2009-04-16T16:51:02Z | [
"python",
"django",
"json",
"django-models",
"serialization"
] |
How do you serialize a model instance in Django? | 757,022 | <p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
| 93 | 2009-04-16T16:47:31Z | 757,233 | <p>It sounds like what you're asking about involves serializing the data structure of a Django model instance for interoperability. The other posters are correct: if you wanted the serialized form to be used with a python application that can query the database via Django's api, then you would wan to serialize a query... | 9 | 2009-04-16T17:36:47Z | [
"python",
"django",
"json",
"django-models",
"serialization"
] |
How do you serialize a model instance in Django? | 757,022 | <p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
| 93 | 2009-04-16T16:47:31Z | 903,369 | <pre><code>ville = UneVille.objects.get(nom='lihlihlihlih')
....
blablablab
.......
return HttpResponse(simplejson.dumps(ville.__dict__))
</code></pre>
<p>I return the dict of my instance</p>
<p>so it return something like {'field1':value,"field2":value,....}</p>
| 2 | 2009-05-24T08:54:13Z | [
"python",
"django",
"json",
"django-models",
"serialization"
] |
How do you serialize a model instance in Django? | 757,022 | <p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
| 93 | 2009-04-16T16:47:31Z | 2,617,501 | <p>I solved this problem by adding a serialization method to my model:</p>
<pre><code>def toJSON(self):
import simplejson
return simplejson.dumps(dict([(attr, getattr(self, attr)) for attr in [f.name for f in self._meta.fields]]))
</code></pre>
<p>Here's the verbose equivalent for those averse to one-liners:<... | 3 | 2010-04-11T15:18:57Z | [
"python",
"django",
"json",
"django-models",
"serialization"
] |
How do you serialize a model instance in Django? | 757,022 | <p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
| 93 | 2009-04-16T16:47:31Z | 3,289,057 | <p>You can easily use a list to wrap the required object and that's all what django serializers need to correctly serialize it, eg.:</p>
<pre><code>from django.core import serializers
# assuming obj is a model instance
serialized_obj = serializers.serialize('json', [ obj, ])
</code></pre>
| 150 | 2010-07-20T10:31:13Z | [
"python",
"django",
"json",
"django-models",
"serialization"
] |
How do you serialize a model instance in Django? | 757,022 | <p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
| 93 | 2009-04-16T16:47:31Z | 6,435,163 | <p>how about this way:</p>
<pre><code>def ins2dic(obj):
SubDic = obj.__dict__
del SubDic['id']
del SubDic['_state']
return SubDic
</code></pre>
<p>or exclude anything you don't want.</p>
| 2 | 2011-06-22T05:11:07Z | [
"python",
"django",
"json",
"django-models",
"serialization"
] |
How do you serialize a model instance in Django? | 757,022 | <p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
| 93 | 2009-04-16T16:47:31Z | 13,884,771 | <p>To avoid the array wrapper, remove it before you return the response:</p>
<pre><code>import json
from django.core import serializers
def getObject(request, id):
obj = MyModel.objects.get(pk=id)
data = serializers.serialize('json', [obj,])
struct = json.loads(data)
data = json.dumps(struct[0])
r... | 31 | 2012-12-14T19:05:17Z | [
"python",
"django",
"json",
"django-models",
"serialization"
] |
How do you serialize a model instance in Django? | 757,022 | <p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
| 93 | 2009-04-16T16:47:31Z | 15,740,398 | <p>Here's my solution for this, which allows you to easily customize the JSON as well as organize related records</p>
<p>Firstly implement a method on the model. I call is <code>json</code> but you can call it whatever you like, e.g.:</p>
<pre><code>class Car(Model):
...
def json(self):
return {
... | 2 | 2013-04-01T08:53:55Z | [
"python",
"django",
"json",
"django-models",
"serialization"
] |
How do you serialize a model instance in Django? | 757,022 | <p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
| 93 | 2009-04-16T16:47:31Z | 17,402,219 | <p>If you're asking how to serialize a single object from a model and you <strong>know</strong> you're only going to get one object in the queryset (for instance, using objects.get), then use something like:</p>
<pre><code>import django.core.serializers
import django.http
import models
def jsonExample(request,poll_id... | 6 | 2013-07-01T10:24:46Z | [
"python",
"django",
"json",
"django-models",
"serialization"
] |
How do you serialize a model instance in Django? | 757,022 | <p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
| 93 | 2009-04-16T16:47:31Z | 29,550,004 | <p>To serialize and deserialze, use the following:</p>
<pre><code>from django.core import serializers
serial = serializers.serialize("json", [obj])
...
# .next() pulls the first object out of the generator
# .object retrieves django object the object from the DeserializedObject
obj = serializers.deserialize("json", s... | 0 | 2015-04-09T22:15:29Z | [
"python",
"django",
"json",
"django-models",
"serialization"
] |
How do you serialize a model instance in Django? | 757,022 | <p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
| 93 | 2009-04-16T16:47:31Z | 35,612,936 | <p>If you're dealing with a list of model instances the best you can do is using <code>serializers.serialize()</code>, it gonna fit your need perfectly. </p>
<p>However, you are to face an issue with trying to serialize a <em>single</em> object, not a <code>list</code> of objects. That way, in order to get rid of diff... | 9 | 2016-02-24T20:57:09Z | [
"python",
"django",
"json",
"django-models",
"serialization"
] |
How do you serialize a model instance in Django? | 757,022 | <p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>
| 93 | 2009-04-16T16:47:31Z | 39,943,877 | <p>Use list, it will solve problem</p>
<p>Step1:</p>
<pre><code> result=YOUR_MODELE_NAME.objects.values('PROP1','PROP2').all();
</code></pre>
<p>Step2:</p>
<pre><code> result=list(result) #after getting data from model convert result to list
</code></pre>
<p>Step3:</p>
<pre><code> return HttpResponse(json.dumps(... | 1 | 2016-10-09T12:56:54Z | [
"python",
"django",
"json",
"django-models",
"serialization"
] |
Converting tree list to hierarchy dict | 757,244 | <p>I have a list of elements with attrs: parent, level, is_leaf_node, is_root_node, is_child_node.</p>
<p>I want to convert this list to hierarchy dict.
Example of output dict:</p>
<pre><code>{
'Technology':
{
'Gadgets':{},
'Gaming':{},
'Programming':
... | 6 | 2009-04-16T17:40:18Z | 757,387 | <p>Everything without a parent is your top level, so make those dicts first. Then do a second pass through your array to find everything with a parent at that top level, etc... It could be written as a loop or a recursive function. You really don't need any of the provided info besides "parent".</p>
| 1 | 2009-04-16T18:13:53Z | [
"python",
"tree",
"hierarchical-trees"
] |
Converting tree list to hierarchy dict | 757,244 | <p>I have a list of elements with attrs: parent, level, is_leaf_node, is_root_node, is_child_node.</p>
<p>I want to convert this list to hierarchy dict.
Example of output dict:</p>
<pre><code>{
'Technology':
{
'Gadgets':{},
'Gaming':{},
'Programming':
... | 6 | 2009-04-16T17:40:18Z | 757,507 | <p>It sounds like what you're basically wanting to do is a variant of <a href="http://en.wikipedia.org/wiki/Topological%5Fsorting" rel="nofollow">topological sorting</a>. The most common algorithm for this is the source removal algorithm. The pseudocode would look something like this:</p>
<pre><code>import copy
def ... | 2 | 2009-04-16T18:42:00Z | [
"python",
"tree",
"hierarchical-trees"
] |
Converting tree list to hierarchy dict | 757,244 | <p>I have a list of elements with attrs: parent, level, is_leaf_node, is_root_node, is_child_node.</p>
<p>I want to convert this list to hierarchy dict.
Example of output dict:</p>
<pre><code>{
'Technology':
{
'Gadgets':{},
'Gaming':{},
'Programming':
... | 6 | 2009-04-16T17:40:18Z | 757,582 | <p>Here's a less sophisticated, recursive version like chmod700 described. Completely untested of course:</p>
<pre><code>def build_tree(nodes):
# create empty tree to fill
tree = {}
# fill in tree starting with roots (those with no parent)
build_tree_recursive(tree, None, nodes)
return tree
def ... | 9 | 2009-04-16T19:02:37Z | [
"python",
"tree",
"hierarchical-trees"
] |
Converting tree list to hierarchy dict | 757,244 | <p>I have a list of elements with attrs: parent, level, is_leaf_node, is_root_node, is_child_node.</p>
<p>I want to convert this list to hierarchy dict.
Example of output dict:</p>
<pre><code>{
'Technology':
{
'Gadgets':{},
'Gaming':{},
'Programming':
... | 6 | 2009-04-16T17:40:18Z | 758,649 | <p>Something simple like this might work:</p>
<pre><code>def build_tree(category_data):
top_level_map = {}
cat_map = {}
for cat_name, parent, depth in cat_data:
cat_map.setdefault(parent, {})
cat_map.setdefault(cat_name, {})
cat_map[parent][cat_name] = cat_map[cat_name]
if depth == 0:
top_l... | 0 | 2009-04-17T01:05:37Z | [
"python",
"tree",
"hierarchical-trees"
] |
Difference in regex behavior between Perl and Python? | 757,476 | <p>I have a couple email addresses, <code>'support@company.com'</code> and <code>'1234567@tickets.company.com'</code>.</p>
<p>In perl, I could take the <code>To:</code> line of a raw email and find either of the above addresses with</p>
<pre><code>/\w+@(tickets\.)?company\.com/i
</code></pre>
<p>In python, I simply ... | 3 | 2009-04-16T18:35:40Z | 757,509 | <p>Two problems jump out at me:</p>
<ol>
<li>You need to use a raw string to avoid having to escape "<code>\</code>"</li>
<li>You need to escape "<code>.</code>"</li>
</ol>
<p>So try:</p>
<pre><code>r'\w+@(tickets\.)?company\.com'
</code></pre>
<p>EDIT</p>
<p>Sample output:</p>
<pre><code>>>> import re
&... | 2 | 2009-04-16T18:42:40Z | [
"python",
"regex",
"perl"
] |
Difference in regex behavior between Perl and Python? | 757,476 | <p>I have a couple email addresses, <code>'support@company.com'</code> and <code>'1234567@tickets.company.com'</code>.</p>
<p>In perl, I could take the <code>To:</code> line of a raw email and find either of the above addresses with</p>
<pre><code>/\w+@(tickets\.)?company\.com/i
</code></pre>
<p>In python, I simply ... | 3 | 2009-04-16T18:35:40Z | 757,518 | <p>I think the problem is in your expectations of extracted values. Try using this in your current Python code:</p>
<pre><code>'(\w+@(?:tickets\.)?company\.com)'
</code></pre>
| 4 | 2009-04-16T18:45:10Z | [
"python",
"regex",
"perl"
] |
Difference in regex behavior between Perl and Python? | 757,476 | <p>I have a couple email addresses, <code>'support@company.com'</code> and <code>'1234567@tickets.company.com'</code>.</p>
<p>In perl, I could take the <code>To:</code> line of a raw email and find either of the above addresses with</p>
<pre><code>/\w+@(tickets\.)?company\.com/i
</code></pre>
<p>In python, I simply ... | 3 | 2009-04-16T18:35:40Z | 757,521 | <p>The documentation for <code>re.findall</code>:</p>
<blockquote>
<pre><code>findall(pattern, string, flags=0)
Return a list of all non-overlapping matches in the string.
If one or more groups are present in the pattern, return a
list of groups; this will be a list of tuples if the pattern
has more t... | 7 | 2009-04-16T18:46:12Z | [
"python",
"regex",
"perl"
] |
Difference in regex behavior between Perl and Python? | 757,476 | <p>I have a couple email addresses, <code>'support@company.com'</code> and <code>'1234567@tickets.company.com'</code>.</p>
<p>In perl, I could take the <code>To:</code> line of a raw email and find either of the above addresses with</p>
<pre><code>/\w+@(tickets\.)?company\.com/i
</code></pre>
<p>In python, I simply ... | 3 | 2009-04-16T18:35:40Z | 757,539 | <p>There isn't a difference in the regexes, but there is a difference in what you are looking for. Your regex is capturing only <code>"tickets."</code> if it exists in both regexes. You probably want something like this</p>
<pre><code>#!/usr/bin/python
import re
regex = re.compile("(\w+@(?:tickets\.)?company\.com)... | 1 | 2009-04-16T18:52:00Z | [
"python",
"regex",
"perl"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.