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
sequence
What is the best way to escape Python strings in PHP?
196,771
<p>I have a PHP application which needs to output a python script, more specifically a bunch of variable assignment statements, eg.</p> <pre><code>subject_prefix = 'This String From User Input' msg_footer = """This one too.""" </code></pre> <p>The contents of subject_prefix et al need to be written to take user input; as such, I need to escape the contents of the strings. Writing something like the following isn't going to cut it; we're stuffed as soon as someone uses a quote or newline or anything else that I'm not aware of that could be hazardous:</p> <pre><code>echo "subject_prefix = '".$subject_prefix."'\n"; </code></pre> <p>So. Any ideas?</p> <p>(Rewriting the app in Python isn't possible due to time constraints. :P )</p> <p><strong>Edit, years later:</strong></p> <p>This was for integration between a web-app (written in PHP) and Mailman (written in Python). I couldn't modify the install of the latter, so I needed to come up with a way to talk in its language to manage its configuration.</p> <p>This was also a <em>really</em> bad idea.</p>
2
2008-10-13T05:20:56Z
1,813,364
<p>I needed to code this to escape a string in the "ntriples" format, which uses <a href="http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals" rel="nofollow">python escaping</a>. </p> <p>The following function takes a utf-8 string and returns it escaped for python (or ntriples format). It may do odd things if given illegal utf-8 data. It doesn't understand about Unicode characters past xFFFF. It does not (currently) wrap the string in double quotes.</p> <p>The uniord function comes from a comment on php.net.</p> <pre><code> function python_string_escape( $string ) { $string = preg_replace( "/\\\\/", "\\\\", $string ); # \\ (first to avoid string re-escaping) $string = preg_replace( "/\n/", "\\n", $string ); # \n $string = preg_replace( "/\r/", "\\r", $string ); # \r $string = preg_replace( "/\t/", "\\t", $string ); # \t $string = preg_replace( "/\"/", "\\\"", $string ); # \" $string = preg_replace( "/([\x{00}-\x{1F}]|[\x{7F}-\x{FFFF}])/ue", "sprintf(\"\\u%04X\",uniord(\"$1\"))", $string ); return $string; } function uniord($c) { $h = ord($c{0}); if ($h &lt;= 0x7F) { return $h; } else if ($h &lt; 0xC2) { return false; } else if ($h &lt;= 0xDF) { return ($h &amp; 0x1F) &lt;&lt; 6 | (ord($c{1}) &amp; 0x3F); } else if ($h &lt;= 0xEF) { return ($h &amp; 0x0F) &lt;&lt; 12 | (ord($c{1}) &amp; 0x3F) &lt;&lt; 6 | (ord($c{2}) &amp; 0x3F); } else if ($h &lt;= 0xF4) { return ($h &amp; 0x0F) &lt;&lt; 18 | (ord($c{1}) &amp; 0x3F) &lt;&lt; 12 | (ord($c{2}) &amp; 0x3F) &lt;&lt; 6 | (ord($c{3}) &amp; 0x3F); } else { return false; } } </code></pre>
0
2009-11-28T18:47:35Z
[ "php", "python", "user-input" ]
Which AES library to use in Ruby/Python?
196,776
<p>I need to be able to send encrypted data between a Ruby client and a Python server (and vice versa) and have been having trouble with the <a href="http://rubyforge.org/projects/ruby-aes" rel="nofollow">ruby-aes</a> gem/library. The library is very easy to use but we've been having trouble passing data between it and the pyCrypto AES library for Python. These libraries seem to be fine when they're the only one being used, but they don't seem to play well across language boundaries. Any ideas?</p> <p>Edit: We're doing the communication over SOAP and have also tried converting the binary data to base64 to no avail. Also, it's more that the encryption/decryption is almost but not exactly the same between the two (e.g., the lengths differ by one or there is extra garbage characters on the end of the decrypted string)</p>
2
2008-10-13T05:25:29Z
196,794
<p>Kind of depends on how you are transferring the encrypted data. It is possible that you are writing a file in one language and then trying to read it in from the other. Python (especially on Windows) requires that you specify binary mode for binary files. So in Python, assuming you want to decrypt there, you should open the file like this:</p> <pre><code>f = open('/path/to/file', 'rb') </code></pre> <p>The "b" indicates binary. And if you are writing the encrypted data to file from Python:</p> <pre><code>f = open('/path/to/file', 'wb') f.write(encrypted_data) </code></pre>
1
2008-10-13T05:42:44Z
[ "python", "ruby", "encryption", "aes" ]
Which AES library to use in Ruby/Python?
196,776
<p>I need to be able to send encrypted data between a Ruby client and a Python server (and vice versa) and have been having trouble with the <a href="http://rubyforge.org/projects/ruby-aes" rel="nofollow">ruby-aes</a> gem/library. The library is very easy to use but we've been having trouble passing data between it and the pyCrypto AES library for Python. These libraries seem to be fine when they're the only one being used, but they don't seem to play well across language boundaries. Any ideas?</p> <p>Edit: We're doing the communication over SOAP and have also tried converting the binary data to base64 to no avail. Also, it's more that the encryption/decryption is almost but not exactly the same between the two (e.g., the lengths differ by one or there is extra garbage characters on the end of the decrypted string)</p>
2
2008-10-13T05:25:29Z
196,896
<p>It's hard to even guess at what's happening without more information ... </p> <p>If I were you, I'd check that in your Python and Ruby programs:</p> <ol> <li>The keys are the same (obviously). Dump them as hex and compare each byte.</li> <li>The initialization vectors are the same. This is the parameter <code>IV</code> in <code>AES.new()</code> in pyCrypto. Dump them as hex too.</li> <li>The modes are the same. The parameter <code>mode</code> in <code>AES.new()</code> in pyCrypto.</li> </ol> <p>There are defaults for <code>IV</code> and <code>mode</code> in pyCrypto, but don't trust that they are the same as in the Ruby implementation. Use one of the simpler modes, like CBC. I've found that different libraries have different interpretations of how the mode complex modes, such as PTR, work.</p> <p>Wikipedia has a great article about how <a href="http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation" rel="nofollow">block cipher modes</a>.</p>
2
2008-10-13T07:05:19Z
[ "python", "ruby", "encryption", "aes" ]
Which AES library to use in Ruby/Python?
196,776
<p>I need to be able to send encrypted data between a Ruby client and a Python server (and vice versa) and have been having trouble with the <a href="http://rubyforge.org/projects/ruby-aes" rel="nofollow">ruby-aes</a> gem/library. The library is very easy to use but we've been having trouble passing data between it and the pyCrypto AES library for Python. These libraries seem to be fine when they're the only one being used, but they don't seem to play well across language boundaries. Any ideas?</p> <p>Edit: We're doing the communication over SOAP and have also tried converting the binary data to base64 to no avail. Also, it's more that the encryption/decryption is almost but not exactly the same between the two (e.g., the lengths differ by one or there is extra garbage characters on the end of the decrypted string)</p>
2
2008-10-13T05:25:29Z
196,905
<p>Turns out what happened was that ruby-aes automatically pads data to fill up 16 chars and sticks a null character on the end of the final string as a delimiter. PyCrypto requires you to do multiples of 16 chars so that was how we figured out what ruby-aes was doing.</p>
3
2008-10-13T07:17:02Z
[ "python", "ruby", "encryption", "aes" ]
Which AES library to use in Ruby/Python?
196,776
<p>I need to be able to send encrypted data between a Ruby client and a Python server (and vice versa) and have been having trouble with the <a href="http://rubyforge.org/projects/ruby-aes" rel="nofollow">ruby-aes</a> gem/library. The library is very easy to use but we've been having trouble passing data between it and the pyCrypto AES library for Python. These libraries seem to be fine when they're the only one being used, but they don't seem to play well across language boundaries. Any ideas?</p> <p>Edit: We're doing the communication over SOAP and have also tried converting the binary data to base64 to no avail. Also, it's more that the encryption/decryption is almost but not exactly the same between the two (e.g., the lengths differ by one or there is extra garbage characters on the end of the decrypted string)</p>
2
2008-10-13T05:25:29Z
197,520
<p>Basically what Hugh said above: check the IV's, key sizes and the chaining modes to make sure everything is identical.</p> <p>Test both sides independantly, encode some information and check that Ruby and Python endoded it identically. You're assuming that the problem has to do with encryption, but it may just be something as simple as sending the encrypted data with <code>puts</code> which throws random newlines into the data. Once you're sure they encrypt the data correctly, check that you receive exactly what you think you sent. Keep going step by step until you find the stage that corrupts the data.</p> <p>Also, I'd suggest using the openssl library that's included in ruby's standard library instead of using an external gem.</p>
1
2008-10-13T13:01:08Z
[ "python", "ruby", "encryption", "aes" ]
Which AES library to use in Ruby/Python?
196,776
<p>I need to be able to send encrypted data between a Ruby client and a Python server (and vice versa) and have been having trouble with the <a href="http://rubyforge.org/projects/ruby-aes" rel="nofollow">ruby-aes</a> gem/library. The library is very easy to use but we've been having trouble passing data between it and the pyCrypto AES library for Python. These libraries seem to be fine when they're the only one being used, but they don't seem to play well across language boundaries. Any ideas?</p> <p>Edit: We're doing the communication over SOAP and have also tried converting the binary data to base64 to no avail. Also, it's more that the encryption/decryption is almost but not exactly the same between the two (e.g., the lengths differ by one or there is extra garbage characters on the end of the decrypted string)</p>
2
2008-10-13T05:25:29Z
197,547
<blockquote> <p>(e.g., the lengths differ by one or there is extra garbage characters on the end of the decrypted string)</p> </blockquote> <p>I missed that bit. There's nothing wrong with your encryption/decryption. It sounds like a padding problem. AES always encodes data in blocks of 128 bits. If the length of your data isn't a multiple of 128 bits the data should be padded before encryption and the padding needs to be removed/ignored after encryption.</p>
5
2008-10-13T13:12:42Z
[ "python", "ruby", "encryption", "aes" ]
How do I emulate Python's named printf parameters in Ruby?
196,841
<p>In Python, you can do this:</p> <pre><code>print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30}) </code></pre> <p>What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.)</p> <p><strong>EDIT:</strong> One of the really excellent benefits of this is that you can store the pre-processed string in a variable and use it as a "template", like so:</p> <pre><code>template = "Hi! I'm %(name)s, and I'm %(age)d years old." def greet(template,name,age): print template % ({"name":name,"age":age}) </code></pre> <p>This is obviously a trivial example, but there is a lot of utility in being able to store such a string for later use. Ruby's <code>"Hi! I'm #{name}"</code> convention is cursorily similar, but the immediate evaluation makes it less versatile.</p> <p>Please don't downvote answers suggesting the <code>#{var}</code> technique, as they came from before this edit. (Random idea kernel: Perhaps answers should be protected from votes if a question author marks them as "outdated"...?)</p>
8
2008-10-13T06:25:29Z
196,847
<p>In a double-quoted string in Ruby, you can insert the result of a Ruby expression like this:</p> <pre><code>puts "Hi! I'm #{name}, and I'm #{age} years old." </code></pre> <p>Just put an expression inside the curly braces. (It could also be something more complex like #{age + 5}, or #{name + ' ' + last_name}, or a function call.)</p>
2
2008-10-13T06:31:22Z
[ "python", "ruby", "string", "printf" ]
How do I emulate Python's named printf parameters in Ruby?
196,841
<p>In Python, you can do this:</p> <pre><code>print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30}) </code></pre> <p>What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.)</p> <p><strong>EDIT:</strong> One of the really excellent benefits of this is that you can store the pre-processed string in a variable and use it as a "template", like so:</p> <pre><code>template = "Hi! I'm %(name)s, and I'm %(age)d years old." def greet(template,name,age): print template % ({"name":name,"age":age}) </code></pre> <p>This is obviously a trivial example, but there is a lot of utility in being able to store such a string for later use. Ruby's <code>"Hi! I'm #{name}"</code> convention is cursorily similar, but the immediate evaluation makes it less versatile.</p> <p>Please don't downvote answers suggesting the <code>#{var}</code> technique, as they came from before this edit. (Random idea kernel: Perhaps answers should be protected from votes if a question author marks them as "outdated"...?)</p>
8
2008-10-13T06:25:29Z
196,850
<p>puts "Hi! I'm #{name}, and I'm #{age} years old."</p>
0
2008-10-13T06:31:53Z
[ "python", "ruby", "string", "printf" ]
How do I emulate Python's named printf parameters in Ruby?
196,841
<p>In Python, you can do this:</p> <pre><code>print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30}) </code></pre> <p>What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.)</p> <p><strong>EDIT:</strong> One of the really excellent benefits of this is that you can store the pre-processed string in a variable and use it as a "template", like so:</p> <pre><code>template = "Hi! I'm %(name)s, and I'm %(age)d years old." def greet(template,name,age): print template % ({"name":name,"age":age}) </code></pre> <p>This is obviously a trivial example, but there is a lot of utility in being able to store such a string for later use. Ruby's <code>"Hi! I'm #{name}"</code> convention is cursorily similar, but the immediate evaluation makes it less versatile.</p> <p>Please don't downvote answers suggesting the <code>#{var}</code> technique, as they came from before this edit. (Random idea kernel: Perhaps answers should be protected from votes if a question author marks them as "outdated"...?)</p>
8
2008-10-13T06:25:29Z
196,854
<p>There are some nice trick to this in Ruby:</p> <pre><code>name = "Peter" @age = 15 # instance variable puts "Hi, you are #{name} and your age is #@age" </code></pre>
6
2008-10-13T06:34:09Z
[ "python", "ruby", "string", "printf" ]
How do I emulate Python's named printf parameters in Ruby?
196,841
<p>In Python, you can do this:</p> <pre><code>print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30}) </code></pre> <p>What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.)</p> <p><strong>EDIT:</strong> One of the really excellent benefits of this is that you can store the pre-processed string in a variable and use it as a "template", like so:</p> <pre><code>template = "Hi! I'm %(name)s, and I'm %(age)d years old." def greet(template,name,age): print template % ({"name":name,"age":age}) </code></pre> <p>This is obviously a trivial example, but there is a lot of utility in being able to store such a string for later use. Ruby's <code>"Hi! I'm #{name}"</code> convention is cursorily similar, but the immediate evaluation makes it less versatile.</p> <p>Please don't downvote answers suggesting the <code>#{var}</code> technique, as they came from before this edit. (Random idea kernel: Perhaps answers should be protected from votes if a question author marks them as "outdated"...?)</p>
8
2008-10-13T06:25:29Z
198,795
<pre><code> class Template def %(h) "Hi! I'm #{h[:name]}s, and I'm #{h[:age]}d years old." end end </code></pre> <p>Then call it with </p> <pre><code>t=Template.new t%({:name =&gt; "Peter", :age =&gt; 18}) </code></pre> <p>This is not exactly what you asked for but could give you a hint.</p>
3
2008-10-13T19:47:39Z
[ "python", "ruby", "string", "printf" ]
How do I emulate Python's named printf parameters in Ruby?
196,841
<p>In Python, you can do this:</p> <pre><code>print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30}) </code></pre> <p>What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.)</p> <p><strong>EDIT:</strong> One of the really excellent benefits of this is that you can store the pre-processed string in a variable and use it as a "template", like so:</p> <pre><code>template = "Hi! I'm %(name)s, and I'm %(age)d years old." def greet(template,name,age): print template % ({"name":name,"age":age}) </code></pre> <p>This is obviously a trivial example, but there is a lot of utility in being able to store such a string for later use. Ruby's <code>"Hi! I'm #{name}"</code> convention is cursorily similar, but the immediate evaluation makes it less versatile.</p> <p>Please don't downvote answers suggesting the <code>#{var}</code> technique, as they came from before this edit. (Random idea kernel: Perhaps answers should be protected from votes if a question author marks them as "outdated"...?)</p>
8
2008-10-13T06:25:29Z
12,562,639
<p>What works (meanwhile), though, is something along the lines of:</p> <pre><code>d = {"key1" =&gt; "value1", "key2" =&gt; "value2"} s = "string to be magically induced with variables, which are \n * %s and \n * %s.\n" print s%d.values() # or print s%[d["key1"], d["key2"]] </code></pre>
2
2012-09-24T09:55:50Z
[ "python", "ruby", "string", "printf" ]
How do I emulate Python's named printf parameters in Ruby?
196,841
<p>In Python, you can do this:</p> <pre><code>print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30}) </code></pre> <p>What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.)</p> <p><strong>EDIT:</strong> One of the really excellent benefits of this is that you can store the pre-processed string in a variable and use it as a "template", like so:</p> <pre><code>template = "Hi! I'm %(name)s, and I'm %(age)d years old." def greet(template,name,age): print template % ({"name":name,"age":age}) </code></pre> <p>This is obviously a trivial example, but there is a lot of utility in being able to store such a string for later use. Ruby's <code>"Hi! I'm #{name}"</code> convention is cursorily similar, but the immediate evaluation makes it less versatile.</p> <p>Please don't downvote answers suggesting the <code>#{var}</code> technique, as they came from before this edit. (Random idea kernel: Perhaps answers should be protected from votes if a question author marks them as "outdated"...?)</p>
8
2008-10-13T06:25:29Z
12,563,022
<p>You can also use </p> <pre><code>printf "1: %&lt;key1&gt;s 2: %&lt;key2&gt;s\n", {:key1 =&gt; "value1", :key2 =&gt; "value2"} </code></pre> <p>or</p> <pre><code>data = {:key1 =&gt; "value1", :key2 =&gt; "value2"} printf "1: %&lt;key1&gt;s 2: %&lt;key2&gt;s\n", data </code></pre> <p>or (this needs ruby 1.9, for the other examples I'm not sure)</p> <pre><code>data = {key1: "value1", key2: "value2"} printf "1: %&lt;key1&gt;s 2: %&lt;key2&gt;s\n", data </code></pre> <p>This prints</p> <pre><code>1: value1 2: value2 </code></pre> <p>Important restriction: The used keys of the hash (<em>data</em> in my example) must be symbols.</p> <hr> <p>A remark on the example above: <code>printf</code> takes one format string and optional parameters. But there is also a <code>String#%</code>-method.</p> <p>The following four calls have all the same result:</p> <pre><code>printf "1: %&lt;key1&gt;s 2: %&lt;key2&gt;s\n" , {:key1 =&gt; "value1", :key2 =&gt; "value2"} printf "1: %&lt;key1&gt;s 2: %&lt;key2&gt;s\n" % {:key1 =&gt; "value1", :key2 =&gt; "value2"} print "1: %&lt;key1&gt;s 2: %&lt;key2&gt;s\n" % {:key1 =&gt; "value1", :key2 =&gt; "value2"} puts "1: %&lt;key1&gt;s 2: %&lt;key2&gt;s" % {:key1 =&gt; "value1", :key2 =&gt; "value2"} </code></pre> <p>The second version uses first the <code>String#%</code>-method and sends the result to <code>printf</code>.</p>
14
2012-09-24T10:19:55Z
[ "python", "ruby", "string", "printf" ]
How do I emulate Python's named printf parameters in Ruby?
196,841
<p>In Python, you can do this:</p> <pre><code>print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30}) </code></pre> <p>What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.)</p> <p><strong>EDIT:</strong> One of the really excellent benefits of this is that you can store the pre-processed string in a variable and use it as a "template", like so:</p> <pre><code>template = "Hi! I'm %(name)s, and I'm %(age)d years old." def greet(template,name,age): print template % ({"name":name,"age":age}) </code></pre> <p>This is obviously a trivial example, but there is a lot of utility in being able to store such a string for later use. Ruby's <code>"Hi! I'm #{name}"</code> convention is cursorily similar, but the immediate evaluation makes it less versatile.</p> <p>Please don't downvote answers suggesting the <code>#{var}</code> technique, as they came from before this edit. (Random idea kernel: Perhaps answers should be protected from votes if a question author marks them as "outdated"...?)</p>
8
2008-10-13T06:25:29Z
13,027,855
<p>you do it like this:</p> <pre><code>values = {:hello =&gt; 'world', :world =&gt; 'hello'} puts "%{world} %{hello}" % values </code></pre> <p>Read this for more info: <a href="http://ruby.runpaint.org/strings#sprintf-hash">http://ruby.runpaint.org/strings#sprintf-hash</a></p> <p>If you need something more sophisticated, read about ERB, and google template engines. If you need to generate web pages, emails etc. you'll find that using template engines is a more robust solution.</p>
14
2012-10-23T09:53:41Z
[ "python", "ruby", "string", "printf" ]
How to ensure user submit only english text
196,924
<p>I am building a project involving natural language processing, since the nlp module currently only deal with english text, so I have to make sure the user submitted content (not long, only several words) is in english. Are there established ways to achieve this? Python or Javascript way preferred.</p>
9
2008-10-13T07:32:12Z
196,940
<p>You could break the phrase up into words and check a dictionary (there are some that you can download, <a href="http://wordlist.sourceforge.net/" rel="nofollow">this</a> may be of interest), but that would require that the dictionary you used was good enough.</p> <p>It would also fall over for proper nouns (my name isn't in the dictionary for example).</p>
0
2008-10-13T07:39:52Z
[ "javascript", "python", "nlp" ]
How to ensure user submit only english text
196,924
<p>I am building a project involving natural language processing, since the nlp module currently only deal with english text, so I have to make sure the user submitted content (not long, only several words) is in english. Are there established ways to achieve this? Python or Javascript way preferred.</p>
9
2008-10-13T07:32:12Z
196,950
<p>If the content is long enough I would suggest some <a href="http://en.wikipedia.org/wiki/Frequency_analysis" rel="nofollow">frequency analysis</a> on the letters. </p> <p>But for a few words I think your best bet is to compare them to an English dictionary and accept the input if half of them match.</p>
7
2008-10-13T07:47:57Z
[ "javascript", "python", "nlp" ]
How to ensure user submit only english text
196,924
<p>I am building a project involving natural language processing, since the nlp module currently only deal with english text, so I have to make sure the user submitted content (not long, only several words) is in english. Are there established ways to achieve this? Python or Javascript way preferred.</p>
9
2008-10-13T07:32:12Z
196,956
<p>Try:</p> <p><a href="http://wordlist.sourceforge.net/" rel="nofollow">http://wordlist.sourceforge.net/</a></p> <p>For a list of English words.</p> <p>You will need to be careful of names, e.g. "Canberra" or "Bill Clinton". These won't appear in the word list. I suggest just checking whether the first letter is capitalized as a first attempt.</p>
1
2008-10-13T07:52:22Z
[ "javascript", "python", "nlp" ]
How to ensure user submit only english text
196,924
<p>I am building a project involving natural language processing, since the nlp module currently only deal with english text, so I have to make sure the user submitted content (not long, only several words) is in english. Are there established ways to achieve this? Python or Javascript way preferred.</p>
9
2008-10-13T07:32:12Z
196,967
<p>I think the most effective way would be to ask the users to submit english text only :)</p> <p>You can show a language selection drop-down over your text area with English/ Other as the options. When user selects "Other", disable the text area with a message that only English language is supported [at the moment].</p>
5
2008-10-13T07:58:58Z
[ "javascript", "python", "nlp" ]
How to ensure user submit only english text
196,924
<p>I am building a project involving natural language processing, since the nlp module currently only deal with english text, so I have to make sure the user submitted content (not long, only several words) is in english. Are there established ways to achieve this? Python or Javascript way preferred.</p>
9
2008-10-13T07:32:12Z
196,974
<p>Check the <a href="http://en.wikipedia.org/wiki/Wikipedia%3aLanguage_recognition_chart" rel="nofollow">Language Recognition Chart</a> </p>
6
2008-10-13T08:05:26Z
[ "javascript", "python", "nlp" ]
How to ensure user submit only english text
196,924
<p>I am building a project involving natural language processing, since the nlp module currently only deal with english text, so I have to make sure the user submitted content (not long, only several words) is in english. Are there established ways to achieve this? Python or Javascript way preferred.</p>
9
2008-10-13T07:32:12Z
197,001
<p>Try n-gram based statistical language recognition. This is a <a href="http://odur.let.rug.nl/~vannoord/TextCat/Demo/" rel="nofollow">link</a> to a demo of an algorithm using this technique, there is also a link to a paper describing the algorithm there. Try the demo, it performs quite well even on very short texts (3-4 words).</p>
3
2008-10-13T08:22:49Z
[ "javascript", "python", "nlp" ]
How to ensure user submit only english text
196,924
<p>I am building a project involving natural language processing, since the nlp module currently only deal with english text, so I have to make sure the user submitted content (not long, only several words) is in english. Are there established ways to achieve this? Python or Javascript way preferred.</p>
9
2008-10-13T07:32:12Z
197,064
<p>You are already doing NLP, if your module doesn't understand what language the text was then either the module doesn't work or the input was not in the correct language.</p>
3
2008-10-13T09:05:29Z
[ "javascript", "python", "nlp" ]
How to ensure user submit only english text
196,924
<p>I am building a project involving natural language processing, since the nlp module currently only deal with english text, so I have to make sure the user submitted content (not long, only several words) is in english. Are there established ways to achieve this? Python or Javascript way preferred.</p>
9
2008-10-13T07:32:12Z
197,074
<p>The <a href="http://en.design-noir.de/mozilla/dictionary-switcher/" rel="nofollow" title="Dictionary Switcher">Dictionary Switcher</a> Firefox extensions has an option to detect the right dictionary as I type.<br /> I guess it checks words against the installed dictionaries, and selects the one giving the less errors...</p> <p>You can't expect all words of the text to be in the dictionary: abbreviations, proper nouns, typos... Beside, some words are common to several languages: a French rock group even made the titles of their disks to have a (different) meaning both in French and in English. So it is a statistical thing: if more than x% of words are found in a good English dictionary, chances are the user types in this language (even if there are mistakes, like probably in this answer, since I am not native English).</p>
0
2008-10-13T09:10:41Z
[ "javascript", "python", "nlp" ]
How to ensure user submit only english text
196,924
<p>I am building a project involving natural language processing, since the nlp module currently only deal with english text, so I have to make sure the user submitted content (not long, only several words) is in english. Are there established ways to achieve this? Python or Javascript way preferred.</p>
9
2008-10-13T07:32:12Z
197,922
<p>Google has a javascript API that has an implementation of language detection. I've only play tested with it, never used it in production.</p> <p><a href="http://code.google.com/apis/ajaxlanguage/documentation/#Detect" rel="nofollow">http://code.google.com/apis/ajaxlanguage/documentation/#Detect</a></p>
5
2008-10-13T15:10:05Z
[ "javascript", "python", "nlp" ]
How to ensure user submit only english text
196,924
<p>I am building a project involving natural language processing, since the nlp module currently only deal with english text, so I have to make sure the user submitted content (not long, only several words) is in english. Are there established ways to achieve this? Python or Javascript way preferred.</p>
9
2008-10-13T07:32:12Z
1,144,727
<p>Maybe "<a href="http://valums.com/a/" rel="nofollow">Ensuring that the user submits only English text [PHP]</a>" article will help you. The code is written in PHP, but is small enough to be easily rewritten.</p>
0
2009-07-17T17:40:45Z
[ "javascript", "python", "nlp" ]
How to check if OS is Vista in Python?
196,930
<p>How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and <a href="http://python.net/crew/mhammond/win32/Downloads.html">pywin32</a> or <a href="http://www.wxpython.org/">wxPython</a>?</p> <p>Essentially, I need a function that called will return True iff current OS is Vista:</p> <pre><code>&gt;&gt;&gt; isWindowsVista() True </code></pre>
24
2008-10-13T07:35:14Z
196,931
<p>The simplest solution I found is this one:</p> <pre><code>import sys def isWindowsVista(): '''Return True iff current OS is Windows Vista.''' if sys.platform != "win32": return False import win32api VER_NT_WORKSTATION = 1 version = win32api.GetVersionEx(1) if not version or len(version) &lt; 9: return False return ((version[0] == 6) and (version[1] == 0) and (version[8] == VER_NT_WORKSTATION)) </code></pre>
8
2008-10-13T07:35:25Z
[ "python", "windows", "windows-vista", "wxpython", "pywin32" ]
How to check if OS is Vista in Python?
196,930
<p>How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and <a href="http://python.net/crew/mhammond/win32/Downloads.html">pywin32</a> or <a href="http://www.wxpython.org/">wxPython</a>?</p> <p>Essentially, I need a function that called will return True iff current OS is Vista:</p> <pre><code>&gt;&gt;&gt; isWindowsVista() True </code></pre>
24
2008-10-13T07:35:14Z
196,962
<p>The solution used in Twisted, which doesn't need pywin32:</p> <pre><code>def isVista(): if getattr(sys, "getwindowsversion", None) is not None: return sys.getwindowsversion()[0] == 6 else: return False </code></pre> <p>Note that it will also match Windows Server 2008.</p>
8
2008-10-13T07:55:47Z
[ "python", "windows", "windows-vista", "wxpython", "pywin32" ]
How to check if OS is Vista in Python?
196,930
<p>How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and <a href="http://python.net/crew/mhammond/win32/Downloads.html">pywin32</a> or <a href="http://www.wxpython.org/">wxPython</a>?</p> <p>Essentially, I need a function that called will return True iff current OS is Vista:</p> <pre><code>&gt;&gt;&gt; isWindowsVista() True </code></pre>
24
2008-10-13T07:35:14Z
200,148
<p>Python has the lovely 'platform' module to help you out.</p> <pre><code>&gt;&gt;&gt; import platform &gt;&gt;&gt; platform.win32_ver() ('XP', '5.1.2600', 'SP2', 'Multiprocessor Free') &gt;&gt;&gt; platform.system() 'Windows' &gt;&gt;&gt; platform.version() '5.1.2600' &gt;&gt;&gt; platform.release() 'XP' </code></pre> <p>NOTE: As mentioned in the comments proper values may not be returned when using older versions of python.</p>
39
2008-10-14T06:10:23Z
[ "python", "windows", "windows-vista", "wxpython", "pywin32" ]
How to check if OS is Vista in Python?
196,930
<p>How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and <a href="http://python.net/crew/mhammond/win32/Downloads.html">pywin32</a> or <a href="http://www.wxpython.org/">wxPython</a>?</p> <p>Essentially, I need a function that called will return True iff current OS is Vista:</p> <pre><code>&gt;&gt;&gt; isWindowsVista() True </code></pre>
24
2008-10-13T07:35:14Z
17,010,604
<p>An idea from <a href="http://www.brunningonline.net/simon/blog/archives/winGuiAuto.py.html" rel="nofollow">http://www.brunningonline.net/simon/blog/archives/winGuiAuto.py.html</a> might help, which can basically answer your question:</p> <pre><code>win_version = {4: "NT", 5: "2K", 6: "XP"}[os.sys.getwindowsversion()[0]] print "win_version=", win_version </code></pre>
0
2013-06-09T14:24:42Z
[ "python", "windows", "windows-vista", "wxpython", "pywin32" ]
Can you list the keyword arguments a Python function receives?
196,960
<p>I have a dict, which I need to pass key/values as keyword arguments.. For example..</p> <pre><code>d_args = {'kw1': 'value1', 'kw2': 'value2'} example(**d_args) </code></pre> <p>This works fine, <em>but</em> if there are values in the d_args dict that are not accepted by the <code>example</code> function, it obviously dies.. Say, if the example function is defined as <code>def example(kw2):</code></p> <p>This is a problem since I don't control either the generation of the <code>d_args</code>, or the <code>example</code> function.. They both come from external modules, and <code>example</code> only accepts some of the keyword-arguments from the dict..</p> <p>Ideally I would just do</p> <pre><code>parsed_kwargs = feedparser.parse(the_url) valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2) PyRSS2Gen.RSS2(**valid_kwargs) </code></pre> <p>I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: <strong>Is there a way to programatically list the keyword arguments the a specific function takes?</strong></p>
64
2008-10-13T07:55:18Z
196,978
<p>This will print names of all passable arguments, keyword and non-keyword ones:</p> <pre><code>def func(one, two="value"): y = one, two return y print func.func_code.co_varnames[:func.func_code.co_argcount] </code></pre> <p>This is because first <code>co_varnames</code> are always parameters (next are local variables, like <code>y</code> in the example above).</p> <p>So now you could have a function:</p> <pre><code>def getValidArgs(func, argsDict): '''Return dictionary without invalid function arguments.''' validArgs = func.func_code.co_varnames[:func.func_code.co_argcount] return dict((key, value) for key, value in argsDict.iteritems() if key in validArgs) </code></pre> <p>Which you then could use like this:</p> <pre><code>&gt;&gt;&gt; func(**getValidArgs(func, args)) </code></pre> <p><hr></p> <p><strong>EDIT</strong>: A small addition: if you <strong>really need only keyword arguments</strong> of a function, you can use the <code>func_defaults</code> attribute to extract them:</p> <pre><code>def getValidKwargs(func, argsDict): validArgs = func.func_code.co_varnames[:func.func_code.co_argcount] kwargsLen = len(func.func_defaults) # number of keyword arguments validKwargs = validArgs[-kwargsLen:] # because kwargs are last return dict((key, value) for key, value in argsDict.iteritems() if key in validKwargs) </code></pre> <p>You could now call your function with known args, but extracted kwargs, e.g.:</p> <pre><code>func(param1, param2, **getValidKwargs(func, kwargsDict)) </code></pre> <p>This assumes that <code>func</code> uses no <code>*args</code> or <code>**kwargs</code> magic in its signature.</p>
25
2008-10-13T08:09:15Z
[ "python", "arguments", "introspection" ]
Can you list the keyword arguments a Python function receives?
196,960
<p>I have a dict, which I need to pass key/values as keyword arguments.. For example..</p> <pre><code>d_args = {'kw1': 'value1', 'kw2': 'value2'} example(**d_args) </code></pre> <p>This works fine, <em>but</em> if there are values in the d_args dict that are not accepted by the <code>example</code> function, it obviously dies.. Say, if the example function is defined as <code>def example(kw2):</code></p> <p>This is a problem since I don't control either the generation of the <code>d_args</code>, or the <code>example</code> function.. They both come from external modules, and <code>example</code> only accepts some of the keyword-arguments from the dict..</p> <p>Ideally I would just do</p> <pre><code>parsed_kwargs = feedparser.parse(the_url) valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2) PyRSS2Gen.RSS2(**valid_kwargs) </code></pre> <p>I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: <strong>Is there a way to programatically list the keyword arguments the a specific function takes?</strong></p>
64
2008-10-13T07:55:18Z
196,997
<p>Extending DzinX's answer:</p> <pre><code>argnames = example.func_code.co_varnames[:func.func_code.co_argcount] args = dict((key, val) for key,val in d_args.iteritems() if key in argnames) example(**args) </code></pre>
3
2008-10-13T08:20:20Z
[ "python", "arguments", "introspection" ]
Can you list the keyword arguments a Python function receives?
196,960
<p>I have a dict, which I need to pass key/values as keyword arguments.. For example..</p> <pre><code>d_args = {'kw1': 'value1', 'kw2': 'value2'} example(**d_args) </code></pre> <p>This works fine, <em>but</em> if there are values in the d_args dict that are not accepted by the <code>example</code> function, it obviously dies.. Say, if the example function is defined as <code>def example(kw2):</code></p> <p>This is a problem since I don't control either the generation of the <code>d_args</code>, or the <code>example</code> function.. They both come from external modules, and <code>example</code> only accepts some of the keyword-arguments from the dict..</p> <p>Ideally I would just do</p> <pre><code>parsed_kwargs = feedparser.parse(the_url) valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2) PyRSS2Gen.RSS2(**valid_kwargs) </code></pre> <p>I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: <strong>Is there a way to programatically list the keyword arguments the a specific function takes?</strong></p>
64
2008-10-13T07:55:18Z
197,053
<p>A little nicer than inspecting the code object directly and working out the variables is to use the inspect module.</p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; def func(a,b,c=42, *args, **kwargs): pass &gt;&gt;&gt; inspect.getargspec(func) (['a', 'b', 'c'], 'args', 'kwargs', (42,)) </code></pre> <p>If you want to know if its callable with a particular set of args, you need the args without a default already specified. These can be got by:</p> <pre><code>def getRequiredArgs(func): args, varargs, varkw, defaults = inspect.getargspec(func) if defaults: args = args[:-len(defaults)] return args # *args and **kwargs are not required, so ignore them. </code></pre> <p>Then a function to tell what you are missing from your particular dict is:</p> <pre><code>def missingArgs(func, argdict): return set(getRequiredArgs(func)).difference(argdict) </code></pre> <p>Similarly, to check for invalid args, use:</p> <pre><code>def invalidArgs(func, argdict): args, varargs, varkw, defaults = inspect.getargspec(func) if varkw: return set() # All accepted return set(argdict) - set(args) </code></pre> <p>And so a full test if it is callable is :</p> <pre><code>def isCallableWithArgs(func, argdict): return not missingArgs(func, argdict) and not invalidArgs(func, argdict) </code></pre> <p>(This is good only as far as python's arg parsing. Any runtime checks for invalid values in kwargs obviously can't be detected.)</p>
98
2008-10-13T09:02:23Z
[ "python", "arguments", "introspection" ]
Can you list the keyword arguments a Python function receives?
196,960
<p>I have a dict, which I need to pass key/values as keyword arguments.. For example..</p> <pre><code>d_args = {'kw1': 'value1', 'kw2': 'value2'} example(**d_args) </code></pre> <p>This works fine, <em>but</em> if there are values in the d_args dict that are not accepted by the <code>example</code> function, it obviously dies.. Say, if the example function is defined as <code>def example(kw2):</code></p> <p>This is a problem since I don't control either the generation of the <code>d_args</code>, or the <code>example</code> function.. They both come from external modules, and <code>example</code> only accepts some of the keyword-arguments from the dict..</p> <p>Ideally I would just do</p> <pre><code>parsed_kwargs = feedparser.parse(the_url) valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2) PyRSS2Gen.RSS2(**valid_kwargs) </code></pre> <p>I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: <strong>Is there a way to programatically list the keyword arguments the a specific function takes?</strong></p>
64
2008-10-13T07:55:18Z
197,101
<p>In Python 3.0:</p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; import fileinput &gt;&gt;&gt; print(inspect.getfullargspec(fileinput.input)) FullArgSpec(args=['files', 'inplace', 'backup', 'bufsize', 'mode', 'openhook'], varargs=None, varkw=None, defaults=(None, 0, '', 0, 'r', None), kwonlyargs=[], kwdefaults=None, annotations={}) </code></pre>
6
2008-10-13T09:32:56Z
[ "python", "arguments", "introspection" ]
How to find out whether subversion working directory is locked by svn?
197,009
<p>A python script is running two parallel python processes ( created via os.fork() ) each of which eventually tries to check out a subversion repository leaf into the same working copy dir.</p> <p>Before running 'svn co ...' command in a sub-process ( via python subprocess module ) the parent python code checks if the working copy dir already exists. </p> <pre><code> if os.path.isdir(checkout_dir): # working copy dir already exists return checkout_dir </code></pre> <p>So that if it does there shouldn't be any 'svn co' running, but rather immediate return from the parent function.</p> <p>Nevertheless some collision happened and one of the python processes failed on 'svn co ..' with the following error.</p> <pre><code>checked-out failed: svn: Working copy '/tmp/qm_23683' locked svn: run 'svn cleanup' to remove locks (type 'svn help cleanup' for details)** </code></pre> <p>So the first question is why the working copy dir existence check didn't work and the second - is there a way to find out that a working copy dir is locked by svn and loop until it is unlocked?</p> <p>Thanks.</p>
2
2008-10-13T08:29:20Z
197,025
<p>Within the directory, there should be a directory called '.svn'. Within this, a file named 'locked' indicates that the directory is locked.</p>
4
2008-10-13T08:39:52Z
[ "python", "svn" ]
How to find out whether subversion working directory is locked by svn?
197,009
<p>A python script is running two parallel python processes ( created via os.fork() ) each of which eventually tries to check out a subversion repository leaf into the same working copy dir.</p> <p>Before running 'svn co ...' command in a sub-process ( via python subprocess module ) the parent python code checks if the working copy dir already exists. </p> <pre><code> if os.path.isdir(checkout_dir): # working copy dir already exists return checkout_dir </code></pre> <p>So that if it does there shouldn't be any 'svn co' running, but rather immediate return from the parent function.</p> <p>Nevertheless some collision happened and one of the python processes failed on 'svn co ..' with the following error.</p> <pre><code>checked-out failed: svn: Working copy '/tmp/qm_23683' locked svn: run 'svn cleanup' to remove locks (type 'svn help cleanup' for details)** </code></pre> <p>So the first question is why the working copy dir existence check didn't work and the second - is there a way to find out that a working copy dir is locked by svn and loop until it is unlocked?</p> <p>Thanks.</p>
2
2008-10-13T08:29:20Z
199,791
<p>This sounds like a potential race condition, in that something like the following can happen:</p> <ol> <li>Process A checks to see if the directory exists (it doesn't yet).</li> <li>Process B checks to see if the directory exists (it doesn't yet).</li> <li>Process A invokes <code>svn</code>, which creates the directory.</li> <li>Process B invokes <code>svn</code>, which subsequently fails.</li> </ol> <p>An easy way to avoid this is to have each process attempt to <em>create</em> the directory rather than checking for its existence. If the other process has already created the directory, the other process is guaranteed to get a well-defined error code under a very wide variety of platforms and filesystems. For instance, this is one of the only reliable ways to do synchronization on many implementations of NFS. Luckily, <code>svn</code> won't care if the working directory already exists.</p> <p>The Python code would look something like this:</p> <pre><code>import os, errno # ... try: os.mkdir(dirName) except OSError, e: if e.errno != errno.EEXIST: raise # some other error print 'Directory already exists.' else: print 'Successfully created new directory.' </code></pre> <p>This technique is easy to implement, very reliable, and useful in a wide variety of situations.</p>
2
2008-10-14T02:09:48Z
[ "python", "svn" ]
Docstrings for data?
197,387
<p>Is there a way to describe the module's data in a similar way that a docstring describes a module or a funcion?</p> <pre><code>class MyClass(object): def my_function(): """This docstring works!""" return True my_list = [] """This docstring does not work!""" </code></pre>
20
2008-10-13T12:24:04Z
197,499
<p>To my knowledge, it is not possible to assign docstrings to module data members.</p> <p><a href="http://www.python.org/dev/peps/pep-0224/">PEP 224</a> suggests this feature, but the PEP was rejected.</p> <p>I suggest you document the data members of a module in the module's docstring:</p> <pre><code># module.py: """About the module. module.data: contains the word "spam" """ data = "spam" </code></pre>
13
2008-10-13T12:55:53Z
[ "python", "docstring" ]
Docstrings for data?
197,387
<p>Is there a way to describe the module's data in a similar way that a docstring describes a module or a funcion?</p> <pre><code>class MyClass(object): def my_function(): """This docstring works!""" return True my_list = [] """This docstring does not work!""" </code></pre>
20
2008-10-13T12:24:04Z
197,566
<p>It <strong>is</strong> possible to make documentation of module's data, with use of <a href="http://epydoc.sourceforge.net/">epydoc</a> syntax. Epydoc is one of the most frequently used documentation tools for Python.</p> <p>The syntax for documenting is <code>#:</code> above the variable initialization line, like this:</p> <pre><code># module.py: #: Very important data. #: Use with caution. #: @type: C{str} data = "important data" </code></pre> <p>Now when you generate your documentation, <code>data</code> will be described as module variable with given description and type <code>str</code>. You can omit the <code>@type</code> line.</p>
9
2008-10-13T13:23:42Z
[ "python", "docstring" ]
Docstrings for data?
197,387
<p>Is there a way to describe the module's data in a similar way that a docstring describes a module or a funcion?</p> <pre><code>class MyClass(object): def my_function(): """This docstring works!""" return True my_list = [] """This docstring does not work!""" </code></pre>
20
2008-10-13T12:24:04Z
199,179
<p>As codeape explains, it's not possible to document general data members.</p> <p>However, it <em>is</em> possible to document <code>property</code> data members:</p> <pre><code>class Foo: def get_foo(self): ... def set_foo(self, val): ... def del_foo(self): ... foo = property(get_foo, set_foo, del_foo, '''Doc string here''') </code></pre> <p>This will give a docstring to the <code>foo</code> attribute, obviously.</p>
10
2008-10-13T22:08:20Z
[ "python", "docstring" ]
Dealing with a string containing multiple character encodings
197,759
<p>I'm not exactly sure how to ask this question really, and I'm no where close to finding an answer, so I hope someone can help me. </p> <p>I'm writing a Python app that connects to a remote host and receives back byte data, which I unpack using Python's built-in struct module. My problem is with the strings, as they include multiple character encodings. Here is an example of such a string:</p> <p>"^LThis is an example ^Gstring with multiple ^Jcharacter encodings"</p> <p>Where the different encoding starts and ends is marked using special escape chars:</p> <ul> <li>^L - Latin1</li> <li>^E - Central Europe</li> <li>^T - Turkish</li> <li>^B - Baltic</li> <li>^J - Japanese</li> <li>^C - Cyrillic</li> <li>^G - Greek</li> </ul> <p>And so on... I need a way to convert this sort of string into Unicode, but I'm really not sure how to do it. I've read up on Python's codecs and string.encode/decode, but I'm none the wiser really. I should mention as well, that I have no control over how the strings are outputted by the host.</p> <p>I hope someone can help me with how to get started on this.</p>
9
2008-10-13T14:26:10Z
197,786
<p>I would write a codec that incrementally scanned the string and decoded the bytes as they came along. Essentially, you would have to separate strings into chunks with a consistent encoding and decode those and append them to the strings that followed them.</p>
3
2008-10-13T14:32:48Z
[ "python", "string", "unicode", "encoding" ]
Dealing with a string containing multiple character encodings
197,759
<p>I'm not exactly sure how to ask this question really, and I'm no where close to finding an answer, so I hope someone can help me. </p> <p>I'm writing a Python app that connects to a remote host and receives back byte data, which I unpack using Python's built-in struct module. My problem is with the strings, as they include multiple character encodings. Here is an example of such a string:</p> <p>"^LThis is an example ^Gstring with multiple ^Jcharacter encodings"</p> <p>Where the different encoding starts and ends is marked using special escape chars:</p> <ul> <li>^L - Latin1</li> <li>^E - Central Europe</li> <li>^T - Turkish</li> <li>^B - Baltic</li> <li>^J - Japanese</li> <li>^C - Cyrillic</li> <li>^G - Greek</li> </ul> <p>And so on... I need a way to convert this sort of string into Unicode, but I'm really not sure how to do it. I've read up on Python's codecs and string.encode/decode, but I'm none the wiser really. I should mention as well, that I have no control over how the strings are outputted by the host.</p> <p>I hope someone can help me with how to get started on this.</p>
9
2008-10-13T14:26:10Z
197,846
<p>There's no built-in functionality for decoding a string like this, since it is really its own custom codec. You simply need to split up the string on those control characters and decode it accordingly.</p> <p>Here's a (very slow) example of such a function that handles latin1 and shift-JIS:</p> <pre><code>latin1 = "latin-1" japanese = "Shift-JIS" control_l = "\x0c" control_j = "\n" encodingMap = { control_l: latin1, control_j: japanese} def funkyDecode(s, initialCodec=latin1): output = u"" accum = "" currentCodec = initialCodec for ch in s: if ch in encodingMap: output += accum.decode(currentCodec) currentCodec = encodingMap[ch] accum = "" else: accum += ch output += accum.decode(currentCodec) return output </code></pre> <p>A faster version might use str.split, or regular expressions.</p> <p>(Also, as you can see in this example, "^J" is the control character for "newline", so your input data is going to have some interesting restrictions.)</p>
4
2008-10-13T14:52:14Z
[ "python", "string", "unicode", "encoding" ]
Dealing with a string containing multiple character encodings
197,759
<p>I'm not exactly sure how to ask this question really, and I'm no where close to finding an answer, so I hope someone can help me. </p> <p>I'm writing a Python app that connects to a remote host and receives back byte data, which I unpack using Python's built-in struct module. My problem is with the strings, as they include multiple character encodings. Here is an example of such a string:</p> <p>"^LThis is an example ^Gstring with multiple ^Jcharacter encodings"</p> <p>Where the different encoding starts and ends is marked using special escape chars:</p> <ul> <li>^L - Latin1</li> <li>^E - Central Europe</li> <li>^T - Turkish</li> <li>^B - Baltic</li> <li>^J - Japanese</li> <li>^C - Cyrillic</li> <li>^G - Greek</li> </ul> <p>And so on... I need a way to convert this sort of string into Unicode, but I'm really not sure how to do it. I've read up on Python's codecs and string.encode/decode, but I'm none the wiser really. I should mention as well, that I have no control over how the strings are outputted by the host.</p> <p>I hope someone can help me with how to get started on this.</p>
9
2008-10-13T14:26:10Z
197,854
<p>I don't suppose you have any way of convincing the person who hosts the other machine to switch to unicode?</p> <p>This is one of the reasons Unicode was invented, after all.</p>
1
2008-10-13T14:55:31Z
[ "python", "string", "unicode", "encoding" ]
Dealing with a string containing multiple character encodings
197,759
<p>I'm not exactly sure how to ask this question really, and I'm no where close to finding an answer, so I hope someone can help me. </p> <p>I'm writing a Python app that connects to a remote host and receives back byte data, which I unpack using Python's built-in struct module. My problem is with the strings, as they include multiple character encodings. Here is an example of such a string:</p> <p>"^LThis is an example ^Gstring with multiple ^Jcharacter encodings"</p> <p>Where the different encoding starts and ends is marked using special escape chars:</p> <ul> <li>^L - Latin1</li> <li>^E - Central Europe</li> <li>^T - Turkish</li> <li>^B - Baltic</li> <li>^J - Japanese</li> <li>^C - Cyrillic</li> <li>^G - Greek</li> </ul> <p>And so on... I need a way to convert this sort of string into Unicode, but I'm really not sure how to do it. I've read up on Python's codecs and string.encode/decode, but I'm none the wiser really. I should mention as well, that I have no control over how the strings are outputted by the host.</p> <p>I hope someone can help me with how to get started on this.</p>
9
2008-10-13T14:26:10Z
197,982
<p>You definitely have to split the string first into the substrings wih different encodings, and decode each one separately. Just for fun, the obligatory "one-line" version:</p> <pre><code>import re encs = { 'L': 'latin1', 'G': 'iso8859-7', ... } decoded = ''.join(substr[2:].decode(encs[substr[1]]) for substr in re.findall('\^[%s][^^]*' % ''.join(encs.keys()), st)) </code></pre> <p>(no error checking, and also you'll want to decide how to handle '^' characters in substrings)</p>
2
2008-10-13T15:24:45Z
[ "python", "string", "unicode", "encoding" ]
Dealing with a string containing multiple character encodings
197,759
<p>I'm not exactly sure how to ask this question really, and I'm no where close to finding an answer, so I hope someone can help me. </p> <p>I'm writing a Python app that connects to a remote host and receives back byte data, which I unpack using Python's built-in struct module. My problem is with the strings, as they include multiple character encodings. Here is an example of such a string:</p> <p>"^LThis is an example ^Gstring with multiple ^Jcharacter encodings"</p> <p>Where the different encoding starts and ends is marked using special escape chars:</p> <ul> <li>^L - Latin1</li> <li>^E - Central Europe</li> <li>^T - Turkish</li> <li>^B - Baltic</li> <li>^J - Japanese</li> <li>^C - Cyrillic</li> <li>^G - Greek</li> </ul> <p>And so on... I need a way to convert this sort of string into Unicode, but I'm really not sure how to do it. I've read up on Python's codecs and string.encode/decode, but I'm none the wiser really. I should mention as well, that I have no control over how the strings are outputted by the host.</p> <p>I hope someone can help me with how to get started on this.</p>
9
2008-10-13T14:26:10Z
197,990
<p>Here's a relatively simple example of how do it...</p> <pre><code># -*- coding: utf-8 -*- import re # Test Data ENCODING_RAW_DATA = ( ('latin_1', 'L', u'Hello'), # Latin 1 ('iso8859_2', 'E', u'dobrý večer'), # Central Europe ('iso8859_9', 'T', u'İyi akşamlar'), # Turkish ('iso8859_13', 'B', u'Į sveikatą!'), # Baltic ('shift_jis', 'J', u'今日は'), # Japanese ('iso8859_5', 'C', u'Здравствуйте'), # Cyrillic ('iso8859_7', 'G', u'Γειά σου'), # Greek ) CODE_TO_ENCODING = dict([(chr(ord(code)-64), encoding) for encoding, code, text in ENCODING_RAW_DATA]) EXPECTED_RESULT = u''.join([line[2] for line in ENCODING_RAW_DATA]) ENCODED_DATA = ''.join([chr(ord(code)-64) + text.encode(encoding) for encoding, code, text in ENCODING_RAW_DATA]) FIND_RE = re.compile('[\x00-\x1A][^\x00-\x1A]*') def decode_single(bytes): return bytes[1:].decode(CODE_TO_ENCODING[bytes[0]]) result = u''.join([decode_single(bytes) for bytes in FIND_RE.findall(ENCODED_DATA)]) assert result==EXPECTED_RESULT, u"Expected %s, but got %s" % (EXPECTED_RESULT, result) </code></pre>
7
2008-10-13T15:29:10Z
[ "python", "string", "unicode", "encoding" ]
Get File Object used by a CSV Reader/Writer Object
198,465
<p>Is there any way to access the file object used by a CSV writer/reader object after it has been instantiated? I openned up the csv module, and it appears it's contest are builtin. I also tried setting the file object as a property but I get the following error:</p> <pre><code>AttributeError: '_csv.writer' object has no attribute 'fileobj' </code></pre>
1
2008-10-13T18:09:06Z
198,553
<p><code>csv.writer</code> is a "builtin" function. That is, it is written in compiled C code rather than Python. So its internal variables can't be accessed from Python code.</p> <p>That being said, I'm not sure <strong>why</strong> you would need to inspect the csv.writer object to find out the file object. That object is specified when creating the object:</p> <pre><code>w = csv.writer(fileobj, dialect, ...) </code></pre> <p>So if you need to access that object later, just save it in another variable.</p>
3
2008-10-13T18:33:54Z
[ "python", "csv" ]
Get File Object used by a CSV Reader/Writer Object
198,465
<p>Is there any way to access the file object used by a CSV writer/reader object after it has been instantiated? I openned up the csv module, and it appears it's contest are builtin. I also tried setting the file object as a property but I get the following error:</p> <pre><code>AttributeError: '_csv.writer' object has no attribute 'fileobj' </code></pre>
1
2008-10-13T18:09:06Z
3,243,629
<p>From what I can tell, there is no straightforward way to get the file object back out once you put it into a csv object. My approach would probably be to subclass the csv writer and readers you're using so they can carry that data around with them. Of course, this assumes the ability to be able to directly access the types of classes the factory function makes (among other things).</p>
0
2010-07-14T05:40:53Z
[ "python", "csv" ]
Can I pickle a python dictionary into a sqlite3 text field?
198,692
<p>Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)</p>
25
2008-10-13T19:11:13Z
198,748
<p>If you want to store a pickled object, you'll need to use a blob, since it is binary data. However, you can, say, base64 encode the pickled object to get a string that can be stored in a text field.</p> <p>Generally, though, doing this sort of thing is indicative of bad design, since you're storing opaque data you lose the ability to use SQL to do any useful manipulation on that data. Although without knowing what you're actually doing, I can't really make a moral call on it.</p>
13
2008-10-13T19:31:36Z
[ "python", "sqlite", "pickle" ]
Can I pickle a python dictionary into a sqlite3 text field?
198,692
<p>Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)</p>
25
2008-10-13T19:11:13Z
198,763
<p>Since Pickle can dump your object graph to a string it should be possible. </p> <p>Be aware though that TEXT fields in SQLite uses database encoding so you might need to convert it to a simple string before you un-pickle.</p>
2
2008-10-13T19:35:59Z
[ "python", "sqlite", "pickle" ]
Can I pickle a python dictionary into a sqlite3 text field?
198,692
<p>Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)</p>
25
2008-10-13T19:11:13Z
198,767
<p>Pickle has both text and binary output formats. If you use the text-based format you can store it in a TEXT field, but it'll have to be a BLOB if you use the (more efficient) binary format.</p>
3
2008-10-13T19:37:31Z
[ "python", "sqlite", "pickle" ]
Can I pickle a python dictionary into a sqlite3 text field?
198,692
<p>Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)</p>
25
2008-10-13T19:11:13Z
198,770
<p>If a dictionary can be pickled, it can be stored in text/blob field as well.</p> <p>Just be aware of the dictionaries that can't be pickled (aka that contain unpickable objects).</p>
2
2008-10-13T19:37:44Z
[ "python", "sqlite", "pickle" ]
Can I pickle a python dictionary into a sqlite3 text field?
198,692
<p>Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)</p>
25
2008-10-13T19:11:13Z
198,829
<p>Yes, you can store a pickled object in a TEXT or BLOB field in an SQLite3 database, as others have explained.</p> <p>Just be aware that some object <strong>cannot be pickled</strong>. The built-in container types can (dict, set, list, tuple, etc.). But some objects, such as file handles, refer to state that is external to their own data structures, and other extension types have similar problems.</p> <p>Since a dictionary can contain arbitrary nested data structures, it might not be pickle-able.</p>
2
2008-10-13T20:00:26Z
[ "python", "sqlite", "pickle" ]
Can I pickle a python dictionary into a sqlite3 text field?
198,692
<p>Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)</p>
25
2008-10-13T19:11:13Z
199,190
<p>SpoonMeiser is correct, you need to have a strong reason to pickle into a database. </p> <p>It's not difficult to write Python objects that implement persistence with SQLite. Then you can use the SQLite CLI to fiddle with the data as well. Which in my experience is worth the extra bit of work, since many debug and admin functions can be simply performed from the CLI rather than writing specific Python code.</p> <p>In the early stages of a project, I did what you propose and ended up re-writing with a Python class for each business object (note: I didn't say for each table!) This way the body of the application can focus on "what" needs to be done rather than "how" it is done.</p>
1
2008-10-13T22:11:31Z
[ "python", "sqlite", "pickle" ]
Can I pickle a python dictionary into a sqlite3 text field?
198,692
<p>Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)</p>
25
2008-10-13T19:11:13Z
199,393
<p>The other option, considering that your requirement is to save a dict and then spit it back out for the user's "viewing pleasure", is to use the <code>shelve</code> module which will let you persist any pickleable data to file. The python docs are <a href="http://docs.python.org/library/shelve.html#example" rel="nofollow">here</a>.</p>
1
2008-10-13T23:13:39Z
[ "python", "sqlite", "pickle" ]
Can I pickle a python dictionary into a sqlite3 text field?
198,692
<p>Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)</p>
25
2008-10-13T19:11:13Z
199,588
<p>Depending on what you're working on, you might want to look into the <a href="http://pypi.python.org/pypi/shove" rel="nofollow">shove</a> module. It does something similar, where it auto-stores Python objects inside a sqlite database (and all sorts of other options) and pretends to be a dictionary (just like the <a href="http://www.python.org/doc/2.5.2/lib/module-shelve.html" rel="nofollow">shelve</a> module).</p>
1
2008-10-14T00:34:57Z
[ "python", "sqlite", "pickle" ]
Can I pickle a python dictionary into a sqlite3 text field?
198,692
<p>Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)</p>
25
2008-10-13T19:11:13Z
200,143
<p>I have to agree with some of the comments here. Be careful and make sure you really want to save pickle data in a db, there's probably a better way.</p> <p>In any case I had trouble in the past trying to save binary data in the sqlite db. Apparently you have to use the sqlite3.Binary() to prep the data for sqlite.</p> <p>Here's some sample code:</p> <pre><code>query = u'''insert into testtable VALUES(?)''' b = sqlite3.Binary(binarydata) cur.execute(query,(b,)) con.commit() </code></pre>
2
2008-10-14T06:07:06Z
[ "python", "sqlite", "pickle" ]
Can I pickle a python dictionary into a sqlite3 text field?
198,692
<p>Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)</p>
25
2008-10-13T19:11:13Z
436,677
<p>I wrote a blog about this idea, except instead of a pickle, I used json, since I wanted it to be interoperable with perl and other programs. </p> <p><a href="http://writeonly.wordpress.com/2008/12/05/simple-object-db-using-json-and-python-sqlite/">http://writeonly.wordpress.com/2008/12/05/simple-object-db-using-json-and-python-sqlite/</a></p> <p>Architecturally, this is a quick and dirty way to get persistence, transactions, and the like for arbitrary data structures. I have found this combination to be really useful when I want persistence, and don't need to do much in the sql layer with the data (or it's very complex to deal with in sql, and simple with generators). </p> <p>The code itself is pretty simple:</p> <pre><code># register the "loader" to get the data back out. sqlite3.register_converter("pickle", cPickle.loads) </code></pre> <p>Then, when you wnat to dump it into the db, </p> <pre><code>p_string = p.dumps( dict(a=1,b=[1,2,3])) conn.execute(''' create table snapshot( id INTEGER PRIMARY KEY AUTOINCREMENT, mydata pickle); ''') conn.execute(''' insert into snapshot values (null, ?)''', (p_string,)) ''') </code></pre>
5
2009-01-12T19:30:07Z
[ "python", "sqlite", "pickle" ]
Can I pickle a python dictionary into a sqlite3 text field?
198,692
<p>Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)</p>
25
2008-10-13T19:11:13Z
1,416,874
<p>See this solution at SourceForge:</p> <p>y_serial.py module :: warehouse Python objects with SQLite</p> <p>"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data."</p> <p><a href="http://yserial.sourceforge.net" rel="nofollow">http://yserial.sourceforge.net</a></p>
0
2009-09-13T04:47:57Z
[ "python", "sqlite", "pickle" ]
Can I pickle a python dictionary into a sqlite3 text field?
198,692
<p>Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)</p>
25
2008-10-13T19:11:13Z
2,340,858
<p>I needed to achieve the same thing too. </p> <p>I turns out it caused me quite a headache before I finally figured out, <a href="http://coding.derkeiler.com/Archive/Python/comp.lang.python/2008-12/msg00352.html">thanks to this post</a>, how to actually make it work in a binary format.</p> <h3>To insert/update:</h3> <pre><code>pdata = cPickle.dumps(data, cPickle.HIGHEST_PROTOCOL) curr.execute("insert into table (data) values (:data)", sqlite3.Binary(pdata)) </code></pre> <p>You must specify the second argument to dumps to force a binary pickling.<br> Also note the <strong>sqlite3.Binary</strong> to make it fit in the BLOB field.</p> <h3>To retrieve data:</h3> <pre><code>curr.execute("select data from table limit 1") for row in curr: data = cPickle.loads(str(row['data'])) </code></pre> <p>When retrieving a BLOB field, sqlite3 gets a 'buffer' python type, that needs to be strinyfied using <strong>str</strong> before being passed to the loads method.</p>
35
2010-02-26T10:23:14Z
[ "python", "sqlite", "pickle" ]
Can I pickle a python dictionary into a sqlite3 text field?
198,692
<p>Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)</p>
25
2008-10-13T19:11:13Z
15,384,886
<p>It is possible to store object data as pickle dump, jason etc but it is also possible to index, them, restrict them and run select queries that use those indices. Here is example with tuples, that can be easily applied for any other python class. All that is needed is explained in python sqlite3 documentation (somebody already posted the link). Anyway here it is all put together in the following example:</p> <pre><code>import sqlite3 import pickle def adapt_tuple(tuple): return pickle.dumps(tuple) sqlite3.register_adapter(tuple, adapt_tuple) #cannot use pickle.dumps directly because of inadequate argument signature sqlite3.register_converter("tuple", pickle.loads) def collate_tuple(string1, string2): return cmp(pickle.loads(string1), pickle.loads(string2)) ######################### # 1) Using declared types con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES) con.create_collation("cmptuple", collate_tuple) cur = con.cursor() cur.execute("create table test(p tuple unique collate cmptuple) ") cur.execute("create index tuple_collated_index on test(p collate cmptuple)") cur.execute("select name, type from sqlite_master") # where type = 'table'") print(cur.fetchall()) p = (1,2,3) p1 = (1,2) cur.execute("insert into test(p) values (?)", (p,)) cur.execute("insert into test(p) values (?)", (p1,)) cur.execute("insert into test(p) values (?)", ((10, 1),)) cur.execute("insert into test(p) values (?)", (tuple((9, 33)) ,)) cur.execute("insert into test(p) values (?)", (((9, 5), 33) ,)) try: cur.execute("insert into test(p) values (?)", (tuple((9, 33)) ,)) except Exception as e: print e cur.execute("select p from test order by p") print "\nwith declared types and default collate on column:" for raw in cur: print raw cur.execute("select p from test order by p collate cmptuple") print "\nwith declared types collate:" for raw in cur: print raw con.create_function('pycmp', 2, cmp) print "\nselect grater than using cmp function:" cur.execute("select p from test where pycmp(p,?) &gt;= 0", ((10, ),) ) for raw in cur: print raw cur.execute("explain query plan select p from test where p &gt; ?", ((3,))) for raw in cur: print raw print "\nselect grater than using collate:" cur.execute("select p from test where p &gt; ?", ((10,),) ) for raw in cur: print raw cur.execute("explain query plan select p from test where p &gt; ?", ((3,))) for raw in cur: print raw cur.close() con.close() </code></pre>
1
2013-03-13T12:07:17Z
[ "python", "sqlite", "pickle" ]
I'm looking for a pythonic way to insert a space before capital letters
199,059
<p>I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word".</p> <p>My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?</p>
8
2008-10-13T21:16:40Z
199,075
<p>You could try:</p> <pre><code>&gt;&gt;&gt; re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWord") 'Word Word Word' </code></pre>
16
2008-10-13T21:20:55Z
[ "python", "regex", "text-files" ]
I'm looking for a pythonic way to insert a space before capital letters
199,059
<p>I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word".</p> <p>My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?</p>
8
2008-10-13T21:16:40Z
199,094
<p>With regexes you can do this:</p> <pre><code>re.sub('([A-Z])', r' \1', str) </code></pre> <p>Of course, that will only work for ASCII characters, if you want to do Unicode it's a whole new can of worms :-)</p>
2
2008-10-13T21:25:17Z
[ "python", "regex", "text-files" ]
I'm looking for a pythonic way to insert a space before capital letters
199,059
<p>I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word".</p> <p>My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?</p>
8
2008-10-13T21:16:40Z
199,120
<p>If there are consecutive capitals, then Gregs result could not be what you look for, since the \w consumes the caracter in front of the captial letter to be replaced.</p> <pre><code>&gt;&gt;&gt; re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWWWWWWWord") 'Word Word WW WW WW Word' </code></pre> <p>A look-behind would solve this:</p> <pre><code>&gt;&gt;&gt; re.sub(r"(?&lt;=\w)([A-Z])", r" \1", "WordWordWWWWWWWord") 'Word Word W W W W W W Word' </code></pre>
22
2008-10-13T21:37:39Z
[ "python", "regex", "text-files" ]
I'm looking for a pythonic way to insert a space before capital letters
199,059
<p>I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word".</p> <p>My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?</p>
8
2008-10-13T21:16:40Z
199,126
<p>Have a look at my answer on <em><a href="http://stackoverflow.com/questions/155303/net-how-can-you-split-a-caps-delimited-string-into-an-array#155487">.NET - How can you split a “caps” delimited string into an array?</a></em></p> <p><strong>Edit:</strong> Maybe better to include it here.</p> <pre><code>re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\1 ', text) </code></pre> <p>For example:</p> <pre><code>"SimpleHTTPServer" =&gt; ["Simple", "HTTP", "Server"] </code></pre>
6
2008-10-13T21:41:49Z
[ "python", "regex", "text-files" ]
I'm looking for a pythonic way to insert a space before capital letters
199,059
<p>I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word".</p> <p>My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?</p>
8
2008-10-13T21:16:40Z
199,215
<p>Perhaps shorter:</p> <pre><code>&gt;&gt;&gt; re.sub(r"\B([A-Z])", r" \1", "DoIThinkThisIsABetterAnswer?") </code></pre>
6
2008-10-13T22:17:14Z
[ "python", "regex", "text-files" ]
I'm looking for a pythonic way to insert a space before capital letters
199,059
<p>I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word".</p> <p>My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?</p>
8
2008-10-13T21:16:40Z
200,122
<p>I agree that the regex solution is the easiest, but I wouldn't say it's the most pythonic.</p> <p>How about:</p> <pre><code>text = 'WordWordWord' new_text = '' is_first_letter = True for letter in text: if not is_first_letter and letter.isupper(): new_text += ' ' + letter else: new_text += letter isFirstLetter = False </code></pre>
0
2008-10-14T05:51:10Z
[ "python", "regex", "text-files" ]
I'm looking for a pythonic way to insert a space before capital letters
199,059
<p>I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word".</p> <p>My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?</p>
8
2008-10-13T21:16:40Z
200,456
<p>I think regexes are the way to go here, but just to give a pure python version without (hopefully) any of the problems ΤΖΩΤΖΙΟΥ has pointed out:</p> <pre><code>def splitCaps(s): result = [] for ch, next in window(s+" ", 2): result.append(ch) if next.isupper() and not ch.isspace(): result.append(' ') return ''.join(result) </code></pre> <p>window() is a utility function I use to operate on a sliding window of items, defined as:</p> <pre><code>import collections, itertools def window(it, winsize, step=1): it=iter(it) # Ensure we have an iterator l=collections.deque(itertools.islice(it, winsize)) while 1: # Continue till StopIteration gets raised. yield tuple(l) for i in range(step): l.append(it.next()) l.popleft() </code></pre>
0
2008-10-14T09:06:22Z
[ "python", "regex", "text-files" ]
Is there any way to get python omnicomplete to work with non-system modules in vim?
199,180
<p>The only thing I can get python omnicomplete to work with are system modules. I get nothing for help with modules in my site-packages or modules that I'm currently working on.</p>
9
2008-10-13T22:08:26Z
199,636
<p>Just ran across this on Python reddit tonight: <a href="http://orestis.gr/blog/2008/10/13/pysmell-v06-released/" rel="nofollow">PySmell</a>. Looks like what you're looking for.</p> <blockquote> <p>PySmell is a python IDE completion helper.</p> <p>It tries to statically analyze Python source code, without executing it, and generates information about a project’s structure that IDE tools can use. </p> </blockquote>
2
2008-10-14T00:55:19Z
[ "python", "vim", "omnicomplete" ]
Is there any way to get python omnicomplete to work with non-system modules in vim?
199,180
<p>The only thing I can get python omnicomplete to work with are system modules. I get nothing for help with modules in my site-packages or modules that I'm currently working on.</p>
9
2008-10-13T22:08:26Z
200,227
<p>I think your after the <a href="http://www.vim.org/scripts/script.php?script_id=850" rel="nofollow">pydiction</a> script. It lets you add your own stuff and site-packages to omni complete. </p> <p>While your at it, add the following to your python.vim file...</p> <pre><code> set iskeyword+=. </code></pre> <p>This will let you auto-complete package functions e.g. if you enter...</p> <pre><code> os.path. </code></pre> <p>and then [CTRL][N], you'll get a list of the functions for os.path.</p>
0
2008-10-14T07:12:40Z
[ "python", "vim", "omnicomplete" ]
Is there any way to get python omnicomplete to work with non-system modules in vim?
199,180
<p>The only thing I can get python omnicomplete to work with are system modules. I get nothing for help with modules in my site-packages or modules that I'm currently working on.</p>
9
2008-10-13T22:08:26Z
201,420
<p>I get completion for my own modules in my PYTHONPATH or site-packages. I'm not sure what version of the pythoncomplete.vim script you're using, but you may want to make sure it's the latest.</p> <p>EDIT: Here's some examples of what I'm seeing on my system...</p> <p>This file (mymodule.py), I puth in a directory in PYTHONPATH, and then in site-packages. Both times I was able to get the screenshot below.</p> <pre><code>myvar = 'test' def myfunction(foo='test'): pass class MyClass(object): pass </code></pre> <p><img src="http://i437.photobucket.com/albums/qq96/jmcantrell/screenshot.png" alt="screenshot" /></p>
2
2008-10-14T14:35:18Z
[ "python", "vim", "omnicomplete" ]
Is there any way to get python omnicomplete to work with non-system modules in vim?
199,180
<p>The only thing I can get python omnicomplete to work with are system modules. I get nothing for help with modules in my site-packages or modules that I'm currently working on.</p>
9
2008-10-13T22:08:26Z
213,253
<p>Once I generated ctags for one of my site-packages, it started working for that package -- so I'm guessing that the omnicomplete function depends on ctags for non-sys modules.</p> <p>EDIT: Not true at all.</p> <p>Here's the problem -- poor testing on my part -- omnicomplete WAS working for parts of my project, just not most of it.</p> <p>The issue was that I'm working on a django project, and in order to import django.db, you need to have an environment variable set. Since I couldn't import django.db, any class that inherited from django.db, or any module that imported a class that inherited from django.db wouldn't complete.</p>
3
2008-10-17T18:19:55Z
[ "python", "vim", "omnicomplete" ]
Is there any way to get python omnicomplete to work with non-system modules in vim?
199,180
<p>The only thing I can get python omnicomplete to work with are system modules. I get nothing for help with modules in my site-packages or modules that I'm currently working on.</p>
9
2008-10-13T22:08:26Z
851,255
<p>While it's important to note that you must properly set your <code>PYTHONPATH</code> environmental variable, per the the previous answer, there is a notable <a href="http://groups.google.com/group/vim%5Fdev/browse%5Fthread/thread/58191d176ebd9722/d9cd31cee304b7df" rel="nofollow">bug in Vim which prevents omnicompletion from working when an import fails</a>. As of Vim 7.2.79, this bug hasn't been fixed.</p>
2
2009-05-12T05:26:38Z
[ "python", "vim", "omnicomplete" ]
Is there any way to get python omnicomplete to work with non-system modules in vim?
199,180
<p>The only thing I can get python omnicomplete to work with are system modules. I get nothing for help with modules in my site-packages or modules that I'm currently working on.</p>
9
2008-10-13T22:08:26Z
1,104,576
<p>Trouble-shooting tip: verify that the module you are trying to omni-complete can be imported by VIM. I had some syntactically correct Python that VIM didn't like:</p> <pre><code>:python import {module-name} Traceback (most recent call last): File "&lt;string&gt;", line 1, in ? File "modulename/__init__.py", line 9 class empty_paranthesis(): ^ SyntaxError: invalid syntax </code></pre> <p>Case-in-point, removing the parenthesis from my class definition allowed VIM to import the module, and subsequently OmniComplete on that module started to work.</p>
2
2009-07-09T15:19:58Z
[ "python", "vim", "omnicomplete" ]
How can I port a legacy Java/J2EE website to a modern scripting language (PHP,Python/Django, etc)?
199,556
<p>I want to move a legacy Java web application (J2EE) to a scripting language - any scripting language - in order to improve programming efficiency.</p> <p>What is the easiest way to do this? Are there any automated tools that can convert the bulk of the business logic?</p>
4
2008-10-14T00:23:28Z
199,593
<p>Using an automated tool to "port" the web application will almost certainly guarantee that future programming efficiency will be minimised -- not improved.</p> <p>A good scripting language can help programming efficiency when used by good programmers who understand good coding practices in that language. Automated tools are usually not designed to output code that is elegent or well-written, only code that works.</p> <p>You'll only get an improvement in programming efficiency after you've put in the effort to re-implement the web app -- which, due to the time required for the reimplementation, may or may not result in an improvement overall.</p>
6
2008-10-14T00:36:30Z
[ "java", "php", "python", "django", "java-ee" ]
How can I port a legacy Java/J2EE website to a modern scripting language (PHP,Python/Django, etc)?
199,556
<p>I want to move a legacy Java web application (J2EE) to a scripting language - any scripting language - in order to improve programming efficiency.</p> <p>What is the easiest way to do this? Are there any automated tools that can convert the bulk of the business logic?</p>
4
2008-10-14T00:23:28Z
199,607
<p>If you already have a large amount of business logic implemented in Java, then I see two possibilities for you.</p> <p>The first is to use a high level language that runs within the JVM and has a web framework, such as <a href="http://groovy.codehaus.org/" rel="nofollow">Groovy</a>/<a href="http://grails.org/" rel="nofollow">Grails</a> or <a href="http://jruby.codehaus.org/" rel="nofollow">JRuby</a> and <a href="http://rads.stackoverflow.com/amzn/click/1590598814" rel="nofollow">Rails</a>. This allows you to directly leverage all of the business logic you've implemented in Java without having to re-architect the entire site. You should be able to take advantage of the framework's improved productivity with respect to the web development and still leverage your existing business logic.</p> <p>An alternative approach is to turn your business logic layer into a set of services available over a standard RPC mechanisim - REST, SOAP, XML-RPC or some other simple XML (YAML or JSON) over HTTP protocol (see also <a href="https://dwr.dev.java.net/" rel="nofollow">DWR</a>) so that the front end can make these RPC calls to your business logic.</p> <p>The first approach, using a high level language on the JVM is probably less re-architecture than the second. </p> <p>If your goal is a complete migration off of Java, then either of these approaches allow you to do so in smaller steps - you may find that this kind of hybrid is better than whole sale deprecation - the JVM has a lot of libraries and integrates well into a lot of other systems.</p>
7
2008-10-14T00:45:59Z
[ "java", "php", "python", "django", "java-ee" ]
How can I port a legacy Java/J2EE website to a modern scripting language (PHP,Python/Django, etc)?
199,556
<p>I want to move a legacy Java web application (J2EE) to a scripting language - any scripting language - in order to improve programming efficiency.</p> <p>What is the easiest way to do this? Are there any automated tools that can convert the bulk of the business logic?</p>
4
2008-10-14T00:23:28Z
199,736
<p>Here's what you have to do.</p> <p>First, be sure you can walk before you run. Build something simple, possibly tangentially related to your main project.</p> <p><strong>DO NOT</strong> build a piece of the final project and hope it will "evolve" into the final project. This never works out well. Why? You'll make dumb mistakes. But you can't delete or rework them because you're supposed to evolve that mistake into the final project.</p> <p>Next, pick a a framework. What? Second? Yes. Second. Until you actually do something with some scripting languages and frameworks, you have no real useful concept of what you're doing. Once you've built something, you now have an informed opinion.</p> <p>"Wait," you say. "To do step 1 I had to pick a framework." True. Step 1, however, contains decisions you're allowed to revoke. Pick the wrong framework for step 1 has no long-term bad effects. It was just learning.</p> <p>Third, with your strategic framework, and some experience, break down your existing site into pieces you can build with your new framework. Prioritize those pieces from most important to least important. </p> <p><strong>DO NOT</strong> plan the entire conversion as one massive project. It never works. It makes a big job more complex than necessary.</p> <p>We'll use Django as the example framework. You'll have templates, view functions, model definitions, URL mapping and other details.</p> <p>For each build, do the following:</p> <ol> <li><p>Convert your existing model to a Django model. This won't ever fit your legacy SQL. You'll have to rethink your model, fix old mistakes, correct old bugs that you've always wanted to correct.</p></li> <li><p>Write unit tests.</p></li> <li><p>Build a conversion utility to export old data and import into the new model.</p></li> <li><p>Build Django admin pages to touch and feel the new data.</p></li> <li><p>Pick representative pages and rework them into the appropriate templates. You might make use of some legacy JSP pages. However, don't waste too much time with this. Use the HTML to create Django templates.</p></li> <li><p>Plan your URL's and view functions. Sometimes, these view functions will leverage legacy action classes. Don't "convert". Rewrite from scratch. Use your new language and framework.</p></li> </ol> <p>The only thing that's worth preserving is the data and the operational concept. Don't try to preserve or convert the code. It's misleading. You might convert unittests from JUnit to Python unittest. </p> <p><hr /></p> <p>I gave this advice a few months ago. I had to do some coaching and review during the processing. The revised site is up and running. No conversion from the old technology; they did the suggested rewrite from scratch. Developer happy. Site works well.</p>
11
2008-10-14T01:43:21Z
[ "java", "php", "python", "django", "java-ee" ]
How can I port a legacy Java/J2EE website to a modern scripting language (PHP,Python/Django, etc)?
199,556
<p>I want to move a legacy Java web application (J2EE) to a scripting language - any scripting language - in order to improve programming efficiency.</p> <p>What is the easiest way to do this? Are there any automated tools that can convert the bulk of the business logic?</p>
4
2008-10-14T00:23:28Z
219,328
<p>A lot of the recommendations being given here are assuming you -- and just you -- are doing a full rewrite of the application. This is probably not the case, and it changes the answer quite a bit</p> <p>If you've already got J2EE kicking around, the correct answer is Grails. It simply is: you probably already have Hibernate and Spring kicking around, and you're going to want the ability to flip back and forth between your old code and your new with a minimum amount of pain. That's exactly Groovy's forte, and it is even smoother than JRuby in this regards.</p> <p>Also, if you've already got a J2EE app kicking around, you've already got Java developers kicking around. In that case, learning Groovy is like falling off a ladder -- literally. With the exception of anonymous inner classes, Groovy is a pure superset of Java, which means that you can write Java code, call it Groovy, and be done with it. As you become increasingly comfortable with the nicities of Groovy, you can integrate them into your Java-ish Groovy code. Before too long, you'll be writing very Groovy code, and not even really have realized the transition.</p>
1
2008-10-20T18:05:01Z
[ "java", "php", "python", "django", "java-ee" ]
Get last answer
200,020
<p>In many symbolic math systems, such as Matlab or Mathematica, you can use a variable like <code>Ans</code> or <code>%</code> to retrieve the last computed value. Is there a similar facility in the Python shell?</p>
87
2008-10-14T04:31:49Z
200,027
<p>Underscore.</p> <pre><code>&gt;&gt;&gt; 5+5 10 &gt;&gt;&gt; _ 10 &gt;&gt;&gt; _ + 5 15 &gt;&gt;&gt; _ 15 </code></pre>
130
2008-10-14T04:35:08Z
[ "python" ]
Get last answer
200,020
<p>In many symbolic math systems, such as Matlab or Mathematica, you can use a variable like <code>Ans</code> or <code>%</code> to retrieve the last computed value. Is there a similar facility in the Python shell?</p>
87
2008-10-14T04:31:49Z
200,045
<p>Just for the record, ipython takes this one step further and you can access every result with _ and its numeric value</p> <pre><code>In [1]: 10 Out[1]: 10 In [2]: 32 Out[2]: 32 In [3]: _ Out[3]: 32 In [4]: _1 Out[4]: 10 In [5]: _2 Out[5]: 32 In [6]: _1 + _2 Out[6]: 42 In [7]: _6 Out[7]: 42 </code></pre> <p>And it is possible to edit ranges of lines with the %ed macro too:</p> <pre><code>In [1]: def foo(): ...: print "bar" ...: ...: In [2]: foo() bar In [3]: %ed 1-2 </code></pre>
41
2008-10-14T04:53:38Z
[ "python" ]
How do I remove a cookie that I've set on someone's computer?
200,250
<p>I've got a web system where users log in, and it stores a cookie of their session. When they log in as someone else or log out I want to remove that original cookie that I stored. What's the best way to do that? I'm using Python and Apache, though I suppose the answer will remain the same for most languages.</p>
5
2008-10-14T07:27:21Z
200,255
<p>I guess the best way is to set the expiration to a date of the cookie to some date in the past.</p>
4
2008-10-14T07:28:51Z
[ "python", "apache", "http", "cookies" ]
How do I remove a cookie that I've set on someone's computer?
200,250
<p>I've got a web system where users log in, and it stores a cookie of their session. When they log in as someone else or log out I want to remove that original cookie that I stored. What's the best way to do that? I'm using Python and Apache, though I suppose the answer will remain the same for most languages.</p>
5
2008-10-14T07:27:21Z
200,265
<p>Set the cookie again, as if you hadn't set it the first time, but specify an expiration date that is in the past.</p>
7
2008-10-14T07:35:43Z
[ "python", "apache", "http", "cookies" ]
How do I remove a cookie that I've set on someone's computer?
200,250
<p>I've got a web system where users log in, and it stores a cookie of their session. When they log in as someone else or log out I want to remove that original cookie that I stored. What's the best way to do that? I'm using Python and Apache, though I suppose the answer will remain the same for most languages.</p>
5
2008-10-14T07:27:21Z
200,271
<p>Return the header</p> <pre> Set-Cookie: token=opaque; Domain=.your.domain; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/ </pre> <p>The Domain and Path must match the original attributes that the cookie was issued under.</p>
1
2008-10-14T07:38:45Z
[ "python", "apache", "http", "cookies" ]
fast filter method in python
200,373
<p>I want to filter two list with any fastest method in python script. I have used the built-in <code>filter()</code> method for this purpose. but it is quite slow and taking too much time because I have very big list, I think more than 5 million item in each list or may be more. I do not know how I will make it. Please if anybody have idea or write small function for it. </p>
-1
2008-10-14T08:25:09Z
200,395
<p>I guess filter() is as fast as you can possibly get without having to code the filtering function in C (and in that case, you better code the whole filtering process in C).</p> <p>Why don't you paste the function you are filtering on? That might lead to easier optimizations.</p> <p>Read <a href="http://www.python.org/doc/essays/list2str.html" rel="nofollow">this</a> about optimization in Python. And <a href="http://docs.python.org/api/api.html" rel="nofollow">this</a> about the Python/C API.</p>
2
2008-10-14T08:39:16Z
[ "python", "list", "filter" ]
fast filter method in python
200,373
<p>I want to filter two list with any fastest method in python script. I have used the built-in <code>filter()</code> method for this purpose. but it is quite slow and taking too much time because I have very big list, I think more than 5 million item in each list or may be more. I do not know how I will make it. Please if anybody have idea or write small function for it. </p>
-1
2008-10-14T08:25:09Z
200,634
<p>Maybe your lists are too large and do not fit in memory, and you experience <a href="http://en.wikipedia.org/wiki/Thrash_(computer_science)" rel="nofollow">thrashing</a>. If the sources are in files, you do not need the whole list in memory all at once. Try using <em><a href="https://docs.python.org/2/library/itertools.html#itertools.ifilter" rel="nofollow">itertools</a></em>, e.g.:</p> <pre><code>from itertools import ifilter def is_important(s): return len(s)&gt;10 filtered_list = ifilter(is_important, open('mylist.txt')) </code></pre> <p>Note that <em>ifilter</em> returns an <em>iterator</em> that is fast and memory efficient.</p> <p><a href="http://www.dabeaz.com/generators/" rel="nofollow">Generator Tricks</a> is a tutorial by David M. Beazley that teaches some interesting uses for <em>generators</em>.</p>
13
2008-10-14T10:18:45Z
[ "python", "list", "filter" ]
fast filter method in python
200,373
<p>I want to filter two list with any fastest method in python script. I have used the built-in <code>filter()</code> method for this purpose. but it is quite slow and taking too much time because I have very big list, I think more than 5 million item in each list or may be more. I do not know how I will make it. Please if anybody have idea or write small function for it. </p>
-1
2008-10-14T08:25:09Z
200,637
<p>Before doing it in C, you could try <a href="http://numpy.scipy.org/" rel="nofollow">numpy</a>. Perhaps you can turn your filtering into number crunching.</p>
1
2008-10-14T10:19:48Z
[ "python", "list", "filter" ]
fast filter method in python
200,373
<p>I want to filter two list with any fastest method in python script. I have used the built-in <code>filter()</code> method for this purpose. but it is quite slow and taking too much time because I have very big list, I think more than 5 million item in each list or may be more. I do not know how I will make it. Please if anybody have idea or write small function for it. </p>
-1
2008-10-14T08:25:09Z
200,648
<p>Filter will create a new list, so if your original is very big, you could end up using up to twice as much memory. If you only need to process the results iteratively, rather than use it as a real random-access list, you are probably better off using ifilter instead. ie.</p> <pre><code>for x in itertools.ifilter(condition_func, my_really_big_list): do_something_with(x) </code></pre> <p>Other speed tips are to use a python builtin, rather than a function you write yourself. There's a itertools.ifilterfalse specifically for the case where you would otherwise need to introduce a lambda to negate your check. (eg "ifilter(lambda x: not x.isalpha(), l)" should be written "ifilterfalse(str.isalpha, l)")</p>
1
2008-10-14T10:24:46Z
[ "python", "list", "filter" ]
fast filter method in python
200,373
<p>I want to filter two list with any fastest method in python script. I have used the built-in <code>filter()</code> method for this purpose. but it is quite slow and taking too much time because I have very big list, I think more than 5 million item in each list or may be more. I do not know how I will make it. Please if anybody have idea or write small function for it. </p>
-1
2008-10-14T08:25:09Z
201,015
<p>It may be useful to know that generally a conditional list comprehension is much faster than the corresponding lambda:</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit.Timer('[x for x in xrange(10) if (x**2 % 4) == 1]').timeit() 2.0544309616088867 &gt;&gt;&gt; timeit.f = lambda x: (x**2 % 4) == 1 timeit.Timer('[x for x in xrange(10) if f(x)]').timeit() &gt;&gt;&gt; 3.4280929565429688 </code></pre> <p>(Not sure why I needed to put f in the <code>timeit</code> namespace, there. Haven't really used the module much.)</p>
1
2008-10-14T12:49:35Z
[ "python", "list", "filter" ]
fast filter method in python
200,373
<p>I want to filter two list with any fastest method in python script. I have used the built-in <code>filter()</code> method for this purpose. but it is quite slow and taking too much time because I have very big list, I think more than 5 million item in each list or may be more. I do not know how I will make it. Please if anybody have idea or write small function for it. </p>
-1
2008-10-14T08:25:09Z
201,019
<p>If you can avoid creating the lists in the first place, you'll be happier.</p> <p>Rather than</p> <pre><code>aBigList = someListMakingFunction() filter( lambda x:x&gt;10, aBigList ) </code></pre> <p>You might want to look at your function that makes the list.</p> <pre><code>def someListMakingGenerator( ): for x in some source: yield x </code></pre> <p>Then your filter doesn't involve a giant tract of memory</p> <pre><code>def myFilter( aGenerator ): for x in aGenerator: if x &gt; 10: yield x </code></pre> <p>By using generators, you don't keep much stuff in memory.</p>
3
2008-10-14T12:50:25Z
[ "python", "list", "filter" ]
Tracd Realm
200,447
<p>I am trying to setup tracd for the project I am currently working on. After creating a password file with the python script given in the <a href="http://trac.edgewall.org/wiki/TracStandalone">site</a> I am trying to start the server with authentication on. But it throws up warning saying No users found in the realm. What actually is a realm - I tried using trac as the value and also tried leaving it empty. I am using Windows XP. I am using Tracd Standalone server.</p> <p>The Command Line sent was: tracd --port 8000 --auth=My_Test_Project,D:\My_Test_Project\Documents\Trac\digest.txt,Trac D:\My_Test_Project\Documents\Trac</p> <p>The Warning message was - 'Warning: found no users in realm: trac'</p> <p>Thanks...</p>
5
2008-10-14T09:01:54Z
200,702
<p>Replacing the above said command line with the one bellow helps.</p> <p>tracd --port 8000 --auth=Trac,D:\My_Test_Project\Documents\Trac\digest.txt,Trac D:\My_Test_Project\Documents\Trac</p> <p>The string after --auth= should be the environment name and not the project name.</p>
5
2008-10-14T10:47:31Z
[ "python", "project-management", "wiki", "trac" ]
Tracd Realm
200,447
<p>I am trying to setup tracd for the project I am currently working on. After creating a password file with the python script given in the <a href="http://trac.edgewall.org/wiki/TracStandalone">site</a> I am trying to start the server with authentication on. But it throws up warning saying No users found in the realm. What actually is a realm - I tried using trac as the value and also tried leaving it empty. I am using Windows XP. I am using Tracd Standalone server.</p> <p>The Command Line sent was: tracd --port 8000 --auth=My_Test_Project,D:\My_Test_Project\Documents\Trac\digest.txt,Trac D:\My_Test_Project\Documents\Trac</p> <p>The Warning message was - 'Warning: found no users in realm: trac'</p> <p>Thanks...</p>
5
2008-10-14T09:01:54Z
202,838
<p>The text referred to says that you must specify the realm name as "trac", not "<strong>T</strong>rac", but I have no chance of testing whether that makes any difference, sorry.</p>
1
2008-10-14T21:07:02Z
[ "python", "project-management", "wiki", "trac" ]
Tracd Realm
200,447
<p>I am trying to setup tracd for the project I am currently working on. After creating a password file with the python script given in the <a href="http://trac.edgewall.org/wiki/TracStandalone">site</a> I am trying to start the server with authentication on. But it throws up warning saying No users found in the realm. What actually is a realm - I tried using trac as the value and also tried leaving it empty. I am using Windows XP. I am using Tracd Standalone server.</p> <p>The Command Line sent was: tracd --port 8000 --auth=My_Test_Project,D:\My_Test_Project\Documents\Trac\digest.txt,Trac D:\My_Test_Project\Documents\Trac</p> <p>The Warning message was - 'Warning: found no users in realm: trac'</p> <p>Thanks...</p>
5
2008-10-14T09:01:54Z
3,844,015
<p>Check your password digest file. Looking at mine it appears that the output is stored as a line with three fields in this format: <code>username:realm:passwordhash</code>. If your getting that warning then it could be a mismatch between the realm field in the digest file and the realm that you're passing in when launching tracd. </p> <hr> <p>Looking in the python generator script there are three options:</p> <ul> <li>-u for user</li> <li>-p for password</li> <li>-r for realm</li> </ul> <p>When I generate my digest file using this command line (assuming you named it trac-digest.py):</p> <pre><code>python trac-digest.py -u user -p pass &gt;&gt; digest.txt </code></pre> <p>it generates this line in my digest.txt:</p> <pre><code>user:trac:1d395970d2a9a075d0536a4d6e4d0679 </code></pre> <p>So looks like the default realm is <em>trac</em> and launching tracd with the --auth option specified like the documentation says always gives me that warning 'Warning: found no users in realm: <em>realm</em>' But when I generate my digest file using the -r parameter:</p> <pre><code>python trac-digest.py -u user -p pass -r realm &gt;&gt; digest.txt </code></pre> <p>it generates this line in my digest.txt:</p> <pre><code>user:realm:1d395970d2a9a075d0536a4d6e4d0679 </code></pre> <p>And I no longer get that warning when I specify the realm that I passed to trac-digest.py.</p>
5
2010-10-02T01:46:59Z
[ "python", "project-management", "wiki", "trac" ]
Store simple user settings in Python
200,599
<p>I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue.</p> <p>The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them.</p> <p>For example, userdb["bob"]["colour_scheme"] would have the value "blue".</p> <p>What is the best way to store it on file? Pickling the dictionary?</p> <p>Are there better ways of doing what I am trying to do?</p>
7
2008-10-14T10:04:46Z
200,611
<p>Using <a href="http://www.python.org/doc/2.5.2/lib/module-cPickle.html">cPickle</a> on the dictionary would be my choice. Dictionaries are a natural fit for these kind of data, so given your requirements I see no reason not to use them. That, unless you are thinking about reading them from non-python applications, in which case you'd have to use a language neutral text format. And even here you could get away with the pickle plus an export tool.</p>
7
2008-10-14T10:10:11Z
[ "python", "database", "website", "settings" ]
Store simple user settings in Python
200,599
<p>I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue.</p> <p>The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them.</p> <p>For example, userdb["bob"]["colour_scheme"] would have the value "blue".</p> <p>What is the best way to store it on file? Pickling the dictionary?</p> <p>Are there better ways of doing what I am trying to do?</p>
7
2008-10-14T10:04:46Z
200,621
<p>If you have a database, I might suggest storing the settings in the database. However, it sounds like ordinary files might suit your environment better.</p> <p>You probably don't want to store <em>all</em> the users settings in the same file, because you might run into trouble with concurrent access to that one file. If you stored each user's settings as a dictionary in their own pickled file, then they would be able to act independently.</p> <p>Pickling is a reasonable way to store such data, but unfortunately the pickle data format is notoriously not-human-readable. You might be better off storing it as <code>repr(dictionary)</code> which will be a more readable format. To reload the user settings, use <code>eval(open("file").read())</code> or something like that.</p>
0
2008-10-14T10:13:48Z
[ "python", "database", "website", "settings" ]
Store simple user settings in Python
200,599
<p>I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue.</p> <p>The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them.</p> <p>For example, userdb["bob"]["colour_scheme"] would have the value "blue".</p> <p>What is the best way to store it on file? Pickling the dictionary?</p> <p>Are there better ways of doing what I am trying to do?</p>
7
2008-10-14T10:04:46Z
200,627
<p>I don't tackle the question which one is best. If you want to handle text-files, I'd consider <a href="http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html">ConfigParser -module</a>. Another you could give a try would be <a href="http://undefined.org/python/">simplejson</a> or <a href="http://www.yaml.org/">yaml</a>. You could also consider a real db table.</p> <p>For instance, you could have a table called userattrs, with three columns:</p> <ul> <li>Int user_id</li> <li>String attribute_name</li> <li>String attribute_value</li> </ul> <p>If there's only few, you could store them into cookies for quick retrieval.</p>
6
2008-10-14T10:15:35Z
[ "python", "database", "website", "settings" ]
Store simple user settings in Python
200,599
<p>I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue.</p> <p>The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them.</p> <p>For example, userdb["bob"]["colour_scheme"] would have the value "blue".</p> <p>What is the best way to store it on file? Pickling the dictionary?</p> <p>Are there better ways of doing what I am trying to do?</p>
7
2008-10-14T10:04:46Z
200,630
<p>Here's the simplest way. Use simple variables and <code>import</code> the settings file.</p> <p>Call the file userprefs.py</p> <pre><code># a user prefs file color = 0x010203 font = "times new roman" position = ( 12, 13 ) size = ( 640, 480 ) </code></pre> <p>In your application, you need to be sure that you can import this file. You have <em>many</em> choices.</p> <ol> <li><p>Using <code>PYTHONPATH</code>. Require <code>PYTHONPATH</code> be set to include the directory with the preferences files.</p> <p>a. An explicit command-line parameter to name the file (not the best, but simple)</p> <p>b. An environment variable to name the file.</p></li> <li><p>Extending <code>sys.path</code> to include the user's home directory</p></li> </ol> <p>Example</p> <pre><code>import sys import os sys.path.insert(0,os.path.expanduser("~")) import userprefs print userprefs.color </code></pre>
4
2008-10-14T10:15:49Z
[ "python", "database", "website", "settings" ]
Store simple user settings in Python
200,599
<p>I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue.</p> <p>The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them.</p> <p>For example, userdb["bob"]["colour_scheme"] would have the value "blue".</p> <p>What is the best way to store it on file? Pickling the dictionary?</p> <p>Are there better ways of doing what I am trying to do?</p>
7
2008-10-14T10:04:46Z
200,638
<p>If human readablity of configfiles matters an alternative might be <a href="http://www.python.org/doc/lib/module-ConfigParser.html" rel="nofollow">the ConfigParser module</a> which allows you to read and write .ini like files. But then you are restricted to one nesting level.</p>
1
2008-10-14T10:19:53Z
[ "python", "database", "website", "settings" ]
Store simple user settings in Python
200,599
<p>I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue.</p> <p>The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them.</p> <p>For example, userdb["bob"]["colour_scheme"] would have the value "blue".</p> <p>What is the best way to store it on file? Pickling the dictionary?</p> <p>Are there better ways of doing what I am trying to do?</p>
7
2008-10-14T10:04:46Z
200,950
<p>I would use <a href="http://www.python.org/doc/2.5.2/lib/module-shelve.html" rel="nofollow">shelve</a> or an <a href="http://www.python.org/doc/2.5.2/lib/module-sqlite3.html" rel="nofollow">sqlite</a> database if I would have to store these setting on the file system. Although, since you are building a website you probably use some kind of database so why not just use that?</p>
2
2008-10-14T12:32:07Z
[ "python", "database", "website", "settings" ]
Store simple user settings in Python
200,599
<p>I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue.</p> <p>The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them.</p> <p>For example, userdb["bob"]["colour_scheme"] would have the value "blue".</p> <p>What is the best way to store it on file? Pickling the dictionary?</p> <p>Are there better ways of doing what I am trying to do?</p>
7
2008-10-14T10:04:46Z
201,020
<p>Is there are particular reason you're not using the database for this? it seems the normal and natural thing to do - or store a pickle of the settings in the db keyed on user id or something.</p> <p>You haven't described the usage patterns of the website, but just thinking of a general website - but I would think that keeping the settings in a database would cause much less disk I/O than using files.</p> <p>OTOH, for settings that might be used by client-side code, storing them as javascript in a static file that can be cached would be handy - at the expense of having multiple places you might have settings. (I'd probably store those settings in the db, and rebuild the static files as necessary)</p>
0
2008-10-14T12:50:27Z
[ "python", "database", "website", "settings" ]
Store simple user settings in Python
200,599
<p>I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue.</p> <p>The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them.</p> <p>For example, userdb["bob"]["colour_scheme"] would have the value "blue".</p> <p>What is the best way to store it on file? Pickling the dictionary?</p> <p>Are there better ways of doing what I am trying to do?</p>
7
2008-10-14T10:04:46Z
201,272
<p>I agree with the reply about using Pickled Dictionary. Very simple and effective for storing simple data in a Dictionary structure.</p>
0
2008-10-14T14:01:44Z
[ "python", "database", "website", "settings" ]
Store simple user settings in Python
200,599
<p>I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue.</p> <p>The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them.</p> <p>For example, userdb["bob"]["colour_scheme"] would have the value "blue".</p> <p>What is the best way to store it on file? Pickling the dictionary?</p> <p>Are there better ways of doing what I am trying to do?</p>
7
2008-10-14T10:04:46Z
201,274
<p>If you don't care about being able to edit the file yourself, and want a quick way to persist python objects, go with <a href="http://www.python.org/doc/2.5.2/lib/module-pickle.html" rel="nofollow">pickle</a>. If you do want the file to be readable by a human, or readable by some other app, use <a href="http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html" rel="nofollow">ConfigParser</a>. If you need anything more complex, go with some sort of database, be it relational (<a href="http://www.python.org/doc/2.5.2/lib/module-sqlite3.html" rel="nofollow">sqlite</a>), or object-oriented (<a href="http://www.divmod.org/trac/wiki/DivmodAxiom" rel="nofollow">axiom</a>, <a href="http://wiki.zope.org/ZODB/FrontPage" rel="nofollow">zodb</a>).</p>
0
2008-10-14T14:02:28Z
[ "python", "database", "website", "settings" ]
Store simple user settings in Python
200,599
<p>I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue.</p> <p>The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them.</p> <p>For example, userdb["bob"]["colour_scheme"] would have the value "blue".</p> <p>What is the best way to store it on file? Pickling the dictionary?</p> <p>Are there better ways of doing what I am trying to do?</p>
7
2008-10-14T10:04:46Z
201,298
<p>For a database-driven website, of course, your best option is a db table. I'm assuming that you are not doing the database thing.</p> <p>If you don't care about human-readable formats, then <code>pickle</code> is a simple and straightforward way to go. I've also heard good reports about <code>simplejson</code>.</p> <p>If human readability is important, two simple options present themselves:</p> <p><strong>Module:</strong> Just use a module. If all you need are a few globals and nothing fancy, then this is the way to go. If you really got desperate, you could define classes and class variables to emulate sections. The downside here: if the file will be hand-edited by a user, errors could be hard to catch and debug.</p> <p><strong>INI format:</strong> I've been using <a href="http://www.voidspace.org.uk/python/configobj.html" rel="nofollow">ConfigObj</a> for this, with quite a bit of success. ConfigObj is essentially a replacement for ConfigParser, with support for nested sections and much more. Optionally, you can define expected types or values for a file and validate it, providing a safety net (and important error feedback) for users/administrators.</p>
3
2008-10-14T14:08:57Z
[ "python", "database", "website", "settings" ]
Store simple user settings in Python
200,599
<p>I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue.</p> <p>The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them.</p> <p>For example, userdb["bob"]["colour_scheme"] would have the value "blue".</p> <p>What is the best way to store it on file? Pickling the dictionary?</p> <p>Are there better ways of doing what I am trying to do?</p>
7
2008-10-14T10:04:46Z
202,988
<p>I would use the <a href="http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html">ConfigParser</a> module, which produces some pretty readable and user-editable output for your example:</p> <pre>[bob] colour_scheme: blue british: yes [joe] color_scheme: that's 'color', silly! british: no</pre> <p>The following code would produce the config file above, and then print it out:</p> <pre><code>import sys from ConfigParser import * c = ConfigParser() c.add_section("bob") c.set("bob", "colour_scheme", "blue") c.set("bob", "british", str(True)) c.add_section("joe") c.set("joe", "color_scheme", "that's 'color', silly!") c.set("joe", "british", str(False)) c.write(sys.stdout) # this outputs the configuration to stdout # you could put a file-handle here instead for section in c.sections(): # this is how you read the options back in print section for option in c.options(section): print "\t", option, "=", c.get(section, option) print c.get("bob", "british") # To access the "british" attribute for bob directly </code></pre> <p>Note that ConfigParser only supports strings, so you'll have to convert as I have above for the Booleans. See <a href="http://effbot.org/librarybook/configparser.htm">effbot</a> for a good run-down of the basics.</p>
8
2008-10-14T21:50:29Z
[ "python", "database", "website", "settings" ]
Store simple user settings in Python
200,599
<p>I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue.</p> <p>The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them.</p> <p>For example, userdb["bob"]["colour_scheme"] would have the value "blue".</p> <p>What is the best way to store it on file? Pickling the dictionary?</p> <p>Are there better ways of doing what I am trying to do?</p>
7
2008-10-14T10:04:46Z
203,001
<p>The built-in <a href="http://www.python.org/doc/2.5.2/lib/module-sqlite3.html" rel="nofollow">sqlite3</a> module would probably be far simpler than most alternatives, and gets you ready to update to a full RDBMS should you ever want or need to.</p>
1
2008-10-14T21:58:00Z
[ "python", "database", "website", "settings" ]
How can I unpack binary hex formatted data in Python?
200,738
<p>Using the PHP <a href="http://www.php.net/pack" rel="nofollow">pack()</a> function, I have converted a string into a binary hex representation:</p> <pre><code>$string = md5(time); // 32 character length $packed = pack('H*', $string); </code></pre> <p>The H* formatting means "Hex string, high nibble first".</p> <p>To unpack this in PHP, I would simply use the <a href="http://www.php.net/unpack" rel="nofollow">unpack()</a> function with the H* format flag.</p> <p>How would I unpack this data in Python?</p>
5
2008-10-14T11:08:07Z
200,761
<p>In Python you use the <a href="http://www.python.org/doc/2.5.2/lib/module-struct.html" rel="nofollow">struct</a> module for this.</p> <pre><code>&gt;&gt;&gt; from struct import * &gt;&gt;&gt; pack('hhl', 1, 2, 3) '\x00\x01\x00\x02\x00\x00\x00\x03' &gt;&gt;&gt; unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03') (1, 2, 3) &gt;&gt;&gt; calcsize('hhl') 8 </code></pre> <p>HTH</p>
8
2008-10-14T11:17:11Z
[ "php", "python", "binary", "hex" ]