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
list
regex to remove URL from text
1,929,793
<p>I want to remove all occurrences of URL [full path, query string] from the text in Python. Any suggestions on how to do this? I am new to regex!</p> <pre><code>http://example.com/url/?x=data </code></pre> <p>This whole URL should be removed! Thanks</p>
1
2009-12-18T18:02:17Z
38,603,401
<p><a href="http://shellykaohsiung.blogspot.tw/2016/07/regular-expression-to-url-removed-in-php.html" rel="nofollow">URL remove Example</a></p> <pre><code>&lt;?php preg_match_all('/&lt;a.*?href=".*?"&gt;(.*?)&lt;[\/]a&gt;/', $content,$arr); $new_content = str_replace($arr[0], $arr[1], $content); echo $new...
-1
2016-07-27T03:50:08Z
[ "python", "regex", "url" ]
PyTables problem - different results when iterating over subset of table
1,929,973
<p>I am new to PyTables, and am looking at using it to process data generated from an agent-based modeling simulation and stored in HDF5. I'm working with a 39 MB test file, and am experiencing some strangeness. Here's the layout of the table:</p> <pre><code> /example/agt_coords (Table(2000000,)) '' description...
3
2009-12-18T18:38:36Z
1,931,993
<p>This is a very common point of confusion when iterating over <code>Table</code> object,</p> <p>When you iterate over a <code>Table</code> the type of item you get is not the data at the item, but an accessor to the table at the current row. So with</p> <pre><code>[x for x in coords if x['agent'] == 1] </code></pr...
7
2009-12-19T04:46:40Z
[ "python", "numpy", "pytables" ]
Some other filter
1,930,120
<p>I have a problem. I've got a string which looks like "var1,var2" and table in database which contains some records looks like "var1, var3", "var3", "var2,var3" an I want to filter them by splitting first string. When any of my string-variable fits to database-variable django will display them. So, when I have string...
0
2009-12-18T19:07:46Z
1,930,244
<p>Rather than this approach, you might have better luck adding a foreign key or a grouping number to your model so you can use the Database to do the splitting for you. </p> <p>So instead of this: </p> <pre><code>class MyModel(models.Model): vars = models.CharField(max_length=200) m = MyModel(vars="var1,var2")...
0
2009-12-18T19:33:24Z
[ "python", "django" ]
Some other filter
1,930,120
<p>I have a problem. I've got a string which looks like "var1,var2" and table in database which contains some records looks like "var1, var3", "var3", "var2,var3" an I want to filter them by splitting first string. When any of my string-variable fits to database-variable django will display them. So, when I have string...
0
2009-12-18T19:07:46Z
1,930,794
<p>I htink that what you want is OR lookups. Try this:</p> <pre><code>var_string = 'var1,var2' vars = var_string.split(',') result = MyModel.objects.none() for var in vars: result |= MyModel.objects.filter(name__icontains=var.strip()) return result </code></pre> <p>You might want to put this in a Manager for reu...
2
2009-12-18T21:28:02Z
[ "python", "django" ]
Prevent RegEx Hang on Large Matches
1,930,135
<p>This is a great regular expression for dates... However it hangs indefinitely on this one page I tried... I wanted to try this page ( <a href="http://pleac.sourceforge.net/pleac%5Fpython/datesandtimes.html" rel="nofollow">http://pleac.sourceforge.net/pleac%5Fpython/datesandtimes.html</a> ) for the fact that it does ...
3
2009-12-18T19:11:03Z
1,930,197
<p>The Python regular expression evaluator can take a long time. Unfortunately, it runs in a worst case exponential time.</p> <p>I assume your "s" contains a copy of the entire page. If so, that could cause very long backtracks in the regular expression evaluator. Perhaps you should break the page up into smaller chun...
0
2009-12-18T19:22:07Z
[ "python", "regex" ]
Prevent RegEx Hang on Large Matches
1,930,135
<p>This is a great regular expression for dates... However it hangs indefinitely on this one page I tried... I wanted to try this page ( <a href="http://pleac.sourceforge.net/pleac%5Fpython/datesandtimes.html" rel="nofollow">http://pleac.sourceforge.net/pleac%5Fpython/datesandtimes.html</a> ) for the fact that it does ...
3
2009-12-18T19:11:03Z
1,930,296
<p>The way the regex is written will cause a <em>lot</em> of backtracking. In addition to the tip about running it on smaller chunks of text, you can also have a simpler (and thus faster) regex that filters out text that cannot match.</p>
0
2009-12-18T19:43:06Z
[ "python", "regex" ]
Prevent RegEx Hang on Large Matches
1,930,135
<p>This is a great regular expression for dates... However it hangs indefinitely on this one page I tried... I wanted to try this page ( <a href="http://pleac.sourceforge.net/pleac%5Fpython/datesandtimes.html" rel="nofollow">http://pleac.sourceforge.net/pleac%5Fpython/datesandtimes.html</a> ) for the fact that it does ...
3
2009-12-18T19:11:03Z
1,930,311
<p>First, you should read up on what an <code>r""</code> string means: you only have to put in backslashes where you really want backslashes, so your regex should really just be:</p> <pre><code>monthnames = "(?:Jan\w*|Feb\w*|Mar\w*|Apr\w*|May|Jun\w?|Jul\w?|Aug\w*|Sep\w*|Oct\w*|Nov(?:ember)?|Dec\w*)" pattern1 = re.com...
0
2009-12-18T19:46:02Z
[ "python", "regex" ]
Prevent RegEx Hang on Large Matches
1,930,135
<p>This is a great regular expression for dates... However it hangs indefinitely on this one page I tried... I wanted to try this page ( <a href="http://pleac.sourceforge.net/pleac%5Fpython/datesandtimes.html" rel="nofollow">http://pleac.sourceforge.net/pleac%5Fpython/datesandtimes.html</a> ) for the fact that it does ...
3
2009-12-18T19:11:03Z
1,930,578
<p>You should read <a href="http://oreilly.com/catalog/9780596002893" rel="nofollow">Mastering Regular Expressions</a>. The problem is:</p> <pre><code>(?:[\d]*[\,\.\ \-]+)* </code></pre> <p>which takes exponential time. Try using:</p> <pre><code>(?:[\d,. \-]*[,. \-])? </code></pre> <p>which should match the same th...
5
2009-12-18T20:43:39Z
[ "python", "regex" ]
PyCrypto with Py2exe
1,930,539
<p>Can you use <a href="http://www.dlitz.net/software/pycrypto/" rel="nofollow">PyCrypto</a> with <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a>? Can you use any arbitrary library for that matter with py2exe?</p> <p>Thanks, Chris</p>
1
2009-12-18T20:37:22Z
1,930,722
<p>I have yet to find anything that py2exe can't actually handle, though from time to time it has lagged developments in Python itself. (For example, for a while it had trouble with the new absolute imports stuff, though I believe that's been resolved. It also wasn't so good with eggs, but I don't know if that has be...
1
2009-12-18T21:14:17Z
[ "python", "py2exe" ]
Operator= in Boost::Python
1,930,610
<p>If I have something like the following class</p> <pre><code>class Foo { private: int _bar; public: Foo&amp; operator=( const Foo&amp; other ) { _bar = other._bar; return *this; } } </code></pre> <p>Is there an easy way to export that functionality to python using boost::python? The...
1
2009-12-18T20:50:13Z
1,930,870
<p>I'm not an expert with Python, but in python the affectation with operator "=" has not the same meaning as in C++: <code>a=b</code> creates a new reference to the same internal object, so there is no point in exporting c++'s <code>operator=</code> into python interface.<br> What you may do is creating a "clone" memb...
3
2009-12-18T21:48:30Z
[ "c++", "python", "boost-python" ]
Operator= in Boost::Python
1,930,610
<p>If I have something like the following class</p> <pre><code>class Foo { private: int _bar; public: Foo&amp; operator=( const Foo&amp; other ) { _bar = other._bar; return *this; } } </code></pre> <p>Is there an easy way to export that functionality to python using boost::python? The...
1
2009-12-18T20:50:13Z
1,930,888
<p>You should not need to expose your assignment operator to python. In python, the assignment operator doesn't re-assign an existing object as a copy of another one, it re-assigns the name to a different object. In python, you are either creating a new object, or create a new object that is a <a href="http://docs.pyth...
4
2009-12-18T21:52:04Z
[ "c++", "python", "boost-python" ]
Operator= in Boost::Python
1,930,610
<p>If I have something like the following class</p> <pre><code>class Foo { private: int _bar; public: Foo&amp; operator=( const Foo&amp; other ) { _bar = other._bar; return *this; } } </code></pre> <p>Is there an easy way to export that functionality to python using boost::python? The...
1
2009-12-18T20:50:13Z
28,128,591
<p>The previous answer using <code>Foo::operator=</code> directly does not work. Do this instead:</p> <pre><code>void assignFoo(Foo&amp; self, const Foo&amp; other) { self = other; } class_&lt;Foo&gt;("Foo") .def("assign", assignFoo); </code></pre> <p>Usage in <code>python</code>:</p> <pre><code>foo, other ...
1
2015-01-24T18:07:37Z
[ "c++", "python", "boost-python" ]
How do I define a SQLAlchemy relation representing the latest object in a collection?
1,930,864
<p>I have a SQLAlchemy model with a one-to-many relationship between table <code>x</code> and table <code>y</code>. The record (if any) with the greatest <code>id</code> in table <code>y</code> where <code>y.x_id = x.id</code> is special. Class <code>X</code> and class <code>Y</code> map tables <code>x</code> and <code...
2
2009-12-18T21:46:57Z
1,931,299
<p>the purely relational way to do it requires using a subquery to get the "latest" or "max" value, correlated to the parent, then equating that with the members of the collection. It means you'll get best results if you put an index on the column that determines "the latest":</p> <pre><code>from sqlalchemy import * ...
4
2009-12-18T23:33:47Z
[ "python", "sqlalchemy" ]
show html with pyqt4
1,930,866
<p>print "hellp world" :)</p> <p>i want to ask you if exist a function or class hwo can show the html code like the browser's jobe</p> <p>thx</p>
0
2009-12-18T21:47:18Z
1,930,889
<p>There is <a href="http://doc.trolltech.com/4.4/qtwebkit.html" rel="nofollow">QtWebKit Module</a> within Qt. It incorporates webkit rendering engine. Whereas you can get access to Qt classes using python binding, you can use Qt official manual as help. Qt designer is also included into pyqt - you can try using it to ...
1
2009-12-18T21:52:36Z
[ "python", "pyqt4" ]
Python: Defining a class with only Integers Defined
1,930,896
<p>I am defining a class where only a set of integers is used. </p> <p>I <strong>cannot</strong> use the following datatypes in defining my class: <code>set, frozenset and dictionaries</code>.</p> <p>i need help defining:</p> <p><code>remove(self,i)</code>: Integer i is removed from the set. An exception is raised ...
0
2009-12-18T21:55:45Z
1,931,003
<blockquote> <p>I cannot use the following datatypes in defining my class: set, frozenset and dictionaries.</p> </blockquote> <p>It looks like you are going to use list. You can use list's <code>remove</code> method and handle exceptions in appropriate way.</p>
1
2009-12-18T22:18:09Z
[ "python", "class" ]
Python: Defining a class with only Integers Defined
1,930,896
<p>I am defining a class where only a set of integers is used. </p> <p>I <strong>cannot</strong> use the following datatypes in defining my class: <code>set, frozenset and dictionaries</code>.</p> <p>i need help defining:</p> <p><code>remove(self,i)</code>: Integer i is removed from the set. An exception is raised ...
0
2009-12-18T21:55:45Z
1,931,076
<p>Assuming you are using an internal list based on what you've said, you could do it like so:</p> <pre><code>class Example(object): def __init__(self): self._list = list() # all your other methods here... def remove(self, i): try: self._list.remove(i) except ValueErro...
2
2009-12-18T22:32:13Z
[ "python", "class" ]
Python: Defining a class with only Integers Defined
1,930,896
<p>I am defining a class where only a set of integers is used. </p> <p>I <strong>cannot</strong> use the following datatypes in defining my class: <code>set, frozenset and dictionaries</code>.</p> <p>i need help defining:</p> <p><code>remove(self,i)</code>: Integer i is removed from the set. An exception is raised ...
0
2009-12-18T21:55:45Z
1,931,108
<p>Here's highly inefficient but complete implementation using <a href="http://docs.python.org/library/collections.html#abcs-abstract-base-classes" rel="nofollow"><code>MutableSet</code> ABC</a>:</p> <pre><code>import collections class MySet(collections.MutableSet): def __init__(self, iterable=tuple()): ...
1
2009-12-18T22:42:40Z
[ "python", "class" ]
Python: Defining a class with only Integers Defined
1,930,896
<p>I am defining a class where only a set of integers is used. </p> <p>I <strong>cannot</strong> use the following datatypes in defining my class: <code>set, frozenset and dictionaries</code>.</p> <p>i need help defining:</p> <p><code>remove(self,i)</code>: Integer i is removed from the set. An exception is raised ...
0
2009-12-18T21:55:45Z
1,942,359
<p>Here is something I did with duplication, take some ideas from it</p> <pre><code>combList = list1 + list2 combList.sort() last = combList[-1] for i in range(len(combList)-2, -1, -1): if last == combList[i]: del combList[i] else: last = combList[i] combList.sort() f...
0
2009-12-21T20:15:45Z
[ "python", "class" ]
Configuring extension modules with distutils/setuptools
1,930,900
<p>I have a Python project with mutiple extension modules written in C, which talk to a third-party library. However, depending on the user's environment and options some modules should not be built, and some compiler flags should be enabled/disabled. The problem is that I have to build the list of extension modules ...
6
2009-12-18T21:56:31Z
1,931,958
<p>My own experience with changing distutils has been weak and shaky, so all I can offer are pointers. Take a look at numpy. That has an entire submodule (numpy.distutils) with ways to work with (or work around) distutils. Otherwise, ask the distutils mailing list.</p>
0
2009-12-19T04:32:46Z
[ "python", "setuptools", "distutils" ]
Configuring extension modules with distutils/setuptools
1,930,900
<p>I have a Python project with mutiple extension modules written in C, which talk to a third-party library. However, depending on the user's environment and options some modules should not be built, and some compiler flags should be enabled/disabled. The problem is that I have to build the list of extension modules ...
6
2009-12-18T21:56:31Z
1,940,353
<p>I would subclass <code>distutils.core.Distribution</code> and pass it with <code>distutils.core.setup(distclass=CustomDistribution)</code> - this gives you access to the command-line parameters in the same way that the normal setup has them, and you can do things like adjusting the extensions list in the <code>Custo...
0
2009-12-21T14:17:46Z
[ "python", "setuptools", "distutils" ]
Configuring extension modules with distutils/setuptools
1,930,900
<p>I have a Python project with mutiple extension modules written in C, which talk to a third-party library. However, depending on the user's environment and options some modules should not be built, and some compiler flags should be enabled/disabled. The problem is that I have to build the list of extension modules ...
6
2009-12-18T21:56:31Z
2,376,647
<blockquote> <p>Is there a preferred way to do this?</p> </blockquote> <p>From my experience working with other people's modules, I can say there is certainly not consensus on the right way to do this.</p> <p>I have tried and rejected subclassing bits of distutils -- I found it fragile and difficult to get working ...
1
2010-03-04T03:13:44Z
[ "python", "setuptools", "distutils" ]
Configuring extension modules with distutils/setuptools
1,930,900
<p>I have a Python project with mutiple extension modules written in C, which talk to a third-party library. However, depending on the user's environment and options some modules should not be built, and some compiler flags should be enabled/disabled. The problem is that I have to build the list of extension modules ...
6
2009-12-18T21:56:31Z
6,883,355
<p>The config command is designed to be subclassed and used by projects with requirements like yours.</p>
0
2011-07-30T13:20:41Z
[ "python", "setuptools", "distutils" ]
Is there a clever way to get the previous/next item using the Django ORM?
1,931,008
<p>Say I have a list of photos ordered by creation date, as follows:</p> <pre><code>class Photo(models.Model): title = models.Char() image = models.Image() created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) </code></pre> <p>I have an arbitrary Photo object ...
20
2009-12-18T22:18:49Z
1,931,065
<p>You're in luck! Django creates <code>get_next_by_foo</code> and <code>get_previous_by_foo</code> methods by default for <code>DateField</code> &amp; <code>DateTimeField</code> as long as they do not have <code>null=True</code>.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; from foo.models import Request &gt;&gt;...
31
2009-12-18T22:30:38Z
[ "python", "django", "django-models" ]
Is there a clever way to get the previous/next item using the Django ORM?
1,931,008
<p>Say I have a list of photos ordered by creation date, as follows:</p> <pre><code>class Photo(models.Model): title = models.Char() image = models.Image() created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) </code></pre> <p>I have an arbitrary Photo object ...
20
2009-12-18T22:18:49Z
38,850,572
<p>To jathanism answer, its usefull, BUT <strong>get_next_by_FOO</strong> and <strong>get_previous_by_FOO</strong> ignore milliseconds... for example it will not work for objects created in loop:</p> <pre><code>for i in range(100): Photo.objects.create(title='bla', ...) obj = Photo.objects.first() obj.get_previou...
0
2016-08-09T12:19:50Z
[ "python", "django", "django-models" ]
Accessing python httplib2 over a network share in windows 7
1,931,353
<p>I am trying to run python from a network share on windows 7. The network share is T:</p> <pre><code>&gt;t:\python-2.6.1\python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import httplib2 htt...
2
2009-12-18T23:52:22Z
1,931,641
<p>Peter, When I copy python-2.6.1 from the network share to my local drive it works fine. It also works fine on my windows XP machine using the same network share.</p>
1
2009-12-19T01:33:38Z
[ "python", "windows-7", "httplib2" ]
Python - assign lists within nest to variable
1,931,380
<p>I am new to python and would appreciate a little help.</p> <p>How does one do the following:</p> <ol> <li><p>Having converted each line within a file to a nested list, e.g. <code>[['line 1', 'a'], ['line 2','b']]</code> how do I flatten the list so that each line is associated with a variable. Assume that the fir...
1
2009-12-19T00:02:28Z
1,931,393
<ol> <li><p>Why do you want to associate each item in a list with a variable? You cannot tell the number of list entries beforehand thus you do not know the exact number of variables to use.</p></li> <li><p>You can use tuple: <code>x = ([list1], [list2])</code></p></li> <li><p>You should write assignment vice-a-versa:<...
0
2009-12-19T00:06:17Z
[ "python", "variables", "loops", "list" ]
Python - assign lists within nest to variable
1,931,380
<p>I am new to python and would appreciate a little help.</p> <p>How does one do the following:</p> <ol> <li><p>Having converted each line within a file to a nested list, e.g. <code>[['line 1', 'a'], ['line 2','b']]</code> how do I flatten the list so that each line is associated with a variable. Assume that the fir...
1
2009-12-19T00:02:28Z
1,931,419
<p>No. 2: I can't see how that would be possible - surely you can only assign one value to a variable?</p>
1
2009-12-19T00:14:09Z
[ "python", "variables", "loops", "list" ]
Python - assign lists within nest to variable
1,931,380
<p>I am new to python and would appreciate a little help.</p> <p>How does one do the following:</p> <ol> <li><p>Having converted each line within a file to a nested list, e.g. <code>[['line 1', 'a'], ['line 2','b']]</code> how do I flatten the list so that each line is associated with a variable. Assume that the fir...
1
2009-12-19T00:02:28Z
1,931,427
<p>do you want:</p> <pre><code>a, b, c = i[2:5] </code></pre>
0
2009-12-19T00:16:51Z
[ "python", "variables", "loops", "list" ]
Python - assign lists within nest to variable
1,931,380
<p>I am new to python and would appreciate a little help.</p> <p>How does one do the following:</p> <ol> <li><p>Having converted each line within a file to a nested list, e.g. <code>[['line 1', 'a'], ['line 2','b']]</code> how do I flatten the list so that each line is associated with a variable. Assume that the fir...
1
2009-12-19T00:02:28Z
1,931,428
<pre><code># Answer to question 1 - just use the built-in functionality of lists. # # There is no need to use variables when lists let you do so much more # in a quick and organised fashion. lines = [] for line in open_file: lines.append(line) </code></pre> <p>Since <a href="http://stackoverflow.com/questions/193...
2
2009-12-19T00:17:20Z
[ "python", "variables", "loops", "list" ]
Python - assign lists within nest to variable
1,931,380
<p>I am new to python and would appreciate a little help.</p> <p>How does one do the following:</p> <ol> <li><p>Having converted each line within a file to a nested list, e.g. <code>[['line 1', 'a'], ['line 2','b']]</code> how do I flatten the list so that each line is associated with a variable. Assume that the fir...
1
2009-12-19T00:02:28Z
1,931,446
<p>if I understand well, you have a list of lists, which can have length 2 or 1 (when the variable name is not known)</p> <p>you would probably want to use a dict to store the lines</p> <p>yet to mention <code>i[:][0]</code> means something different you wanted, it's the same as <code>i[0]</code> (<code>i[:]</code> w...
0
2009-12-19T00:22:51Z
[ "python", "variables", "loops", "list" ]
How to change the max_length in a django subclass?
1,931,404
<p>I have the following model in django:</p> <pre><code>class Node(models.Model): name = models.CharField(max_length=255) </code></pre> <p>And this subclass of the above model:</p> <pre><code>class Thingy(Node): name = models.CharField(max_length=100) otherstuff = models.CharField(max_length=255) <...
1
2009-12-19T00:09:16Z
1,931,471
<p>Your implementation is totally wrong, that is not how you suppose to write parent and child class. either define name in parent class or child class, if you define it in a parent class then you can't define again in the child because new field will be created instead. so if you want to change max_length in the child...
3
2009-12-19T00:29:49Z
[ "python", "django" ]
How to parse somewhat wrong JSON with Python?
1,931,454
<p>I have a following JSON string coming from external input source:</p> <pre><code>{value: "82363549923gnyh49c9djl239pjm01223", id: 17893} </code></pre> <p>This is wrong-formatted JSON string ("id" and "value" must be in quotes), but I need to parse it anyway. I have tried simplejson and json-py and seems they could...
15
2009-12-19T00:25:08Z
1,931,461
<p>You could use a string parser to fix it first, a regex could do it provided that this is as complicated as the JSON will get.</p>
0
2009-12-19T00:27:33Z
[ "python", "json", "google-app-engine" ]
How to parse somewhat wrong JSON with Python?
1,931,454
<p>I have a following JSON string coming from external input source:</p> <pre><code>{value: "82363549923gnyh49c9djl239pjm01223", id: 17893} </code></pre> <p>This is wrong-formatted JSON string ("id" and "value" must be in quotes), but I need to parse it anyway. I have tried simplejson and json-py and seems they could...
15
2009-12-19T00:25:08Z
1,931,531
<p>since YAML (>=1.2) is a superset of JSON, you can do:</p> <pre><code>&gt;&gt;&gt; import yaml &gt;&gt;&gt; s = '{value: "82363549923gnyh49c9djl239pjm01223", id: 17893}' &gt;&gt;&gt; yaml.load(s) {'id': 17893, 'value': '82363549923gnyh49c9djl239pjm01223'} </code></pre>
19
2009-12-19T00:48:21Z
[ "python", "json", "google-app-engine" ]
How to parse somewhat wrong JSON with Python?
1,931,454
<p>I have a following JSON string coming from external input source:</p> <pre><code>{value: "82363549923gnyh49c9djl239pjm01223", id: 17893} </code></pre> <p>This is wrong-formatted JSON string ("id" and "value" must be in quotes), but I need to parse it anyway. I have tried simplejson and json-py and seems they could...
15
2009-12-19T00:25:08Z
1,934,501
<p>Pyparsing includes a JSON parser example, here is the <a href="http://pyparsing.wikispaces.com/file/view/jsonParser.py" rel="nofollow">online source</a>. You could modify the definition of memberDef to allow a non-quoted string for the member name, and then you could use this to parser your not-quite-JSON source te...
0
2009-12-19T23:50:53Z
[ "python", "json", "google-app-engine" ]
How to parse somewhat wrong JSON with Python?
1,931,454
<p>I have a following JSON string coming from external input source:</p> <pre><code>{value: "82363549923gnyh49c9djl239pjm01223", id: 17893} </code></pre> <p>This is wrong-formatted JSON string ("id" and "value" must be in quotes), but I need to parse it anyway. I have tried simplejson and json-py and seems they could...
15
2009-12-19T00:25:08Z
27,155,665
<p>You can use <a href="http://deron.meranda.us/python/demjson/" rel="nofollow">demjson</a>.</p> <pre><code>&gt;&gt;&gt; import demjson &gt;&gt;&gt; demjson.decode('{foo:3}') {u'foo': 3} </code></pre>
3
2014-11-26T17:43:18Z
[ "python", "json", "google-app-engine" ]
Python - ignore lines in a file
1,931,527
<p>How does one ignore lines in a file?</p> <p>Example:</p> <p>If you know that the first lines in a file will begin with say, a or b and the remainder of lines end with c, how does one parse the file so that lines beginning a or b are ignored and lines ending c are converted to a nested list?</p> <p>What I have so ...
1
2009-12-19T00:47:36Z
1,931,534
<p>One way to do it is to replace 'pass' with 'continue'. This will continue to the next line in the file without doing anything. You will also need to append line to list_1</p> <pre><code>if line[-1] == 'c': list_1.append([line.strip().split()]) </code></pre>
1
2009-12-19T00:50:05Z
[ "python", "file", "loops", "ignore", "lines" ]
Python - ignore lines in a file
1,931,527
<p>How does one ignore lines in a file?</p> <p>Example:</p> <p>If you know that the first lines in a file will begin with say, a or b and the remainder of lines end with c, how does one parse the file so that lines beginning a or b are ignored and lines ending c are converted to a nested list?</p> <p>What I have so ...
1
2009-12-19T00:47:36Z
1,931,538
<p>You can add <code>if</code> conditions to list comprehensions.</p> <pre><code>z_list = [i.strip().split() for i in z if i[-1] == 'c'] </code></pre> <p>or</p> <pre><code>z_list = [i.strip().split() for i in z if (i[0] &lt;&gt; 'a' and i[0] &lt;&gt; 'b')] </code></pre>
2
2009-12-19T00:52:17Z
[ "python", "file", "loops", "ignore", "lines" ]
Python - ignore lines in a file
1,931,527
<p>How does one ignore lines in a file?</p> <p>Example:</p> <p>If you know that the first lines in a file will begin with say, a or b and the remainder of lines end with c, how does one parse the file so that lines beginning a or b are ignored and lines ending c are converted to a nested list?</p> <p>What I have so ...
1
2009-12-19T00:47:36Z
1,931,552
<p><a href="http://docs.python.org/library/stdtypes.html#str.startswith">startswith</a> can take a tuple of strings to match, so you can do this:</p> <pre><code>[line.strip().split() for line in z if not line.startswith(('a', 'b'))] </code></pre> <p>This will work even if a and b are words or sentences not just chara...
9
2009-12-19T00:57:51Z
[ "python", "file", "loops", "ignore", "lines" ]
Python - ignore lines in a file
1,931,527
<p>How does one ignore lines in a file?</p> <p>Example:</p> <p>If you know that the first lines in a file will begin with say, a or b and the remainder of lines end with c, how does one parse the file so that lines beginning a or b are ignored and lines ending c are converted to a nested list?</p> <p>What I have so ...
1
2009-12-19T00:47:36Z
1,931,559
<p>One very general approach is to "filter" the file by removing some lines:</p> <pre><code>import itertools zlist = [l.strip.split() for l in itertools.ifilter(lambda line: line[0] not in 'ab', z)] </code></pre> <p>You can use <code>itertools.ifilter</code> any time you want to "selectively filter" an iterable, gett...
3
2009-12-19T01:00:00Z
[ "python", "file", "loops", "ignore", "lines" ]
Python - ignore lines in a file
1,931,527
<p>How does one ignore lines in a file?</p> <p>Example:</p> <p>If you know that the first lines in a file will begin with say, a or b and the remainder of lines end with c, how does one parse the file so that lines beginning a or b are ignored and lines ending c are converted to a nested list?</p> <p>What I have so ...
1
2009-12-19T00:47:36Z
1,931,576
<pre><code>f=open("file") for line in f: li=line.strip() if not li[0] in ["a","b"] and li[-1]=="c": print line.rstrip() f.close() </code></pre>
0
2009-12-19T01:07:59Z
[ "python", "file", "loops", "ignore", "lines" ]
Python - ignore lines in a file
1,931,527
<p>How does one ignore lines in a file?</p> <p>Example:</p> <p>If you know that the first lines in a file will begin with say, a or b and the remainder of lines end with c, how does one parse the file so that lines beginning a or b are ignored and lines ending c are converted to a nested list?</p> <p>What I have so ...
1
2009-12-19T00:47:36Z
1,931,674
<p>For those interested in the solution.</p> <p>And also, another question!</p> <p>Example file format:</p> <pre><code>c this is a comment p m 1468 1 267 260 32 0 8 1 0 </code></pre> <p>Code:</p> <pre><code>fname = raw_input('Please enter the name of file: ') z = open(fname, 'r') required_list = [line.strip().sp...
0
2009-12-19T01:50:05Z
[ "python", "file", "loops", "ignore", "lines" ]
Under what circumstances do Python unittests fail to run?
1,931,567
<p>I have a standalone Django app that I'm working on right now. You can see the code at <a href="http://github.com/foxbunny/Djassets" rel="nofollow">Github</a>. In one of the edits, I introduced an error that caused the source tree to be deleted. I reset to an earlier revision, and suddenly my unittests stopped workin...
1
2009-12-19T01:02:43Z
1,931,584
<p>Problem solved. Turns out it was a Django-specific problem. I had a models.py file in my app that wasn't part of git repo for some strange reason. Once the source tree was removed, and code from repo restored, the models.py was no longer there, so tests wouldn't run... Silly mistake.</p>
1
2009-12-19T01:11:19Z
[ "python", "unit-testing" ]
Python Datatype for a fixed-length FIFO
1,931,589
<p>I would like to know if there is a native datatype in Python that acts like a fixed-length FIFO buffer. For example, I want do create a length-5 FIFO buffer that is initialized with all zeros. Then, it might look like this:</p> <p>[0,0,0,0,0]</p> <p>Then, when I call the put function on the object, it will shift...
14
2009-12-19T01:14:10Z
1,931,603
<pre><code>x = collections.deque(5*[0], 5) </code></pre> <p>See <a href="http://docs.python.org/library/collections.html?highlight=collections.deque#collections.deque">the docs</a> for more about <code>collections.deque</code>; the method you call <code>push</code> is actually called <code>appendleft</code> in that ty...
26
2009-12-19T01:20:54Z
[ "python" ]
Python Datatype for a fixed-length FIFO
1,931,589
<p>I would like to know if there is a native datatype in Python that acts like a fixed-length FIFO buffer. For example, I want do create a length-5 FIFO buffer that is initialized with all zeros. Then, it might look like this:</p> <p>[0,0,0,0,0]</p> <p>Then, when I call the put function on the object, it will shift...
14
2009-12-19T01:14:10Z
5,191,873
<p>Just one more example to this post</p> <pre><code>from collections import deque domains = ['1.com','2.com','3.com'] d = deque(domains) d.pop() #pop(delete) 3.com here d.appendleft('new.com') print d </code></pre> <p>result:</p> <pre><code>deque(['new.com', '1.com', '2.com']) </code></pre>
2
2011-03-04T09:25:17Z
[ "python" ]
Python Datatype for a fixed-length FIFO
1,931,589
<p>I would like to know if there is a native datatype in Python that acts like a fixed-length FIFO buffer. For example, I want do create a length-5 FIFO buffer that is initialized with all zeros. Then, it might look like this:</p> <p>[0,0,0,0,0]</p> <p>Then, when I call the put function on the object, it will shift...
14
2009-12-19T01:14:10Z
7,913,731
<p>you can also use list</p> <pre><code>a = [0,0,0,0,0] a.pop(0) a.append(1) print a result [0,0,0,0,1] </code></pre> <p>or for left side in right out, otherwise </p> <pre><code>a.pop(5) a.insert(0,1) print a result [1,0,0,0,0] </code></pre>
5
2011-10-27T09:01:11Z
[ "python" ]
python post large files to django
1,931,673
<p>I am trying to find the best way (most efficient way) to post large files from a python application to a Django server.</p> <p>If I rely on raw_post_data on the Django side then all the content needs to be in RAM before I can read it which doesn't seem efficient at all if the file received is 100s of megs.</p> <p>...
4
2009-12-19T01:49:09Z
1,931,788
<p>I think only files less than 2.5MB are stored in the memory, any file that is larger than 2.5MB is streamed or written to temporary file in temp directory..</p> <p>reference: <a href="http://simonwillison.net/2008/Jul/1/uploads/">http://simonwillison.net/2008/Jul/1/uploads/</a> and here <a href="http://docs.djangop...
5
2009-12-19T02:55:23Z
[ "python", "django", "post", "upload" ]
python post large files to django
1,931,673
<p>I am trying to find the best way (most efficient way) to post large files from a python application to a Django server.</p> <p>If I rely on raw_post_data on the Django side then all the content needs to be in RAM before I can read it which doesn't seem efficient at all if the file received is 100s of megs.</p> <p>...
4
2009-12-19T01:49:09Z
1,932,534
<p>If you really want to optimize it and don't want Django to suffer whilst the bytes are being streamed and thus occupying one of the Django threads you can use the <a href="http://www.grid.net.ru/nginx/upload.en.html" rel="nofollow">nginx upload module</a> (see also <a href="http://brainspl.at/articles/2008/07/20/ngi...
2
2009-12-19T10:12:30Z
[ "python", "django", "post", "upload" ]
How to load remote javascript into a SpiderMonkey context?
1,931,688
<p>I have a server which will be serving up javascript files, I need to grab it and execute some of it's functions using SpiderMonkey in python. How can I do this?</p>
1
2009-12-19T01:55:57Z
1,933,952
<p>hope the following example helps:</p> <pre><code>&gt;&gt;&gt; import urllib2 &gt;&gt;&gt; import spidermonkey &gt;&gt;&gt; js = spidermonkey.Runtime() &gt;&gt;&gt; js_ctx = js.new_context() &gt;&gt;&gt; script = urllib2.urlopen('http://etherhack.co.uk/hashing/whirlpool/js/whirlpool.js').read() &gt;&gt;&gt; js_ctx.e...
2
2009-12-19T19:47:00Z
[ "javascript", "python", "http", "spidermonkey" ]
Django 1.1 date-based generic view problem - archive_year, archive_month, archive_day
1,931,708
<p>I'm on my first Django blog and when trying to get the posts by year, month and day, using the built-in generic view from Django, but I don't get proper results. <em>(Sorry for my non-professional first question.. if someone knows what is the appropriate question, please let me know)</em></p> <p>Well, I think it's ...
0
2009-12-19T02:11:09Z
1,931,723
<p>The month information is stored in the context variable <code>date_list</code>, not <code>pub_date</code>.</p> <p>From the django docs for <a href="https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-date-based-archive-year" rel="nofollow"><code>archive_year</code></a>:</p> <blockquote> ...
2
2009-12-19T02:18:09Z
[ "python", "html", "django", "django-templates" ]
What is the use of strings like "-*- Mode: Python -*-" found at the top of some python files?
1,931,781
<p>Here are the top few lines (all comments) from a python application. What do the first two comment lines indicate? Are they special markers for another app?</p> <blockquote> # -*- Mode: Python -*-<br /> # vi:si:et:sw=4:sts=4:ts=4<br /> #<br /> # Istanbul - A desktop recorder<br /> # Copyright (C) 2005 Zaheer Abbas ...
2
2009-12-19T02:53:58Z
1,931,795
<p>Its define tab size 4 spaces to text editors like <strong>vi</strong></p>
2
2009-12-19T02:58:21Z
[ "python" ]
What is the use of strings like "-*- Mode: Python -*-" found at the top of some python files?
1,931,781
<p>Here are the top few lines (all comments) from a python application. What do the first two comment lines indicate? Are they special markers for another app?</p> <blockquote> # -*- Mode: Python -*-<br /> # vi:si:et:sw=4:sts=4:ts=4<br /> #<br /> # Istanbul - A desktop recorder<br /> # Copyright (C) 2005 Zaheer Abbas ...
2
2009-12-19T02:53:58Z
1,931,807
<p>The first line is an emacs thing (although it may also be a vi thing). It basically tells it that it should use python-mode to read the file. You'll usually see this if the file ends in an extension other than .py.</p> <p>As mentioned, the second line deals with spacings.</p>
3
2009-12-19T03:03:16Z
[ "python" ]
Python - Check Order of Lines in File
1,931,802
<p>How does one check the order of lines in a file?</p> <p>Example file:</p> <pre><code>a b c d e f b c d e f g 1 2 3 4 5 0 </code></pre> <p>Requirements:</p> <ol> <li>All lines beginning a, must precede lines beginning b.</li> <li>There is no limit on number of lines beginning a.</li> <li>Lines beginning a, may or...
1
2009-12-19T03:01:22Z
1,931,826
<p>You can get all the lines into a list with <code>lines = open(thefile).readlines()</code> and then work on the list -- not maximally efficient but maximally simple, as you require.</p> <p>Again simplest is to do multiple loops, one per condition (except 2, which is not a condition that can be violated, and 5 which ...
2
2009-12-19T03:16:18Z
[ "python", "file", "order", "lines" ]
Python - Check Order of Lines in File
1,931,802
<p>How does one check the order of lines in a file?</p> <p>Example file:</p> <pre><code>a b c d e f b c d e f g 1 2 3 4 5 0 </code></pre> <p>Requirements:</p> <ol> <li>All lines beginning a, must precede lines beginning b.</li> <li>There is no limit on number of lines beginning a.</li> <li>Lines beginning a, may or...
1
2009-12-19T03:01:22Z
1,931,851
<p>A straightforward iterative method. This defines a function to determine a linetype from 1 to 3. Then we iterate over the lines in the file. An unknown line type or a linetype less than any previous one will raise an exception.</p> <pre><code>def linetype(line): if line.startswith("a"): return 1 ...
4
2009-12-19T03:27:16Z
[ "python", "file", "order", "lines" ]
Python - Check Order of Lines in File
1,931,802
<p>How does one check the order of lines in a file?</p> <p>Example file:</p> <pre><code>a b c d e f b c d e f g 1 2 3 4 5 0 </code></pre> <p>Requirements:</p> <ol> <li>All lines beginning a, must precede lines beginning b.</li> <li>There is no limit on number of lines beginning a.</li> <li>Lines beginning a, may or...
1
2009-12-19T03:01:22Z
1,931,857
<p>You don't need to index the lines. For every line you can chceck/set some conditions. If some condition is not met, raise an error. E.g. rule 1: you will have variable was_b initially set to False. In each iteration (besides from other checks / sets), check also, if the line starts with "b". If does, set was_b = Tru...
0
2009-12-19T03:30:42Z
[ "python", "file", "order", "lines" ]
Python - Check Order of Lines in File
1,931,802
<p>How does one check the order of lines in a file?</p> <p>Example file:</p> <pre><code>a b c d e f b c d e f g 1 2 3 4 5 0 </code></pre> <p>Requirements:</p> <ol> <li>All lines beginning a, must precede lines beginning b.</li> <li>There is no limit on number of lines beginning a.</li> <li>Lines beginning a, may or...
1
2009-12-19T03:01:22Z
1,932,314
<p>Restrictions on lines:</p> <p><code>I</code>. There must be no lines that begin with <code>'a'</code> after we've encountered a line that begins with <code>'b'</code>.</p> <p><code>II</code>. If we encountered a numeric line then a previous one must start with <code>'b'</code>. (or your 4-th condition allows anoth...
0
2009-12-19T08:00:37Z
[ "python", "file", "order", "lines" ]
How to generate an audio stream using gst-python?
1,932,120
<p>I'm looking to generate a stream in gstreamer, and I'd prefer to do it from python if possible. This points towards using gst-python, but I don't see a clear way to do it. It looks like creating a new stream would require making a gstreamer plugin, which gst-python doesn't seem to be able to do.</p> <p>To clarify, ...
3
2009-12-19T06:02:03Z
1,942,816
<p>Take a look at <code>appsrc</code> (<code>gst-inspect appsrc</code>). I used its counterpart <code>appsink</code> to get data out of a gstreamer pipeline.</p> <p>And here's an (almost)-working example. <a href="http://gstreamer-devel.966125.n4.nabble.com/appsrc-random-crash-td973529.html" rel="nofollow">http://gstr...
3
2009-12-21T21:44:40Z
[ "python", "audio", "gstreamer" ]
packaging cryptography software and distributing
1,932,200
<p>I'm developing a python GUI application and plan on calling external program packaged with my program to do some encryption. I noticed from sites like OpenSSL that talk about export laws regarding cryptography software.</p> <p>If I can't package binary forms of the cryptography software with my application, how can...
1
2009-12-19T06:43:46Z
1,932,236
<p>You need to pick your target audiences with care, especially when you are dancing around with ITAR -- the International Traffic in Arms Regulations. Identify the countries you can legally export your product to and then, at the very least, say that people from other countries can't download it. You may have to do mo...
5
2009-12-19T07:15:21Z
[ "python", "cryptography", "aes", "itar" ]
packaging cryptography software and distributing
1,932,200
<p>I'm developing a python GUI application and plan on calling external program packaged with my program to do some encryption. I noticed from sites like OpenSSL that talk about export laws regarding cryptography software.</p> <p>If I can't package binary forms of the cryptography software with my application, how can...
1
2009-12-19T06:43:46Z
1,932,436
<p>i have often seen people rely on an external package for the cryptographic part: you can package your software without the cryptographic package, and tell your user that they have to download and install the cryptographic part from the original publisher. </p> <p>this is effectively moving the responsibility for th...
0
2009-12-19T09:13:18Z
[ "python", "cryptography", "aes", "itar" ]
Can't get MySQL source query to work using Python mysqldb module
1,932,298
<p>I have the following lines of code:</p> <pre><code>sql = "source C:\\My Dropbox\\workspace\\projects\\hosted_inv\\create_site_db.sql" cursor.execute (sql) </code></pre> <p>When I execute my program, I get the following error:</p> <blockquote> <p>Error 1064: You have an error in your SQL syntax; check the manual...
5
2009-12-19T07:52:15Z
1,932,307
<p>'source' is not an SQL command, but an internal command of the mysql command line client. </p>
3
2009-12-19T07:57:55Z
[ "python", "mysql", "scripting" ]
Can't get MySQL source query to work using Python mysqldb module
1,932,298
<p>I have the following lines of code:</p> <pre><code>sql = "source C:\\My Dropbox\\workspace\\projects\\hosted_inv\\create_site_db.sql" cursor.execute (sql) </code></pre> <p>When I execute my program, I get the following error:</p> <blockquote> <p>Error 1064: You have an error in your SQL syntax; check the manual...
5
2009-12-19T07:52:15Z
1,932,332
<p>The <code>source</code> command is one of the <a href="http://dev.mysql.com/doc/refman/5.1/en/mysql-commands.html" rel="nofollow">built-in commands</a> recognized only by the mysql command-line client. It is not supported as a statement you can execute via any API.</p> <p>Some people think you can simply split an ...
7
2009-12-19T08:07:37Z
[ "python", "mysql", "scripting" ]
Can't get MySQL source query to work using Python mysqldb module
1,932,298
<p>I have the following lines of code:</p> <pre><code>sql = "source C:\\My Dropbox\\workspace\\projects\\hosted_inv\\create_site_db.sql" cursor.execute (sql) </code></pre> <p>When I execute my program, I get the following error:</p> <blockquote> <p>Error 1064: You have an error in your SQL syntax; check the manual...
5
2009-12-19T07:52:15Z
1,932,336
<p>I believe the "source" command is specific to the mysql shell executable - it is not an sql command and cannot be interpreted correctly when executed as an sql statement.</p> <p>To achieve your goal, you probably need to read your script file and parse it into individual sql statements, then execute them one at a t...
1
2009-12-19T08:09:04Z
[ "python", "mysql", "scripting" ]
Can't get MySQL source query to work using Python mysqldb module
1,932,298
<p>I have the following lines of code:</p> <pre><code>sql = "source C:\\My Dropbox\\workspace\\projects\\hosted_inv\\create_site_db.sql" cursor.execute (sql) </code></pre> <p>When I execute my program, I get the following error:</p> <blockquote> <p>Error 1064: You have an error in your SQL syntax; check the manual...
5
2009-12-19T07:52:15Z
1,932,358
<p>As others said, you cannot use the command <code>source</code> in MySQLdb Python API</p> <p>So, instead of running that, load the file and execute it</p> <p>Lets say your .sql file has </p> <pre><code>create database test; </code></pre> <p>Read the content like </p> <pre><code>sql=open("test.sql").read() </code...
9
2009-12-19T08:27:17Z
[ "python", "mysql", "scripting" ]
Can't get MySQL source query to work using Python mysqldb module
1,932,298
<p>I have the following lines of code:</p> <pre><code>sql = "source C:\\My Dropbox\\workspace\\projects\\hosted_inv\\create_site_db.sql" cursor.execute (sql) </code></pre> <p>When I execute my program, I get the following error:</p> <blockquote> <p>Error 1064: You have an error in your SQL syntax; check the manual...
5
2009-12-19T07:52:15Z
2,577,137
<p>I ran into the same problem! </p> <p>As a solution I installed the library <a href="http://code.google.com/p/python-sqlparse/" rel="nofollow">sqlparse</a> and used the sqlparse.split( sql ) results. I had to check that sql_parts don't include blank lines as solo statements... Otherwise "WOW" sqlparse is pretty grea...
1
2010-04-05T06:08:56Z
[ "python", "mysql", "scripting" ]
Printing Lines in a File
1,932,491
<p>So here's the problem I have, </p> <p>I can find the Search Term in my file but at the moment I can only print out the line that the Search Term is in. (Thanks to Questions posted by people earlier =)). But I cannot print out all the lines to the end of the file after the Search Term. Here is the coding I have so f...
0
2009-12-19T09:50:03Z
1,932,513
<p>You could set a boolean flag, e.g. "found = True"; and do a check for found==True, and if so print the line.</p> <p>Code below:</p> <pre><code>search_term = r'\b%s\b' % search_term found = False; for line in open(f, 'r'): if found==True: print line, elif re.match(search_term, line): ...
0
2009-12-19T10:01:18Z
[ "python", "text", "printing" ]
Printing Lines in a File
1,932,491
<p>So here's the problem I have, </p> <p>I can find the Search Term in my file but at the moment I can only print out the line that the Search Term is in. (Thanks to Questions posted by people earlier =)). But I cannot print out all the lines to the end of the file after the Search Term. Here is the coding I have so f...
0
2009-12-19T09:50:03Z
1,932,529
<p>It can be much improved if you first compile the regex:</p> <pre><code>search_term_regex = re.compile(r'\b%s\b' % search_term) found = False for line in open(f): if not found: found = bool(search_term_regex.findall(line)) if found: print line, </code></pre> <p>Then you're not repeating the...
1
2009-12-19T10:08:56Z
[ "python", "text", "printing" ]
General questions regarding Python language
1,932,643
<p>I'm a newbie to programming and I've decided to start with Python. Just curious though, is it enough/recommended to learn Python from <a href="http://docs.python.org/tutorial/" rel="nofollow">online tutorials</a> or from books? I want to go further than simple "Hello World!" programs. I'm not sure if books will actu...
0
2009-12-19T11:16:27Z
1,932,644
<p>You study the EXIF format, study the GIF/JPEG format, open the binary file, scan it and get the data out.</p>
0
2009-12-19T11:17:41Z
[ "python" ]
General questions regarding Python language
1,932,643
<p>I'm a newbie to programming and I've decided to start with Python. Just curious though, is it enough/recommended to learn Python from <a href="http://docs.python.org/tutorial/" rel="nofollow">online tutorials</a> or from books? I want to go further than simple "Hello World!" programs. I'm not sure if books will actu...
0
2009-12-19T11:16:27Z
1,932,653
<p>Well, I learnt all my Python from online sources (not just tutorials, but reference documentation, blog posts and other texts). It's certainly possible, although some people prefer the "guided" way a book teaches you, particularly people new to programming (at that point I had already been programming for years).</p...
4
2009-12-19T11:20:58Z
[ "python" ]
General questions regarding Python language
1,932,643
<p>I'm a newbie to programming and I've decided to start with Python. Just curious though, is it enough/recommended to learn Python from <a href="http://docs.python.org/tutorial/" rel="nofollow">online tutorials</a> or from books? I want to go further than simple "Hello World!" programs. I'm not sure if books will actu...
0
2009-12-19T11:16:27Z
1,932,658
<p>There are a few very good online resources:</p> <ul> <li><p><a href="http://docs.python.org/tutorial/" rel="nofollow">The Python Tutorial</a>.</p></li> <li><p><a href="http://www.diveintopython.org/" rel="nofollow">Dive Into Python. Python from novice to pro.</a></p></li> <li><p><a href="http://python.net/~goodger/...
1
2009-12-19T11:22:16Z
[ "python" ]
General questions regarding Python language
1,932,643
<p>I'm a newbie to programming and I've decided to start with Python. Just curious though, is it enough/recommended to learn Python from <a href="http://docs.python.org/tutorial/" rel="nofollow">online tutorials</a> or from books? I want to go further than simple "Hello World!" programs. I'm not sure if books will actu...
0
2009-12-19T11:16:27Z
1,932,668
<p>The tutorials are there to teach you the language syntax and the standard library, not really on how to solve a particular programming problem. Think of what you learn there as your toolbox. </p> <p>I think I understand what you are saying. You want to break above and beyond the simple applications and write your o...
2
2009-12-19T11:25:52Z
[ "python" ]
General questions regarding Python language
1,932,643
<p>I'm a newbie to programming and I've decided to start with Python. Just curious though, is it enough/recommended to learn Python from <a href="http://docs.python.org/tutorial/" rel="nofollow">online tutorials</a> or from books? I want to go further than simple "Hello World!" programs. I'm not sure if books will actu...
0
2009-12-19T11:16:27Z
1,932,936
<p>If by '<em>newbie to programming</em>' you mean that you just started it last week or something along the lines, then maybe you might want to give the <a href="http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2008/LectureVideos/index.htm" rel="nofollow">MIT OpenCourseWare Introduction t...
2
2009-12-19T13:38:09Z
[ "python" ]
General questions regarding Python language
1,932,643
<p>I'm a newbie to programming and I've decided to start with Python. Just curious though, is it enough/recommended to learn Python from <a href="http://docs.python.org/tutorial/" rel="nofollow">online tutorials</a> or from books? I want to go further than simple "Hello World!" programs. I'm not sure if books will actu...
0
2009-12-19T11:16:27Z
1,932,961
<p>If stuff like recursion, modules, classes, iteration, exceptions, dictionaries, are indeed new to you, I suggest <a href="http://openbookproject.net/thinkcs/python/english2e/" rel="nofollow">How to Think Like a Computer Scientist in Python</a> (lovingly abbreviated as ThinkCSPy in the community ;-).</p> <p>It is a ...
2
2009-12-19T13:48:45Z
[ "python" ]
remove numbers from a list without changing total sum
1,932,657
<p>I have a list of numbers (example: <code>[-1, 1, -4, 5]</code>) and I have to remove numbers from the list without changing the total sum of the list. I want to remove the numbers with biggest absolute value possible, without changing the total, in the example removing <code>[-1, -4, 5]</code> will leave <code>[1]</...
7
2009-12-19T11:22:00Z
1,932,687
<p>if you redefine the problem as finding a subset whose sum equals the value of the complete set, you will realize that this is a NP-Hard problem, (<a href="http://en.wikipedia.org/wiki/Subset%5Fsum%5Fproblem" rel="nofollow">subset sum</a>) </p> <p>so there is no polynomial complexity solution for this problem . <...
11
2009-12-19T11:36:01Z
[ "python", "math", "sum", "combinations", "mathematical-optimization" ]
remove numbers from a list without changing total sum
1,932,657
<p>I have a list of numbers (example: <code>[-1, 1, -4, 5]</code>) and I have to remove numbers from the list without changing the total sum of the list. I want to remove the numbers with biggest absolute value possible, without changing the total, in the example removing <code>[-1, -4, 5]</code> will leave <code>[1]</...
7
2009-12-19T11:22:00Z
1,932,753
<p>I do not program in Python so my apologies for not offering code. But I think I can help with the algorithm:</p> <ol> <li>Find the sum</li> <li>Add numbers with the lowest value until you get to the same sum</li> <li>Everything else can be deleted</li> </ol> <p>I hope this helps</p>
0
2009-12-19T12:06:42Z
[ "python", "math", "sum", "combinations", "mathematical-optimization" ]
remove numbers from a list without changing total sum
1,932,657
<p>I have a list of numbers (example: <code>[-1, 1, -4, 5]</code>) and I have to remove numbers from the list without changing the total sum of the list. I want to remove the numbers with biggest absolute value possible, without changing the total, in the example removing <code>[-1, -4, 5]</code> will leave <code>[1]</...
7
2009-12-19T11:22:00Z
1,932,775
<p>Your requirements don't say if the function is allowed to change the list order or not. Here's a possibility:</p> <pre><code>def remove(items): items.sort() running = original = sum(items) try: items.index(original) # we just want the exception return [original] except ValueError: ...
0
2009-12-19T12:20:14Z
[ "python", "math", "sum", "combinations", "mathematical-optimization" ]
remove numbers from a list without changing total sum
1,932,657
<p>I have a list of numbers (example: <code>[-1, 1, -4, 5]</code>) and I have to remove numbers from the list without changing the total sum of the list. I want to remove the numbers with biggest absolute value possible, without changing the total, in the example removing <code>[-1, -4, 5]</code> will leave <code>[1]</...
7
2009-12-19T11:22:00Z
1,933,787
<pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright © 2009 Clóvis Fabrício Costa # Licensed under GPL version 3.0 or higher def posneg_calcsums(subset): sums = {} for group in chain.from_iterable(combinations(subset, n+1) for n in xrange(len(subset))): ...
4
2009-12-19T18:46:15Z
[ "python", "math", "sum", "combinations", "mathematical-optimization" ]
remove numbers from a list without changing total sum
1,932,657
<p>I have a list of numbers (example: <code>[-1, 1, -4, 5]</code>) and I have to remove numbers from the list without changing the total sum of the list. I want to remove the numbers with biggest absolute value possible, without changing the total, in the example removing <code>[-1, -4, 5]</code> will leave <code>[1]</...
7
2009-12-19T11:22:00Z
23,525,014
<p>This can be solved using integer programming. You can define a binary variable s_i for each of your list elements x_i and minimize \sum_i s_i, limited by the constraint that \sum_i (x_i*s_i) is equal to the original sum of your list.</p> <p>Here's an implementation using the <code>lpSolve</code> package in R:</p> ...
0
2014-05-07T18:03:37Z
[ "python", "math", "sum", "combinations", "mathematical-optimization" ]
Weblogic domain and cluster creation with WLST
1,933,000
<p>I want to create a cluster with 2 managed servers on 2 different physical machines.</p> <p>I have following tasks to be performed (please correct me if I miss something)</p> <ol> <li>Domain creation.</li> <li>Set admin server properties and create AdminServer under SSL</li> <li>Create logical machines for the phys...
3
2009-12-19T14:10:36Z
2,258,690
<p>I eventually found the answer. I am posting here for reference.</p> <p>Out of the 5 mentioned tasks, all can be performed with an offline wlst script. All of them have to be performed on the node where AdminServer is supposed to live.</p> <p>Now, for updating the domain information on the second node, there is an ...
5
2010-02-13T19:12:12Z
[ "python", "weblogic", "jython", "wlst" ]
Weblogic domain and cluster creation with WLST
1,933,000
<p>I want to create a cluster with 2 managed servers on 2 different physical machines.</p> <p>I have following tasks to be performed (please correct me if I miss something)</p> <ol> <li>Domain creation.</li> <li>Set admin server properties and create AdminServer under SSL</li> <li>Create logical machines for the phys...
3
2009-12-19T14:10:36Z
32,569,619
<p>There are two steps missed after the step 1, you need to copy the configuration from the machine where the AdminServer is running run to the other machine in the cluster using the command pack content in Weblogic installation:</p> <p>1.1 On the machine where the AdminServer is running run <code>./pack.shdomain=/hom...
0
2015-09-14T16:32:05Z
[ "python", "weblogic", "jython", "wlst" ]
How do you listen to notifications from iTunes on a Mac (Using the NSDistributedNotificationCenter)
1,933,107
<p>Looking for help/tutorials/sample code of using python to listen to <a href="http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSDistributedNotificationCenter%5FClass/Reference/Reference.html#//apple%5Fref/doc/uid/20000396-2831" rel="nofollow">distributed notifications</a> from ...
4
2009-12-19T14:59:38Z
1,936,087
<p>The source code for GrowlTunes might give you some clues here. You'd have to translate from Objective-C to PyObjC, but eh, whatever. :)</p> <p><a href="http://growl.info/hg/growl-development/file/4aa7c658ee1a/Extras/GrowlTunes/GrowlTunesController.m" rel="nofollow">GrowlTurnesController.m</a> (Or grab the whole gro...
4
2009-12-20T15:07:27Z
[ "python", "osx", "notifications", "pyobjc" ]
How do you listen to notifications from iTunes on a Mac (Using the NSDistributedNotificationCenter)
1,933,107
<p>Looking for help/tutorials/sample code of using python to listen to <a href="http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSDistributedNotificationCenter%5FClass/Reference/Reference.html#//apple%5Fref/doc/uid/20000396-2831" rel="nofollow">distributed notifications</a> from ...
4
2009-12-19T14:59:38Z
1,936,674
<p>If anyone comes by to this question, i figured out how to listen, the code below works. However accessing attributes do not seem to work like standard python attribute access. </p> <p>Update: you do not access attributes as you would in python i.e (.x), the code has been updated below, it now generates a dict cal...
10
2009-12-20T19:16:47Z
[ "python", "osx", "notifications", "pyobjc" ]
make python replace un-encodable chars with a string by default
1,933,184
<p>I want to make python ignore chars it can't encode, by simply replacing them with the string <code>"&lt;could not encode&gt;"</code>.</p> <p>E.g, assuming the default encoding is ascii, the command</p> <pre><code>'%s is the word'%'ébác' </code></pre> <p>would yield</p> <pre><code>'&lt;could not encode&gt;b&lt;...
6
2009-12-19T15:28:16Z
1,933,219
<p>The <a href="http://docs.python.org/library/stdtypes.html#str.encode"><code>str.encode</code></a> function takes an optional argument defining the error handling:</p> <pre><code>str.encode([encoding[, errors]]) </code></pre> <p>From the docs:</p> <blockquote> <p>Return an encoded version of the string. Default ...
11
2009-12-19T15:39:20Z
[ "python", "replace", "encode" ]
make python replace un-encodable chars with a string by default
1,933,184
<p>I want to make python ignore chars it can't encode, by simply replacing them with the string <code>"&lt;could not encode&gt;"</code>.</p> <p>E.g, assuming the default encoding is ascii, the command</p> <pre><code>'%s is the word'%'ébác' </code></pre> <p>would yield</p> <pre><code>'&lt;could not encode&gt;b&lt;...
6
2009-12-19T15:28:16Z
1,933,235
<pre><code>&gt;&gt;&gt; help("".encode) Help on built-in function encode: encode(...) S.encode([encoding[,errors]]) -&gt; object Encodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that ...
4
2009-12-19T15:45:28Z
[ "python", "replace", "encode" ]
Programmable transparent forward proxy
1,933,217
<p>I'm looking for a way to script a transparent forward proxy such as the ones that users point their browsers to in proxy settings.</p> <p>I've discovered a distinct tradeoff in forward proxies between scriptability and robustness. For example, their are countless proxies developed in <a href="http://github.com/why...
9
2009-12-19T15:37:27Z
1,933,255
<p>If you looking for a Perl solution then take a look at <a href="http://search.cpan.org/dist/HTTP-Proxy/" rel="nofollow"><code>HTTP::Proxy</code></a></p> <p>Not sure of any mod_perl solutions though. <a href="http://search.cpan.org" rel="nofollow">CPAN</a> does bring up <a href="http://search.cpan.org/dist/Apache-P...
2
2009-12-19T15:53:12Z
[ "python", "ruby", "perl", "apache", "proxy" ]
Programmable transparent forward proxy
1,933,217
<p>I'm looking for a way to script a transparent forward proxy such as the ones that users point their browsers to in proxy settings.</p> <p>I've discovered a distinct tradeoff in forward proxies between scriptability and robustness. For example, their are countless proxies developed in <a href="http://github.com/why...
9
2009-12-19T15:37:27Z
1,933,333
<p>I've been working on a HTTP library in python, written with proxy servers specifically in mind as a use case. It isn't very mature at this point (certainly needs more testing, and unit tests), but it's complete enough that I find it useful. I don't know if it would meet any of your needs or not. </p> <p>The libra...
2
2009-12-19T16:26:22Z
[ "python", "ruby", "perl", "apache", "proxy" ]
Programmable transparent forward proxy
1,933,217
<p>I'm looking for a way to script a transparent forward proxy such as the ones that users point their browsers to in proxy settings.</p> <p>I've discovered a distinct tradeoff in forward proxies between scriptability and robustness. For example, their are countless proxies developed in <a href="http://github.com/why...
9
2009-12-19T15:37:27Z
1,933,357
<p>Squid and Apache both have mechanisms to call external scripts for allow/deny decisions per-request. This allows you to use either for their proxy engines, but call your external script per request for processing of arbitrary complexity. Your code only has to manage the business logic, not the heavy lifting.</p>...
3
2009-12-19T16:34:08Z
[ "python", "ruby", "perl", "apache", "proxy" ]
Programmable transparent forward proxy
1,933,217
<p>I'm looking for a way to script a transparent forward proxy such as the ones that users point their browsers to in proxy settings.</p> <p>I've discovered a distinct tradeoff in forward proxies between scriptability and robustness. For example, their are countless proxies developed in <a href="http://github.com/why...
9
2009-12-19T15:37:27Z
1,933,403
<p>I'd use <a href="http://www.squid-cache.org/" rel="nofollow">squid</a>, which can execute other programs to change the requests on the fly.</p>
0
2009-12-19T16:46:01Z
[ "python", "ruby", "perl", "apache", "proxy" ]
I want to display name in front of field instead of
1,933,299
<p>..whatdoyoucallitanyway..</p> <p>I have this model:</p> <pre><code>class Kaart(models.Model): name = models.CharField(max_length=200, name="Kaardi peakiri", help_text="Sisesta kaardi pealkiri (maksimum tähemärkide arv on 38)", blank=False, null=False) url = models.CharField(max_length=200, blank=False, n...
1
2009-12-19T16:11:51Z
1,933,328
<p>You need to use <code>verbose_name</code> instead of <code>name</code> in your model.</p> <pre><code>name = models.CharField(max_length=200, verbose_name="Kaardi peakiri", help_text="Sisesta kaardi pealkiri (maksimum tähemärkide arv on 38)", blank=False, null=False) </code></pre> <p><a href="http://docs.djangopr...
14
2009-12-19T16:25:12Z
[ "python", "django", "django-forms" ]
I want to display name in front of field instead of
1,933,299
<p>..whatdoyoucallitanyway..</p> <p>I have this model:</p> <pre><code>class Kaart(models.Model): name = models.CharField(max_length=200, name="Kaardi peakiri", help_text="Sisesta kaardi pealkiri (maksimum tähemärkide arv on 38)", blank=False, null=False) url = models.CharField(max_length=200, blank=False, n...
1
2009-12-19T16:11:51Z
1,933,336
<p>According to <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#field-types" rel="nofollow">the documentation</a>, the <code>ModelForm</code>'s widget pulls its <code>label</code> value from the <code>verbose_name</code> attribute.</p>
0
2009-12-19T16:27:08Z
[ "python", "django", "django-forms" ]
Python - specify which function in file to use on command line
1,933,400
<p>Assume you have a programme with multiple functions defined. Each function is called in a separate for loop. Is it possible to specify which function should be called via the command line?</p> <p>Example:</p> <pre><code>python prog.py -x &lt;&lt;&lt;filname&gt;&gt;&gt; </code></pre> <p>Where -x tells python to go...
2
2009-12-19T16:45:29Z
1,933,407
<p>The Python idiom for the main entry point:</p> <pre><code>if __name__ == '__main__': main() </code></pre> <p>Replace <code>main()</code> by whatever function should go first ... (more on <code>if name ...</code>: <a href="http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm">http://effbot.org/pyfaq/tutor...
10
2009-12-19T16:47:32Z
[ "python", "command-line", "function" ]
Python - specify which function in file to use on command line
1,933,400
<p>Assume you have a programme with multiple functions defined. Each function is called in a separate for loop. Is it possible to specify which function should be called via the command line?</p> <p>Example:</p> <pre><code>python prog.py -x &lt;&lt;&lt;filname&gt;&gt;&gt; </code></pre> <p>Where -x tells python to go...
2
2009-12-19T16:45:29Z
1,933,422
<p>Yes, the built in functions 'exec()' and 'eval()' are your friends. Just add '()' to the name of the function. However, you should wonder whether this is the best solution for the actual problem. The fact that it is technically possible does not mean it is also the best solution. Using 'exec()' and 'eval()' is gener...
0
2009-12-19T16:50:40Z
[ "python", "command-line", "function" ]
Python - specify which function in file to use on command line
1,933,400
<p>Assume you have a programme with multiple functions defined. Each function is called in a separate for loop. Is it possible to specify which function should be called via the command line?</p> <p>Example:</p> <pre><code>python prog.py -x &lt;&lt;&lt;filname&gt;&gt;&gt; </code></pre> <p>Where -x tells python to go...
2
2009-12-19T16:45:29Z
1,933,436
<p>You want the <a href="http://www.faqs.org/docs/diveintopython/kgp%5Fcommandline.html"><code>sys</code></a> module.</p> <p>For example:</p> <pre><code>import sys #Functions def a(filename): pass def b(filename): pass def c(filename): pass #Function chooser func_arg = {"-a": a, "-b": b, "-c": c} #Do it if __name_...
6
2009-12-19T16:55:34Z
[ "python", "command-line", "function" ]
Python - specify which function in file to use on command line
1,933,400
<p>Assume you have a programme with multiple functions defined. Each function is called in a separate for loop. Is it possible to specify which function should be called via the command line?</p> <p>Example:</p> <pre><code>python prog.py -x &lt;&lt;&lt;filname&gt;&gt;&gt; </code></pre> <p>Where -x tells python to go...
2
2009-12-19T16:45:29Z
1,933,471
<p>If you just want to use this to quickly test different functions during development and similar situations, you can use the <code>-c</code> command line parameter:</p> <pre><code>python -c 'import myfile; myfile.somefunc()' </code></pre>
4
2009-12-19T17:03:06Z
[ "python", "command-line", "function" ]
Python - specify which function in file to use on command line
1,933,400
<p>Assume you have a programme with multiple functions defined. Each function is called in a separate for loop. Is it possible to specify which function should be called via the command line?</p> <p>Example:</p> <pre><code>python prog.py -x &lt;&lt;&lt;filname&gt;&gt;&gt; </code></pre> <p>Where -x tells python to go...
2
2009-12-19T16:45:29Z
1,933,495
<p>A very simple way is the following:</p> <pre><code>import sys x_is_set=False for arg in sys.argv[1:]: if arg == '-x': x_is_set=True if x_is_set: print "-x is set" </code></pre>
1
2009-12-19T17:07:30Z
[ "python", "command-line", "function" ]
Why should exec() and eval() be avoided?
1,933,451
<p>I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case. </p> <p>So, hopefully, one will be presented here. Why should we (at least, generally) not use <code>exec()</code> and <code>eval()</code>?</p> <p>EDIT: I see that people are assuming ...
18
2009-12-19T16:58:08Z
1,933,462
<p>Allowing these function in a context where they might run user input is a security issue, and sanitizers that actually work are hard to write.</p>
2
2009-12-19T17:01:40Z
[ "python" ]
Why should exec() and eval() be avoided?
1,933,451
<p>I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case. </p> <p>So, hopefully, one will be presented here. Why should we (at least, generally) not use <code>exec()</code> and <code>eval()</code>?</p> <p>EDIT: I see that people are assuming ...
18
2009-12-19T16:58:08Z
1,933,463
<pre><code>s = "import shutil; shutil.rmtree('/nonexisting')" eval(s) </code></pre> <p>Now assume somebody can control s from a web application, for example.</p> <p><strong>Don't try to do this on your computer</strong></p>
1
2009-12-19T17:01:51Z
[ "python" ]
Why should exec() and eval() be avoided?
1,933,451
<p>I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case. </p> <p>So, hopefully, one will be presented here. Why should we (at least, generally) not use <code>exec()</code> and <code>eval()</code>?</p> <p>EDIT: I see that people are assuming ...
18
2009-12-19T16:58:08Z
1,933,468
<p>Same reason you shouldn't login as root: it's too easy to shoot yourself in the foot.</p>
2
2009-12-19T17:02:46Z
[ "python" ]
Why should exec() and eval() be avoided?
1,933,451
<p>I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case. </p> <p>So, hopefully, one will be presented here. Why should we (at least, generally) not use <code>exec()</code> and <code>eval()</code>?</p> <p>EDIT: I see that people are assuming ...
18
2009-12-19T16:58:08Z
1,933,473
<p>Reason #1: One security flaw (ie. programming errors... and we can't claim those can be avoided) and you've just given the user access to the shell of the server.</p>
1
2009-12-19T17:03:15Z
[ "python" ]
Why should exec() and eval() be avoided?
1,933,451
<p>I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case. </p> <p>So, hopefully, one will be presented here. Why should we (at least, generally) not use <code>exec()</code> and <code>eval()</code>?</p> <p>EDIT: I see that people are assuming ...
18
2009-12-19T16:58:08Z
1,933,481
<p>There are often clearer, more direct ways to get the same effect. If you build a complex string and pass it to exec, the code is difficult to follow, and difficult to test. </p> <p>Example: I wrote code that read in string keys and values and set corresponding fields in an object. It looked like this: </p> <pre><c...
14
2009-12-19T17:04:00Z
[ "python" ]
Why should exec() and eval() be avoided?
1,933,451
<p>I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case. </p> <p>So, hopefully, one will be presented here. Why should we (at least, generally) not use <code>exec()</code> and <code>eval()</code>?</p> <p>EDIT: I see that people are assuming ...
18
2009-12-19T16:58:08Z
1,933,502
<p>Try this in the interactive interpreter and see what happens:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; eval('{"name" : %s}' % ("sys.exit(1)")) </code></pre> <p>Of course, this is a corner case, but it can be tricky to prevent things like this.</p>
1
2009-12-19T17:08:22Z
[ "python" ]
Why should exec() and eval() be avoided?
1,933,451
<p>I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case. </p> <p>So, hopefully, one will be presented here. Why should we (at least, generally) not use <code>exec()</code> and <code>eval()</code>?</p> <p>EDIT: I see that people are assuming ...
18
2009-12-19T16:58:08Z
1,933,525
<p>Security aside, <code>eval</code> and <code>exec</code> are often marked as undesirable because of the complexity they induce. When you see a <code>eval</code> call you often don't know what's really going on behind it, because it acts on data that's usually in a variable. This makes code harder to read.</p> <p>Inv...
8
2009-12-19T17:14:30Z
[ "python" ]