title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python: Creating map with 2 lists
39,402,690
<p>I want to create map data from 2 list data. I have a simple example like below. What I want to do is create 'new_map' data like below. If it contains specific data, the value should be True.</p> <pre><code>all_s = ['s1', 's2', 's3', 's4'] data = ['s2', 's4'] new_map = {'s1': False, 's2': True, 's3': False, 's4': True} </code></pre> <p>Are there any smart way (like lambda) to implement this? My python env is 3.X. Of course I can resolve this problem if I use for-iter simply. But I wonder there are better ways.</p>
0
2016-09-09T01:57:55Z
39,402,725
<p>Try a <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow">dict comprehension</a>:</p> <pre><code>new_map = {i: i in data for i in all_s} </code></pre>
2
2016-09-09T02:02:14Z
[ "python", "python-3.x" ]
Python: Creating map with 2 lists
39,402,690
<p>I want to create map data from 2 list data. I have a simple example like below. What I want to do is create 'new_map' data like below. If it contains specific data, the value should be True.</p> <pre><code>all_s = ['s1', 's2', 's3', 's4'] data = ['s2', 's4'] new_map = {'s1': False, 's2': True, 's3': False, 's4': True} </code></pre> <p>Are there any smart way (like lambda) to implement this? My python env is 3.X. Of course I can resolve this problem if I use for-iter simply. But I wonder there are better ways.</p>
0
2016-09-09T01:57:55Z
39,402,834
<p>I'd use a dictionary comprehension: </p> <pre><code>x = {i:True if i in data else False for i in all_s} </code></pre>
1
2016-09-09T02:17:16Z
[ "python", "python-3.x" ]
How to speed up printing line by line to a file in Python?
39,402,698
<p>Say I'm printing numbers from two arrays into a file:</p> <pre><code>from numpy import random number_of_points = 10000 a = random.rand(number_of_points) b = random.rand(number_of_points) fh = open('file.txt', 'w') for i in range(number_of_points): for j in range(number_of_points): print('%f %f' % (a[i], b[j]), file=fh) </code></pre> <p>I feel this is making lots of calls to the system to print, whereas sending one call containing this information would be faster. Is this correct? If so, how could I do this? Are there faster ways to implement this?</p>
3
2016-09-09T01:58:47Z
39,402,872
<p><code>print</code> has a lot of bells and whistles you're not using, and you're using C-style looping with indexing instead of direct iteration, both of which add needless overhead. You might be able to speed it up a bit by limiting the Python level work, pushing it to the C layer.</p> <p>For example, in this case, you could replace the whole doubly-nested loop structure with:</p> <pre><code>import itertools # You could use '%f %f\n'.__mod__ as the map function if you like, I just # find the modern format strings a little nicer fh.writelines(itertools.starmap('{} {}\n'.format, itertools.product(a, b))) </code></pre> <p>which uses <code>product</code> to produce the results of your nested loops and indexing directly, <code>starmap</code>+<code>str.format</code> to create the lines, and <code>fh.writelines</code> to exhaust the generator created by <code>starmap</code>, writing all of its outputs directly to the file with a single function call, instead of 100,000,000 calls to to <code>print</code>.</p> <p>Aside from the fixed (unrelated to number of items iterated) setup cost to create the generators and pass the final generator to <code>fh.writelines</code>, the actual iteration, formatting and I/O work will take place entirely at the C layer on the CPython reference interpreter, so it should run quite fast.</p>
2
2016-09-09T02:22:02Z
[ "python", "python-3.x" ]
Accessing individual element of a tuple on in RDD
39,402,754
<p>Can we access individual element of a tuple in RDD in pyspark? In PIG we use $0,$1 etc ... So something similar do we have in pySpark. If the tuple have 10 elements, how to get 5th and 7th element ? Which function I should use. How to retrieve only needed elements.</p>
-2
2016-09-09T02:06:02Z
39,406,795
<p>Is this what you want?</p> <pre><code>rdd57 = rdd.map(lambda x: (x[5], x[7])) </code></pre>
1
2016-09-09T08:08:54Z
[ "python", "apache-spark", "pyspark" ]
Avoid duplicated operations in lambda functions
39,402,791
<p>I'm using a lambda function to extract the number in a string:</p> <pre><code>text = "some text with a number: 31" get_number = lambda info,pattern: re.search('{}\s*(\d)'.format(pattern),info.lower()).group(1) if re.search('{}\s*(\d)'.format(pattern),info.lower()) else None get_number(text,'number:') </code></pre> <p>How can I avoid to make this operation twice?:</p> <pre><code>re.search('{}\s*(\d)'.format(pattern),info.lower() </code></pre>
0
2016-09-09T02:11:29Z
39,402,934
<p>You can use <code>findall()</code> instead, it handles a no match <em>gracefully</em>. <code>or</code> is the only statement needed to satisfy the return conditions. The <code>None</code> is evaluated last, thus returned if an empty list is found (<em>implicit truthiness of literals like lists</em>).</p> <pre><code>&gt;&gt;&gt; get_number = lambda info,pattern: re.findall('{}\s*(\d)'.format(pattern),info.lower()) or None &gt;&gt;&gt; print get_number(text, 'number:') ['3'] &gt;&gt;&gt; print get_number(text, 'Hello World!') &gt;&gt;&gt; </code></pre> <p>That being said, I'd recommend defining a regular <strong>named</strong> function using <code>def</code> instead. You can extract more complex parts of this code to variables, leading to an easier to follow algorithm. Writing long anonymous function can lead to code smells. Something similar to below:</p> <pre><code>def get_number(source_text, pattern): regex = '{}\s*(\d)'.format(pattern) matches = re.findall(regex, source_text.lower()) return matches or None </code></pre>
4
2016-09-09T02:30:26Z
[ "python", "regex", "lambda" ]
Avoid duplicated operations in lambda functions
39,402,791
<p>I'm using a lambda function to extract the number in a string:</p> <pre><code>text = "some text with a number: 31" get_number = lambda info,pattern: re.search('{}\s*(\d)'.format(pattern),info.lower()).group(1) if re.search('{}\s*(\d)'.format(pattern),info.lower()) else None get_number(text,'number:') </code></pre> <p>How can I avoid to make this operation twice?:</p> <pre><code>re.search('{}\s*(\d)'.format(pattern),info.lower() </code></pre>
0
2016-09-09T02:11:29Z
39,402,955
<p>This is super ugly, not going to lie, but it does work and avoids returning a match object if it's found, but does return None when it's not:</p> <pre><code>lambda info,pattern: max(re.findall('{}\s*(\d)'.format(pattern),info.lower()),[None],key=lambda x: x != [])[0] </code></pre>
1
2016-09-09T02:32:41Z
[ "python", "regex", "lambda" ]
Need help verifying a signature with the Python Cryptography library
39,402,792
<p>I'm trying to verify a signature using the Python Cryptography library as stated here <a href="https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/" rel="nofollow">https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/</a> <a href="http://i.stack.imgur.com/I4INn.png" rel="nofollow"><img src="http://i.stack.imgur.com/I4INn.png" alt="enter image description here"></a></p> <p>This is in the context of a client-server TCP chat app, and the client has calculated the signature, and sent it to the client to verify that it is indeed the correct server. The signature is passed to a function to verify.</p> <pre><code>def VerifySignature(signature): with open("server_publickey.pem", "rb") as key_file: public_key = serialization.load_pem_public_key( key_file.read(), #password=None, backend=default_backend() ) verifier = public_key.verifier( signature, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) message = b"the message that the server verified" verifier.update(message) if verifier.verify(): return 1 else: return 0 </code></pre> <p>I notice that 0 is being returned. According to the Cryptography specs, it looks like if the verifier.verify() fails it returns an exception, so I don't know how else to test this.</p>
0
2016-09-09T02:11:40Z
39,585,567
<p><code>verify</code> raises an exception or returns <code>None</code>. Accordingly, this code</p> <pre><code>if verifier.verify(): return 1 else: return 0 </code></pre> <p>will always return 0 even though in reality the verification check has passed. You are correct that the proper way to use <code>verify</code> is to wrap it in a try block and handle the <code>InvalidSignature</code> exception in the event of failure.</p>
0
2016-09-20T04:12:43Z
[ "python", "python-3.x", "rsa", "digital-signature" ]
How to pad a string with leading zeros in Python 3
39,402,795
<p>I'm trying to make <code>length = 001</code> in Python 3 but whenever I try to print it out it truncates the value without the leading zeros (<code>length = 1</code>). How would I stop this happening without having to cast <code>length</code> to a string before printing it out?</p>
0
2016-09-09T02:12:17Z
39,402,853
<p>Python integers don't have an inherent length or number of significant digits. If you want them to print a specific way, you need to convert them to a string. There are several ways you can do so that let you specify things like padding characters and minimum lengths.</p> <p>To pad with zeros to a minimum of three characters, try:</p> <pre><code>length = 1 print(format(length, '03')) </code></pre>
2
2016-09-09T02:19:36Z
[ "python", "python-3.x", "math", "rounding" ]
How to pad a string with leading zeros in Python 3
39,402,795
<p>I'm trying to make <code>length = 001</code> in Python 3 but whenever I try to print it out it truncates the value without the leading zeros (<code>length = 1</code>). How would I stop this happening without having to cast <code>length</code> to a string before printing it out?</p>
0
2016-09-09T02:12:17Z
39,402,910
<p>Using the <code>zfill()</code> helper method to pad the string with zeros as illustrated below:</p> <pre><code>print str(1).zfill(3); </code></pre>
2
2016-09-09T02:26:51Z
[ "python", "python-3.x", "math", "rounding" ]
Failed to install dependency on Bluemix with a personal setup pypiserver
39,402,829
<p>I'm trying to push a python Django application in Bluemix.</p> <p>I use some global dependency, and a personal package which have some global dependency. </p> <p>My application runs good, when I just add my personal package in my application folder. </p> <p>e.g.in requirements.txt:</p> <pre><code>Mezzanine==4.1.0 cartridge Django==1.9.7 -r ./my_personal_package/requirements.txt </code></pre> <p>in ./my_personal_package/requirements.txt: </p> <pre><code>pyOpenSSL==16.0.0 requests==2.9.1 psutil==4.3.0 </code></pre> <p>But, if I package my personal package as a pypi package with pip tool. and put it in a personal pypi server that bluemix can access. My application will be failed to start. it failed on install a cffi package(Error message append in the end of this question)</p> <p>my requirements.txt is as following:</p> <pre><code>-extra-index-url https://mypypiserver.mybluemix.net/repos/simple/ my-personal-package Mezzanine==4.1.0 cartridge Django==1.9.7 </code></pre> <p>I compared the packages downloaded with method 1 and method 2, they are exactly the same. method 2 only failed on installing cffi:</p> <pre><code>2016-09-08T20:40:32.62-0500 [STG/0] OUT Running setup.py install for cffi: started 2016-09-08T20:40:33.42-0500 [STG/0] OUT Running setup.py install for cffi: finished with status 'error' </code></pre> <p>Error Messages:</p> <pre><code>016-09-08T20:40:33.43-0500 [STG/0] OUT Complete output from command /app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-k3BUbl/cffi/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-C_rmOt-record/install-record.txt --single-version-externally-managed --compile: 2016-09-08T20:40:33.43-0500 [STG/0] OUT Perhaps you should add the directory containing `libffi.pc' 2016-09-08T20:40:33.43-0500 [STG/0] OUT to the PKG_CONFIG_PATH environment variable 2016-09-08T20:40:33.43-0500 [STG/0] OUT Package libffi was not found in the pkg-config search path. 2016-09-08T20:40:33.44-0500 [STG/0] OUT Package libffi was not found in the pkg-config search path. 2016-09-08T20:40:33.44-0500 [STG/0] OUT Perhaps you should add the directory containing `libffi.pc' 2016-09-08T20:40:33.44-0500 [STG/0] OUT to the PKG_CONFIG_PATH environment variable 2016-09-08T20:40:33.44-0500 [STG/0] OUT Package libffi was not found in the pkg-config search path. 2016-09-08T20:40:33.44-0500 [STG/0] OUT to the PKG_CONFIG_PATH environment variable 2016-09-08T20:40:33.44-0500 [STG/0] OUT Package libffi was not found in the pkg-config search path. 2016-09-08T20:40:33.43-0500 [STG/0] OUT Package libffi was not found in the pkg-config search path. 2016-09-08T20:40:33.43-0500 [STG/0] OUT Perhaps you should add the directory containing `libffi.pc' 2016-09-08T20:40:33.43-0500 [STG/0] OUT to the PKG_CONFIG_PATH environment variable 2016-09-08T20:40:33.44-0500 [STG/0] OUT No package 'libffi' found 2016-09-08T20:40:33.44-0500 [STG/0] OUT Perhaps you should add the directory containing `libffi.pc' 2016-09-08T20:40:33.44-0500 [STG/0] OUT No package 'libffi' found 2016-09-08T20:40:33.44-0500 [STG/0] OUT Perhaps you should add the directory containing `libffi.pc' 2016-09-08T20:40:33.44-0500 [STG/0] OUT to the PKG_CONFIG_PATH environment variable 2016-09-08T20:40:33.44-0500 [STG/0] OUT No package 'libffi' found 2016-09-08T20:40:33.44-0500 [STG/0] OUT running install 2016-09-08T20:40:33.44-0500 [STG/0] OUT running build 2016-09-08T20:40:33.44-0500 [STG/0] OUT running build_py 2016-09-08T20:40:33.44-0500 [STG/0] OUT creating build 2016-09-08T20:40:33.44-0500 [STG/0] OUT creating build/lib.linux-x86_64-2.7 2016-09-08T20:40:33.44-0500 [STG/0] OUT creating build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/cparser.py -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/vengine_gen.py -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/commontypes.py -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/lock.py -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/recompiler.py -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/backend_ctypes.py -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/vengine_cpy.py -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/__init__.py -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/setuptools_ext.py -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/cffi_opcode.py -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/model.py -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/ffiplatform.py -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/api.py -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/verifier.py -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/_cffi_include.h -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/parse_c_type.h -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT running build_ext 2016-09-08T20:40:33.44-0500 [STG/0] OUT building '_cffi_backend' extension 2016-09-08T20:40:33.44-0500 [STG/0] OUT creating build/temp.linux-x86_64-2.7/c 2016-09-08T20:40:33.45-0500 [STG/0] OUT gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DUSE__THREAD -I/usr/include/ffi -I/usr/include/libffi -I/app/.heroku/python/include/python2.7 -c c/_cffi_backend.c -o build/temp.linux-x86_64-2.7/c/_cffi_backend.o 2016-09-08T20:40:33.45-0500 [STG/0] OUT c/_cffi_backend.c:15:17: fatal error: ffi.h: No such file or directory 2016-09-08T20:40:33.45-0500 [STG/0] OUT #include &lt;ffi.h&gt; 2016-09-08T20:40:33.45-0500 [STG/0] OUT compilation terminated. 2016-09-08T20:40:33.45-0500 [STG/0] OUT error: command 'gcc' failed with exit status 1 2016-09-08T20:40:33.45-0500 [STG/0] OUT ---------------------------------------- 2016-09-08T20:40:33.44-0500 [STG/0] OUT copying cffi/_embedding.h -&gt; build/lib.linux-x86_64-2.7/cffi 2016-09-08T20:40:33.44-0500 [STG/0] OUT creating build/temp.linux-x86_64-2.7 2016-09-08T20:40:34.65-0500 [STG/0] ERR Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-k3BUbl/cffi/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-C_rmOt-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-k3BUbl/cffi/ </code></pre>
0
2016-09-09T02:16:20Z
39,477,431
<p>The cffi installation failed due to "No package 'libffi' found". 'libffi' is notoriously messy to install and use. Since you are using a pypi server hosting dependence packages, the first place that I would like to check is whether the server is setup properly according to <a href="http://cffi.readthedocs.io/en/latest/installation.html" rel="nofollow">cffi installation instructions</a>. </p>
0
2016-09-13T19:15:34Z
[ "python", "django", "ibm-bluemix" ]
square root n by computing the next Xi term
39,402,871
<p>I am stuck on a problem from a textbook. It asks:</p> <blockquote> <p>Write your own square root approximation function using the equation <code>Xk+1 = 1/2 * (Xk + n/(Xk)</code>, where <code>X0 = 1</code>.</p> <p>This equation says that the sqrt'n' can be found by repeatedly computing the next Xi term. The larger number of terms used, the better the answer. Allow your function to have two input parameters, the number that you want the square root of and the number of terms to compute.'</p> </blockquote> <p>I am using Python3.5.2 for this. </p> <p><img src="http://i.stack.imgur.com/ujq7t.jpg" alt="attached a picture of the problem"> </p> <p>Thanks!</p>
0
2016-09-09T02:22:01Z
39,403,203
<p>A new school year, an old Babylonian method.</p> <p>So, I won't solve this for you, but I can get you started.</p> <p>We can write a little function that computes each <code>x_{k+1}</code>:</p> <pre><code>def sqrt_step(n, xk): return 1/2.0 * (xk + float(n)/xk) </code></pre> <p>Let's set <code>n = 100</code>.</p> <pre><code>sqrt_step(100, 1) # returns 50.5 </code></pre> <p>Now let's feed that number into the function a few more times:</p> <pre><code>sqrt_step(100, 50.5) # 26.2 sqrt_step(100, 26.2) # 15.0 sqrt_step(100, 15.0) # 10.8 </code></pre> <p>...this converges to 10 as <code>k</code> goes to infinity.</p> <p>Now, if only there was a way to perform an operation over and over again <code>k</code> times...I'm thinking of a three letter word that starts with 'f' and rhymes with 'ore'...</p> <hr> <h1>EDIT</h1> <p>You've made an honest effort to solve the problem -- which I'm going to <em>assume</em> is a homework <em>practice exercise</em> and <strong>not</strong> an assignment. </p> <p>You can solve this simply by using the <code>sqrt_step</code> function inside of a new function. This can be done as follows:</p> <pre><code>def square_root(n, k): xk = 1 for i in range(k): xk = sqrt_step(n, xk) # or just: xk = 1/2.0 * (xk + float(n)/xk) return xk </code></pre> <p>Tests:</p> <pre><code>square_root(64, 100) # 8.0 square_root(144, 100) # 12.0 </code></pre> <p>As you become more advanced, you will learn about functional programming techniques that allow you to avoid overwriting variables and explicitly writing <code>for</code> loops. For now however, this is the most straightforward approach.</p>
0
2016-09-09T03:07:06Z
[ "python", "square-root", "function-approximation" ]
Django F field iteration
39,402,920
<p>I created a simple Django model to explore F field but could iterate over the field.</p> <pre><code>class PostgreSQLModel(models.Model): class Meta: abstract = True required_db_vendor = 'postgresql' class NullableIntegerArrayModel(PostgreSQLModel): field = ArrayField(models.IntegerField(), blank=True, null=True) </code></pre> <p>Now, from my django shell I created a F object as below.Not sure what this object contains. Does it contain all the ids? How can I iterate over the result?</p> <pre><code>&gt;&gt;&gt; a=F('id') &gt;&gt;&gt; a F(id) &gt;&gt;&gt; dir(a) ['ADD', 'BITAND', 'BITOR', 'DIV', 'MOD', 'MUL', 'POW', 'SUB', '__add__', '__and__', '__class__', '__delattr__', '__dict__', '__dir__', '__div__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__mod__', '__module__', '__mul__', '__ne__', '__new__', '__or__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__weakref__', '_combine', 'asc', 'bitand', 'bitor', 'desc', 'name', 'resolve_expression'] </code></pre>
1
2016-09-09T02:28:05Z
39,403,426
<p>F is not a field.</p> <blockquote> <p>An F() object represents the value of a model field or annotated column. It makes it possible to refer to model field values and perform database operations using them without actually having to pull them out of the database into Python memory. - <a href="https://docs.djangoproject.com/en/1.10/ref/models/expressions/#f-expressions" rel="nofollow">F() expressions</a></p> </blockquote> <p>In summary, you use <code>F()</code> objects whenever you need to reference another field's value in your queries. By itself, <code>F()</code> objects doesn't mean anything. They're used to reference a field value on the same queryset. </p> <p>For example (a very simple example), in your model, if you want to query objects where <code>field</code> value is twice its <code>id</code>, you would need to <a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/#filters-can-reference-fields-on-the-model" rel="nofollow">reference <code>id</code> field's value</a> while filtering, so you could use <code>F()</code> like this:</p> <pre><code>NullableIntegerArrayModel.objects.filter(field=F('id') *2) </code></pre> <p><code>F('id')</code> simply references the <code>id</code> value for that model. Django uses it to create corresponding SQL statement. In this case something like this:</p> <pre><code>'SELECT "app_model"."id", "app_model"."field" FROM "app_model" WHERE "app_model"."field" = (("app_model"."id" * 2))' </code></pre> <p>Without <code>F()</code> expressions you would either write your raw SQL or do the filtering in Python (which reduces the performance especially when there are lots of objects). </p> <hr> <p>References:</p> <ul> <li><a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/#filters-can-reference-fields-on-the-model" rel="nofollow">Filters can reference fields on model</a></li> <li><a href="https://docs.djangoproject.com/en/1.10/ref/models/expressions/#django.db.models.F" rel="nofollow">F expressions</a></li> </ul> <p>From <code>F()</code> class definition:</p> <blockquote> <p>An object capable of resolving references to existing query objects. - <a href="https://docs.djangoproject.com/en/1.10/_modules/django/db/models/expressions/#F" rel="nofollow">F source</a></p> </blockquote>
2
2016-09-09T03:32:51Z
[ "python", "django" ]
I cannot run my python script in powershell?
39,402,932
<p>Okay so before I asked this question, I searched for answers through other questions. For starters, I am learning python through Learnpythonthehardway.org now I am learning a lot and already on the fourth example but I need to solve this as its really bothering me. So when I go to run the file, I type:</p> <pre><code>ex3.py </code></pre> <p>and I get this:</p> <pre><code>ex3.py : The term 'ex3.py' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + ex3.py + ~~~~~~ + CategoryInfo : ObjectNotFound: (ex3.py:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException </code></pre> <p>So then I check my path and its </p> <pre><code>C:\User\Ally&gt; </code></pre> <p>so I save the file under Ally AND it still doesn't work. I am so done and cannot find a solution. since I need my files to run, I found a temporary method and this is how I run my files,</p> <pre><code> C:\Python27\EX\ex2.py </code></pre> <p>Powershell can run python by itself and my CMD as well. I change both PATH and PATHTEXT to run Python and .py files.</p> <p>I do not want to use my temporary fix, I want to find a permanent solution, (A problem should NOT be fixed more than once, if so... it wasn't really fixed)</p>
0
2016-09-09T02:30:12Z
39,403,038
<p>I think you want to run <code>python ex2.py</code> instead of just <code>ex2.py</code>. There is probably a way to get it to run like that but I don't think that is common practice. </p>
0
2016-09-09T02:42:31Z
[ "python", "powershell" ]
I cannot run my python script in powershell?
39,402,932
<p>Okay so before I asked this question, I searched for answers through other questions. For starters, I am learning python through Learnpythonthehardway.org now I am learning a lot and already on the fourth example but I need to solve this as its really bothering me. So when I go to run the file, I type:</p> <pre><code>ex3.py </code></pre> <p>and I get this:</p> <pre><code>ex3.py : The term 'ex3.py' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + ex3.py + ~~~~~~ + CategoryInfo : ObjectNotFound: (ex3.py:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException </code></pre> <p>So then I check my path and its </p> <pre><code>C:\User\Ally&gt; </code></pre> <p>so I save the file under Ally AND it still doesn't work. I am so done and cannot find a solution. since I need my files to run, I found a temporary method and this is how I run my files,</p> <pre><code> C:\Python27\EX\ex2.py </code></pre> <p>Powershell can run python by itself and my CMD as well. I change both PATH and PATHTEXT to run Python and .py files.</p> <p>I do not want to use my temporary fix, I want to find a permanent solution, (A problem should NOT be fixed more than once, if so... it wasn't really fixed)</p>
0
2016-09-09T02:30:12Z
39,406,102
<p>If <strong>ex2.py</strong> is in folder C:\Python27\EX\</p> <p>The PowerShell session would be</p> <pre><code>PS C:\Python27\&gt; python C:\Python27\EX\ex2.py </code></pre>
0
2016-09-09T07:28:53Z
[ "python", "powershell" ]
I cannot run my python script in powershell?
39,402,932
<p>Okay so before I asked this question, I searched for answers through other questions. For starters, I am learning python through Learnpythonthehardway.org now I am learning a lot and already on the fourth example but I need to solve this as its really bothering me. So when I go to run the file, I type:</p> <pre><code>ex3.py </code></pre> <p>and I get this:</p> <pre><code>ex3.py : The term 'ex3.py' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + ex3.py + ~~~~~~ + CategoryInfo : ObjectNotFound: (ex3.py:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException </code></pre> <p>So then I check my path and its </p> <pre><code>C:\User\Ally&gt; </code></pre> <p>so I save the file under Ally AND it still doesn't work. I am so done and cannot find a solution. since I need my files to run, I found a temporary method and this is how I run my files,</p> <pre><code> C:\Python27\EX\ex2.py </code></pre> <p>Powershell can run python by itself and my CMD as well. I change both PATH and PATHTEXT to run Python and .py files.</p> <p>I do not want to use my temporary fix, I want to find a permanent solution, (A problem should NOT be fixed more than once, if so... it wasn't really fixed)</p>
0
2016-09-09T02:30:12Z
39,406,245
<p>PowerShell won't run commands in the current folder by default. Just like on Unix-likes you have to prefix the command with <code>.\</code> or <code>./</code>, so the following should work:</p> <pre><code>.\ex.py </code></pre> <p>That's assuming Python is installed in a way that you can run commands like that, which must include <code>.py</code> in <code>$Env:PATHEXT</code> and a file association for <code>.py</code> files.</p> <p>If there is just a file association but <code>.py</code> is not in <code>$Env:PATHEXT</code> you're going through <code>ShellExecute</code> (you can also enforce this with <code>Invoke-Item</code>) and thus the interpreter cannot live in the same console as your PowerShell session. The interpreter will run, but in a separate window.</p>
0
2016-09-09T07:37:01Z
[ "python", "powershell" ]
Debug the "NaN" error of sklearn using pandas dataframe input
39,402,956
<p>I read my input as pandas dataframe and filled NaN by:</p> <pre><code>df = df.fillna(0) </code></pre> <p>After that I split into train and test set and do a classification using sklearn.</p> <pre><code>features = df.drop('class',axis=1) labels = df['class'] features_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size=0.3, random_state=42) clf.fit(features_train, labels_train) </code></pre> <p>But I still got an "NaN error": ValueError: Input contains NaN, infinity or a value too large for dtype('float32'). It seems that fillna() didn't find the missing data. How can I find where the "NaN" is?</p>
0
2016-09-09T02:32:53Z
39,403,641
<pre><code>df.isnull().sum() </code></pre> <p>that can show you if/where any NaN's exist inside the dataframe</p>
0
2016-09-09T03:58:22Z
[ "python", "pandas", "scikit-learn" ]
Debug the "NaN" error of sklearn using pandas dataframe input
39,402,956
<p>I read my input as pandas dataframe and filled NaN by:</p> <pre><code>df = df.fillna(0) </code></pre> <p>After that I split into train and test set and do a classification using sklearn.</p> <pre><code>features = df.drop('class',axis=1) labels = df['class'] features_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size=0.3, random_state=42) clf.fit(features_train, labels_train) </code></pre> <p>But I still got an "NaN error": ValueError: Input contains NaN, infinity or a value too large for dtype('float32'). It seems that fillna() didn't find the missing data. How can I find where the "NaN" is?</p>
0
2016-09-09T02:32:53Z
39,406,287
<p>You ask </p> <blockquote> <p>How can I find where the "NaN" is</p> </blockquote> <p>Would it be helpful to visualize where the problematic data lie in the frame?</p> <p>You could try <code>matplotlib.pyplot.spy</code></p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt # lets make some initial clean data df = pd.DataFrame( data={ 'alpha': [0, 1, 2], 'beta': [3, 4, 5], 'gamma': [6, 7, 8] }, index=['one', 'two', 'three'] ) # add some problematic points # `NaN`s, infinities and stuff that is # just not numeric df.loc['one', 'beta'] = 'not a number but not NaN' df.loc['two', 'alpha'] = np.NaN df.loc['three', 'gamma'] = np.infty fig, axes = plt.subplots(1, 3) axes[0].spy(df.isnull()) axes[0].set_title('NaN elements') axes[1].spy(df == np.infty) axes[1].set_title('infinite elements') axes[2].spy(~df.applymap(np.isreal)) axes[2].set_title('Non numeric elements') </code></pre>
-1
2016-09-09T07:39:03Z
[ "python", "pandas", "scikit-learn" ]
Openpyxl. Max_columns giving error
39,402,970
<p>I'm using openpyxl-2.4.0-b1 and Python version 34. Following is my code:</p> <p>from openpyxl import load_workbook from openpyxl import Workbook</p> <pre><code>filename= str(input('Please enter the filename name, with the entire path and extension: ')) wb = load_workbook(filename) ws = wb.worksheets[0] row_main = 1 #Main Program starts here. Loop for the entire file print ('Col =', ws.max_column()) while (row_main &lt;(ws.max_row())): #Process rows for each column print ('ROW =', row_main) row_main += 1 </code></pre> <p>It runs into an error: Traceback (most recent call last): print ('Col =', ws.max_column()) TypeError: 'int' object is not callable</p> <p>I can't use <em>get</em> because it has been deprecated. Many thanks in advance. </p>
-1
2016-09-09T02:34:07Z
39,403,343
<p>As <code>max_column</code> is <code>property</code>, so just use the name to get its value:</p> <pre><code>print('Col =', ws.max_column) </code></pre> <p>Also apply on <code>max_row</code>:</p> <pre><code>while (row_main &lt; ws.max_row): </code></pre>
0
2016-09-09T03:21:53Z
[ "python", "openpyxl" ]
cx_Oracle with multiple Oracle client versions
39,402,974
<p>I am running Python 2.7 and am using cx_Oracle on a linux 64 bit OS. I need to be able to run against either an 11.2 or 12.1 Oracle client since I can't be sure which client will be installed on the deployed target. I know there are cx_Oracle built against each Oracle client. How can I be sure that the app will work? I should mention I am using pyinstaller to package up the application. Is there a version of cx_Oracle the is built against both Oracle clients or am I required to have two different versions of my application...one for 11g and one for a 12c client?</p>
0
2016-09-09T02:34:49Z
39,412,375
<p>Although in theory you should be able to build an Oracle 11g version of cx_Oracle and use it with both an Oracle 11g and Oracle 12c client, I wouldn't recommend it. If you are able to convince your users to use the Oracle 12c instant client that would be the simplest. That client is able to access both 11g and 12c databases without any difficulty. But if that isn't possible, the other option is the following:</p> <p>1) Compile cx_Oracle for both 11g and 12c and place both copies in your installation named (for example) cx_Oracle_11g.so and cx_Oracle_12c.so.</p> <p>2) Import cx_Oracle dynamically using code like the following:</p> <pre><code>for version in ("11g", "12c"): fileName = os.path.join(installDir, "cx_Oracle_%s.so" % version) try: module = imp.load_dynamic("cx_Oracle", fileName) break except ImportError: pass </code></pre> <p>3) Use the dynamically imported module wherever you need it in the same way as before. Since the dynamically loaded module was named cx_Oracle you should be able to import it in other code in the regular way and it will find the one you dynamically loaded.</p>
0
2016-09-09T13:10:36Z
[ "python", "python-2.7", "cx-oracle" ]
Python - NLTK separating punctuation
39,402,983
<p>i'm pretty new to Python, i'm trying to use NLTK to remove stopwords of my file. The code is working, however it's separating punctuation, if my text is a tweet with a mention (@user), i get "@ user". Later i'll need to do a word frequency, and i need mentions and hashtags to be working properly. My code:</p> <pre><code>from nltk.corpus import stopwords from nltk.tokenize import word_tokenize import codecs arquivo = open('newfile.txt', encoding="utf8") linha = arquivo.readline() while linha: stop_word = set(stopwords.words("portuguese")) word_tokens = word_tokenize(linha) filtered_sentence = [w for w in word_tokens if not w in stop_word] filtered_sentence = [] for w in word_tokens: if w not in stop_word: filtered_sentence.append(w) fp = codecs.open("stopwords.txt", "a", "utf-8") for words in (filtered_sentence): fp.write(words + " ") fp.write("\n") linha= arquivo.readline() </code></pre> <p><strong>EDIT</strong> Not sure if this is the best way to do it, but i fixed it this way:</p> <pre><code>for words in (filtered_sentence): fp.write(words) if words not in string.punctuation: fp.write(" ") fp.write("\n") </code></pre>
2
2016-09-09T02:35:50Z
39,409,120
<p>instead of <code>word_tokenize</code>, you could use <a href="http://www.nltk.org/api/nltk.tokenize.html#module-nltk.tokenize.casual" rel="nofollow">Twitter-aware tokenizer</a> provided by nltk:</p> <pre><code>from nltk.tokenize import TweetTokenizer ... tknzr = TweetTokenizer() ... word_tokens = tknzr.tokenize(linha) </code></pre>
3
2016-09-09T10:12:06Z
[ "python", "nltk" ]
Showing results python command to the web cgi
39,403,120
<p>I have a python script and it runs well if executed in a terminal or command line , but after I try even internal server error occurred . how to enhance the script to be run on the web.</p> <p>HTML</p> <pre><code>&lt;html&gt;&lt;body&gt; &lt;form enctype="multipart/form-data" action="http://localhost/cgi-bin/coba5.py" method="post"&gt; &lt;p&gt;File: &lt;input type="file" name="file"&gt;&lt;/p&gt; &lt;p&gt;&lt;input type="submit" value="Upload"&gt;&lt;/p&gt; &lt;/form&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p>PYTHON</p> <pre><code>#!/usr/bin/python import cgi, os import cgitb; cgitb.enable() import simplejson as json import optparse import sys try: # Windows needs stdio set for binary mode. import msvcrt msvcrt.setmode (0, os.O_BINARY) # stdin = 0 msvcrt.setmode (1, os.O_BINARY) # stdout = 1 except ImportError: pass form = cgi.FieldStorage() # A nested FieldStorage instance holds the file fileitem = form['file'] fn = os.path.basename(fileitem.filename) data = open('/tmp/upload-cgi/' + fn, 'wb').write(fileitem.file.read()) data=fileitem.file.read() location_database = open('/home/bioinformatics2/DW/taxo.json', 'r') database = json.load(location_database) for line in data: for taxonomy in database: if taxonomy["genus"] == line.replace('\n','') : print "Kingdom: %s," % taxonomy['kingdom'], print "phylum: %s," % taxonomy['phylum'], print "class: %s," % taxonomy['class'], print "order: %s," % taxonomy['order'], print "family: %s," % taxonomy['family'], print "genus: %s" % taxonomy['genus'] break else: print ("No found genus on taxanomy") </code></pre>
0
2016-09-09T02:54:27Z
39,403,286
<p>You're not outputting the HTTP header. At a minimum, you need to output:</p> <pre><code>print "Content-Type: text/plain" print "" </code></pre> <p>You are also reading the file twice:</p> <pre><code>data = open('/tmp/upload-cgi/' + fn, 'wb').write(fileitem.file.read()) data=fileitem.file.read() </code></pre> <p>The second <code>fileitem.file.read()</code> will probably not read any content, since the file should already be at the end-of-file, and so <code>data</code> will be empty.</p>
1
2016-09-09T03:17:01Z
[ "python", "cgi", "cgi-bin" ]
Why does re.match/re.search work, but re.findall doesn't work?
39,403,125
<p>I use re.match to find the string like this:</p> <pre><code>print(re.match('''#include(\s)?".*"''', '''#include "my.h"''')) </code></pre> <p>then I got the result like this:</p> <pre><code>&lt;_sre.SRE_Match object; span=(0, 15), match='#include "my.h"'&gt; </code></pre> <p>and then I replace match function:</p> <pre><code>print(re.findall('''#include(\s)?".*"''', '''#include "my.h"''')) </code></pre> <p>the result is:</p> <pre><code>[' '] </code></pre> <p>I was confused, why dosen't <code>re.findall</code> return the matched string? What's wrong with my regular expression?</p>
0
2016-09-09T02:54:54Z
39,403,162
<p>From <code>help(re.findall)</code>:</p> <blockquote> <p>Return a list of all non-overlapping matches in the string.</p> <p>If one or more capturing groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.</p> <p>Empty matches are included in the result.</p> </blockquote> <p>Your parenthesized bit, <code>(\s)</code>, is a capturing group, so <code>re.findall</code> returns a list of the captures. There&rsquo;s only one capturing group, so each item in the list is just a string, rather than a tuple.</p> <p>You can make the group non-capturing using <code>?:</code>, i.e. <code>(?:\s)?</code>. That isn&rsquo;t very useful at that point, though, since it&rsquo;s equivalent to just <code>\s?</code>. For more flexibility &ndash; e.g. if you ever need to capture more than one part &ndash; <code>re.finditer</code> is probably the best way to go:</p> <pre><code>for m in re.finditer(r'#include\s*"(.*?)"', '#include "my.h"'): print('Included %s using %s' % (m.group(1), m.group(0))) </code></pre>
0
2016-09-09T03:00:58Z
[ "python", "regex" ]
RSA encryption python not working with small primes
39,403,153
<p>I have implemented RSA encryption and decryption code which is working for values <code>p,q,d = 61,53,17</code>. I took these values as they are mentioned in wikipedia. I beleive that p and q should be prime and d is chosen such that d and phi(n) are relatively prime.</p> <p>If I change the values to <code>p,q,d = 3,17,19</code>, my decryption is not working. Can you please help me with this? Here is my code:</p> <pre><code>#!/usr/bin/python3 # -*- coding: utf-8 -*- def main(): str = 'computer' p,q,d = 61,53,17 #p,q,d = 3,17,19 cipher_text = list() plain_text = list() for c in str: cipher_char = EncryptCharRSA(c, p, q ,d) cipher_text.append(cipher_char) for x in cipher_text: plain_char = DecryptCharRSA(x, p, q, d) plain_text.append(plain_char) print ('Original Message: ', str) print ('Encrypted Message(UTF-8 Unicode characters) : ', end='') for element in cipher_text: print(element,end = '') print ('\nDecrypted Message: ', end='') for element in plain_text: print(element,end='') def EncryptCharRSA(msg , p, q, d): n = p * q phi = (p-1) * (q-1) cipher_no = 0 cipher_char = '' for c in msg: # conver char to ascii for calculation cipher_no = (ord(c)** d) % n cipher_char = chr(cipher_no) return cipher_char #print (cipher_no) #plain_no = (cipher_no ** d) % n def DecryptCharRSA(msg,p, q,d): n = p * q phi = (p-1) * (q-1) e = ModularMultiplicativeInverse(d,phi) for c in msg: plain_no = (ord(c) ** e) % n plain_char = chr(plain_no) return plain_char # Get modular multiplicative inverse def ModularMultiplicativeInverse(d,n): i = 1 while True: if (d * i) % n == 1: return i i = i + 1 if __name__ == '__main__' : main() </code></pre>
0
2016-09-09T02:59:22Z
39,417,336
<p>What you call <code>d</code> is actually <code>e</code> the public exponent and what you call <code>e</code> is actually <code>d</code> the private exponent. </p> <p>Naming aside, your problem is that you're encrypting plaintext character code points that are larger than or equal to <code>n</code>. If they are, then you're actually encrypting not <code>ord("A")</code> (=65), but rather <code>ord("A") % n</code>. For small <code>n</code> as in your case this would lead to unrecoverable ciphertext:</p> <pre><code>&gt;&gt;&gt; n = 3 * 17 # 51 &gt;&gt;&gt; ord("A") 65 &gt;&gt;&gt; ord("A") % n 14 </code></pre> <p>And that is exactly that you would be able to decrypt. RSA is not something that can be used to encrypt arbitrarily big data. Normally, you would combine it with a secure and fast block cipher such as AES through <a href="https://en.wikipedia.org/wiki/Hybrid_cryptosystem" rel="nofollow">hybrid encryption</a>.</p>
2
2016-09-09T18:04:06Z
[ "python", "python-3.x", "cryptography", "rsa", "modular-arithmetic" ]
Writing regular expression in python
39,403,156
<p>I am weak in writing regular expressions so I'm going to need some help on the one. I need a regular expression that match to <code>section 7.01</code> and then <code>(a)</code></p> <p>Basically with <code>section</code> can be followed by any number like <code>6.1</code>/<code>7.1</code>/<code>2.1</code></p> <p>Examples:</p> <pre><code>SECTION 7.01. Events of Default. If any of the following events ("Events of Default") shall occur: (a) any Borrower shall fail to pay any principal of any Loan when and as the same shall become due and payable, whether at the due date thereof or at a date fixed for prepayment thereof or otherwise; </code></pre> <p>I am trying to write an regular expression which can give me groups which contains these</p> <p>Group 1</p> <pre><code>SECTION 7.01. Events of Default. If any of the following events ("Events of Default") shall occur: </code></pre> <p>Group 2</p> <pre><code>(a) any Borrower shall fail to pay any principal of any Loan when and as the same shall become due and payable, whether at the due date thereof or at a date fixed for prepayment thereof or otherwise; </code></pre> <p>Also there can be more points after <code>(a)</code> like <code>b</code> and so on.</p> <p>Please help me out in writing an regular expression.</p>
2
2016-09-09T02:59:34Z
39,403,402
<p>I got this to work:</p> <pre><code>s = """ SECTION 7.01. Events of Default. If any of the following events ("Events of Default") shall occur: (a) any Borrower shall fail to pay any principal of any Loan when and as the same shall become due and payable, whether at the due date thereof or at a date fixed for prepayment thereof or otherwise; """ r = r'(SECTION 7\.01\.[\s\w\.()"]*:)[\s]*(\(a\)[\s\w,]*;)' mo = re.search(r, s) print('Group 1: ' + mo.group(1)) print('Group 2: ' + mo.group(2)) </code></pre> <p>If you wanted to make it generic, so you could grab the any number or section, you could try:</p> <pre><code>r = r'(SECTION [1-9]\.[0-9]{2}\.[\s\w\.()"]*:)[\s]*(\([a-z]\)[\s\w,]*;)' </code></pre>
0
2016-09-09T03:28:40Z
[ "python", "regex" ]
Writing regular expression in python
39,403,156
<p>I am weak in writing regular expressions so I'm going to need some help on the one. I need a regular expression that match to <code>section 7.01</code> and then <code>(a)</code></p> <p>Basically with <code>section</code> can be followed by any number like <code>6.1</code>/<code>7.1</code>/<code>2.1</code></p> <p>Examples:</p> <pre><code>SECTION 7.01. Events of Default. If any of the following events ("Events of Default") shall occur: (a) any Borrower shall fail to pay any principal of any Loan when and as the same shall become due and payable, whether at the due date thereof or at a date fixed for prepayment thereof or otherwise; </code></pre> <p>I am trying to write an regular expression which can give me groups which contains these</p> <p>Group 1</p> <pre><code>SECTION 7.01. Events of Default. If any of the following events ("Events of Default") shall occur: </code></pre> <p>Group 2</p> <pre><code>(a) any Borrower shall fail to pay any principal of any Loan when and as the same shall become due and payable, whether at the due date thereof or at a date fixed for prepayment thereof or otherwise; </code></pre> <p>Also there can be more points after <code>(a)</code> like <code>b</code> and so on.</p> <p>Please help me out in writing an regular expression.</p>
2
2016-09-09T02:59:34Z
39,403,552
<p>You can use the following approach, however, multiple <strong>assumptions</strong> are made. The section headers must begin with <code>SECTION</code> and end with a colon <code>:</code>. Secondly the sub-sections must begin with <em>matching</em> parenthesis', and end with a semi-colon. </p> <pre><code>import re def extract_groups(s): sanitized_string = ''.join(line.strip() for line in s.split('\n')) sections = re.findall(r'SECTION.*?:', sanitized_string) sub_sections = re.findall(r'\([a-z]\).*?;', sanitized_string) return sections, sub_sections </code></pre> <p><strong>Sample Output:</strong></p> <pre><code>&gt;&gt;&gt; s = """SECTION 7.01. Events of Default. If any of the following events ("Events of Default") shall occur: (a) Whether at the due date thereof or at a date fixed for prepayment thereof or otherwise; (b) Test; SECTION 7.02. Second section:""" &gt;&gt;&gt; print extract_groups(s) (['SECTION 7.01. Events of Default. If any of the following events("Events of Default") shall occur:', 'SECTION 7.02. Second section:'], ['(a) Whether at the due date thereofor at a date fixed for prepayment thereof or otherwise;', '(b) Test;']) </code></pre>
4
2016-09-09T03:47:12Z
[ "python", "regex" ]
Writing regular expression in python
39,403,156
<p>I am weak in writing regular expressions so I'm going to need some help on the one. I need a regular expression that match to <code>section 7.01</code> and then <code>(a)</code></p> <p>Basically with <code>section</code> can be followed by any number like <code>6.1</code>/<code>7.1</code>/<code>2.1</code></p> <p>Examples:</p> <pre><code>SECTION 7.01. Events of Default. If any of the following events ("Events of Default") shall occur: (a) any Borrower shall fail to pay any principal of any Loan when and as the same shall become due and payable, whether at the due date thereof or at a date fixed for prepayment thereof or otherwise; </code></pre> <p>I am trying to write an regular expression which can give me groups which contains these</p> <p>Group 1</p> <pre><code>SECTION 7.01. Events of Default. If any of the following events ("Events of Default") shall occur: </code></pre> <p>Group 2</p> <pre><code>(a) any Borrower shall fail to pay any principal of any Loan when and as the same shall become due and payable, whether at the due date thereof or at a date fixed for prepayment thereof or otherwise; </code></pre> <p>Also there can be more points after <code>(a)</code> like <code>b</code> and so on.</p> <p>Please help me out in writing an regular expression.</p>
2
2016-09-09T02:59:34Z
39,403,795
<p>In an effort to help you learn, should you have to write another set of regex, I would recommend you check out the docs below: <a href="https://docs.python.org/3/howto/regex.html#regex-howto" rel="nofollow">https://docs.python.org/3/howto/regex.html#regex-howto</a></p> <p>This is the "easy" introduction to python regex. Essentially, you're going to define a pattern, and use the above link as a reference to build your pattern as you need it. Then, call the pattern to apply it to whatever needs processing. </p>
0
2016-09-09T04:17:05Z
[ "python", "regex" ]
python lambda PyCharm suggests adding @Property decorator to function
39,403,168
<pre><code> def establishedSessions(self): return reduce(lambda x, y: x and y, loggedInUsers.values()) </code></pre> <p>So I have a dictionary of sessions with key of username and value is a Boolean indicating if that user is logged in. I want to know if all users are connected which this function does nicely. PyCharm is suggesting I add a @Property decorator. </p> <p>I think I kind of understand what the @Property decorator does but I don't see why it would apply in this case. </p>
0
2016-09-09T03:01:46Z
39,403,276
<p>The <code>@property</code> decorator (not <code>@Property</code>) creates a descriptor that allows you to access what looks like a member variable of an object but whose value is the return value of your function. I.e. you would reference <code>obj.established_sessions</code> rather than <code>obj.established_sessions()</code>.</p> <p>A property cannot take parameters, and generally should not have side effects. Your function meets both criteria, so it could easily be a property. It doesn't have to be one.</p>
2
2016-09-09T03:15:35Z
[ "python", "lambda", "properties" ]
Python opencv sorting contours
39,403,183
<p>I am following this question:</p> <p><a href="http://stackoverflow.com/questions/38654302/how-can-i-sort-contours-from-left-to-right-and-top-to-bottom">How can I sort contours from left to right and top to bottom?</a></p> <p>to sort contours from left-to-right and top-to-bottom. However, my contours are found using this (OpenCV 3):</p> <pre><code>im2, contours, hierarchy = cv2.findContours(threshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) </code></pre> <p>and they are formatted like this:</p> <pre><code> array([[[ 1, 1]], [[ 1, 36]], [[63, 36]], [[64, 35]], [[88, 35]], [[89, 34]], [[94, 34]], [[94, 1]]], dtype=int32)] </code></pre> <p>When I run the code </p> <pre><code>max_width = max(contours, key=lambda r: r[0] + r[2])[0] max_height = max(contours, key=lambda r: r[3])[3] nearest = max_height * 1.4 contours.sort(key=lambda r: (int(nearest * round(float(r[1])/nearest)) * max_width + r[0])) </code></pre> <p>I am getting the error </p> <pre><code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() </code></pre> <p>so I changed it to this:</p> <pre><code>max_width = max(contours, key=lambda r: np.max(r[0] + r[2]))[0] max_height = max(contours, key=lambda r: np.max(r[3]))[3] nearest = max_height * 1.4 contours.sort(key=lambda r: (int(nearest * round(float(r[1])/nearest)) * max_width + r[0])) </code></pre> <p>but now I am getting the error:</p> <p><code>TypeError: only length-1 arrays can be converted to Python scalars</code></p> <p><strong>EDIT:</strong></p> <p>After reading the answer below I modified my code:</p> <p><strong>EDIT 2</strong></p> <p>This is the code that I use to "dilate" the characters and find the contours</p> <pre><code>kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(35,35)) # dilate the image to get text # binaryContour is just the black and white image shown below dilation = cv2.dilate(binaryContour,kernel,iterations = 2) </code></pre> <p><strong>END OF EDIT 2</strong></p> <pre><code>im2, contours, hierarchy = cv2.findContours(dilation,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) myContours = [] # Process the raw contours to get bounding rectangles for cnt in reversed(contours): epsilon = 0.1*cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt,epsilon,True) if len(approx == 4): rectangle = cv2.boundingRect(cnt) myContours.append(rectangle) max_width = max(myContours, key=lambda r: r[0] + r[2])[0] max_height = max(myContours, key=lambda r: r[3])[3] nearest = max_height * 1.4 myContours.sort(key=lambda r: (int(nearest * round(float(r[1])/nearest)) * max_width + r[0])) i=0 for x,y,w,h in myContours: letter = binaryContour[y:y+h, x:x+w] cv2.rectangle(binaryContour,(x,y),(x+w,y+h),(255,255,255),2) cv2.imwrite("pictures/"+str(i)+'.png', letter) # save contour to file i+=1 </code></pre> <p>Contours before sorting:</p> <pre><code>[(1, 1, 94, 36), (460, 223, 914, 427), (888, 722, 739, 239), (35,723, 522, 228), (889, 1027, 242, 417), (70, 1028, 693, 423), (1138, 1028, 567, 643), (781, 1030, 98, 413), (497, 1527, 303, 132), (892, 1527, 168, 130), (37, 1719, 592, 130), (676, 1721, 413, 129), (1181, 1723, 206, 128), (30, 1925, 997, 236), (1038, 1929, 170, 129), (140, 2232, 1285, 436)] </code></pre> <p>Contours after sorting:</p> <p>(<strong>NOTE:</strong> This is not the order I want the contours to be sorted in. Refer to image at the bottom)</p> <pre><code>[(1, 1, 94, 36), (460, 223, 914, 427), (35, 723, 522, 228), (70,1028, 693, 423), (781, 1030, 98, 413), (888, 722, 739, 239), (889, 1027, 242, 417), (1138, 1028, 567, 643), (30, 1925, 997, 236), (37, 1719, 592, 130), (140, 2232, 1285, 436), (497, 1527, 303, 132), (676, 1721, 413, 129), (892, 1527, 168, 130), (1038, 1929, 170, 129), (1181, 1723, 206, 128)] </code></pre> <p>Image I am working with</p> <p><a href="http://i.stack.imgur.com/9VayB.png" rel="nofollow"><img src="http://i.stack.imgur.com/9VayB.png" alt="enter image description here"></a></p> <p>I want to find the contours in the following order: <a href="http://i.stack.imgur.com/s4jKm.png" rel="nofollow"><img src="http://i.stack.imgur.com/s4jKm.png" alt="enter image description here"></a></p> <p>Dilation image used for finding contours <a href="http://i.stack.imgur.com/sTyvW.png" rel="nofollow"><img src="http://i.stack.imgur.com/sTyvW.png" alt="enter image description here"></a></p>
7
2016-09-09T03:04:28Z
39,411,372
<p>It appears the <a href="http://stackoverflow.com/questions/38654302/how-can-i-sort-contours-from-left-to-right-and-top-to-bottom">question</a> you linked works not with the raw contours but first obtains a bounding rectangle using <code>cv2.boundingRect</code>. Only then does it make sense to calculate <code>max_width</code> and <code>max_height</code>. The code you posted suggests that you are trying to sort the raw contours, not bounding rectangles. If that is not the case, can you provide a more complete piece of your code, including a list of multiple contours that you are trying to sort?</p>
0
2016-09-09T12:14:59Z
[ "python", "python-2.7", "opencv", "lambda", "opencv3.0" ]
Python opencv sorting contours
39,403,183
<p>I am following this question:</p> <p><a href="http://stackoverflow.com/questions/38654302/how-can-i-sort-contours-from-left-to-right-and-top-to-bottom">How can I sort contours from left to right and top to bottom?</a></p> <p>to sort contours from left-to-right and top-to-bottom. However, my contours are found using this (OpenCV 3):</p> <pre><code>im2, contours, hierarchy = cv2.findContours(threshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) </code></pre> <p>and they are formatted like this:</p> <pre><code> array([[[ 1, 1]], [[ 1, 36]], [[63, 36]], [[64, 35]], [[88, 35]], [[89, 34]], [[94, 34]], [[94, 1]]], dtype=int32)] </code></pre> <p>When I run the code </p> <pre><code>max_width = max(contours, key=lambda r: r[0] + r[2])[0] max_height = max(contours, key=lambda r: r[3])[3] nearest = max_height * 1.4 contours.sort(key=lambda r: (int(nearest * round(float(r[1])/nearest)) * max_width + r[0])) </code></pre> <p>I am getting the error </p> <pre><code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() </code></pre> <p>so I changed it to this:</p> <pre><code>max_width = max(contours, key=lambda r: np.max(r[0] + r[2]))[0] max_height = max(contours, key=lambda r: np.max(r[3]))[3] nearest = max_height * 1.4 contours.sort(key=lambda r: (int(nearest * round(float(r[1])/nearest)) * max_width + r[0])) </code></pre> <p>but now I am getting the error:</p> <p><code>TypeError: only length-1 arrays can be converted to Python scalars</code></p> <p><strong>EDIT:</strong></p> <p>After reading the answer below I modified my code:</p> <p><strong>EDIT 2</strong></p> <p>This is the code that I use to "dilate" the characters and find the contours</p> <pre><code>kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(35,35)) # dilate the image to get text # binaryContour is just the black and white image shown below dilation = cv2.dilate(binaryContour,kernel,iterations = 2) </code></pre> <p><strong>END OF EDIT 2</strong></p> <pre><code>im2, contours, hierarchy = cv2.findContours(dilation,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) myContours = [] # Process the raw contours to get bounding rectangles for cnt in reversed(contours): epsilon = 0.1*cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt,epsilon,True) if len(approx == 4): rectangle = cv2.boundingRect(cnt) myContours.append(rectangle) max_width = max(myContours, key=lambda r: r[0] + r[2])[0] max_height = max(myContours, key=lambda r: r[3])[3] nearest = max_height * 1.4 myContours.sort(key=lambda r: (int(nearest * round(float(r[1])/nearest)) * max_width + r[0])) i=0 for x,y,w,h in myContours: letter = binaryContour[y:y+h, x:x+w] cv2.rectangle(binaryContour,(x,y),(x+w,y+h),(255,255,255),2) cv2.imwrite("pictures/"+str(i)+'.png', letter) # save contour to file i+=1 </code></pre> <p>Contours before sorting:</p> <pre><code>[(1, 1, 94, 36), (460, 223, 914, 427), (888, 722, 739, 239), (35,723, 522, 228), (889, 1027, 242, 417), (70, 1028, 693, 423), (1138, 1028, 567, 643), (781, 1030, 98, 413), (497, 1527, 303, 132), (892, 1527, 168, 130), (37, 1719, 592, 130), (676, 1721, 413, 129), (1181, 1723, 206, 128), (30, 1925, 997, 236), (1038, 1929, 170, 129), (140, 2232, 1285, 436)] </code></pre> <p>Contours after sorting:</p> <p>(<strong>NOTE:</strong> This is not the order I want the contours to be sorted in. Refer to image at the bottom)</p> <pre><code>[(1, 1, 94, 36), (460, 223, 914, 427), (35, 723, 522, 228), (70,1028, 693, 423), (781, 1030, 98, 413), (888, 722, 739, 239), (889, 1027, 242, 417), (1138, 1028, 567, 643), (30, 1925, 997, 236), (37, 1719, 592, 130), (140, 2232, 1285, 436), (497, 1527, 303, 132), (676, 1721, 413, 129), (892, 1527, 168, 130), (1038, 1929, 170, 129), (1181, 1723, 206, 128)] </code></pre> <p>Image I am working with</p> <p><a href="http://i.stack.imgur.com/9VayB.png" rel="nofollow"><img src="http://i.stack.imgur.com/9VayB.png" alt="enter image description here"></a></p> <p>I want to find the contours in the following order: <a href="http://i.stack.imgur.com/s4jKm.png" rel="nofollow"><img src="http://i.stack.imgur.com/s4jKm.png" alt="enter image description here"></a></p> <p>Dilation image used for finding contours <a href="http://i.stack.imgur.com/sTyvW.png" rel="nofollow"><img src="http://i.stack.imgur.com/sTyvW.png" alt="enter image description here"></a></p>
7
2016-09-09T03:04:28Z
39,445,901
<p>What you actually need is to devise a formula to convert your contour information to a rank and use that rank to sort the contours, Since you need to sort the contours from top to Bottom and left to right so your formula must involve the <code>origin</code> of a given contour to calculate its rank. For example we can use this simple method:</p> <pre><code>def get_contour_precedence(contour, cols): origin = cv2.boundingRect(contour) return origin[1] * cols + origin[0] </code></pre> <p>It gives a rank to each contour depending upon the origin of contour. It varies largely when two consecutive contours lie vertically but varies marginally when contours are stacked horizontally. So in this way, First the contours would be grouped from Top to Bottom and in case of Clash the less variant value among the horizontal laid contours would be used. </p> <pre><code>import cv2 def get_contour_precedence(contour, cols): tolerance_factor = 10 origin = cv2.boundingRect(contour) return ((origin[1] // tolerance_factor) * tolerance_factor) * cols + origin[0] img = cv2.imread("/Users/anmoluppal/Downloads/9VayB.png", 0) _, img = cv2.threshold(img, 70, 255, cv2.THRESH_BINARY) im, contours, h = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours.sort(key=lambda x:get_contour_precedence(x, img.shape[1])) # For debugging purposes. for i in xrange(len(contours)): img = cv2.putText(img, str(i), cv2.boundingRect(contours[i])[:2], cv2.FONT_HERSHEY_COMPLEX, 1, [125]) </code></pre> <p><a href="http://i.stack.imgur.com/ooNMj.png" rel="nofollow"><img src="http://i.stack.imgur.com/ooNMj.png" alt="enter image description here"></a></p> <p>If you see closely, the third row where <code>3, 4, 5, 6</code> contours are placed the <code>6</code> comes between 3 and 5, The reason is that the <code>6</code>th contour is slightly below the line of <code>3, 4, 5</code> contours.</p> <p>Tell me is you want the output in other way around we can tweak the <code>get_contour_precedence</code> to get <code>3, 4, 5, 6</code> ranks of contour corrected. </p>
3
2016-09-12T08:10:37Z
[ "python", "python-2.7", "opencv", "lambda", "opencv3.0" ]
Python opencv sorting contours
39,403,183
<p>I am following this question:</p> <p><a href="http://stackoverflow.com/questions/38654302/how-can-i-sort-contours-from-left-to-right-and-top-to-bottom">How can I sort contours from left to right and top to bottom?</a></p> <p>to sort contours from left-to-right and top-to-bottom. However, my contours are found using this (OpenCV 3):</p> <pre><code>im2, contours, hierarchy = cv2.findContours(threshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) </code></pre> <p>and they are formatted like this:</p> <pre><code> array([[[ 1, 1]], [[ 1, 36]], [[63, 36]], [[64, 35]], [[88, 35]], [[89, 34]], [[94, 34]], [[94, 1]]], dtype=int32)] </code></pre> <p>When I run the code </p> <pre><code>max_width = max(contours, key=lambda r: r[0] + r[2])[0] max_height = max(contours, key=lambda r: r[3])[3] nearest = max_height * 1.4 contours.sort(key=lambda r: (int(nearest * round(float(r[1])/nearest)) * max_width + r[0])) </code></pre> <p>I am getting the error </p> <pre><code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() </code></pre> <p>so I changed it to this:</p> <pre><code>max_width = max(contours, key=lambda r: np.max(r[0] + r[2]))[0] max_height = max(contours, key=lambda r: np.max(r[3]))[3] nearest = max_height * 1.4 contours.sort(key=lambda r: (int(nearest * round(float(r[1])/nearest)) * max_width + r[0])) </code></pre> <p>but now I am getting the error:</p> <p><code>TypeError: only length-1 arrays can be converted to Python scalars</code></p> <p><strong>EDIT:</strong></p> <p>After reading the answer below I modified my code:</p> <p><strong>EDIT 2</strong></p> <p>This is the code that I use to "dilate" the characters and find the contours</p> <pre><code>kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(35,35)) # dilate the image to get text # binaryContour is just the black and white image shown below dilation = cv2.dilate(binaryContour,kernel,iterations = 2) </code></pre> <p><strong>END OF EDIT 2</strong></p> <pre><code>im2, contours, hierarchy = cv2.findContours(dilation,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) myContours = [] # Process the raw contours to get bounding rectangles for cnt in reversed(contours): epsilon = 0.1*cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt,epsilon,True) if len(approx == 4): rectangle = cv2.boundingRect(cnt) myContours.append(rectangle) max_width = max(myContours, key=lambda r: r[0] + r[2])[0] max_height = max(myContours, key=lambda r: r[3])[3] nearest = max_height * 1.4 myContours.sort(key=lambda r: (int(nearest * round(float(r[1])/nearest)) * max_width + r[0])) i=0 for x,y,w,h in myContours: letter = binaryContour[y:y+h, x:x+w] cv2.rectangle(binaryContour,(x,y),(x+w,y+h),(255,255,255),2) cv2.imwrite("pictures/"+str(i)+'.png', letter) # save contour to file i+=1 </code></pre> <p>Contours before sorting:</p> <pre><code>[(1, 1, 94, 36), (460, 223, 914, 427), (888, 722, 739, 239), (35,723, 522, 228), (889, 1027, 242, 417), (70, 1028, 693, 423), (1138, 1028, 567, 643), (781, 1030, 98, 413), (497, 1527, 303, 132), (892, 1527, 168, 130), (37, 1719, 592, 130), (676, 1721, 413, 129), (1181, 1723, 206, 128), (30, 1925, 997, 236), (1038, 1929, 170, 129), (140, 2232, 1285, 436)] </code></pre> <p>Contours after sorting:</p> <p>(<strong>NOTE:</strong> This is not the order I want the contours to be sorted in. Refer to image at the bottom)</p> <pre><code>[(1, 1, 94, 36), (460, 223, 914, 427), (35, 723, 522, 228), (70,1028, 693, 423), (781, 1030, 98, 413), (888, 722, 739, 239), (889, 1027, 242, 417), (1138, 1028, 567, 643), (30, 1925, 997, 236), (37, 1719, 592, 130), (140, 2232, 1285, 436), (497, 1527, 303, 132), (676, 1721, 413, 129), (892, 1527, 168, 130), (1038, 1929, 170, 129), (1181, 1723, 206, 128)] </code></pre> <p>Image I am working with</p> <p><a href="http://i.stack.imgur.com/9VayB.png" rel="nofollow"><img src="http://i.stack.imgur.com/9VayB.png" alt="enter image description here"></a></p> <p>I want to find the contours in the following order: <a href="http://i.stack.imgur.com/s4jKm.png" rel="nofollow"><img src="http://i.stack.imgur.com/s4jKm.png" alt="enter image description here"></a></p> <p>Dilation image used for finding contours <a href="http://i.stack.imgur.com/sTyvW.png" rel="nofollow"><img src="http://i.stack.imgur.com/sTyvW.png" alt="enter image description here"></a></p>
7
2016-09-09T03:04:28Z
39,542,610
<p>I hope this links help you</p> <p><a href="http://answers.opencv.org/question/31515/sorting-contours-from-left-to-right-and-top-to-bottom/" rel="nofollow">opencv answers - sort contour left right top bottom</a></p> <p><a href="http://www.pyimagesearch.com/2015/04/20/sorting-contours-using-python-and-opencv/" rel="nofollow">Andrian's sort with python</a></p>
0
2016-09-17T03:36:15Z
[ "python", "python-2.7", "opencv", "lambda", "opencv3.0" ]
How to stop python script from exiting on error
39,403,202
<p>I wrote a small python script to do a bulk whois check of some domains using pythonwhois to do the checking. </p> <p>The script reads domains from testdomains.txt and checks them one by one. Then it logs some information regarding the domain to results.txt</p> <p>This is my script:</p> <pre><code>from time import sleep import pythonwhois def lookup(domain): sleep(5) response = pythonwhois.get_whois(domain) ns = response['nameservers'] return ns with open("testdomains.txt") as infile: domainfile = open('results.txt','w') for domain in infile: ns = (lookup(domain)) domainfile.write(domain.rstrip() + ',' + ns+'\n') domainfile.close() </code></pre> <p>My problem arises when a domain is not registered or when the whois server fails to reply for some reason. The script exits like this:</p> <pre><code>Traceback (most recent call last): File "test8.py", line 17, in &lt;module&gt; ns = lookup(domain) File "test8.py", line 9, in lookup ns = response['nameservers'] TypeError: 'NoneType' object has no attribute '__getitem__' </code></pre> <p>My question is, what can I do to avoid the entire script from exiting?</p> <p>In case of an error, I would like the script to jump to the next domain and keep running and not exit. Logging the error to results.txt would definitely be good too.</p> <p>Thanks!</p>
1
2016-09-09T03:06:59Z
39,403,239
<pre><code>with open("testdomains.txt") as infile: domainfile = open('results.txt','w') for domain in infile: try: ns = (lookup(domain)) domainfile.write(domain.rstrip() + ',' + ns+'\n')\ except TypeError: pass domainfile.close() </code></pre>
0
2016-09-09T03:11:29Z
[ "python" ]
How to stop python script from exiting on error
39,403,202
<p>I wrote a small python script to do a bulk whois check of some domains using pythonwhois to do the checking. </p> <p>The script reads domains from testdomains.txt and checks them one by one. Then it logs some information regarding the domain to results.txt</p> <p>This is my script:</p> <pre><code>from time import sleep import pythonwhois def lookup(domain): sleep(5) response = pythonwhois.get_whois(domain) ns = response['nameservers'] return ns with open("testdomains.txt") as infile: domainfile = open('results.txt','w') for domain in infile: ns = (lookup(domain)) domainfile.write(domain.rstrip() + ',' + ns+'\n') domainfile.close() </code></pre> <p>My problem arises when a domain is not registered or when the whois server fails to reply for some reason. The script exits like this:</p> <pre><code>Traceback (most recent call last): File "test8.py", line 17, in &lt;module&gt; ns = lookup(domain) File "test8.py", line 9, in lookup ns = response['nameservers'] TypeError: 'NoneType' object has no attribute '__getitem__' </code></pre> <p>My question is, what can I do to avoid the entire script from exiting?</p> <p>In case of an error, I would like the script to jump to the next domain and keep running and not exit. Logging the error to results.txt would definitely be good too.</p> <p>Thanks!</p>
1
2016-09-09T03:06:59Z
39,403,243
<p>You want to make use of exception handling here with a <code>try/except</code>.</p> <p>Read the documentation on exception handling <a href="https://docs.python.org/3/tutorial/errors.html" rel="nofollow">here</a></p> <p>Taking the snippet of code of interest, you wrap your call inside a try: </p> <pre><code>for domain in infile: try: ns = lookup(domain) except TypeError as e: # should probably use a logger here instead of print print('domain not found: {}'.format(e)) print('Continuing...') domainfile.write(domain.rstrip() + ',' + ns+'\n') domainfile.close() </code></pre>
4
2016-09-09T03:11:38Z
[ "python" ]
How to stop python script from exiting on error
39,403,202
<p>I wrote a small python script to do a bulk whois check of some domains using pythonwhois to do the checking. </p> <p>The script reads domains from testdomains.txt and checks them one by one. Then it logs some information regarding the domain to results.txt</p> <p>This is my script:</p> <pre><code>from time import sleep import pythonwhois def lookup(domain): sleep(5) response = pythonwhois.get_whois(domain) ns = response['nameservers'] return ns with open("testdomains.txt") as infile: domainfile = open('results.txt','w') for domain in infile: ns = (lookup(domain)) domainfile.write(domain.rstrip() + ',' + ns+'\n') domainfile.close() </code></pre> <p>My problem arises when a domain is not registered or when the whois server fails to reply for some reason. The script exits like this:</p> <pre><code>Traceback (most recent call last): File "test8.py", line 17, in &lt;module&gt; ns = lookup(domain) File "test8.py", line 9, in lookup ns = response['nameservers'] TypeError: 'NoneType' object has no attribute '__getitem__' </code></pre> <p>My question is, what can I do to avoid the entire script from exiting?</p> <p>In case of an error, I would like the script to jump to the next domain and keep running and not exit. Logging the error to results.txt would definitely be good too.</p> <p>Thanks!</p>
1
2016-09-09T03:06:59Z
39,403,279
<p>There are two ways: 1.) Either you can remove the brittle code to make sure expection doesn't occur. Example:</p> <pre><code>from time import sleep import pythonwhois def lookup(domain): sleep(5) response = pythonwhois.get_whois(domain) ns = response.get('nameservers') return ns with open("testdomains.txt") as infile: domainfile = open('results.txt','w') for domain in infile: ns = (lookup(domain)) if ns: domainfile.write(domain.rstrip() + ',' + ns+'\n') domainfile.close() </code></pre> <p>2.) Handle exception gracefully and let code to continue. As suggested above.</p>
0
2016-09-09T03:16:06Z
[ "python" ]
Finding the closest possible values from two dictionaries
39,403,236
<p>Let's suppose you have two existing dictionaries <code>A</code> and <code>B</code></p> <p>If you already choose an initial two items from dictionaries <code>A</code> and <code>B</code> with values <code>A1 = 1.0</code> and <code>B1 = 2.0</code>, respectively, is there any way to find any two different existing items in the dictionaries <code>A</code> and <code>B</code> that each have different values (i.e. <code>A2</code> and <code>B2</code>) from <code>A1</code> and <code>B1</code>, and would also minimize the value <code>(A2-A1)**2 + (B2-B1)**2</code>?</p> <p>The number of items in the dictionary is unfixed and could exceed 100,000.</p> <p>Edit - This is important: the keys for <code>A</code> and <code>B</code> are the same, but the values corresponding to those keys in <code>A</code> and <code>B</code> are different. A particular choice of key will yield an ordered pair (A1,B1) that is different from any other possible order pair (A2,B2)—different keys have different order pairs. For example, both <code>A</code> and <code>B</code> will have the key <code>3,4</code> and this will yield a value of <code>1.0</code> for dict <code>A</code> and <code>2.0</code> for <code>B</code>. This one key will then be compared to every other key possible to find the other ordered pair (i.e. both the key and values of the items in <code>A</code> and <code>B</code>) that minimizes the squared differences between them. </p>
2
2016-09-09T03:11:20Z
39,403,388
<p>You'll need a specialized data structure, not a standard Python dictionary. Look up quad-tree or kd-tree. You are effectively minimizing the Euclidean distance between two points (your objective function is just a square root away from Euclidean distance, and your dictionary A is storing x-coordinates, B y-coordinates.). Computational-geometry people have been studying this for years.</p> <p>Well, maybe I am misreading your question and making it harder than it is. Are you saying that you can pick <em>any</em> value from A and <em>any</em> value from B, regardless of whether their keys are the same? For instance, the pick from A could be K:V (3,4):2.0, and the pick from B could be (5,6):3.0? Or does it have to be (3,4):2.0 from A and (3,4):6.0 from B? If the former, the problem is easy: just run through the values from A and find the closest to A1; then run through the values from B and find the closest to B1. If the latter, my first paragraph was the right answer.</p> <p>Your comment says that the harder problem is the one you want to solve, so here is a little more. Sedgewick's slides explain how the static grid, the 2d-tree, and the quad-tree work. <a href="http://algs4.cs.princeton.edu/lectures/99GeometricSearch.pdf" rel="nofollow">http://algs4.cs.princeton.edu/lectures/99GeometricSearch.pdf</a> . Slides 15 through 29 explain mainly the 2d-tree, with 27 through 29 covering the solution to the nearest-neighbor problem. Since you have the constraint that the point the algorithm finds must share neither x- nor y-coordinate with the query point, you might have to implement the algorithm yourself or modify an existing implementation. One alternative strategy is to use a kNN data structure (k nearest neighbors, as opposed to the single nearest neighbor), experiment with k, and hope that your chosen k will always be large enough to find at least one neighbor that meets your constraint.</p>
2
2016-09-09T03:27:09Z
[ "python", "python-2.7", "dictionary" ]
Beautiful soup isn't showing the links
39,403,268
<p>I am trying to scrap an anime website for the anime episodes links and titles, but the output is showing nothing or shows [] only.<br> This is the code am using:</p> <pre><code>import requests from bs4 import BeautifulSoup r = requests.get('http://animeonline.vip/info/phi-brain-kami-puzzle-3') soup = BeautifulSoup(r.content, "html.parser") for link in soup.find_all('a',{'class':"list_episode"}): print(link) </code></pre> <p>Anyway, I suppose this will only list down the links inside that class. How can I show title beside each link?</p> <p>I have no idea what I am doing wrong.</p> <p>Thanks</p>
0
2016-09-09T03:14:11Z
39,403,331
<p>The <code>div</code> has the class attribute, not the anchor tags, you were almost there</p> <pre><code>for link in soup.find_all('div', {'class': 'list_episode'}): print(link) </code></pre>
0
2016-09-09T03:20:59Z
[ "python", "visual-studio", "python-3.4", "ptvs" ]
OSx pip install awscli
39,403,306
<p>Please help.</p> <p>I'm following a tutorial to AWS and I need to install the AWS CLI on my Mac with the following result:</p> <pre><code>sisko$ pip install awscli Collecting awscli Using cached awscli-1.10.63-py2.py3-none-any.whl Requirement already satisfied (use --upgrade to upgrade): docutils&gt;=0.10 in /Library/Python/2.7/site-packages (from awscli) Requirement already satisfied (use --upgrade to upgrade): rsa&lt;=3.5.0,&gt;=3.1.2 in /Library/Python/2.7/site-packages (from awscli) Collecting s3transfer&lt;0.2.0,&gt;=0.1.0 (from awscli) Using cached s3transfer-0.1.3-py2.py3-none-any.whl Collecting botocore==1.4.53 (from awscli) Using cached botocore-1.4.53-py2.py3-none-any.whl Collecting colorama&lt;=0.3.7,&gt;=0.2.5 (from awscli) Using cached colorama-0.3.7-py2.py3-none-any.whl Requirement already satisfied (use --upgrade to upgrade): pyasn1&gt;=0.1.3 in /Library/Python/2.7/site-packages (from rsa&lt;=3.5.0,&gt;=3.1.2-&gt;awscli) Requirement already satisfied (use --upgrade to upgrade): futures&lt;4.0.0,&gt;=2.2.0; python_version == "2.6" or python_version == "2.7" in /Library/Python/2.7/site-packages (from s3transfer&lt;0.2.0,&gt;=0.1.0-&gt;awscli) Collecting python-dateutil&lt;3.0.0,&gt;=2.1 (from botocore==1.4.53-&gt;awscli) Using cached python_dateutil-2.5.3-py2.py3-none-any.whl Collecting jmespath&lt;1.0.0,&gt;=0.7.1 (from botocore==1.4.53-&gt;awscli) Using cached jmespath-0.9.0-py2.py3-none-any.whl Collecting six&gt;=1.5 (from python-dateutil&lt;3.0.0,&gt;=2.1-&gt;botocore==1.4.53-&gt;awscli) Using cached six-1.10.0-py2.py3-none-any.whl Installing collected packages: six, python-dateutil, jmespath, botocore, s3transfer, colorama, awscli Found existing installation: six 1.4.1 DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project. Uninstalling six-1.4.1: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/req/req_set.py", line 736, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/req/req_install.py", line 742, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/utils/__init__.py", line 267, in renames shutil.move(old, new) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move copy2(src, real_dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2 copystat(src, dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat os.chflags(dst, st.st_flags) OSError: [Errno 1] Operation not permitted: '/var/folders/s4/snsk01z551qdj37bpj3dtzpm0000gn/T/pip-38wpB3-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info' </code></pre> <p><strong>The last section of the output complains about an exception which I know nothing on how to resolve.</strong></p> <p>I downloaded and installed Python-3.5.2 but when I execute <code>python --version</code> my commandline reports <strong>Python 2.7.10</strong></p>
0
2016-09-09T03:18:27Z
39,403,360
<p>I just realised there is provision to surpress that exception with the following:</p> <pre><code>$ sudo pip install awscli --ignore-installed six </code></pre> <p>Issue resolved. Hope this helps others</p>
0
2016-09-09T03:23:20Z
[ "python", "osx", "aws-cli" ]
How to update PyQt elements in a script wrapper without using emits in original script
39,403,364
<p>I have a script which I have written a gui wrapper (In PyQt4) to make it easier to use for external users. I'd like to monitor the status of certain stages of the script (eg. Running, Failed, Waiting, etc.) while updating PyQt elements to reflect this. Ideally I don't want to modify the original script to include emits or signals as many of the places I run it on don't have PyQt4 installed. Is this possible? </p>
0
2016-09-09T03:23:33Z
39,417,745
<p>It's easy enough to write your own system for emitting signals:</p> <pre><code>from collections import defaultdict slots = defaultdict(list) def connect(signal, slot): slots[signal].append(slot) def disconnect(signal, slot=None): if slot is not None: slots[signal] = [x for x in slots[signal] if x is not slot] else: del slots[signal][:] def emit(signal, *args): for slot in slots[signal]: slot(*args) ... emit('statusChanged', 'Failed', 'error message') </code></pre> <p>Now your PyQt4 wrapper can connect to these signals and either handle them directly, or re-emit an appropriate PyQt signal as necessary:</p> <pre><code>import myscript class MainWindow(QtGui.QMainWindow): statusChanged = QtCore.pyqtSignal(str, str) def __init__(self): super(MainWindow, self).__init__() myscript.connect('statusChanged', self.handleStatusChanged) def handleStatusChanged(self, status, message): print(status, message) self.statusChanged.emit(status, message) </code></pre>
0
2016-09-09T18:30:54Z
[ "python", "python-3.x", "pyqt4" ]
Is there a tool to check what names I have used from a "wildly" imported module?
39,403,430
<p>I've been using python to do computations for my research. In an effort to clean up my terrible code, I've been reading <a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html" rel="nofollow">Code Like a Pythonista: Idiomatic Python</a> by David Goodger. </p> <p>In this article, Goodger advises against "wild-card" imports of the form</p> <pre><code>from module import * </code></pre> <p>My code uses a lot of these. I'd like to clean my code up, but I'm not sure how. I'm curious if there is a way to check what names from <code>module</code> I have used in my code. This way I could either explicitly import these names or replace the names with <code>module.name</code>. Is there a tool designed to accomplish such a task?</p>
3
2016-09-09T03:33:18Z
39,403,532
<p>Use a tool like <code>pyflakes</code> (which you should use anyway) to note which names in your code become undefined after you replace <code>from module import *</code> with <code>import module</code>. Once you've positively identified every instance of a name imported from <code>module</code>, you can assess whether to</p> <ol> <li>Always use <code>import module</code> and <code>module.x</code> for <code>x</code> imported from <code>module</code>.</li> <li>Use <code>import module as m</code> and <code>m.x</code> if the module name is long.</li> <li>Selectively import some names from <code>module</code> into the module namespace with <code>from module import x, y, z</code></li> </ol> <p>The above three are not mutually exclusive; as an extreme example, you can use all three in the same module:</p> <pre><code>import really.long.module.name import really.long.module.name as rlmn from really.long.module.name import obvious_name really.long.module.name.foo() # full module name rlmn.bar() # module alias obvious_name() # imported name </code></pre> <p>all in the same code. (I don't <em>recommend</em> using all three in the same module. Stick with either the full module name <em>or</em> the alias throughout a single module, but there is no harm importing common, obvious names directly and using the fully qualified name for more obscure module attributes.)</p>
4
2016-09-09T03:45:30Z
[ "python" ]
Is there a tool to check what names I have used from a "wildly" imported module?
39,403,430
<p>I've been using python to do computations for my research. In an effort to clean up my terrible code, I've been reading <a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html" rel="nofollow">Code Like a Pythonista: Idiomatic Python</a> by David Goodger. </p> <p>In this article, Goodger advises against "wild-card" imports of the form</p> <pre><code>from module import * </code></pre> <p>My code uses a lot of these. I'd like to clean my code up, but I'm not sure how. I'm curious if there is a way to check what names from <code>module</code> I have used in my code. This way I could either explicitly import these names or replace the names with <code>module.name</code>. Is there a tool designed to accomplish such a task?</p>
3
2016-09-09T03:33:18Z
39,403,595
<h2>Overview</h2> <p>One approach is to:</p> <ul> <li>Manually (or even automatically) identify each of the modules you've imported from using the <code>*</code> approach, </li> <li>Import them in a separate file,</li> <li>And then do a search-and-replace if they appear in <code>sys.modules[&lt;module&gt;].__dict__</code>, which <a href="https://docs.python.org/3/reference/import.html#loaders" rel="nofollow">keeps track</a> of which objects from a Python module have been loaded.</li> </ul> <p>See for yourself <code>sys.modules</code> in action:</p> <pre><code>from numpy import * import sys sys.modules['numpy'].__dict__.keys() # will display everything you just imported from `numpy` &gt;&gt;&gt; ['disp', 'union1d', 'all', 'issubsctype', 'savez', 'atleast_2d', 'restoredot', 'ptp', 'PackageLoader', 'ix_', 'mirr', 'blackman', 'FLOATING_POINT_SUPPORT', 'division', 'busdaycalendar', 'pkgload', 'void', 'ubyte', 'moveaxis', 'ERR_RAISE', 'void0', 'tri', 'diag_indices', 'array_equal', 'fmod', 'True_', 'indices', 'loads', 'round', 'set_numeric_ops', 'pmt', 'nanstd', '_mat', 'cosh', 'object0', 'argpartition', 'FPE_OVERFLOW', 'index_exp', 'append', 'compat', 'nanargmax', 'hstack', 'typename', 'diag', 'rollaxis', 'ERR_WARN', 'polyfit', 'version', 'memmap', 'nan_to_num', 'complex64', 'fmax', 'spacing', 'sinh', '__git_revision__', 'unicode_', 'sinc', 'trunc', 'vstack', 'ERR_PRINT', 'asscalar', 'copysign', 'less_equal', 'BUFSIZE', 'object_', 'divide', 'csingle', 'dtype', 'unsignedinteger', 'fastCopyAndTranspose', 'bitwise_and', 'uintc', 'select', 'deg2rad', 'nditer', 'eye', 'kron', 'newbuffer', 'negative', 'busday_offset', 'mintypecode', 'MAXDIMS', 'sort', 'einsum', 'uint0', 'zeros_like', 'int_asbuffer', 'uint8', 'chararray', 'linspace', 'resize', 'uint64', 'ma', 'true_divide', 'Inf', 'finfo', 'triu_indices', 'complex256', 'add_newdoc', 'seterrcall', 'logical_or', 'minimum', 'WRAP', 'tan', 'absolute', 'MAY_SHARE_EXACT', 'numarray', 'array_repr', 'get_array_wrap', 'polymul', 'tile', 'array_str', 'setdiff1d', 'sin', 'longlong', 'product', 'int16', 'str_', 'mat', 'fv', 'max', 'asanyarray', 'uint', 'npv', 'logaddexp', 'flatnonzero', 'amin', 'correlate', 'fromstring', 'left_shift', 'searchsorted', 'int64', 'may_share_memory', 'dsplit', 'intersect1d', 'can_cast', 'ppmt', 'show_config', 'cumsum', 'roots', 'outer', 'CLIP', 'fix', 'busday_count', 'timedelta64', 'degrees', 'choose', 'FPE_INVALID', 'recfromcsv', 'fill_diagonal', 'empty_like', 'logaddexp2', 'greater', 'histogram2d', 'polyint', 'arctan2', 'datetime64', 'complexfloating', 'ndindex', 'ctypeslib', 'PZERO', 'isfortran', 'asfarray', 'nanmedian', 'radians', 'fliplr', 'alen', 'recarray', 'modf', 'mean', 'square', 'ogrid', 'MAY_SHARE_BOUNDS', 'nanargmin', 'r_', 'diag_indices_from', 'hanning', 's_', 'allclose', 'extract', 'float16', 'ulonglong', 'matrix', 'asarray', 'poly1d', 'promote_types', 'rec', 'datetime_as_string', 'uint32', 'math', 'log2', '__builtins__', 'cumproduct', 'diagonal', 'atleast_1d', 'meshgrid', 'column_stack', 'put', 'byte', 'remainder', 'row_stack', 'expm1', 'nper', 'ndfromtxt', 'matmul', 'place', 'DataSource', 'newaxis', 'arccos', 'signedinteger', 'ndim', 'rint', 'number', 'rank', 'little_endian', 'ldexp', 'lookfor', 'array', 'vsplit', 'common_type', 'size', 'logical_xor', 'geterrcall', 'sometrue', 'exp2', 'bool8', 'msort', 'alltrue', 'zeros', 'False_', '__NUMPY_SETUP__', 'nansum', 'bool_', 'inexact', 'nanpercentile', 'broadcast', 'copyto', 'short', 'arctanh', 'typecodes', 'rot90', 'savetxt', 'sign', 'int_', 'std', 'not_equal', 'fromfunction', 'tril_indices_from', '__config__', 'double', 'require', 'rate', 'typeNA', 'str', 'getbuffer', 'abs', 'clip', 'savez_compressed', 'frompyfunc', 'triu_indices_from', 'conjugate', 'alterdot', 'asfortranarray', 'binary_repr', 'angle', 'lib', 'min', 'unwrap', 'apply_over_axes', 'ERR_LOG', 'right_shift', 'take', 'broadcast_to', 'byte_bounds', 'trace', 'warnings', 'any', 'shares_memory', 'compress', 'histogramdd', 'issubclass_', 'multiply', 'mask_indices', 'amax', 'logical_not', 'average', 'partition', 'nbytes', 'exp', 'sum', 'dot', 'int0', 'nanprod', 'longfloat', 'random', 'setxor1d', 'copy', 'FPE_UNDERFLOW', 'frexp', 'errstate', 'nanmin', 'swapaxes', 'SHIFT_OVERFLOW', 'infty', 'fft', 'ModuleDeprecationWarning', 'digitize', '__file__', 'NZERO', 'ceil', 'ones', 'add_newdoc_ufunc', '_NoValue', 'deprecate', 'median', 'geterr', 'convolve', 'isreal', 'where', 'isfinite', 'SHIFT_UNDERFLOW', 'MachAr', 'argmax', 'testing', 'deprecate_with_doc', 'full', 'polyder', 'rad2deg', 'isnan', '__all__', 'irr', 'sctypeDict', 'NINF', 'min_scalar_type', 'count_nonzero', 'sort_complex', 'nested_iters', 'concatenate', 'vdot', 'bincount', 'transpose', 'array2string', 'corrcoef', 'fromregex', 'vectorize', 'set_printoptions', 'isrealobj', 'trim_zeros', 'unravel_index', 'cos', 'float64', 'log1p', 'ushort', 'equal', 'cumprod', 'float_', 'vander', 'geterrobj', 'load', 'fromiter', 'poly', 'bitwise_or', 'polynomial', 'diff', 'iterable', 'array_split', 'get_include', 'pv', 'tensordot', 'piecewise', 'invert', 'UFUNC_PYVALS_NAME', 'SHIFT_INVALID', 'c_', 'flexible', 'pi', '__doc__', 'empty', 'VisibleDeprecationWarning', 'find_common_type', 'isposinf', 'arcsin', 'sctypeNA', 'imag', 'sctype2char', 'singlecomplex', 'SHIFT_DIVIDEBYZERO', 'matrixlib', 'apply_along_axis', 'reciprocal', 'tanh', 'dstack', 'cov', 'cast', 'logspace', 'packbits', 'issctype', 'mgrid', 'longdouble', 'signbit', 'conj', 'asmatrix', 'inf', 'flatiter', 'bitwise_xor', 'fabs', 'generic', 'reshape', 'NaN', 'cross', 'sqrt', '__package__', 'longcomplex', 'complex', 'pad', 'split', 'floor_divide', '__version__', 'format_parser', 'nextafter', 'polyval', 'flipud', 'i0', 'iscomplexobj', 'sys', 'mafromtxt', 'bartlett', 'polydiv', 'stack', 'identity', 'safe_eval', 'greater_equal', 'Tester', 'trapz', 'PINF', 'object', 'recfromtxt', 'oldnumeric', 'add_newdocs', 'RankWarning', 'ascontiguousarray', 'less', 'putmask', 'UFUNC_BUFSIZE_DEFAULT', 'unicode', 'half', 'NAN', 'absolute_import', 'typeDict', '__path__', 'shape', 'setbufsize', 'cfloat', 'RAISE', 'isscalar', 'character', 'bench', 'source', 'add', 'uint16', 'cbrt', 'bool', 'ufunc', 'save', 'ravel', 'float32', 'real', 'int32', 'tril_indices', 'around', 'lexsort', 'complex_', 'ComplexWarning', 'unicode0', 'ipmt', '_import_tools', 'atleast_3d', 'isneginf', 'integer', 'unique', 'mod', 'insert', 'bitwise_not', 'getbufsize', 'array_equiv', 'arange', 'asarray_chkfinite', 'in1d', 'interp', 'hypot', 'logical_and', 'get_printoptions', 'diagflat', 'float128', 'nonzero', 'kaiser', 'ERR_IGNORE', 'polysub', 'fromfile', 'prod', 'nanmax', 'core', 'who', 'seterrobj', 'power', 'bytes_', 'percentile', 'FPE_DIVIDEBYZERO', '__name__', 'subtract', 'print_function', 'nanmean', 'frombuffer', 'iscomplex', 'add_docstring', 'argsort', 'fmin', 'ones_like', 'is_busday', 'arcsinh', 'intc', 'float', 'ndenumerate', 'intp', 'unpackbits', 'Infinity', 'log', 'cdouble', 'complex128', 'long', 'round_', 'broadcast_arrays', 'inner', 'var', 'sctypes', 'log10', 'uintp', 'linalg', 'histogram', 'issubdtype', 'maximum_sctype', 'squeeze', 'int8', 'info', 'seterr', 'argmin', 'genfromtxt', 'maximum', 'record', 'obj2sctype', 'clongdouble', 'euler_gamma', 'arccosh', 'delete', 'tril', 'int', 'ediff1d', 'char', 'single', 'loadtxt', 'hsplit', 'ScalarType', 'triu', 'floating', 'expand_dims', 'floor', 'polyadd', 'nan', 'TooHardError', 'emath', 'arctan', 'bmat', 'isclose', 'ERR_DEFAULT', 'test', 'roll', 'string0', 'compare_chararrays', 'iinfo', 'real_if_close', 'repeat', 'nanvar', 'hamming', 'ALLOW_THREADS', 'ravel_multi_index', 'string_', 'isinf', 'ndarray', 'e', 'ERR_CALL', 'datetime_data', 'clongfloat', 'full_like', 'result_type', 'gradient', 'base_repr', 'argwhere', 'set_string_function'] </code></pre> <p>You can either manually check if a function name you're not sure of appears here using <code>if &lt;function_name&gt; in sys.modules[&lt;module&gt;].__dict__</code>, or you can write a neat automated script that goes through each entry in <code>sys.modules[&lt;module&gt;]</code>.</p> <p>I would favour the latter for anything too sophisticated, and the former for diagnostic purposes.</p> <h2>Rough Implementation of Automatic Tool</h2> <p>A very, very, very quick-and-dirty example of how to write such an automated script:</p> <pre><code>import re import sys with open('file_I_want_to_change.py', 'r+') as f: file_contents = f.read() # get the entire file as a string search_string = r"from ([a-zA-Z]+) import *" # regex to find all loaded module names module_names = re.findall(search_string, file_contents) map(__import__, module_names) # import ALL of these modules names at once for module in module_names: for function_name in sys.modules[module].__dict__: # do a very quick-and-dirty replace-all file_contents = file_contents.replace(function_name, "{0}.{1}".format(module, function_name)) f.seek(0) # move to start of file f.write(file_contents) </code></pre> <p>This is not very robust, and you shouldn't use it as-is! You may find yourself overwriting names <em>not</em> from the module but that are defined anyway. </p> <p>It's probably best to allow some form of user interaction to confirm you want to apply a change for each function name found. But it gets the gist across.</p> <p>This has been tested with the following simple example file:</p> <pre><code>from numpy import * array([1]) </code></pre> <p>becomes </p> <pre><code>from numpy import * numpy.array([1]) </code></pre> <p><strong>EDIT:</strong> I have since created a much more robust and useful command line utility <a href="https://github.com/AkshatM/wildcard_import_fixer" rel="nofollow">here</a></p>
3
2016-09-09T03:52:43Z
[ "python" ]
Python sorting nested dictionary list
39,403,450
<p>I am trying to sort a nested dictionary in Python. Right now I have a dictionary of dictionaries. I was able to sort the outer keys using sorted on the list before I started building the dictionary, but I am unable to get the inner keys sorted at this time. I've been trying to mess with the sorted API but am having problems with it.</p> <p>Right now I have:</p> <pre><code>myDict = {'A': {'Key3':4,'Key2':3,'Key4':2,'Key1':1}, 'B': {'Key4':1,'Key3':2,'Key2':3,'Key1':4}, 'C': {'Key1':4,'Key2':2,'Key4':1,'Key3':3}}; </code></pre> <p>But I would like:</p> <pre><code>myDict = {'A': {'Key1':1,'Key2':3,'Key3':4,'Key4':2}, 'B': {'Key1':4,'Key2':3,'Key2':1,'Key4':1}, 'C': {'Key1':4,'Key2':2,'Key3':3,'Key4':1}}; </code></pre> <p>I appreciate the help!</p>
2
2016-09-09T03:34:53Z
39,403,584
<pre><code>&gt;&gt;&gt; from collections import OrderedDict &gt;&gt;&gt; def sortedDict(items): ... return OrderedDict(sorted(items)) &gt;&gt;&gt; myDict = {'A': {'Key3':4,'Key2':3,'Key4':2,'Key1':1}, ... 'B': {'Key4':1,'Key3':2,'Key2':3,'Key1':4}, ... 'C': {'Key1':4,'Key2':2,'Key4':1,'Key3':3}} &gt;&gt;&gt; sortedDict((key, sortedDict(value.items())) for key, value in myDict.items()) </code></pre>
1
2016-09-09T03:51:26Z
[ "python", "python-3.x", "sorting", "dictionary" ]
How can I get Tangential direction Vector in Python
39,403,477
<p>I can get some info from a Arc.</p> <ul> <li>FirstPoint   [x,y,z]</li> <li>LastPoint   [x,y,z]</li> <li>Center    [x,y,z]</li> <li>Axis      [x,y,z] # Perpendicular to the plane</li> </ul> <p>How can I get the FirstPoint&amp;LastPoint's tangential direction Vector ?</p> <p>I want to get a intersection Point from two direction vector.</p> <p>PS: Work in FreeCAD.</p> <p>Thanks for any reply</p> <p>best regards, Eason</p>
2
2016-09-09T03:39:21Z
39,403,696
<p>We'll need a lot more information to give a good answer, but here is a first attempt, with questions after.</p> <p>One way to approximate a tangent vector is with a secant vector: If your curve is given parametrically as a function of t and you want the tangent at t_0, then choose some small number e; evaluate the function at t_0 + e and at t_0 - e; then subtract the two results to get the secant vector. It will be a good approximation to the tangent vector if your curve isn't too curvy in that interval around t.</p> <p>Now for the questions. How is your question related to Python, and where does FreeCAD come in? You have constructed the curve in FreeCAD, and you want to compute tangents in Python? Can you say anything about the curve, like whether it's a cubic spline curve, whether it curves in only one direction, what you mean by "center" and "axis"? (An arbitrary curve with tangent vectors isn't necessarily a cubic spline, might curve in very complicated ways, and doesn't have any notion of a center or axis.)</p>
1
2016-09-09T04:04:39Z
[ "python", "math", "direction", "freecad" ]
How can I get Tangential direction Vector in Python
39,403,477
<p>I can get some info from a Arc.</p> <ul> <li>FirstPoint   [x,y,z]</li> <li>LastPoint   [x,y,z]</li> <li>Center    [x,y,z]</li> <li>Axis      [x,y,z] # Perpendicular to the plane</li> </ul> <p>How can I get the FirstPoint&amp;LastPoint's tangential direction Vector ?</p> <p>I want to get a intersection Point from two direction vector.</p> <p>PS: Work in FreeCAD.</p> <p>Thanks for any reply</p> <p>best regards, Eason</p>
2
2016-09-09T03:39:21Z
39,404,477
<p>s.Curve</p> <pre><code>Circle (Radius : 1, Position : (0.335157, 11.988, 5.55452), Direction : (-0.914329, -0.257151, 0.312851)) </code></pre> <p>s.Vertex1.Point #FirstPoint</p> <pre><code>Vector (0.7393506936636021, 11.360676836326173, 6.220155663200929) </code></pre> <p>s.Vertex2.Point #LastPoint</p> <pre><code>Vector (0.3602513339713556, 12.723079925995924, 6.232050903393676) </code></pre> <p>s.Curve.FirstParameter</p> <p><code>0.0</code></p> <p>s.Curve.LastParameter</p> <pre><code>6.283185307179586 </code></pre> <p>It's a simple arc.</p>
0
2016-09-09T05:34:11Z
[ "python", "math", "direction", "freecad" ]
How can I get Tangential direction Vector in Python
39,403,477
<p>I can get some info from a Arc.</p> <ul> <li>FirstPoint   [x,y,z]</li> <li>LastPoint   [x,y,z]</li> <li>Center    [x,y,z]</li> <li>Axis      [x,y,z] # Perpendicular to the plane</li> </ul> <p>How can I get the FirstPoint&amp;LastPoint's tangential direction Vector ?</p> <p>I want to get a intersection Point from two direction vector.</p> <p>PS: Work in FreeCAD.</p> <p>Thanks for any reply</p> <p>best regards, Eason</p>
2
2016-09-09T03:39:21Z
39,409,346
<p>Circular arc from <code>A</code> to <code>B</code> with center <code>M</code> and normal vector <code>N</code>.</p> <p>The tangent directions can be obtained by the <em>cross product</em>. </p> <ul> <li>Tangent at <code>A</code>: <code>N x (A-M)</code></li> <li>Tangent at <code>B</code>: <code>(B-M) x N</code></li> </ul> <p>Both correspond to a rotation of 90DEG or -90DEG of the radius vectors around the axis <code>N</code></p>
1
2016-09-09T10:22:19Z
[ "python", "math", "direction", "freecad" ]
How to show a pandas dataframe as a flask-boostrap table?
39,403,529
<p>I would like to show a pandas dataframe as a boostrap-html table with flask, thus I tried the following:</p> <p>The data (.csv table):</p> <pre><code>Name Birth Month Origin Age Gender Carly Jan Uk 10 F Rachel Sep UK 20 F Nicky Sep MEX 30 F Wendy Oct UK 40 F Judith Nov MEX 39 F </code></pre> <p>The python code (<code>python_script.py</code>):</p> <pre><code>from flask import * import pandas as pd app = Flask(__name__) @app.route("/tables") def show_tables(): data = pd.read_csv('table.csv') data.set_index(['Name'], inplace=True) data.index.name=None females = data.loc[data.Gender=='f'] return render_template('view.html',tables=[females.to_html(classes='female')], titles = ['na', 'Female surfers']) if __name__ == "__main__": app.run(debug=True) </code></pre> <p>The <code>templates</code> directory (<code>view.html</code>):</p> <pre><code>&lt;!doctype html&gt; &lt;title&gt;Simple tables&lt;/title&gt; &lt;link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}"&gt; &lt;div class=page&gt; &lt;h1&gt;Surfer groups&lt;/h1&gt; {% for table in tables %} &lt;h2&gt;{{titles[loop.index]}}&lt;/h2&gt; {{ table|safe }} {% endfor %} &lt;/div&gt; </code></pre> <p>The boostrap <code>style.css</code>:</p> <pre><code>body { font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;} a, h1, h2 { color: #377ba8; } h1, h2 { margin: 0; } h1 { border-bottom: 2px solid #eee; } h2 { font-size: 1.2em; } table.dataframe, .dataframe th, .dataframe td { border: none; border-bottom: 1px solid #C8C8C8; border-collapse: collapse; text-align:left; padding: 10px; margin-bottom: 40px; font-size: 0.9em; } .male th { background-color: #add8e6; color: white; } .female th { background-color: #77dd77; color: white; } tr:nth-child(odd) { background-color:#eee; } tr:nth-child(even) { background-color:#fff; } tr:hover { background-color: #ffff99;} </code></pre> <p>So far, when I run my <code>python_script.py</code>:</p> <pre><code> * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger pin code: 123-221-151 </code></pre> <p>I got two issues: a Not Found error and when I go to <code>http://127.0.0.1:5000/tables</code> I got an <code>builtins.KeyError KeyError: 'Name'</code>. Any idea of how to show a pandas dataframe as a table with pandas and flask?.</p>
-1
2016-09-09T03:45:17Z
39,403,732
<p>The problem here is with the <code>data.csv</code> file. When you do <code>read_csv()</code> on it:</p> <pre><code>In [45]: pd.read_csv("/tmp/a.csv") Out[45]: Name Birth Month Origin Age Gender 0 Carly Jan Uk 10 F 1 Rachel Sep UK 20 F 2 Nicky Sep MEX 30 F 3 Wendy Oct UK 40 F 4 Judith Nov MEX 39 F In [46]: df = pd.read_csv("/tmp/a.csv") In [47]: df.columns Out[47]: Index([u'Name Birth Month Origin Age Gender'], dtype='object') </code></pre> <p>As you can see, there is only one column, instead of four, because it can't understand that 'Birth Month' is supposed to be one column. To fix this, you can open the file and change the first line to:</p> <pre><code>"Name" "Birth Month" "Origin" "Age" "Gender" </code></pre> <p>And, then while reading the csv:</p> <pre><code>In [62]: pd.read_csv("/tmp/a.csv", sep='\s+', quotechar='"') Out[62]: Name Birth Month Origin Age Gender 0 Carly Jan Uk 10 F 1 Rachel Sep UK 20 F 2 Nicky Sep MEX 30 F 3 Wendy Oct UK 40 F 4 Judith Nov MEX 39 F </code></pre> <p>Or you could have also just changed <code>Birth Month</code> to <code>Birth_Month</code></p> <p>For the '404 Not Found' error, the problem is that you have not defined any route for '/'. So, (after editing the header of the csv) I would do something like:</p> <pre><code>from flask import * import pandas as pd app = Flask(__name__) @app.route("/tables") def show_tables(): data = pd.read_csv("/tmp/a.csv", sep='\s+', quotechar='"') data.set_index(['Name'], inplace=True) data.index.name=None females = data.loc[data.Gender=='F'] return render_template('view.html',tables=[females.to_html(classes='female')], titles = ['na', 'Female surfers']) @app.route("/") def show_home(): return "Hello Guys! Visit: &lt;a href='/tables'&gt; this link &lt;/a&gt;" if __name__ == "__main__": app.run(debug=True) </code></pre>
1
2016-09-09T04:09:22Z
[ "python", "html", "python-3.x", "pandas", "flask" ]
Can list comprehension have a prefix, suffix?
39,403,551
<p>I need to create a list comprehension and add one extra item at the start and end. Is there a better way than just using a helper function to do it?</p> <pre><code># convert tuple from permutation into a list with predecessor and successor def perm_to_list(predecessor, perm, successor): result = [predecessor] result.extend(list(perm)) result.append(successor) return result candidates = [perm_to_list(prefix, x, suffix) for x in permutations(something)] </code></pre>
2
2016-09-09T03:47:09Z
39,403,571
<p>To match the sample code (where you add prefix and suffix to each element of a list comprehension)</p> <pre><code>candidates = [[prefix] + list(x) + [suffix] for x in permutations(something)] </code></pre> <p>To answer the question you actually asked (to add a prefix and suffix to the list comprehension itself)</p> <pre><code>candidates = [prefix] + [somefunction(x) for x in permutations(something)] + [suffix] </code></pre>
3
2016-09-09T03:49:15Z
[ "python", "list-comprehension" ]
Can list comprehension have a prefix, suffix?
39,403,551
<p>I need to create a list comprehension and add one extra item at the start and end. Is there a better way than just using a helper function to do it?</p> <pre><code># convert tuple from permutation into a list with predecessor and successor def perm_to_list(predecessor, perm, successor): result = [predecessor] result.extend(list(perm)) result.append(successor) return result candidates = [perm_to_list(prefix, x, suffix) for x in permutations(something)] </code></pre>
2
2016-09-09T03:47:09Z
39,403,746
<p>As an alternative if speed is <em>critical</em>, thought I'd offer this approach. You can use a <a href="https://docs.python.org/2/library/collections.html#collections.deque" rel="nofollow"><code>deque</code></a> which has native support for appending to either the <em>head</em> or <em>tail</em> of the structure. </p> <p>It's a double-ended queue data structure, and as such offers <strong><em>O(1)</em></strong> prepending as opposed to <strong><em>O(n)</em></strong> for lists.</p> <pre><code>from collections import deque dq = deque(range(1,10)) # Test list passed to deque -&gt; deque([1, 2, 3, 4, 5, 6, 7, 8, 9]) dq.appendleft(0) dq.append(10) print dq deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) </code></pre>
2
2016-09-09T04:10:50Z
[ "python", "list-comprehension" ]
Can list comprehension have a prefix, suffix?
39,403,551
<p>I need to create a list comprehension and add one extra item at the start and end. Is there a better way than just using a helper function to do it?</p> <pre><code># convert tuple from permutation into a list with predecessor and successor def perm_to_list(predecessor, perm, successor): result = [predecessor] result.extend(list(perm)) result.append(successor) return result candidates = [perm_to_list(prefix, x, suffix) for x in permutations(something)] </code></pre>
2
2016-09-09T03:47:09Z
39,404,671
<p>There is a new <a href="https://www.python.org/dev/peps/pep-0448/" rel="nofollow">feature</a> available only in Python 3.5:</p> <p>Unpacking of iterables anywhere in a list:</p> <pre><code>[prefix, *iterable, suffix] </code></pre> <p>(I wish they added it sooner)</p>
1
2016-09-09T05:51:10Z
[ "python", "list-comprehension" ]
Create gantt chart with hlines?
39,403,580
<p>I've tried for several hours to make this work. I tried using 'python-gantt' package, without luck. I also tried plotly (which was beautiful, but I can't host my sensitive data on their site, so that won't work). </p> <p>My starting point is code from here: <a href="http://stackoverflow.com/questions/31820578/how-to-plot-stacked-event-duration-gantt-charts-using-python-pandas">How to plot stacked event duration (Gantt Charts) using Python Pandas?</a> </p> <p>Three Requirements:</p> <ul> <li>Include the 'Name' on the y axis rather than the numbers. </li> <li>If someone has multiple events, put all the event periods on one line (this will make pattern identification easier), e.g. Lisa will only have one line on the visual.</li> <li>Include the 'Event' listed on top of the corresponding line (if possible), e.g. Lisa's first line would say "Hire".</li> </ul> <p>The code will need to be dynamic to accommodate many more people and more possible event types...</p> <p>I'm open to suggestions to visualize: I want to show the duration for various staffing events throughout the year, as to help identify patterns.</p> <pre><code>from datetime import datetime import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as dt df = pd.DataFrame({'Name': ['Joe','Joe','Lisa','Lisa','Lisa','Alice'], 'Event': ['Hire','Term','Hire','Transfer','Term','Term'], 'Start_Date': ["2014-01-01","2014-02-01","2015-01-01","2015-02-01","2015-03-01","2016-01-01"], 'End_Date': ["2014-01-31","2014-03-15","2015-01-31","2015-02-28","2015-05-01","2016-09-01"] }) df = df[['Name','Event','Start_Date','End_Date']] df.Start_Date = pd.to_datetime(df.Start_Date).astype(datetime) df.End_Date = pd.to_datetime(df.End_Date).astype(datetime) fig = plt.figure() ax = fig.add_subplot(111) ax = ax.xaxis_date() ax = plt.hlines(df.index, dt.date2num(df.Start_Date), dt.date2num(df.End_Date)) </code></pre>
6
2016-09-09T03:50:49Z
39,493,954
<p>I encountered the same problem in the past. You seem to appreciate the aesthetics of <a href="https://plot.ly/python/gantt/" rel="nofollow">Plotly</a>. Here is a little piece of code which uses <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.broken_barh" rel="nofollow">matplotlib.pyplot.broken_barh</a> instead of <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hlines" rel="nofollow">matplotlib.pyplot.hlines</a>.</p> <p><a href="http://i.stack.imgur.com/Bpr3I.png" rel="nofollow"><img src="http://i.stack.imgur.com/Bpr3I.png" alt="Gantt Chart with broken_barh"></a></p> <pre><code>from collections import defaultdict from datetime import datetime from datetime import date import pandas as pd import matplotlib.dates as mdates import matplotlib.patches as mpatches import matplotlib.pyplot as plt df = pd.DataFrame({ 'Name': ['Joe', 'Joe', 'Lisa', 'Lisa', 'Lisa', 'Alice'], 'Event': ['Hire', 'Term', 'Hire', 'Transfer', 'Term', 'Term'], 'Start_Date': ['2014-01-01', '2014-02-01', '2015-01-01', '2015-02-01', '2015-03-01', '2016-01-01'], 'End_Date': ['2014-01-31', '2014-03-15', '2015-01-31', '2015-02-28', '2015-05-01', '2016-09-01'] }) df = df[['Name', 'Event', 'Start_Date', 'End_Date']] df.Start_Date = pd.to_datetime(df.Start_Date).astype(datetime) df.End_Date = pd.to_datetime(df.End_Date).astype(datetime) names = df.Name.unique() nb_names = len(names) fig = plt.figure() ax = fig.add_subplot(111) bar_width = 0.8 default_color = 'blue' colors_dict = defaultdict(lambda: default_color, Hire='green', Term='red', Transfer='orange') # Plot the events for index, name in enumerate(names): mask = df.Name == name start_dates = mdates.date2num(df.loc[mask].Start_Date) end_dates = mdates.date2num(df.loc[mask].End_Date) durations = end_dates - start_dates xranges = zip(start_dates, durations) ymin = index - bar_width / 2.0 ywidth = bar_width yrange = (ymin, ywidth) facecolors = [colors_dict[event] for event in df.loc[mask].Event] ax.broken_barh(xranges, yrange, facecolors=facecolors, alpha=1.0) # you can set alpha to 0.6 to check if there are some overlaps # Shrink the x-axis box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) # Add the legend patches = [mpatches.Patch(color=color, label=key) for (key, color) in colors_dict.items()] patches = patches + [mpatches.Patch(color=default_color, label='Other')] plt.legend(handles=patches, bbox_to_anchor=(1, 0.5), loc='center left') # Format the x-ticks ax.xaxis.set_major_locator(mdates.YearLocator()) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y')) ax.xaxis.set_minor_locator(mdates.MonthLocator()) # Format the y-ticks ax.set_yticks(range(nb_names)) ax.set_yticklabels(names) # Set the limits date_min = date(df.Start_Date.min().year, 1, 1) date_max = date(df.End_Date.max().year + 1, 1, 1) ax.set_xlim(date_min, date_max) # Format the coords message box ax.format_xdata = mdates.DateFormatter('%Y-%m-%d') # Set the title ax.set_title('Gantt Chart') plt.show() </code></pre> <p>I hope this will help you.</p>
0
2016-09-14T15:09:06Z
[ "python", "pandas", "matplotlib" ]
SqlAlchemy or_ with multi-part clauses
39,403,647
<p>I have a list of independent clauses that look like:</p> <pre><code>'cls.status = :status_1 AND cls.password_valid = 0' 'cls.status = :status_1 AND cls.reason = :reason_1' ... </code></pre> <p>I'm wanting to add them to the where clause in sqlalchemy</p> <p>using <code>query = query.filter(or_(*clauses))</code> which says to me I should read them (in the where clause) as:</p> <pre><code>WHERE ... AND ((tbl1.status = :status_2 AND tbl1.password_valid = 0) OR (tbl1.status = :status_3 AND tbl1.reason = :reason_1)) </code></pre> <p>For some reason when I add multipart clauses to the query, it sees them as single part and I get this instead:</p> <pre><code>WHERE ... AND (tbl1.status = :status_2 AND tbl1.password_valid = 0 OR tbl1.status = :status_3 AND tbl1.reason = :reason_1) </code></pre> <p>Which is NOT equivalent to what I expect. How do I get it to introduce parens around the multipart clauses that are being OR'd together? All the examples I find are single clause statements being OR'd so of course they work</p>
0
2016-09-09T03:59:06Z
39,403,902
<p>Using <code>or_</code>, you have to wrap stuff up in a parens separated by commas.</p> <p><code>query.filter(or_( something == 'this', something == 'that' ) ) </code></p> <p>If you want to separate your clauses with parens, you can use the alternate bitwise operator <code>|</code></p> <p>ex:</p> <p><code>query.filter( (something == 'this') | (something == 'that')) </code></p>
0
2016-09-09T04:31:06Z
[ "python", "sqlalchemy" ]
Mean of values in a column for unique values in another column (Python)
39,403,705
<p>I am using Python 2.7 (Anaconda) for processing tabular data. I have loaded a textfile with two columns, e.g. </p> <pre><code>[[ 1. 8.] [ 2. 4.] [ 3. 1.] [ 4. 5.] [ 5. 6.] [ 1. 9.] [ 2. 0.] [ 3. 7.] [ 4. 3.] [ 5. 2.]] </code></pre> <p>my goal is to calculate the mean over all values in the second column which match the unique values in the first one, e.g. the mean value for 1 would be 8.5, for 2 it would be two, for 3 it would be 4. First, I filtered out the unique values in the first column by extracting the column and applying np.unique() resulting in the array "unique". I created a loop that works when I define the unique value:</p> <pre><code>mean= 0 values=[] for i in range(0,len(first),1): if first[i]==1: values.append(second[i]) print(np.mean(values)) </code></pre> <p>where first and second are the specific columns. Now I want to make this not so specific. I tried</p> <pre><code>mean = 0 values = [] means=[] for i in unique: for k in range(0,len(first),1): if first[k]==i: values.append(second[k]) mean = np.mean(values) means.append(mean) mean=0 values=[] print(means) </code></pre> <p>but it only returns the original second column. Does anybody have an idea on how to make this code non-specific? In reality, I have about 70k rows, so I cannot do it mannually. Thanks and regards, Maurus</p>
2
2016-09-09T04:06:28Z
39,403,897
<p>In pandas, you can achieve this by using <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">groupby</a>:</p> <pre><code>In [97]: data Out[97]: array([[ 1., 8.], [ 2., 4.], [ 3., 1.], [ 4., 5.], [ 5., 6.], [ 1., 9.], [ 2., 0.], [ 3., 7.], [ 4., 3.], [ 5., 2.]]) In [98]: import pandas as pd In [99]: df = pd.DataFrame(data, columns=['first', 'second']) In [100]: df.groupby('first').mean().reset_index() Out[100]: first second 0 1.0 8.5 1 2.0 2.0 2 3.0 4.0 3 4.0 4.0 4 5.0 4.0 </code></pre>
1
2016-09-09T04:30:40Z
[ "python", "mean", "tabular-data" ]
Mean of values in a column for unique values in another column (Python)
39,403,705
<p>I am using Python 2.7 (Anaconda) for processing tabular data. I have loaded a textfile with two columns, e.g. </p> <pre><code>[[ 1. 8.] [ 2. 4.] [ 3. 1.] [ 4. 5.] [ 5. 6.] [ 1. 9.] [ 2. 0.] [ 3. 7.] [ 4. 3.] [ 5. 2.]] </code></pre> <p>my goal is to calculate the mean over all values in the second column which match the unique values in the first one, e.g. the mean value for 1 would be 8.5, for 2 it would be two, for 3 it would be 4. First, I filtered out the unique values in the first column by extracting the column and applying np.unique() resulting in the array "unique". I created a loop that works when I define the unique value:</p> <pre><code>mean= 0 values=[] for i in range(0,len(first),1): if first[i]==1: values.append(second[i]) print(np.mean(values)) </code></pre> <p>where first and second are the specific columns. Now I want to make this not so specific. I tried</p> <pre><code>mean = 0 values = [] means=[] for i in unique: for k in range(0,len(first),1): if first[k]==i: values.append(second[k]) mean = np.mean(values) means.append(mean) mean=0 values=[] print(means) </code></pre> <p>but it only returns the original second column. Does anybody have an idea on how to make this code non-specific? In reality, I have about 70k rows, so I cannot do it mannually. Thanks and regards, Maurus</p>
2
2016-09-09T04:06:28Z
39,404,120
<p>Write a comparison statement checking the first column for your unique value, use that statement as a <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow">boolean index</a>, </p> <pre><code>&gt;&gt;&gt; mask = a[:,0] == 1 &gt;&gt;&gt; a[mask] array([[ 1., 8.], [ 1., 9.]]) for n in np.unique(a[:,0]): mask = a[:,0] == n print(np.mean(a[mask], axis = 0)) &gt;&gt;&gt; [ 1. 8.5] [ 2. 2.] [ 3. 4.] [ 4. 4.] [ 5. 4.] </code></pre> <hr> <p>If your data file looks something like this</p> <pre><code>''' 1., 8. 2., 4. 3., 1. 4., 5. ''' </code></pre> <p>and you don't really need a numpy array, just use a dictionary:</p> <pre><code>import collections d = collections.defaultdict(list) with open('file.txt') as f: for line in f: line = line.strip() first, second = map(float, line.split(',')) d[first].append(second) for first, second in d.iteritems(): print(first, sum(second) / len(second)) </code></pre>
1
2016-09-09T04:58:20Z
[ "python", "mean", "tabular-data" ]
newbie python modulo unexpected result
39,403,805
<p>Could use some help as I don't really see where I'm going wrong: </p> <p><code>totalseconds/86400</code></p> <p><code>1.2494560185185186</code></p> <p><code>totalseconds%86400</code></p> <p><code>21553</code></p> <p>Shouldnt I be getting <code>24945</code>...? </p> <p>Thanks for any help! </p>
-3
2016-09-09T04:18:40Z
39,403,978
<p>modulo is the remainder after division, not the fractional part of the decimal.</p>
0
2016-09-09T04:40:28Z
[ "python", "modulo" ]
Action after writing to txt
39,403,809
<p>Is there anyway I can check, once that the .txt file has been written? Is this able to be done with a while condition?</p> <p>For example:</p> <pre><code>writetotxt = open(mytxt, 'w') writetotxt.write('Line 1' + '\n') writetotxt.write('Line 2') writetotxt.close() def txtwritten(): firstline = linecache.getline(mytxt, 1) secline = linecache.getline(mytxt, 2) check = firstline + secline </code></pre> <p>But, while the process, it returns a blank result. When it is finished writing to text file, then it displays line 1 and 2.</p> <p>Can a for condition be set to determine whether it is finished writing to the txt?</p>
2
2016-09-09T04:19:23Z
39,403,969
<p>Also look at the <code>flush()</code> file method call and the <code>buffering</code> argument to <code>open</code>.</p> <p>Two reasons that trying to read immediately after writing:</p> <ol> <li>you're not opening the file to allow reading (need to open with mode <code>w+</code> to allow reading)</li> <li>files are buffered by default: calls to <code>write()</code> add to the buffer; until the buffer fills up, a <code>flush()</code> call is made, or the file is closed, the contents of the buffer will not actually be written to disk.</li> </ol>
2
2016-09-09T04:39:22Z
[ "python", "variables" ]
How to refer to something as an object instead of as a list?
39,403,965
<p>Let's say I have two objects of the MapTile class:</p> <pre><code>class MapTile(object): #The main class for stationary things that inhabit the grid ... grass, trees, rocks and stuff. def __init__(self, name, internal_column, internal_row, visible): self.name = name self.internal_column = internal_column self.internal_row = internal_row self.visible = visible </code></pre> <p>Which inhabit a 2-dimensional array, their respective internal_column and internal_row attributes representing their coordinates in the array. </p> <p>I want to write a function that returns the distance between two such objects. Here is what I have so far:</p> <pre><code>def return_distance(self, pointA, pointB): distance = math.sqrt((pointA.internal_column - pointB.internal_column)**2 + (pointA.internal_row - pointB.internal_row)**2) return distance </code></pre> <p>Where pointA and pointB would be the two objects. </p> <p>When I try it out, I get this error: </p> <pre><code>Traceback (most recent call last): File "/Users/kosay.jabre/Desktop/Monster.py", line 380, in &lt;module&gt; Map.update() File "/Users/kosay.jabre/Desktop/Monster.py", line 297, in update if Map.return_distance(Map.Grid[column][row], character) &lt;= character.visionrange: File "/Users/kosay.jabre/Desktop/Monster.py", line 245, in return_distance distance = math.sqrt((pointA.internal_column - pointB.internal_column)**2 + (pointA.internal_row - pointB.internal_row)**2) AttributeError: 'list' object has no attribute 'internal_column' </code></pre> <p>I am calling the distance function like this: </p> <pre><code>for character in Map.everyone: for column in range(MAPSIZE): for row in range(MAPSIZE): if Map.return_distance(Map.Grid[column][row], character) &lt;= character.visionrange: Map.Grid[column][row].visible = True </code></pre> <p>What should I do? How can I access the attributes of the object in "Map.Grid[column][row]" instead of "Map.Grid[column][row]" itself as a list? Here is how Map.Grid is created: </p> <pre><code>MAPSIZE = 25 class Map(object): #The main class; where the action happens global MAPSIZE Grid = [] friendlies = [] enemies = [] everyone = [friendlies + enemies] visible = [] for row in range(MAPSIZE): # Creating grid Grid.append([]) for column in range(MAPSIZE): Grid[row].append([]) for row in range(MAPSIZE): #Filling grid with grass for column in range(MAPSIZE): TempTile = MapTile("Grass", column, row, False) Grid[column][row].append(TempTile) </code></pre> <p>And I add things directly to Map.everyone like this:</p> <pre><code>for column in range(MAPSIZE): for row in range(MAPSIZE): for i in range(len(Map.Grid[column][row])): if Map.Grid[column][row][i].__class__.__name__ == "Character": Map.everyone.append(Map.Grid[column][row][i]) </code></pre> <p>Here is the full, full code as I'm running it: </p> <pre><code>import random import math import pygame pygame.init() Clock = pygame.time.Clock() Screen = pygame.display.set_mode([650, 650]) DONE = False MAPSIZE = 25 #how many tiles TURN = 0 TILEWIDTH = 20 #pixel size of tile TILEHEIGHT = 20 TILEMARGIN = 4 BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) BROWN = (123, 123, 0) MOVECOLOR = (150, 250, 150) KeyLookup = { pygame.K_LEFT: "W", pygame.K_RIGHT: "E", pygame.K_DOWN: "S", pygame.K_UP: "N" } class MapTile(object): #The main class for stationary things that inhabit the grid ... grass, trees, rocks and stuff. def __init__(self, name, internal_column, internal_row, visible): self.name = name self.internal_column = internal_column self.internal_row = internal_row self.visible = visible class Character(object): #can move around and do cool stuff def __init__(self, name, HP, internal_column, internal_row, damage, allegiance): self.name = name self.HP = HP self.internal_column = internal_column self.internal_row = internal_row self.damage = damage self.allegiance = allegiance visionrange = 10 moves_left = 15 direction = "N" def move(self, direction): #how characters move around if self.collision_check(direction): print("Collision") return if self.moves_left == 0: print("No more moves left") return elif direction == "N": self.internal_row -= 1 self.direction = "N" elif direction == "W": self.internal_column -= 1 self.direction = "W" elif direction == "E": self.internal_column += 1 self.direction = "E" elif direction == "S": self.internal_row += 1 self.direction = "S" self.moves_left = self.moves_left - 1 def collision_check(self, direction): if direction == "N": if self.internal_row == 0: return True if len(Map.Grid[self.internal_column][(self.internal_row)-1]) &gt; 1: return True elif direction == "W": if self.internal_column == 0: return True if len(Map.Grid[self.internal_column-1][(self.internal_row)]) &gt; 1: return True elif direction == "E": if self.internal_column == MAPSIZE-1: return True if len(Map.Grid[self.internal_column+1][(self.internal_row)]) &gt; 1: return True elif direction == "S": if self.internal_row == MAPSIZE-1: return True if len(Map.Grid[self.internal_column][(self.internal_row)+1]) &gt; 1: return True return False def attack(self, direction): if self.collision_check(direction): print("Attack attempt.") if self.direction == "N": for i in range(0, len(Map.Grid[self.internal_column][self.internal_row-1])): if Map.Grid[int(self.internal_column)][int(self.internal_row-1)][i].__class__.__name__ == "Character": Map.Grid[self.internal_column][self.internal_row-1][i].HP -= self.damage print(str(self.damage) + " damage") elif self.direction == "E": for i in range(0, len(Map.Grid[self.internal_column+1][self.internal_row])): if Map.Grid[self.internal_column+1][self.internal_row][i].__class__.__name__ == "Character": Map.Grid[self.internal_column+1][self.internal_row][i].HP -= self.damage print(str(self.damage) + " damage") elif self.direction == "W": for i in range(0, len(Map.Grid[self.internal_column-1][self.internal_row])): if Map.Grid[self.internal_column-1][self.internal_row][i].__class__.__name__ == "Character": Map.Grid[self.internal_column-1][self.internal_row][i].HP -= self.damage print(str(self.damage) + " damage") elif self.direction == "S": for i in range(0, len(Map.Grid[self.internal_column][self.internal_row+1])): if Map.Grid[self.internal_column][self.internal_row+1][i].__class__.__name__ == "Character": Map.Grid[self.internal_column][self.internal_row+1][i].HP -= self.damage print(str(self.damage) + " damage") self.moves_left = self.moves_left - 1 def ranged_attack(self, direction): if self.direction == "S": for k in range(1, (MAPSIZE - self.internal_row)): for i in range(0, len(Map.Grid[self.internal_column][self.internal_row + k])): if Map.Grid[self.internal_column][self.internal_row + k][i].__class__.__name__ == "Character": Map.Grid[self.internal_column][self.internal_row + k][i].HP -= self.damage print(str(self.damage) + " damage") self.moves_left = self.moves_left - 1 if self.direction == "N": for k in range(1, self.internal_row): for i in range(0, len(Map.Grid[self.internal_column][self.internal_row - k])): if Map.Grid[self.internal_column][self.internal_row - k][i].__class__.__name__ == "Character": Map.Grid[self.internal_column][self.internal_row - k][i].HP -= self.damage print(str(self.damage) + " damage") self.moves_left = self.moves_left - 1 if self.direction == "W": for k in range(1, self.internal_column): for i in range(0, len(Map.Grid[self.internal_column - k][self.internal_row])): if Map.Grid[self.internal_column - k][self.internal_row][i].__class__.__name__ == "Character": Map.Grid[self.internal_column - k][self.internal_row][i].HP -= self.damage print(str(self.damage) + " damage") self.moves_left = self.moves_left - 1 if self.direction == "E": for k in range(1, (MAPSIZE - self.internal_column)): for i in range(0, len(Map.Grid[self.internal_column + k][self.internal_row])): if Map.Grid[self.internal_column + k][self.internal_row][i].__class__.__name__ == "Character": Map.Grid[self.internal_column + k][self.internal_row][i].HP -= self.damage print(str(self.damage) + " damage") self.moves_left = self.moves_left - 1 else: return class Goblin(Character): def __init__(self): Character.__init__(self, "Goblin", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1), 10, random.randint(0,1)) def random_move(self): i = random.randint(0,3) if i == 0: self.move("N") elif i == 1: self.move("S") elif i == 2: self.move("W") elif i == 3: self.move("E") self.moves_left = 10 class Archer(Character): def __init__(self): Character.__init__(self, "Archer", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1)) class Warrior(Character): def __init__(self): Character.__init__(self, "Warrior", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1)) class Scout(Character): def __init__(self): Character.__init__(self, "Scout", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1)) class Rogue(Character): def __init__(self): Character.__init__(self, "Rogue", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1)) class Wizard(Character): def __init__(self): Character.__init__(self, "Wizard", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1)) class Map(object): #The main class; where the action happens global MAPSIZE wild_characters = [] can_move = [] no_moves = [] Grid = [] friendlies = [] enemies = [] everyone = [friendlies + enemies] visible = [] for row in range(MAPSIZE): # Creating grid Grid.append([]) for column in range(MAPSIZE): Grid[row].append([]) for row in range(MAPSIZE): #Filling grid with grass for column in range(MAPSIZE): TempTile = MapTile("Grass", column, row, False) Grid[column][row].append(TempTile) for row in range(MAPSIZE): #Putting some rocks near the top for column in range(MAPSIZE): TempTile = MapTile("Rock", column, row, False) if row == 1: Grid[column][row].append(TempTile) for i in range(10): #Trees in random places random_row = random.randint(0, MAPSIZE - 1) random_column = random.randint(0, MAPSIZE - 1) TempTile = MapTile("Tree", random_column, random_row, False) Grid[random_column][random_row].append(TempTile) def generate_hero(self): #Generate a character and place it randomly temp_hero = Character("Hero", 30, random.randint(0, MAPSIZE - 1), random.randint(0, MAPSIZE - 1) , 10, random.randint(0,1)) self.Grid[temp_hero.internal_column][temp_hero.internal_row].append(temp_hero) self.can_move.append(temp_hero) if temp_hero.allegiance == 0: self.friendlies.append(temp_hero) elif temp_hero.allegiance == 1: self.enemies.append(temp_hero) def return_distance(self, pointA, pointB): distance = math.sqrt((pointA.internal_column - pointB.internal_column)**2 + (pointA.internal_row - pointB.internal_row)**2) return distance def generate_goblin(self): #Generate a character and place it randomly random_row = random.randint(0, MAPSIZE - 1) random_column = random.randint(0, MAPSIZE - 1) temp_goblin = Goblin() self.Grid[random_column][random_row].append(temp_goblin) Map.wild_characters.append(temp_goblin) def update(self): for column in range(MAPSIZE): #These nested loops go through entire grid for row in range(MAPSIZE): #They check if any objects internal coordinates for i in range(len(Map.Grid[column][row])): #disagree with its place on the grid and update it accordingly if Map.Grid[column][row][i].internal_column != column: TempChar = Map.Grid[column][row][i] Map.Grid[column][row].remove(Map.Grid[column][row][i]) Map.Grid[int(TempChar.internal_column)][int(TempChar.internal_row)].append(TempChar) elif Map.Grid[column][row][i].internal_row != row: TempChar = Map.Grid[column][row][i] Map.Grid[column][row].remove(Map.Grid[column][row][i]) Map.Grid[int(TempChar.internal_column)][int(TempChar.internal_row)].append(TempChar) temparr = Map.no_moves[:] for characterobject in temparr: #This moves any characters with moves to the can move list if len(temparr) &gt; 0: if characterobject.moves_left &gt; 0: Map.can_move.append(characterobject) Map.no_moves.remove(characterobject) if characterobject.HP &lt;= 0: Map.no_moves.remove(characterobject) arr = Map.can_move[:] # copy for item in arr: if item.moves_left == 0: Map.can_move.remove(item) Map.no_moves.append(item) if item.HP &lt;= 0: Map.can_move.remove(item) for column in range(MAPSIZE): for row in range(MAPSIZE): for i in range(len(Map.Grid[column][row])): if Map.Grid[column][row][i].__class__.__name__ == "Character": if Map.Grid[column][row][i].HP &lt;= 0: Map.Grid[column][row].remove(Map.Grid[column][row][i]) print("Character died") for column in range(MAPSIZE): for row in range(MAPSIZE): for i in range(len(Map.Grid[column][row])): if Map.Grid[column][row][i].__class__.__name__ == "Character": Map.everyone.append(Map.Grid[column][row][i]) for character in Map.everyone: for column in range(MAPSIZE): for row in range(MAPSIZE): if Map.return_distance(Map.Grid[column][row][0], character ) &lt;= 15: Map.Grid[column][row].visible = True def listofcharacters(self): for column in range(MAPSIZE): for row in range(MAPSIZE): for i in range(len(Map.Grid[column][row])): if Map.Grid[column][row][i].__class__.__name__ == "Character": print("Column: ", Map.Grid[column][row][i].internal_column, ", Row: ", Map.Grid[column][row][i].internal_row, ", Allegiance: ", Map.Grid[column][row][i].allegiance) Map = Map() Map.generate_hero() while not DONE: #Main pygame loop for event in pygame.event.get(): #catching events if event.type == pygame.QUIT: DONE = True elif event.type == pygame.MOUSEBUTTONDOWN: Pos = pygame.mouse.get_pos() column = Pos[0] // (TILEWIDTH + TILEMARGIN) #Translating the position of the mouse into rows and columns row = Pos[1] // (TILEHEIGHT + TILEMARGIN) print(str(row) + ", " + str(column)) for i in range(len(Map.Grid[column][row])): print(str(Map.Grid[column][row][i].name)) #print stuff that inhabits that square elif event.type == pygame.KEYDOWN: wild_char_arr = Map.wild_characters[:] for wildcharacter in wild_char_arr: if wildcharacter.name == "Goblin": wildcharacter.random_move() if event.key == 97: # Keypress: a print("New turn.") temparr = Map.no_moves[:] for item in temparr: if item.moves_left == 0: item.moves_left = 15 TURN = TURN + 1 print("Turn: ", TURN) elif event.key == 115: # Keypress: s print("Generated hero.") Map.generate_hero() elif event.key == 113: # Keypress: q print("ranged attack") Map.can_move[0].ranged_attack(Map.can_move[0].direction) elif event.key == 119: # Keypress: w print("Generated hero.") Map.generate_hero() elif event.key == 101: # Keypress: e print("Generated hero.") Map.generate_hero() elif event.key == 114: # Keypress: r print("Generated hero.") Map.generate_hero() elif event.key == 116: # Keypress: t print("Generated hero.") Map.generate_hero() elif event.key == 100: # Keypress: d Map.generate_goblin() print("Generated goblin.") elif event.key == 102: # Keypress: f Map.can_move[0].attack(Map.can_move[0].direction) elif len(Map.can_move) &gt; 0: Map.can_move[0].move(KeyLookup[event.key]) else: print("invalid") Map.update() Screen.fill(BLACK) for row in range(MAPSIZE): # Drawing grid for column in range(MAPSIZE): for i in range(0, len(Map.Grid[column][row])): Color = WHITE if len(Map.can_move) &gt; 0: # Creating colored area around character showing his move range if (math.sqrt((Map.can_move[0].internal_column - column)**2 + (Map.can_move[0].internal_row - row)**2)) &lt;= Map.can_move[0].moves_left: Color = MOVECOLOR if len(Map.Grid[column][row]) &gt; 1: Color = RED if Map.Grid[column][row][i].name == "Tree": Color = GREEN if str(Map.Grid[column][row][i].__class__.__name__) == "Character": Color = BROWN pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN, (TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN, TILEWIDTH, TILEHEIGHT]) if str(Map.Grid[column][row][i].__class__.__name__) == "Character": if Map.Grid[column][row][i].direction == "N": Color = RED pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN + 8, (TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN, TILEWIDTH/4, TILEHEIGHT/4]) if str(Map.Grid[column][row][i].__class__.__name__) == "Character": if Map.Grid[column][row][i].direction == "S": Color = RED pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN + 8, (TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN*5 - 1 , TILEWIDTH/4, TILEHEIGHT/4]) if str(Map.Grid[column][row][i].__class__.__name__) == "Character": if Map.Grid[column][row][i].direction == "E": Color = RED pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN + 15, (TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN*5 - 8, TILEWIDTH/4, TILEHEIGHT/4]) if str(Map.Grid[column][row][i].__class__.__name__) == "Character": if Map.Grid[column][row][i].direction == "W": Color = RED pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN , (TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN*5 - 8 , TILEWIDTH/4, TILEHEIGHT/4]) Clock.tick(60) pygame.display.flip() pygame.quit() </code></pre>
4
2016-09-09T04:39:07Z
39,404,060
<p>In <code>Map</code>:</p> <pre><code>friendlies = [] enemies = [] everyone = [friendlies + enemies] </code></pre> <p>This means <code>everyone</code> is defined as as a list of an empty list: <code>[ [] + [] ]</code> == <code>[ [] ]</code>. This in turn means:</p> <pre><code>for character in Map.everyone: </code></pre> <p><code>character</code> is the empty list <code>[]</code>, which causes your error.</p> <p>Also, because this is evaluated once at the time of the assignment, when you later modify <code>friendlies</code> and <code>enemies</code> it does not change the value of <code>everyone</code>.</p>
3
2016-09-09T04:51:01Z
[ "python", "python-3.x", "oop", "multidimensional-array", "game-engine" ]
How to refer to something as an object instead of as a list?
39,403,965
<p>Let's say I have two objects of the MapTile class:</p> <pre><code>class MapTile(object): #The main class for stationary things that inhabit the grid ... grass, trees, rocks and stuff. def __init__(self, name, internal_column, internal_row, visible): self.name = name self.internal_column = internal_column self.internal_row = internal_row self.visible = visible </code></pre> <p>Which inhabit a 2-dimensional array, their respective internal_column and internal_row attributes representing their coordinates in the array. </p> <p>I want to write a function that returns the distance between two such objects. Here is what I have so far:</p> <pre><code>def return_distance(self, pointA, pointB): distance = math.sqrt((pointA.internal_column - pointB.internal_column)**2 + (pointA.internal_row - pointB.internal_row)**2) return distance </code></pre> <p>Where pointA and pointB would be the two objects. </p> <p>When I try it out, I get this error: </p> <pre><code>Traceback (most recent call last): File "/Users/kosay.jabre/Desktop/Monster.py", line 380, in &lt;module&gt; Map.update() File "/Users/kosay.jabre/Desktop/Monster.py", line 297, in update if Map.return_distance(Map.Grid[column][row], character) &lt;= character.visionrange: File "/Users/kosay.jabre/Desktop/Monster.py", line 245, in return_distance distance = math.sqrt((pointA.internal_column - pointB.internal_column)**2 + (pointA.internal_row - pointB.internal_row)**2) AttributeError: 'list' object has no attribute 'internal_column' </code></pre> <p>I am calling the distance function like this: </p> <pre><code>for character in Map.everyone: for column in range(MAPSIZE): for row in range(MAPSIZE): if Map.return_distance(Map.Grid[column][row], character) &lt;= character.visionrange: Map.Grid[column][row].visible = True </code></pre> <p>What should I do? How can I access the attributes of the object in "Map.Grid[column][row]" instead of "Map.Grid[column][row]" itself as a list? Here is how Map.Grid is created: </p> <pre><code>MAPSIZE = 25 class Map(object): #The main class; where the action happens global MAPSIZE Grid = [] friendlies = [] enemies = [] everyone = [friendlies + enemies] visible = [] for row in range(MAPSIZE): # Creating grid Grid.append([]) for column in range(MAPSIZE): Grid[row].append([]) for row in range(MAPSIZE): #Filling grid with grass for column in range(MAPSIZE): TempTile = MapTile("Grass", column, row, False) Grid[column][row].append(TempTile) </code></pre> <p>And I add things directly to Map.everyone like this:</p> <pre><code>for column in range(MAPSIZE): for row in range(MAPSIZE): for i in range(len(Map.Grid[column][row])): if Map.Grid[column][row][i].__class__.__name__ == "Character": Map.everyone.append(Map.Grid[column][row][i]) </code></pre> <p>Here is the full, full code as I'm running it: </p> <pre><code>import random import math import pygame pygame.init() Clock = pygame.time.Clock() Screen = pygame.display.set_mode([650, 650]) DONE = False MAPSIZE = 25 #how many tiles TURN = 0 TILEWIDTH = 20 #pixel size of tile TILEHEIGHT = 20 TILEMARGIN = 4 BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) BROWN = (123, 123, 0) MOVECOLOR = (150, 250, 150) KeyLookup = { pygame.K_LEFT: "W", pygame.K_RIGHT: "E", pygame.K_DOWN: "S", pygame.K_UP: "N" } class MapTile(object): #The main class for stationary things that inhabit the grid ... grass, trees, rocks and stuff. def __init__(self, name, internal_column, internal_row, visible): self.name = name self.internal_column = internal_column self.internal_row = internal_row self.visible = visible class Character(object): #can move around and do cool stuff def __init__(self, name, HP, internal_column, internal_row, damage, allegiance): self.name = name self.HP = HP self.internal_column = internal_column self.internal_row = internal_row self.damage = damage self.allegiance = allegiance visionrange = 10 moves_left = 15 direction = "N" def move(self, direction): #how characters move around if self.collision_check(direction): print("Collision") return if self.moves_left == 0: print("No more moves left") return elif direction == "N": self.internal_row -= 1 self.direction = "N" elif direction == "W": self.internal_column -= 1 self.direction = "W" elif direction == "E": self.internal_column += 1 self.direction = "E" elif direction == "S": self.internal_row += 1 self.direction = "S" self.moves_left = self.moves_left - 1 def collision_check(self, direction): if direction == "N": if self.internal_row == 0: return True if len(Map.Grid[self.internal_column][(self.internal_row)-1]) &gt; 1: return True elif direction == "W": if self.internal_column == 0: return True if len(Map.Grid[self.internal_column-1][(self.internal_row)]) &gt; 1: return True elif direction == "E": if self.internal_column == MAPSIZE-1: return True if len(Map.Grid[self.internal_column+1][(self.internal_row)]) &gt; 1: return True elif direction == "S": if self.internal_row == MAPSIZE-1: return True if len(Map.Grid[self.internal_column][(self.internal_row)+1]) &gt; 1: return True return False def attack(self, direction): if self.collision_check(direction): print("Attack attempt.") if self.direction == "N": for i in range(0, len(Map.Grid[self.internal_column][self.internal_row-1])): if Map.Grid[int(self.internal_column)][int(self.internal_row-1)][i].__class__.__name__ == "Character": Map.Grid[self.internal_column][self.internal_row-1][i].HP -= self.damage print(str(self.damage) + " damage") elif self.direction == "E": for i in range(0, len(Map.Grid[self.internal_column+1][self.internal_row])): if Map.Grid[self.internal_column+1][self.internal_row][i].__class__.__name__ == "Character": Map.Grid[self.internal_column+1][self.internal_row][i].HP -= self.damage print(str(self.damage) + " damage") elif self.direction == "W": for i in range(0, len(Map.Grid[self.internal_column-1][self.internal_row])): if Map.Grid[self.internal_column-1][self.internal_row][i].__class__.__name__ == "Character": Map.Grid[self.internal_column-1][self.internal_row][i].HP -= self.damage print(str(self.damage) + " damage") elif self.direction == "S": for i in range(0, len(Map.Grid[self.internal_column][self.internal_row+1])): if Map.Grid[self.internal_column][self.internal_row+1][i].__class__.__name__ == "Character": Map.Grid[self.internal_column][self.internal_row+1][i].HP -= self.damage print(str(self.damage) + " damage") self.moves_left = self.moves_left - 1 def ranged_attack(self, direction): if self.direction == "S": for k in range(1, (MAPSIZE - self.internal_row)): for i in range(0, len(Map.Grid[self.internal_column][self.internal_row + k])): if Map.Grid[self.internal_column][self.internal_row + k][i].__class__.__name__ == "Character": Map.Grid[self.internal_column][self.internal_row + k][i].HP -= self.damage print(str(self.damage) + " damage") self.moves_left = self.moves_left - 1 if self.direction == "N": for k in range(1, self.internal_row): for i in range(0, len(Map.Grid[self.internal_column][self.internal_row - k])): if Map.Grid[self.internal_column][self.internal_row - k][i].__class__.__name__ == "Character": Map.Grid[self.internal_column][self.internal_row - k][i].HP -= self.damage print(str(self.damage) + " damage") self.moves_left = self.moves_left - 1 if self.direction == "W": for k in range(1, self.internal_column): for i in range(0, len(Map.Grid[self.internal_column - k][self.internal_row])): if Map.Grid[self.internal_column - k][self.internal_row][i].__class__.__name__ == "Character": Map.Grid[self.internal_column - k][self.internal_row][i].HP -= self.damage print(str(self.damage) + " damage") self.moves_left = self.moves_left - 1 if self.direction == "E": for k in range(1, (MAPSIZE - self.internal_column)): for i in range(0, len(Map.Grid[self.internal_column + k][self.internal_row])): if Map.Grid[self.internal_column + k][self.internal_row][i].__class__.__name__ == "Character": Map.Grid[self.internal_column + k][self.internal_row][i].HP -= self.damage print(str(self.damage) + " damage") self.moves_left = self.moves_left - 1 else: return class Goblin(Character): def __init__(self): Character.__init__(self, "Goblin", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1), 10, random.randint(0,1)) def random_move(self): i = random.randint(0,3) if i == 0: self.move("N") elif i == 1: self.move("S") elif i == 2: self.move("W") elif i == 3: self.move("E") self.moves_left = 10 class Archer(Character): def __init__(self): Character.__init__(self, "Archer", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1)) class Warrior(Character): def __init__(self): Character.__init__(self, "Warrior", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1)) class Scout(Character): def __init__(self): Character.__init__(self, "Scout", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1)) class Rogue(Character): def __init__(self): Character.__init__(self, "Rogue", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1)) class Wizard(Character): def __init__(self): Character.__init__(self, "Wizard", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1)) class Map(object): #The main class; where the action happens global MAPSIZE wild_characters = [] can_move = [] no_moves = [] Grid = [] friendlies = [] enemies = [] everyone = [friendlies + enemies] visible = [] for row in range(MAPSIZE): # Creating grid Grid.append([]) for column in range(MAPSIZE): Grid[row].append([]) for row in range(MAPSIZE): #Filling grid with grass for column in range(MAPSIZE): TempTile = MapTile("Grass", column, row, False) Grid[column][row].append(TempTile) for row in range(MAPSIZE): #Putting some rocks near the top for column in range(MAPSIZE): TempTile = MapTile("Rock", column, row, False) if row == 1: Grid[column][row].append(TempTile) for i in range(10): #Trees in random places random_row = random.randint(0, MAPSIZE - 1) random_column = random.randint(0, MAPSIZE - 1) TempTile = MapTile("Tree", random_column, random_row, False) Grid[random_column][random_row].append(TempTile) def generate_hero(self): #Generate a character and place it randomly temp_hero = Character("Hero", 30, random.randint(0, MAPSIZE - 1), random.randint(0, MAPSIZE - 1) , 10, random.randint(0,1)) self.Grid[temp_hero.internal_column][temp_hero.internal_row].append(temp_hero) self.can_move.append(temp_hero) if temp_hero.allegiance == 0: self.friendlies.append(temp_hero) elif temp_hero.allegiance == 1: self.enemies.append(temp_hero) def return_distance(self, pointA, pointB): distance = math.sqrt((pointA.internal_column - pointB.internal_column)**2 + (pointA.internal_row - pointB.internal_row)**2) return distance def generate_goblin(self): #Generate a character and place it randomly random_row = random.randint(0, MAPSIZE - 1) random_column = random.randint(0, MAPSIZE - 1) temp_goblin = Goblin() self.Grid[random_column][random_row].append(temp_goblin) Map.wild_characters.append(temp_goblin) def update(self): for column in range(MAPSIZE): #These nested loops go through entire grid for row in range(MAPSIZE): #They check if any objects internal coordinates for i in range(len(Map.Grid[column][row])): #disagree with its place on the grid and update it accordingly if Map.Grid[column][row][i].internal_column != column: TempChar = Map.Grid[column][row][i] Map.Grid[column][row].remove(Map.Grid[column][row][i]) Map.Grid[int(TempChar.internal_column)][int(TempChar.internal_row)].append(TempChar) elif Map.Grid[column][row][i].internal_row != row: TempChar = Map.Grid[column][row][i] Map.Grid[column][row].remove(Map.Grid[column][row][i]) Map.Grid[int(TempChar.internal_column)][int(TempChar.internal_row)].append(TempChar) temparr = Map.no_moves[:] for characterobject in temparr: #This moves any characters with moves to the can move list if len(temparr) &gt; 0: if characterobject.moves_left &gt; 0: Map.can_move.append(characterobject) Map.no_moves.remove(characterobject) if characterobject.HP &lt;= 0: Map.no_moves.remove(characterobject) arr = Map.can_move[:] # copy for item in arr: if item.moves_left == 0: Map.can_move.remove(item) Map.no_moves.append(item) if item.HP &lt;= 0: Map.can_move.remove(item) for column in range(MAPSIZE): for row in range(MAPSIZE): for i in range(len(Map.Grid[column][row])): if Map.Grid[column][row][i].__class__.__name__ == "Character": if Map.Grid[column][row][i].HP &lt;= 0: Map.Grid[column][row].remove(Map.Grid[column][row][i]) print("Character died") for column in range(MAPSIZE): for row in range(MAPSIZE): for i in range(len(Map.Grid[column][row])): if Map.Grid[column][row][i].__class__.__name__ == "Character": Map.everyone.append(Map.Grid[column][row][i]) for character in Map.everyone: for column in range(MAPSIZE): for row in range(MAPSIZE): if Map.return_distance(Map.Grid[column][row][0], character ) &lt;= 15: Map.Grid[column][row].visible = True def listofcharacters(self): for column in range(MAPSIZE): for row in range(MAPSIZE): for i in range(len(Map.Grid[column][row])): if Map.Grid[column][row][i].__class__.__name__ == "Character": print("Column: ", Map.Grid[column][row][i].internal_column, ", Row: ", Map.Grid[column][row][i].internal_row, ", Allegiance: ", Map.Grid[column][row][i].allegiance) Map = Map() Map.generate_hero() while not DONE: #Main pygame loop for event in pygame.event.get(): #catching events if event.type == pygame.QUIT: DONE = True elif event.type == pygame.MOUSEBUTTONDOWN: Pos = pygame.mouse.get_pos() column = Pos[0] // (TILEWIDTH + TILEMARGIN) #Translating the position of the mouse into rows and columns row = Pos[1] // (TILEHEIGHT + TILEMARGIN) print(str(row) + ", " + str(column)) for i in range(len(Map.Grid[column][row])): print(str(Map.Grid[column][row][i].name)) #print stuff that inhabits that square elif event.type == pygame.KEYDOWN: wild_char_arr = Map.wild_characters[:] for wildcharacter in wild_char_arr: if wildcharacter.name == "Goblin": wildcharacter.random_move() if event.key == 97: # Keypress: a print("New turn.") temparr = Map.no_moves[:] for item in temparr: if item.moves_left == 0: item.moves_left = 15 TURN = TURN + 1 print("Turn: ", TURN) elif event.key == 115: # Keypress: s print("Generated hero.") Map.generate_hero() elif event.key == 113: # Keypress: q print("ranged attack") Map.can_move[0].ranged_attack(Map.can_move[0].direction) elif event.key == 119: # Keypress: w print("Generated hero.") Map.generate_hero() elif event.key == 101: # Keypress: e print("Generated hero.") Map.generate_hero() elif event.key == 114: # Keypress: r print("Generated hero.") Map.generate_hero() elif event.key == 116: # Keypress: t print("Generated hero.") Map.generate_hero() elif event.key == 100: # Keypress: d Map.generate_goblin() print("Generated goblin.") elif event.key == 102: # Keypress: f Map.can_move[0].attack(Map.can_move[0].direction) elif len(Map.can_move) &gt; 0: Map.can_move[0].move(KeyLookup[event.key]) else: print("invalid") Map.update() Screen.fill(BLACK) for row in range(MAPSIZE): # Drawing grid for column in range(MAPSIZE): for i in range(0, len(Map.Grid[column][row])): Color = WHITE if len(Map.can_move) &gt; 0: # Creating colored area around character showing his move range if (math.sqrt((Map.can_move[0].internal_column - column)**2 + (Map.can_move[0].internal_row - row)**2)) &lt;= Map.can_move[0].moves_left: Color = MOVECOLOR if len(Map.Grid[column][row]) &gt; 1: Color = RED if Map.Grid[column][row][i].name == "Tree": Color = GREEN if str(Map.Grid[column][row][i].__class__.__name__) == "Character": Color = BROWN pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN, (TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN, TILEWIDTH, TILEHEIGHT]) if str(Map.Grid[column][row][i].__class__.__name__) == "Character": if Map.Grid[column][row][i].direction == "N": Color = RED pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN + 8, (TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN, TILEWIDTH/4, TILEHEIGHT/4]) if str(Map.Grid[column][row][i].__class__.__name__) == "Character": if Map.Grid[column][row][i].direction == "S": Color = RED pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN + 8, (TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN*5 - 1 , TILEWIDTH/4, TILEHEIGHT/4]) if str(Map.Grid[column][row][i].__class__.__name__) == "Character": if Map.Grid[column][row][i].direction == "E": Color = RED pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN + 15, (TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN*5 - 8, TILEWIDTH/4, TILEHEIGHT/4]) if str(Map.Grid[column][row][i].__class__.__name__) == "Character": if Map.Grid[column][row][i].direction == "W": Color = RED pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN , (TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN*5 - 8 , TILEWIDTH/4, TILEHEIGHT/4]) Clock.tick(60) pygame.display.flip() pygame.quit() </code></pre>
4
2016-09-09T04:39:07Z
39,404,077
<p>It looks like you are creating a list of lists of lists, when you just need a list of lists. The <code>row</code> list can contain your <code>MapTile</code>s directly; no need to fill it with more lists.</p> <p>Try this instead: </p> <pre><code>for row in range(MAPSIZE): # Creating grid Grid.append([]) for row in range(MAPSIZE): #Filling grid with grass for column in range(MAPSIZE): TempTile = MapTile("Grass", column, row, False) Grid[row].append(TempTile) </code></pre> <p>This way, Grid is just a list of rows, and each row is a list of tiles, one tile per column.</p>
3
2016-09-09T04:53:44Z
[ "python", "python-3.x", "oop", "multidimensional-array", "game-engine" ]
Delete Operation in Basic Implementation of the Binary Search Tree in python
39,404,026
<p>I am almost done with my Binary Search Tree implementation in Python except for the Deletion operation.</p> <p>So far, in all the use cases of the function that I have tested so far: 1. leaf nodes are deleted correctly 2. nodes with two children are deleted correctly 3. root nodes are deleted correctly</p> <p>but I am not able to delete nodes with either the left child or the right child. my Eclipse IDE showed me that some of the statements have no effect (the statements that are underlined as yellow in the following picture), so I have tried the program in my iPython Notebook local server, but the result seems to be the same.</p> <p>lines 43-57: <a href="http://i.stack.imgur.com/DBgEz.png" rel="nofollow"><img src="http://i.stack.imgur.com/DBgEz.png" alt="enter image description here"></a></p> <p>what is it that I am missing out in my python program? please help me out. Here is my code :</p> <pre><code>prevnode = None class Node: def __init__(self,data): self.data = data self.left = None self.right = None def insert(node,info): if node.data is None: node.data = info elif info &lt; node.data: if node.left is None: node.left = Node(None) insert(node.left,info) elif info &gt;= node.data: if node.right is None: node.right = Node(None) insert(node.right,info) def search(node,info): if node is None: print "Node with the mentioned data is not found" if node.data == info: print "Found the node containing value held by info" elif info &lt; node.data and node.left is not None: search(node.left,info) elif info &gt; node.data and node.right is not None: search(node.right,info) def delete(node,info): global prevnode if info == node.data: print "This is the place where info is stored" if node.left is None and node.right is None: if prevnode.left is not None and prevnode.left.data == node.data: prevnode.left = None del node elif prevnode.right is not None and prevnode.right.data == node.data: prevnode.right = None del node return elif node.left is not None and node.right is None: if prevnode.left is not None and prevnode.left.data == node.data: prevnode.left == node.left del node elif prevnode.right is not None and prevnode.right.data == node.data: prevnode.right == node.left del node return elif node.left is None and node.right is not None: if prevnode.left is not None and prevnode.left.data == node.data: prevnode.left == node.right del node elif prevnode.right is not None and prevnode.right.data == node.data: prevnode.right == node.right del node return elif node.left is not None and node.right is not None: node.data = None prevnode = node.right successor = prevnode.left if successor is None: node.data = prevnode.data node.right = prevnode.right elif successor is not None: while successor.left is not None: prevnode = successor successor = prevnode.left if successor.right is None: node.data = successor.data prevnode.left = None del successor elif successor.right is not None: prevnode.left = successor.right node.data = successor.data successor.right = None del successor elif info &lt; node.data: print "We will have to go to the left child of the current node" prevnode = node print "parent of the left child will be prevnode : ",prevnode.data delete(node.left,info) elif info &gt;= node.data: print "We will have to go to the right child of the current node" prevnode = node print "parent of the right child will be prevnode : ",prevnode.data delete(node.right,info) def display(node,parent): if node is not None: print "value at this node is ",node.data if parent is None: print "it is the root node" else: print "the parent is ",parent.data if node.left is not None: display(node.left,node) if node.right is not None: display(node.right,node) else: return BST = Node(None) while True: choice = int(raw_input("Please enter your choice 1.Insert, 2.Search, 3.Delete, 4.Display, 5.Exit")) if choice == 1: num = int(raw_input("Please enter the number you wish to insert")) insert(BST,num) elif choice == 2: num = int(raw_input("Please enter the number you wish to find")) search(BST,num) elif choice == 3: num = int(raw_input("Please enter the number you wish to delete")) delete(BST,num) elif choice == 4: print "Displaying the Tree" display(BST,None) elif choice == 5: break else: print "Please enter the correct input" </code></pre> <p><strong>P.S: just in case there are any wrong indentations(I am pretty sure there are none though), they can be indented properly</strong></p>
3
2016-09-09T04:46:44Z
39,404,143
<p>There is a simple typo. You're using == instead of =.</p> <p>So instead of this:</p> <pre><code> elif node.left is not None and node.right is None: if prevnode.left is not None and prevnode.left.data == node.data: prevnode.left == node.left del node elif prevnode.right is not None and prevnode.right.data == node.data: prevnode.right == node.left del node return elif node.left is None and node.right is not None: if prevnode.left is not None and prevnode.left.data == node.data: prevnode.left == node.right del node elif prevnode.right is not None and prevnode.right.data == node.data: prevnode.right == node.right del node return </code></pre> <p>You want to do this:</p> <pre><code> elif node.left is not None and node.right is None: if prevnode.left is not None and prevnode.left.data == node.data: prevnode.left = node.left # Changed == to = del node elif prevnode.right is not None and prevnode.right.data == node.data: prevnode.right = node.left # Changed == to = del node return elif node.left is None and node.right is not None: if prevnode.left is not None and prevnode.left.data == node.data: prevnode.left = node.right # Changed == to = del node elif prevnode.right is not None and prevnode.right.data == node.data: prevnode.right = node.right # Changed == to = del node return </code></pre>
2
2016-09-09T05:00:13Z
[ "python" ]
Is it possible to name a variable 'in' in python?
39,404,033
<p>I am making a unit converter for a homework assignment, and I am using abbreviations for the various units of measurement as variable names, but when I try to define 'in' as a variable, it thinks I mean to use the word 'in' as if I wanted to say 'for x in y' or something like that, and I get the following error:</p> <pre><code> File "unit_converter-v1.py", line 13 in = 12 ^ SyntaxError: invalid syntax </code></pre> <p>Is there any way to get around this?</p> <p>I know I could just use the word 'inch' or 'inches' but then I would have to type 'inch' or 'inches' into the program every time I needed to convert inches, and I want to make the process as efficient as possible (I'm a senior in highschool, and my phisics teacher will allow us to use unit converters on tests and quizzes if we write the code ourselves. The point is that time is valuable and I need to be as time-efficient as possible).</p>
0
2016-09-09T04:47:25Z
39,404,067
<p><code>in</code> is a python keyword, so no you cannot use it as a variable or function or class name.</p> <p>See <a href="https://docs.python.org/2/reference/lexical_analysis.html#keywords" rel="nofollow">https://docs.python.org/2/reference/lexical_analysis.html#keywords</a> for the list of keywords in Python 2.7.12.</p>
3
2016-09-09T04:52:03Z
[ "python", "python-2.7", "units-of-measurement", "unit-conversion" ]
Is it possible to name a variable 'in' in python?
39,404,033
<p>I am making a unit converter for a homework assignment, and I am using abbreviations for the various units of measurement as variable names, but when I try to define 'in' as a variable, it thinks I mean to use the word 'in' as if I wanted to say 'for x in y' or something like that, and I get the following error:</p> <pre><code> File "unit_converter-v1.py", line 13 in = 12 ^ SyntaxError: invalid syntax </code></pre> <p>Is there any way to get around this?</p> <p>I know I could just use the word 'inch' or 'inches' but then I would have to type 'inch' or 'inches' into the program every time I needed to convert inches, and I want to make the process as efficient as possible (I'm a senior in highschool, and my phisics teacher will allow us to use unit converters on tests and quizzes if we write the code ourselves. The point is that time is valuable and I need to be as time-efficient as possible).</p>
0
2016-09-09T04:47:25Z
39,404,117
<p><strong>in</strong> is a reserved word, so you won't be able to use it as a variable name; the easiest solution would be to use a different name.</p> <p>Python makes it easier to identify reserved words with the <code>keyword.iskeyword</code> function, as described <a href="http://stackoverflow.com/questions/22864221/is-the-list-of-python-reserved-words-and-builtins-available-in-a-library">here</a></p> <p>BTW, naming things was described as the most difficult task for a developer by itworld <a href="http://www.itworld.com/article/2823759/enterprise-software/124383-Arg-The-9-hardest-things-programmers-have-to-do.html#slide10" rel="nofollow">this article</a>.</p>
2
2016-09-09T04:58:13Z
[ "python", "python-2.7", "units-of-measurement", "unit-conversion" ]
Is it possible to name a variable 'in' in python?
39,404,033
<p>I am making a unit converter for a homework assignment, and I am using abbreviations for the various units of measurement as variable names, but when I try to define 'in' as a variable, it thinks I mean to use the word 'in' as if I wanted to say 'for x in y' or something like that, and I get the following error:</p> <pre><code> File "unit_converter-v1.py", line 13 in = 12 ^ SyntaxError: invalid syntax </code></pre> <p>Is there any way to get around this?</p> <p>I know I could just use the word 'inch' or 'inches' but then I would have to type 'inch' or 'inches' into the program every time I needed to convert inches, and I want to make the process as efficient as possible (I'm a senior in highschool, and my phisics teacher will allow us to use unit converters on tests and quizzes if we write the code ourselves. The point is that time is valuable and I need to be as time-efficient as possible).</p>
0
2016-09-09T04:47:25Z
39,404,212
<p>As the other answers state, you can't. However, you can simply change the case of it as an alternative.</p> <p><code>In = 2</code> is valid and will work. So would any other variation with at least one of the characters capitalized.</p>
2
2016-09-09T05:07:42Z
[ "python", "python-2.7", "units-of-measurement", "unit-conversion" ]
How to find assets of installed pip package
39,404,107
<p>While deploying my application, I need to install a library which contains some assets that must be served from an static directory. That means, during the deploy, I must do the following:</p> <ol> <li><code>pip install</code> the package</li> <li>Find the <em>absolute</em> location where the package has been installed (this is usually <code>site-packages</code> in the virtualenv or global location)</li> <li>Copy the assets from the installed package to the static directory</li> </ol> <p>Is there a portable way of doing step 2? The only starting piece of data that I have to find the installed package is <code>pip</code> / <code>python</code>.</p> <p>Is there a way to tell <code>python</code>: in what absolute location have you installed a certain package?</p>
0
2016-09-09T04:57:34Z
39,404,283
<p>If you install package <code>abc</code>, you should be able to import that package and get its base location in a python program with:</p> <pre><code>import abc import os print(os.path.dirname(abc.__file__)) </code></pre> <p>if importing is not possible because of some side-effect this might have you can walk <code>sys.path</code> and look for <code>abc.py</code> or <code>abc/__init__.py</code>.</p> <p>If you have multiple installations, you might not find the version you just installed, but in that case you also would not be running that when importing <code>abc</code>, but an older version.</p>
1
2016-09-09T05:15:29Z
[ "python", "pip" ]
How to find assets of installed pip package
39,404,107
<p>While deploying my application, I need to install a library which contains some assets that must be served from an static directory. That means, during the deploy, I must do the following:</p> <ol> <li><code>pip install</code> the package</li> <li>Find the <em>absolute</em> location where the package has been installed (this is usually <code>site-packages</code> in the virtualenv or global location)</li> <li>Copy the assets from the installed package to the static directory</li> </ol> <p>Is there a portable way of doing step 2? The only starting piece of data that I have to find the installed package is <code>pip</code> / <code>python</code>.</p> <p>Is there a way to tell <code>python</code>: in what absolute location have you installed a certain package?</p>
0
2016-09-09T04:57:34Z
39,404,340
<p>You can try finding your installed package via the following command.</p> <pre><code>pip show installed-package-name </code></pre> <p>This will return a bunch of attributes with package location. See below example.</p> <pre><code>C:\&gt; pip show selenium --- Metadata-Version: 2.0 Name: selenium Version: 3.0.0b2 Summary: Python bindings for Selenium Home-page: https://github.com/SeleniumHQ/selenium/ Author: UNKNOWN Author-email: UNKNOWN License: UNKNOWN Location: d:\appl\python27\lib\site-packages Requires: </code></pre>
1
2016-09-09T05:21:20Z
[ "python", "pip" ]
How to find assets of installed pip package
39,404,107
<p>While deploying my application, I need to install a library which contains some assets that must be served from an static directory. That means, during the deploy, I must do the following:</p> <ol> <li><code>pip install</code> the package</li> <li>Find the <em>absolute</em> location where the package has been installed (this is usually <code>site-packages</code> in the virtualenv or global location)</li> <li>Copy the assets from the installed package to the static directory</li> </ol> <p>Is there a portable way of doing step 2? The only starting piece of data that I have to find the installed package is <code>pip</code> / <code>python</code>.</p> <p>Is there a way to tell <code>python</code>: in what absolute location have you installed a certain package?</p>
0
2016-09-09T04:57:34Z
39,404,369
<p>See <a href="https://docs.python.org/2/library/pkgutil.html#pkgutil.get_data" rel="nofollow">pkgutil.get_data</a>. File-system based approaches break with packages that are installed as zip-file.</p>
0
2016-09-09T05:24:08Z
[ "python", "pip" ]
How to save the python scipts made on Python console in Pycharm?
39,404,270
<p>I have been writing scripts in Python console provided in Pycharm but now I need to save them on my desktop and run them at some later point. I can not happen to find any option to do so for the console scripts. </p>
2
2016-09-09T05:13:56Z
39,411,013
<p>I don't think there is a way to save the contents of a console session within PyCharm (or any other editor that I know of). As @daladier pointed out in the comments, though, <a href="http://ipython.org/ipython-doc/stable/overview.html" rel="nofollow">iPython</a> may be what you are looking for. Using <a href="http://jupyter.org/" rel="nofollow">Jupyter Notebooks</a> which are based on iPython you can create interactive cells in notebooks that behave similar to the console.</p>
0
2016-09-09T11:54:38Z
[ "python", "pycharm" ]
Extracting links and titles only
39,404,358
<p>I am trying to extract links and titles for these links in an anime website, However, I am only able to extract the whole tag, I just want the href and the title.</p> <p>Here`s the code am using:</p> <pre><code>import requests from bs4 import BeautifulSoup r = requests.get('http://animeonline.vip/info/phi-brain-kami-puzzle-3') soup = BeautifulSoup(r.content, "html.parser") for link in soup.find_all('div', class_='list_episode'): href = link.get('href') print(href) </code></pre> <p>And here`s the website html:</p> <pre><code>&lt;a href="http://animeonline.vip/phi-brain-kami-puzzle-3-episode-25" title="Phi Brain: Kami no Puzzle 3 episode 25"&gt; Phi Brain: Kami no Puzzle 3 episode 25 &lt;span&gt; 26-03-2014&lt;/span&gt; &lt;/a&gt; </code></pre> <p>And this is the output:</p> <pre><code>C:\Python34\python.exe C:/Users/M.Murad/PycharmProjects/untitled/Webcrawler.py None Process finished with exit code 0 </code></pre> <p>All that I want is all links and titles in that class (episodes and their links)</p> <p>Thanks.</p>
0
2016-09-09T05:23:09Z
39,404,475
<p>The entire page has only one element with class 'list_episode', so you can filter out the 'a' tags and then fetch the value for attribute 'href':</p> <pre><code>In [127]: import requests ...: from bs4 import BeautifulSoup ...: ...: r = requests.get('http://animeonline.vip/info/phi-brain-kami-puzzle-3') ...: soup = BeautifulSoup(r.content, "html.parser") ...: In [128]: [x.get('href') for x in soup.find('div', class_='list_episode').find_all('a')] Out[128]: [u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-25', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-24', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-23', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-22', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-21', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-20', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-19', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-18', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-17', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-16', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-15', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-14', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-13', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-12', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-11', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-10', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-9', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-8', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-7', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-6', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-5', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-4', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-3', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-2', u'http://animeonline.vip/phi-brain-kami-puzzle-3-episode-1'] </code></pre>
1
2016-09-09T05:34:04Z
[ "python", "visual-studio", "web-scraping", "python-3.4", "ptvs" ]
Extracting links and titles only
39,404,358
<p>I am trying to extract links and titles for these links in an anime website, However, I am only able to extract the whole tag, I just want the href and the title.</p> <p>Here`s the code am using:</p> <pre><code>import requests from bs4 import BeautifulSoup r = requests.get('http://animeonline.vip/info/phi-brain-kami-puzzle-3') soup = BeautifulSoup(r.content, "html.parser") for link in soup.find_all('div', class_='list_episode'): href = link.get('href') print(href) </code></pre> <p>And here`s the website html:</p> <pre><code>&lt;a href="http://animeonline.vip/phi-brain-kami-puzzle-3-episode-25" title="Phi Brain: Kami no Puzzle 3 episode 25"&gt; Phi Brain: Kami no Puzzle 3 episode 25 &lt;span&gt; 26-03-2014&lt;/span&gt; &lt;/a&gt; </code></pre> <p>And this is the output:</p> <pre><code>C:\Python34\python.exe C:/Users/M.Murad/PycharmProjects/untitled/Webcrawler.py None Process finished with exit code 0 </code></pre> <p>All that I want is all links and titles in that class (episodes and their links)</p> <p>Thanks.</p>
0
2016-09-09T05:23:09Z
39,405,634
<p>So what is happening is, your link element has all the information in anchor <code>&lt;div&gt;</code> and class = "last_episode" but this has a lot of anchors in it which holds the link in "href" and title in "title".</p> <p>Just modify the code a little and you will have what you want.</p> <pre><code>import requests from bs4 import BeautifulSoup r = requests.get('http://animeonline.vip/info/phi-brain-kami-puzzle-3') soup = BeautifulSoup(r.content, "html.parser") for link in soup.find_all('div', class_='list_episode'): href_and_title = [(a.get("href"), a.get("title")) for a in link.find_all("a")] print href_and_title </code></pre> <p>output will be in form of [(href,title),(href,title),........(href,title)]</p> <p>Edit(Explanation):</p> <p>So what is happening is when you do </p> <pre><code>soup.find_all('div', class_='list_episode') </code></pre> <p>It gives you all details (in html page) with "div" and class "last_episode" but now this anchor holds a huge set of anchors with different "href" and title details, so to get that we use a for loop (there can be multiple anchors (<code>&lt;a&gt;</code>)) and ".get()".</p> <pre><code> href_and_title = [(a.get("href"), a.get("title")) for a in link.find_all("a")] </code></pre> <p>I hope it's clearer this time .</p>
-1
2016-09-09T07:01:41Z
[ "python", "visual-studio", "web-scraping", "python-3.4", "ptvs" ]
Django how to define permissions so users can only edit certain model hierarchies?
39,404,451
<p>If I have models like this..</p> <pre><code>class Family(Model): name = models.CharField() class Father(Model): family = ForeignKey(Family) class Mother(Model): family = ForeignKey(Family) class Child(Model): family = ForeignKey(Family) </code></pre> <p>Django makes group permissions automatically so I can define groups that can edit/create/etc... the family model.</p> <p>How can I limit it to only let a user edit a certain instance of the family model? So if I want the 'Johnson' family admin to only have permission to edit things under the 'Johnson' family tree. </p> <p>I can think of two ways, one would be defining a custom permission like (<a href="https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#custom-permissions" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#custom-permissions</a>) but I have no idea what the docs are saying there and they do not do a good job of explaining it. </p> <p>I can also think of possibly adding a field on the user model and checking the value of that, but it feels wrong to do it that way...</p>
3
2016-09-09T05:31:48Z
39,404,709
<p>I can imagine two ways for achieving what you want, but that'd be experimental and I don't know if it would follow the good practices :</p> <h2>1 - <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#programmatically-creating-permissions" rel="nofollow">Programmatically created permissions</a> :</h2> <p>With codename partially based on the instance. For example, creating a permission with a codename containing the instance the user could edit :</p> <pre><code>perm = Permission.objects.create(codename='can_create_'+str(obj.id), name='can edit instance with id ' + str(obj.id)) user.user_permissions.add(perm) </code></pre> <p>and then :</p> <pre><code>if user.has_perm('can_create_' + str(relevant_id)): </code></pre> <h2>2 - <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#manytomanyfield" rel="nofollow">ManyToMany relationships as permissions</a> :</h2> <p>Probably the field idea you had yourself :</p> <pre><code>class myModel(models.Model): editors = models.ManyToManyField(User, related_name='mymodel_can_edit') </code></pre> <p>and then just add and remove the instances a user can delete in its <code>mymodel_can_edit</code> field just like you manage the permissions in its <code>user_permissions</code> field.</p> <p>But I didn't test any of these solution. If you try it could you tell what you think about it? :)</p>
1
2016-09-09T05:54:19Z
[ "python", "django" ]
Django how to define permissions so users can only edit certain model hierarchies?
39,404,451
<p>If I have models like this..</p> <pre><code>class Family(Model): name = models.CharField() class Father(Model): family = ForeignKey(Family) class Mother(Model): family = ForeignKey(Family) class Child(Model): family = ForeignKey(Family) </code></pre> <p>Django makes group permissions automatically so I can define groups that can edit/create/etc... the family model.</p> <p>How can I limit it to only let a user edit a certain instance of the family model? So if I want the 'Johnson' family admin to only have permission to edit things under the 'Johnson' family tree. </p> <p>I can think of two ways, one would be defining a custom permission like (<a href="https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#custom-permissions" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#custom-permissions</a>) but I have no idea what the docs are saying there and they do not do a good job of explaining it. </p> <p>I can also think of possibly adding a field on the user model and checking the value of that, but it feels wrong to do it that way...</p>
3
2016-09-09T05:31:48Z
39,406,306
<p>You can use django modules that provide this functionality. I personally use <a href="https://github.com/django-guardian/django-guardian" rel="nofollow">django-guardian</a> which offers per-object permissions using an interface similar to the original <code>has_perm</code> method.</p>
0
2016-09-09T07:40:03Z
[ "python", "django" ]
How can I join a third table into the result of two joint tables?
39,404,504
<p>I was writing a python program to read the names of columns and the type of the columns need to satisfied.</p> <p>I want to place the results like this: </p> <pre><code>id_index=Column(int) </code></pre> <p>by using print</p> <pre><code>print "{0}{1}=Column({2})".format(" "*5,SysColumns.name,SysTypes.xtype) </code></pre> <p>I will use three tables: <code>SysColumns</code>, <code>SysObjects</code>, and <code>SysTypes</code>:</p> <pre><code>class SysColumns(BaseModel): __tablename__ = "SysColumns" name=Column(String,primary_key=True) colorder=Column(Integer,primary_key=True) id=Column(Integer,primary_key=True) xtype = Column(String, primary_key=True) class SysObjects(BaseModel): __tablename__ = "SysObjects" name=Column(String) id=Column(Integer,primary_key=True) xtype=Column(String,primary_key=True) class SysTypes(BaseModel): __tablename__ = "SysTypes" name = Column(String, primary_key=True) xtype = Column(String) </code></pre> <p><code>SysColumns</code> has the same column <code>id</code> in <code>SysObjects</code>, while <code>SysTypes</code> has the same column <code>xtype</code> in <code>SysColumns</code>.</p> <p>The original code is as below:</p> <pre><code>def dispMod(session,tableName): result=session.query(SysColumns). \ join(SysObjects,SysColumns.id==SysObjects.id).\ filter(SysObjects.xtype=='u').\ filter(SysObjects.name==tableName).\ order_by(SysColumns.colorder) for sysColumns in result: print "{0}{1}=Column({2})".format(" "*5,SysColumns.name,SysColumns.xtype) </code></pre> <p>The result can be displayed like: </p> <pre><code>id_index=Column(56) </code></pre> <p>Now I need to search the number 56 in <code>SysTypes</code> to change it in to the type it stand for.</p> <p><code>SysTypes</code> has columns of <code>SysTypes.xtype</code> and <code>SysTypes.name</code>. I want it to show me the name instead of the <code>xtype</code>:</p> <pre><code>print "{0}{1}=Column({2})".format(" "*5,SysColumns.name,Systypes.name) </code></pre> <p>I don't know how to use the result above to join the Systypes table to find the name in it.</p> <p>Can I write the query to search <code>SysColumns.name</code> and <code>SysTypes.name</code> for one time?</p>
1
2016-09-09T05:36:50Z
39,406,104
<p>Simply add the join after the other and select the names only:</p> <pre><code>session.query(SysColumns.name, SysTypes.name).\ join(SysObjects, SysColumns.id == SysObjects.id).\ join(SysTypes, SysTypes.xtype == SysColumns.xtype).\ filter(SysObjects.xtype == 'u').\ filter(SysObjects.name == tableName).\ order_by(SysColumns.colorder) </code></pre>
0
2016-09-09T07:28:56Z
[ "python", "sqlalchemy" ]
how to print lines in a file by seeking a position from another text file in python?
39,404,505
<p>This is my code for getting lines from a file by seeking a position using f.seek() method but I am getting a wrong output. it is printing from middle of the first line. can u help me to solve this please?</p> <pre><code>f=open(r"sample_text_file","r") last_pos=int(f.read()) f1=open(r"C:\Users\ddadi\Documents\project2\check\log_file3.log","r") f1.seek(last_pos) for i in f1: print i last_position=f1.tell() with open('sample_text.txt', 'a') as handle: handle.write(str(last_position)) </code></pre> <p>sample_text file contains the file pointer offset which is returned by f1.tell() </p>
0
2016-09-09T05:37:03Z
39,404,614
<p>If it's printing from the middle of a line that's almost certainly because your offset is wrong. You don't explain how you came by the magic number you use as an argument to <code>seek</code>, and without that information it's difficult to help more precisely.</p> <p>One thing is, however, rather important. It's not a very good idea to use <code>seek</code> on a file that is open in text mode (the default in Python). Try using <code>open(..., 'rb')</code> and see if the process becomes a little more predictable. It sounds as though you may have got the offset by counting characters after reading in text mode, but good old Windows includes carriage return characters in text files, which are removed by the Python I/O routines before your program sees the text.</p>
1
2016-09-09T05:46:57Z
[ "python", "file" ]
When should I use list.count(0), and how do I to discount the "False" item?
39,404,581
<p><code>a.count(0)</code> always returns 11, so what should I do to discount the <code>False</code> and return 10?</p> <pre><code>a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9] </code></pre>
18
2016-09-09T05:43:27Z
39,404,665
<p>Python 2.x interprets <code>False</code> as <code>0</code> and vice versa. AFAIK even <code>None</code> and <code>""</code> can be considered <code>False</code> in conditions. Redefine count as follows: </p> <pre><code>sum(1 for item in a if item == 0 and type(item) == int) </code></pre> <p>or (Thanks to <a href="http://stackoverflow.com/questions/39404581/when-use-list-count0-how-to-discount-false-item/39404665?noredirect=1#comment66136825_39404665">Kevin</a>, and <a href="http://stackoverflow.com/questions/39404581/when-use-list-count0-how-to-discount-false-item/39404665?noredirect=1#comment66142335_39404665">Bakuriu</a> for their comments): </p> <pre><code>sum(1 for item in a if item == 0 and type(item) is type(0)) </code></pre> <p>or as suggested by <a href="http://stackoverflow.com/users/793428/ozgur">ozgur</a> in comments (<strong>which is not recommended and is considered wrong</strong>, see <a href="http://stackoverflow.com/questions/39404581/when-use-list-count0-how-to-discount-false-item/39404665?noredirect=1#comment66136825_39404665">this</a>), simply: </p> <pre><code>sum(1 for item in a if item is 0) </code></pre> <p>it <strong>may</strong> (<a href="http://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers?noredirect=1&amp;lq=1">“is” operator behaves unexpectedly with integers</a>) work for <em>small</em> primary types, but if your list contains objects, please consider what <code>is</code> operator does: </p> <p>From the documentation for the <a href="http://docs.python.org/2/reference/expressions.html#not-in" rel="nofollow"><code>is</code> operator</a>:</p> <blockquote> <p>The operators <code>is</code> and <code>is not</code> test for object identity: <code>x is y</code> is true if and only if x and y are the same object.</p> </blockquote> <p>More information about <code>is</code> operator: <a href="http://stackoverflow.com/questions/13650293/understanding-pythons-is-operator">Understanding Python's "is" operator</a></p>
11
2016-09-09T05:50:35Z
[ "python", "list", "count", "boolean" ]
When should I use list.count(0), and how do I to discount the "False" item?
39,404,581
<p><code>a.count(0)</code> always returns 11, so what should I do to discount the <code>False</code> and return 10?</p> <pre><code>a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9] </code></pre>
18
2016-09-09T05:43:27Z
39,404,682
<p>You could use <code>sum</code> and a generator expression:</p> <pre><code>&gt;&gt;&gt; sum((x==0 and x is not False) for x in ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9]) 10 </code></pre>
9
2016-09-09T05:52:00Z
[ "python", "list", "count", "boolean" ]
When should I use list.count(0), and how do I to discount the "False" item?
39,404,581
<p><code>a.count(0)</code> always returns 11, so what should I do to discount the <code>False</code> and return 10?</p> <pre><code>a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9] </code></pre>
18
2016-09-09T05:43:27Z
39,404,722
<p>You need to filter out the Falses yourself.</p> <pre><code>&gt;&gt;&gt; a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9] &gt;&gt;&gt; len([x for x in a if x == 0 and x is not False]) 10 </code></pre> <hr> <p>Old answer is CPython specific and it's better to use solutions that work on all Python implementations.</p> <p>Since <strong>CPython</strong> <a href="http://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers">keeps a pool of small integer objects</a>, zero included, you can filter the list with the <code>is</code> operator.</p> <p>This of course shouldn't be used for value comparisons but in this case it works since zeros are what we want to find.</p> <pre><code>&gt;&gt;&gt; a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9] &gt;&gt;&gt; [x for x in a if x is 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] &gt;&gt;&gt; len(_) 10 </code></pre>
8
2016-09-09T05:55:35Z
[ "python", "list", "count", "boolean" ]
When should I use list.count(0), and how do I to discount the "False" item?
39,404,581
<p><code>a.count(0)</code> always returns 11, so what should I do to discount the <code>False</code> and return 10?</p> <pre><code>a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9] </code></pre>
18
2016-09-09T05:43:27Z
39,404,976
<p>Solving this problem more generally, you could make your own subclass of list:</p> <pre><code>class key_equality_list(list): def __init__(self, key, items): super(key_equality_list, self).__init__(items) self._f = key def __contains__(self, x): return any(self._f(x) == self._f(item) for item in self) def count(self, x): return sum(self._f(x) == self._f(item) for item in self) </code></pre> <p>And then define a key function that checks types:</p> <pre><code>type_and_val = lambda x: (x, type(x)) </code></pre> <p>So your usage becomes:</p> <pre><code>&gt;&gt;&gt; a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9] &gt;&gt;&gt; a = key_equality_list(type_and_val, a) &gt;&gt;&gt; a.count(0) 10 &gt;&gt;&gt; a.count(False) 1 </code></pre>
3
2016-09-09T06:18:04Z
[ "python", "list", "count", "boolean" ]
When should I use list.count(0), and how do I to discount the "False" item?
39,404,581
<p><code>a.count(0)</code> always returns 11, so what should I do to discount the <code>False</code> and return 10?</p> <pre><code>a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9] </code></pre>
18
2016-09-09T05:43:27Z
39,408,988
<p>Another option is to first "decorate" the list by adding the types and the count:</p> <pre><code>decorated_seq = list(map(lambda x: (x, type(x)), sequence)) decorated_seq.count((0, type(0))) </code></pre> <p>If you want to have <code>0 == 0.0</code> you could do:</p> <pre><code>decorated_seq = list(map(lambda x: (x, isinstance(x, bool)), sequence)) decorated_seq.count((0, False)) </code></pre> <p>Which counts all <code>0</code>s that are <em>not</em> of type <code>bool</code> (i.e. <code>False</code>s). In this way you can define what <code>count</code> should do in any way you want, at the cost of creating a temporary list.</p>
2
2016-09-09T10:04:49Z
[ "python", "list", "count", "boolean" ]
When should I use list.count(0), and how do I to discount the "False" item?
39,404,581
<p><code>a.count(0)</code> always returns 11, so what should I do to discount the <code>False</code> and return 10?</p> <pre><code>a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9] </code></pre>
18
2016-09-09T05:43:27Z
39,410,430
<p>Many appropriate answers already given. Of course, an alternative is to filter the list on the type of the element you are querying for first.</p> <pre><code>&gt;&gt;&gt; a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9] &gt;&gt;&gt; def count(li, item): ... return list(filter(lambda x: type(x) == type(item), li)).count(item) ... &gt;&gt;&gt; &gt;&gt;&gt; count(a, 0) 10 &gt;&gt;&gt; count(a, False) 1 &gt;&gt;&gt; count(a, "a") 1 &gt;&gt;&gt; class my_own_int(int): pass ... &gt;&gt;&gt; a.append(my_own_int(5)) &gt;&gt;&gt; a.count(5) 1 &gt;&gt;&gt; count(a, 5) 0 </code></pre> <p>In case you are worried about the copy, you can use <code>sum</code> and abuse the fact we are trying to circumvent above (that <code>True == 1</code>).</p> <pre><code>def count(li, item): return sum(map(lambda x: x == item, filter(lambda x: type(x) == type(item), li))) </code></pre>
1
2016-09-09T11:20:58Z
[ "python", "list", "count", "boolean" ]
When should I use list.count(0), and how do I to discount the "False" item?
39,404,581
<p><code>a.count(0)</code> always returns 11, so what should I do to discount the <code>False</code> and return 10?</p> <pre><code>a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9] </code></pre>
18
2016-09-09T05:43:27Z
39,411,589
<p>Since <code>count</code> returns the number of items equal to its input, and since <code>0</code> is equal to <code>False</code> in Python, one way to approach this is to pass in something that is equal to <code>0</code> but is not equal to <code>False</code>.</p> <p>Python itself provides no such object, but we can write one:</p> <pre><code>class Zero: def __eq__(self, other): return other == 0 and other is not False print([1, 2, 0, False].count(Zero())) </code></pre> <p>Be aware that there are other things in Python that, like <code>False</code>, are equal to <code>0</code>. I can think of <code>0.0</code>, <code>decimal.Decimal(0)</code>, and <code>fractions.Fraction(0,1)</code>. Furthermore, anybody can subclass <code>int</code> to create other "fake 0 values", just like <code>False</code>. The code above counts all of these, treating <code>False</code> as the only special case, but you might want to do something different in your <code>__eq__</code>.</p> <p>Of course "under the covers" this is very similar to just doing <code>sum(other == 0 and other is not False for other in a)</code>. But considering how <code>count()</code> is defined, it should come as no surprise that <code>a.count(x)</code> is similar to <code>sum(x == y for y in a)</code>.</p> <p>You would only do this in the rare case where you have for some reason already decided to use <code>count</code> (perhaps because you're using some third-party code that's going to call it), and need to come up with a suitable object to pass it. Basically, it treats <code>count</code> as a function that calls an arbitrary function we write (requiring only that this function be the <code>__eq__</code> function of the argument) and counts the number of true return values. This is an accurate description of what <code>count</code> does, but not really the point of <code>count</code> since <code>sum</code> is more explicit.</p>
2
2016-09-09T12:26:25Z
[ "python", "list", "count", "boolean" ]
When should I use list.count(0), and how do I to discount the "False" item?
39,404,581
<p><code>a.count(0)</code> always returns 11, so what should I do to discount the <code>False</code> and return 10?</p> <pre><code>a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9] </code></pre>
18
2016-09-09T05:43:27Z
39,414,037
<p>How about this functional style solution:</p> <pre><code>print zip(a, map(type, a)).count((0, int)) &gt;&gt;&gt; 10 </code></pre> <p>Timing this against some of the other answers here, this also seems to be one of the quickest:</p> <pre class="lang-python prettyprint-override"><code>t0 = time.time() for i in range(100000): zip(a, map(type, a)).count((0, int)) print time.time() - t0 &gt;&gt;&gt; 0.275855064392 t0 = time.time() for i in range(100000): sum(1 for item in a if item == 0 and type(item) == int) print time.time() - t0 &gt;&gt;&gt; 0.478030204773 t0 = time.time() for i in range(100000): sum(1 for item in a if item == 0 and type(item) is type(0)) print time.time() - t0 &gt;&gt;&gt; 0.52236700058 t0 = time.time() for i in range(100000): sum((x==0 and x is not False) for x in a) print time.time() - t0 &gt;&gt;&gt; 0.450266122818 </code></pre>
6
2016-09-09T14:34:26Z
[ "python", "list", "count", "boolean" ]
When should I use list.count(0), and how do I to discount the "False" item?
39,404,581
<p><code>a.count(0)</code> always returns 11, so what should I do to discount the <code>False</code> and return 10?</p> <pre><code>a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9] </code></pre>
18
2016-09-09T05:43:27Z
39,436,485
<p>If you run into that kind of problems frequently you can introduce the following class<sup>*</sup></p> <pre><code>class Exactly: def __init__(self, something): self.value = something def __eq__(self, other): return type(self.value) == type(other) and self.value == other </code></pre> <p>and use it as follows:</p> <pre><code>a.count(Exactly(0)) </code></pre> <hr> <p><sup>*</sup> Of course you may need to enhance it for other operations too.</p>
0
2016-09-11T13:13:30Z
[ "python", "list", "count", "boolean" ]
Why does this regex result in four items?
39,404,701
<p>I want to split a string by <code></code>, <code>-&gt;</code>, <code>=&gt;</code>, or those wrapped with several spaces, meaning that I can get two items, <code>she</code> and <code>he</code>, from the following strings after being split:<br> <code>"she he", "she he", "she he ", "she he ", "she-&gt;he", "she -&gt;he", "she=&gt;he", "she=&gt; he", " she-&gt; he ", " she =&gt; he \n"</code></p> <p>I have tried using this:</p> <pre><code>re.compile("(?&lt;!^)((\\s*[-=]&gt;\\s*)|[\\s+\t])(?!$\n)(?=[^\s])").split(' she -&gt; he \n') </code></pre> <p>What I get is a list with four items: <code>[' she', ' -&gt; ', ' -&gt; ', 'he \n']</code>.</p> <p>And for this, </p> <pre><code>re.compile("(?&lt;!^)((\\s*[-=]&gt;\\s*)|[\\s+\t])(?!$\n)(?=[^\s])").split('she he') </code></pre> <p>I get this: <code>['she', ' ', None, 'he']</code>.</p> <p>Why are there four items? And how can I get only two without the middle two?</p>
1
2016-09-09T05:53:23Z
39,405,020
<p>If you can just strip your input string. From your description, all you need is to split the words on either <code>\s+</code> or <code>\s*-&gt;\s*</code> or <code>\s*=&gt;\s*</code></p> <p>So here is my solution:</p> <pre><code>p = re.compile(r'\s*[-=]&gt;\s*|\s+') input1 = "she he" input2 = " she -&gt; he \n".strip() print p.split(input1) print p.split(input2) </code></pre> <p>Your output would be just 'she' and 'he':</p> <pre><code>['she', 'he'] </code></pre>
3
2016-09-09T06:20:50Z
[ "python", "regex", "split" ]
Why does this regex result in four items?
39,404,701
<p>I want to split a string by <code></code>, <code>-&gt;</code>, <code>=&gt;</code>, or those wrapped with several spaces, meaning that I can get two items, <code>she</code> and <code>he</code>, from the following strings after being split:<br> <code>"she he", "she he", "she he ", "she he ", "she-&gt;he", "she -&gt;he", "she=&gt;he", "she=&gt; he", " she-&gt; he ", " she =&gt; he \n"</code></p> <p>I have tried using this:</p> <pre><code>re.compile("(?&lt;!^)((\\s*[-=]&gt;\\s*)|[\\s+\t])(?!$\n)(?=[^\s])").split(' she -&gt; he \n') </code></pre> <p>What I get is a list with four items: <code>[' she', ' -&gt; ', ' -&gt; ', 'he \n']</code>.</p> <p>And for this, </p> <pre><code>re.compile("(?&lt;!^)((\\s*[-=]&gt;\\s*)|[\\s+\t])(?!$\n)(?=[^\s])").split('she he') </code></pre> <p>I get this: <code>['she', ' ', None, 'he']</code>.</p> <p>Why are there four items? And how can I get only two without the middle two?</p>
1
2016-09-09T05:53:23Z
39,405,588
<p>As indicated in comments already, each pair of parentheses in your regex forms a capture group, and each of those is returned by the regex <code>split()</code> function. As per the <a href="https://docs.python.org/2/library/re.html#re.split" rel="nofollow">documentation</a>,</p> <blockquote> <p>If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list.</p> </blockquote> <p>Python regular expressions have a facility for non-capturing parentheses. You use <code>(?:</code> instead of just <code>(</code> for the opening parenthesis to group without capturing.</p> <pre><code>&gt;&gt;&gt; re.compile("(?&lt;!^)((\\s*[-=]&gt;\\s*)|[\\s+\t])(?!$\n)(?=[^\s])").split('she he') ['she', ' ', None, 'he'] &gt;&gt;&gt; re.compile("(?&lt;!^)(?:(?:\\s*[-=]&gt;\\s*)|[\\s+\t])(?!$\n)(?=[^\s])").split('she he') ['she', 'he'] </code></pre> <p>It's not exactly clear why you include a tab explicitly in the character class with <code>\s</code>; the <code>\s</code> already includes tab as one of the many whitespace characters it matches.</p> <p>It's also not clear what you expect <code>$\n</code> to match. <code>$</code> is the end of the line and <code>\n</code> is a literal newline character, so you seem to be trying to deal with newlines; but <code>$</code> alone already covers that. The only difference between <code>$</code> and <code>$\n</code> is that if the end of the string (the last line in a multi-line string) is not newline-terminated, that will not match the latter.</p> <p>The <code>(?&lt;!^)</code> is also peculiar -- a better way to avoid matching an empty string is to make sure your regular expression always matches something.</p> <p>From your requirements, it seems that</p> <pre><code>re.compile(r'\s*[-=]&gt;\s*|\s+').split('he she') </code></pre> <p>would do what you want more succinctly and readably. This matches an ASCII arrow (single- or double-stoke) with optional whitespace on both sides, or if that fails, falls back to a sequence of whitespace.</p>
1
2016-09-09T06:59:21Z
[ "python", "regex", "split" ]
Why does this regex result in four items?
39,404,701
<p>I want to split a string by <code></code>, <code>-&gt;</code>, <code>=&gt;</code>, or those wrapped with several spaces, meaning that I can get two items, <code>she</code> and <code>he</code>, from the following strings after being split:<br> <code>"she he", "she he", "she he ", "she he ", "she-&gt;he", "she -&gt;he", "she=&gt;he", "she=&gt; he", " she-&gt; he ", " she =&gt; he \n"</code></p> <p>I have tried using this:</p> <pre><code>re.compile("(?&lt;!^)((\\s*[-=]&gt;\\s*)|[\\s+\t])(?!$\n)(?=[^\s])").split(' she -&gt; he \n') </code></pre> <p>What I get is a list with four items: <code>[' she', ' -&gt; ', ' -&gt; ', 'he \n']</code>.</p> <p>And for this, </p> <pre><code>re.compile("(?&lt;!^)((\\s*[-=]&gt;\\s*)|[\\s+\t])(?!$\n)(?=[^\s])").split('she he') </code></pre> <p>I get this: <code>['she', ' ', None, 'he']</code>.</p> <p>Why are there four items? And how can I get only two without the middle two?</p>
1
2016-09-09T05:53:23Z
39,405,890
<p>Each time you are using parentheses "()" you are creating a capturing group. A capturing group is a part of a match. A match always refers to the complete regex string. That is why you are getting 4 results. </p> <p>Documentation says: <a href="https://docs.python.org/2/library/re.html" rel="nofollow">"If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list."</a></p> <p>You could try making the groups "non-capturing" as Rawing suggested. Do this by simply prepending "?:" inside the parentheses you do not want to be captured. </p> <p>I would just leave out the parentheses altogether:</p> <pre><code>res = re.compile("\\s*[-=]&gt;\\s*|\\s*").split(' she -&gt; he \n') res = filter(None, res) res = list(res) </code></pre> <p>Output:</p> <pre><code>['she', 'he'] </code></pre>
0
2016-09-09T07:16:27Z
[ "python", "regex", "split" ]
Adding attribute from the different table with Pandas
39,404,740
<p>I am using Pandas to process table.</p> <pre><code>[table1] sample1 sample2 sample3 A 11 22 33 B 1 2 3 [table2] sample3 sample4 sample2 D 333 444 222 [Result] sample1 sample2 sample3 A 11 22 33 B 1 2 3 D NaN 222 333 </code></pre> <p>I have two tables, and I want to add row <code>D</code> (of table 2) to table 1, considering the column name. If the column in table 1 exists in table 2, the corresponding value of <code>D</code> is added to table 1, like sample 2 and sample 3. If the column in table does not exist in table 2 like sample 1, the value of D is set to <code>NaN</code> or ignored.</p> <p>Is there any simple way to do this with Pandas?</p>
3
2016-09-09T05:57:12Z
39,404,774
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> and then remove column <code>sample4</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow"><code>drop</code></a>:</p> <pre><code>print (pd.concat([table1, table2]).drop('sample4', axis=1)) sample1 sample2 sample3 A 11.0 22 33 B 1.0 2 3 D NaN 222 333 </code></pre> <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.intersection.html" rel="nofollow"><code>intersection</code></a> for selecting columns in both <code>DataFrames</code> and then concat subset of <code>table2</code> by these columns:</p> <pre><code>print (table2.columns.intersection(table1.columns)) Index(['sample2', 'sample3'], dtype='object') print (pd.concat([table1,table2[table2.columns.intersection(table1.columns)]])) sample1 sample2 sample3 A 11.0 22 33 B 1.0 2 3 D NaN 222 333 </code></pre> <p>Then if need remove rows with <code>NaN</code> use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="nofollow"><code>dropna</code></a>:</p> <pre><code>print (pd.concat([table1, table2]).drop('sample4', axis=1).dropna()) sample1 sample2 sample3 A 11.0 22 33 B 1.0 2 3 </code></pre>
3
2016-09-09T06:00:07Z
[ "python", "pandas", "dataframe", null, "concat" ]
Adding attribute from the different table with Pandas
39,404,740
<p>I am using Pandas to process table.</p> <pre><code>[table1] sample1 sample2 sample3 A 11 22 33 B 1 2 3 [table2] sample3 sample4 sample2 D 333 444 222 [Result] sample1 sample2 sample3 A 11 22 33 B 1 2 3 D NaN 222 333 </code></pre> <p>I have two tables, and I want to add row <code>D</code> (of table 2) to table 1, considering the column name. If the column in table 1 exists in table 2, the corresponding value of <code>D</code> is added to table 1, like sample 2 and sample 3. If the column in table does not exist in table 2 like sample 1, the value of D is set to <code>NaN</code> or ignored.</p> <p>Is there any simple way to do this with Pandas?</p>
3
2016-09-09T05:57:12Z
39,405,073
<p>You can generalize jezrael's <a href="http://stackoverflow.com/a/39404774/3635816">answer</a> by first subselecting columns from <code>table2</code> which are in <code>table1</code>. This is quite neatly done using <a href="http://stackoverflow.com/a/39404774/3635816"><code>numpy.in1d</code></a>. This also avoids forming a potentially huge temporary data frame with columns from both data frames. Example:</p> <pre><code>import numpy as np import pandas as pd table1 = pd.DataFrame([[11, 22, 33], [1, 2, 3]], index=list('AB'), columns=['sample1', 'sample2', 'sample3']) table2 = pd.DataFrame([[333, 444, 222]], index=['D'], columns=['sample3', 'sample4', 'sample2']) # Sub-select columns... cols_in_table1 = table2.columns[np.in1d(table2.columns, table1.columns)] # ... and concatenate. results = pd.concat((table1, table2[cols_in_table1])) print(results) </code></pre> <p>Which prints:</p> <pre><code> sample1 sample2 sample3 A 11.0 22 33 B 1.0 2 3 D NaN 222 333 </code></pre>
3
2016-09-09T06:24:04Z
[ "python", "pandas", "dataframe", null, "concat" ]
Convert Nested JSON to Excel using Python
39,404,961
<p>I want to convert Nested JSON to Excel file format using Python. I've done nearly as per requirements but I want to achieve excel format as below.</p> <p><strong>JSON</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>[ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Cooktops/zgbs/appliances/3741261", "subCategory": [ ], "title": "Cooktops" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Dishwashers/zgbs/appliances/3741271", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Built-Dishwashers/zgbs/appliances/3741281", "subCategory": [ ], "title": "Built-In Dishwashers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Portable-Countertop-Dishwashers/zgbs/appliances/3741301", "subCategory": [ ], "title": "Portable &amp; Countertop Dishwashers" } ], "title": "Dishwashers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Freezers/zgbs/appliances/3741331", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Chest-Freezers/zgbs/appliances/3741341", "subCategory": [ ], "title": "Chest Freezers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Upright-Freezers/zgbs/appliances/3741351", "subCategory": [ ], "title": "Upright Freezers" } ], "title": "Freezers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Ice-Makers/zgbs/appliances/2399939011", "subCategory": [ ], "title": "Ice Makers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Range-Hoods/zgbs/appliances/3741441", "subCategory": [ ], "title": "Range Hoods" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Ranges/zgbs/appliances/3741411", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Drop-Ranges/zgbs/appliances/3741421", "subCategory": [ ], "title": "Drop-In Ranges" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Freestanding-Ranges/zgbs/appliances/3741431", "subCategory": [ ], "title": "Freestanding Ranges" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Slide-Ranges/zgbs/appliances/2399946011", "subCategory": [ ], "title": "Slide-In Ranges" } ], "title": "Ranges" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Refrigerators/zgbs/appliances/3741361", "subCategory": [ ], "title": "Refrigerators" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Wall-Ovens/zgbs/appliances/3741481", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Combination-Microwave-Wall-Ovens/zgbs/appliances/3741491", "subCategory": [ ], "title": "Combination Microwave &amp; Wall Ovens" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Double-Wall-Ovens/zgbs/appliances/3741501", "subCategory": [ ], "title": "Double Wall Ovens" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Single-Wall-Ovens/zgbs/appliances/3741511", "subCategory": [ ], "title": "Single Wall Ovens" } ], "title": "Wall Ovens" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Warming-Drawers/zgbs/appliances/2399955011", "subCategory": [ ], "title": "Warming Drawers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Washers-Dryers/zgbs/appliances/2383576011", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Clothes-Dryers/zgbs/appliances/13397481", "subCategory": [ ], "title": "Dryers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Clothes-Washing-Machines/zgbs/appliances/13397491", "subCategory": [ ], "title": "Washers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Combination-Washers-Dryers/zgbs/appliances/13755271", "subCategory": [ ], "title": "All-in-One Combination Washers &amp; Dryers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Stacked-Washer-Dryer-Units/zgbs/appliances/2399957011", "subCategory": [ ], "title": "Stacked Washer &amp; Dryer Units" } ], "title": "Washers &amp; Dryers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Wine-Cellars/zgbs/appliances/3741521", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Built-Wine-Cellars/zgbs/appliances/3741551", "subCategory": [ ], "title": "Built-In Wine Cellars" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Freestanding-Wine-Cellars/zgbs/appliances/3741541", "subCategory": [ ], "title": "Freestanding Wine Cellars" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Furniture-Style-Wine-Cellars/zgbs/appliances/3741561", "subCategory": [ ], "title": "Furniture-Style Wine Cellars" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Small-Wine-Cellars/zgbs/appliances/3741531", "subCategory": [ ], "title": "Small Wine Cellars" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Wine-Cellar-Cooling-Systems/zgbs/appliances/3741581", "subCategory": [ ], "title": "Wine Cellar Cooling Systems" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Wine-Rooms/zgbs/appliances/3741571", "subCategory": [ ], "title": "Wine Rooms" } ], "title": "Wine Cellars" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Home-Appliance-Warranties/zgbs/appliances/2242350011", "subCategory": [ ], "title": "Appliance Warranties" } ]</code></pre> </div> </div> </p> <p>I'm traversing all subCategories like this:</p> <pre><code>row = 1 def TraverseJSONTree(jsonObject, count=0): title = jsonObject.get('title') url = jsonObject.get('url') print 'Title: ' + title + ' , Position: ' + str(count) worksheet.write_string(row, count, title) worksheet.write_string(row, 6, url) global row row+=1 subCategories = jsonObject.get('subCategory',[]) for category in subCategories: TraverseJSONTree(category, count+1) for jsonObject in json.loads(jsonArray): TraverseJSONTree(jsonObject) </code></pre> <p><a href="http://i.stack.imgur.com/pejPe.png" rel="nofollow"><img src="http://i.stack.imgur.com/pejPe.png" alt="enter image description here"></a></p> <p><strong>Expected Result</strong></p> <p><a href="http://i.stack.imgur.com/bLQcX.png" rel="nofollow"><img src="http://i.stack.imgur.com/bLQcX.png" alt="enter image description here"></a></p>
0
2016-09-09T06:16:43Z
39,406,461
<p>Modification : Simplest way to do this would be to use csv module, say we have the whole json in the variable a</p> <pre><code>import csv import cPickle as pickle fieldnames = ['Category1', 'Category1.1', 'url'] csvfile = open("category.csv", 'wb') csvfilewriter = csv.DictWriter(csvfile, fieldnames=fieldnames,dialect='excel', delimiter=',') csvfilewriter.writeheader() for b in a: data = [] data.append(b['title']) data.append("") data.append(b['url']) csvfilewriter.writerow(dict(zip(fieldnames,data))) data = [] for i in xrange(len(b['subCategory'])): data.append(b['title']) data.append(b['subCategory'][i]['title']) data.append(b['subCategory'][i]['url']) csvfilewriter.writerow(dict(zip(fieldnames,data))) </code></pre> <p>You will have the desired csv in the same location. This works for only two subcategories (because i have checked the data given by you and say there were only two categories (ie 1 and 1.1)) but in case you want for more than repeat the same(I know it's not the most efficient way couldn't think of any in such a short time)</p> <p>You can also use pandas module to convert the dictionary import pandas as pd pd.DataFrame.from_dict(dcitionaty_element)</p> <p>And then do it on all the dictionaries in that json and merge them and save it to a csv file. </p>
0
2016-09-09T07:49:33Z
[ "python", "json", "excel" ]
Convert Nested JSON to Excel using Python
39,404,961
<p>I want to convert Nested JSON to Excel file format using Python. I've done nearly as per requirements but I want to achieve excel format as below.</p> <p><strong>JSON</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>[ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Cooktops/zgbs/appliances/3741261", "subCategory": [ ], "title": "Cooktops" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Dishwashers/zgbs/appliances/3741271", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Built-Dishwashers/zgbs/appliances/3741281", "subCategory": [ ], "title": "Built-In Dishwashers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Portable-Countertop-Dishwashers/zgbs/appliances/3741301", "subCategory": [ ], "title": "Portable &amp; Countertop Dishwashers" } ], "title": "Dishwashers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Freezers/zgbs/appliances/3741331", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Chest-Freezers/zgbs/appliances/3741341", "subCategory": [ ], "title": "Chest Freezers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Upright-Freezers/zgbs/appliances/3741351", "subCategory": [ ], "title": "Upright Freezers" } ], "title": "Freezers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Ice-Makers/zgbs/appliances/2399939011", "subCategory": [ ], "title": "Ice Makers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Range-Hoods/zgbs/appliances/3741441", "subCategory": [ ], "title": "Range Hoods" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Ranges/zgbs/appliances/3741411", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Drop-Ranges/zgbs/appliances/3741421", "subCategory": [ ], "title": "Drop-In Ranges" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Freestanding-Ranges/zgbs/appliances/3741431", "subCategory": [ ], "title": "Freestanding Ranges" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Slide-Ranges/zgbs/appliances/2399946011", "subCategory": [ ], "title": "Slide-In Ranges" } ], "title": "Ranges" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Refrigerators/zgbs/appliances/3741361", "subCategory": [ ], "title": "Refrigerators" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Wall-Ovens/zgbs/appliances/3741481", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Combination-Microwave-Wall-Ovens/zgbs/appliances/3741491", "subCategory": [ ], "title": "Combination Microwave &amp; Wall Ovens" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Double-Wall-Ovens/zgbs/appliances/3741501", "subCategory": [ ], "title": "Double Wall Ovens" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Single-Wall-Ovens/zgbs/appliances/3741511", "subCategory": [ ], "title": "Single Wall Ovens" } ], "title": "Wall Ovens" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Warming-Drawers/zgbs/appliances/2399955011", "subCategory": [ ], "title": "Warming Drawers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Washers-Dryers/zgbs/appliances/2383576011", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Clothes-Dryers/zgbs/appliances/13397481", "subCategory": [ ], "title": "Dryers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Clothes-Washing-Machines/zgbs/appliances/13397491", "subCategory": [ ], "title": "Washers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Combination-Washers-Dryers/zgbs/appliances/13755271", "subCategory": [ ], "title": "All-in-One Combination Washers &amp; Dryers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Stacked-Washer-Dryer-Units/zgbs/appliances/2399957011", "subCategory": [ ], "title": "Stacked Washer &amp; Dryer Units" } ], "title": "Washers &amp; Dryers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Wine-Cellars/zgbs/appliances/3741521", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Built-Wine-Cellars/zgbs/appliances/3741551", "subCategory": [ ], "title": "Built-In Wine Cellars" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Freestanding-Wine-Cellars/zgbs/appliances/3741541", "subCategory": [ ], "title": "Freestanding Wine Cellars" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Furniture-Style-Wine-Cellars/zgbs/appliances/3741561", "subCategory": [ ], "title": "Furniture-Style Wine Cellars" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Small-Wine-Cellars/zgbs/appliances/3741531", "subCategory": [ ], "title": "Small Wine Cellars" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Wine-Cellar-Cooling-Systems/zgbs/appliances/3741581", "subCategory": [ ], "title": "Wine Cellar Cooling Systems" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Wine-Rooms/zgbs/appliances/3741571", "subCategory": [ ], "title": "Wine Rooms" } ], "title": "Wine Cellars" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Home-Appliance-Warranties/zgbs/appliances/2242350011", "subCategory": [ ], "title": "Appliance Warranties" } ]</code></pre> </div> </div> </p> <p>I'm traversing all subCategories like this:</p> <pre><code>row = 1 def TraverseJSONTree(jsonObject, count=0): title = jsonObject.get('title') url = jsonObject.get('url') print 'Title: ' + title + ' , Position: ' + str(count) worksheet.write_string(row, count, title) worksheet.write_string(row, 6, url) global row row+=1 subCategories = jsonObject.get('subCategory',[]) for category in subCategories: TraverseJSONTree(category, count+1) for jsonObject in json.loads(jsonArray): TraverseJSONTree(jsonObject) </code></pre> <p><a href="http://i.stack.imgur.com/pejPe.png" rel="nofollow"><img src="http://i.stack.imgur.com/pejPe.png" alt="enter image description here"></a></p> <p><strong>Expected Result</strong></p> <p><a href="http://i.stack.imgur.com/bLQcX.png" rel="nofollow"><img src="http://i.stack.imgur.com/bLQcX.png" alt="enter image description here"></a></p>
0
2016-09-09T06:16:43Z
39,407,589
<pre><code>row = 1 def TraverseJSONTree(jsonObject, main_title=None, count=0): if main_title is None: main_title = title = jsonObject.get('title') else: title = jsonObject.get('title') url = jsonObject.get('url') print 'Title: ' + title + ' , Position: ' + str(count) if main_title is not None: worksheet.write_string(row, 0, title) worksheet.write_string(row, count, title) worksheet.write_string(row, 6, url) global row row+=1 subCategories = jsonObject.get('subCategory',[]) for category in subCategories: TraverseJSONTree(category, main_title, count+1) for jsonObject in json.loads(jsonArray): TraverseJSONTree(jsonObject) </code></pre> <p>it will return your expected output as it needs a check if category is there then you have to right the original title on the 0th col in excel reamin as same.</p>
1
2016-09-09T08:53:34Z
[ "python", "json", "excel" ]
Convert Nested JSON to Excel using Python
39,404,961
<p>I want to convert Nested JSON to Excel file format using Python. I've done nearly as per requirements but I want to achieve excel format as below.</p> <p><strong>JSON</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>[ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Cooktops/zgbs/appliances/3741261", "subCategory": [ ], "title": "Cooktops" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Dishwashers/zgbs/appliances/3741271", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Built-Dishwashers/zgbs/appliances/3741281", "subCategory": [ ], "title": "Built-In Dishwashers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Portable-Countertop-Dishwashers/zgbs/appliances/3741301", "subCategory": [ ], "title": "Portable &amp; Countertop Dishwashers" } ], "title": "Dishwashers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Freezers/zgbs/appliances/3741331", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Chest-Freezers/zgbs/appliances/3741341", "subCategory": [ ], "title": "Chest Freezers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Upright-Freezers/zgbs/appliances/3741351", "subCategory": [ ], "title": "Upright Freezers" } ], "title": "Freezers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Ice-Makers/zgbs/appliances/2399939011", "subCategory": [ ], "title": "Ice Makers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Range-Hoods/zgbs/appliances/3741441", "subCategory": [ ], "title": "Range Hoods" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Ranges/zgbs/appliances/3741411", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Drop-Ranges/zgbs/appliances/3741421", "subCategory": [ ], "title": "Drop-In Ranges" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Freestanding-Ranges/zgbs/appliances/3741431", "subCategory": [ ], "title": "Freestanding Ranges" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Slide-Ranges/zgbs/appliances/2399946011", "subCategory": [ ], "title": "Slide-In Ranges" } ], "title": "Ranges" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Refrigerators/zgbs/appliances/3741361", "subCategory": [ ], "title": "Refrigerators" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Wall-Ovens/zgbs/appliances/3741481", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Combination-Microwave-Wall-Ovens/zgbs/appliances/3741491", "subCategory": [ ], "title": "Combination Microwave &amp; Wall Ovens" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Double-Wall-Ovens/zgbs/appliances/3741501", "subCategory": [ ], "title": "Double Wall Ovens" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Single-Wall-Ovens/zgbs/appliances/3741511", "subCategory": [ ], "title": "Single Wall Ovens" } ], "title": "Wall Ovens" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Warming-Drawers/zgbs/appliances/2399955011", "subCategory": [ ], "title": "Warming Drawers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Washers-Dryers/zgbs/appliances/2383576011", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Clothes-Dryers/zgbs/appliances/13397481", "subCategory": [ ], "title": "Dryers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Clothes-Washing-Machines/zgbs/appliances/13397491", "subCategory": [ ], "title": "Washers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Combination-Washers-Dryers/zgbs/appliances/13755271", "subCategory": [ ], "title": "All-in-One Combination Washers &amp; Dryers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Stacked-Washer-Dryer-Units/zgbs/appliances/2399957011", "subCategory": [ ], "title": "Stacked Washer &amp; Dryer Units" } ], "title": "Washers &amp; Dryers" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Wine-Cellars/zgbs/appliances/3741521", "subCategory": [ { "url": "https://www.amazon.com/Best-Sellers-Appliances-Built-Wine-Cellars/zgbs/appliances/3741551", "subCategory": [ ], "title": "Built-In Wine Cellars" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Freestanding-Wine-Cellars/zgbs/appliances/3741541", "subCategory": [ ], "title": "Freestanding Wine Cellars" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Furniture-Style-Wine-Cellars/zgbs/appliances/3741561", "subCategory": [ ], "title": "Furniture-Style Wine Cellars" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Small-Wine-Cellars/zgbs/appliances/3741531", "subCategory": [ ], "title": "Small Wine Cellars" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Wine-Cellar-Cooling-Systems/zgbs/appliances/3741581", "subCategory": [ ], "title": "Wine Cellar Cooling Systems" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Wine-Rooms/zgbs/appliances/3741571", "subCategory": [ ], "title": "Wine Rooms" } ], "title": "Wine Cellars" }, { "url": "https://www.amazon.com/Best-Sellers-Appliances-Home-Appliance-Warranties/zgbs/appliances/2242350011", "subCategory": [ ], "title": "Appliance Warranties" } ]</code></pre> </div> </div> </p> <p>I'm traversing all subCategories like this:</p> <pre><code>row = 1 def TraverseJSONTree(jsonObject, count=0): title = jsonObject.get('title') url = jsonObject.get('url') print 'Title: ' + title + ' , Position: ' + str(count) worksheet.write_string(row, count, title) worksheet.write_string(row, 6, url) global row row+=1 subCategories = jsonObject.get('subCategory',[]) for category in subCategories: TraverseJSONTree(category, count+1) for jsonObject in json.loads(jsonArray): TraverseJSONTree(jsonObject) </code></pre> <p><a href="http://i.stack.imgur.com/pejPe.png" rel="nofollow"><img src="http://i.stack.imgur.com/pejPe.png" alt="enter image description here"></a></p> <p><strong>Expected Result</strong></p> <p><a href="http://i.stack.imgur.com/bLQcX.png" rel="nofollow"><img src="http://i.stack.imgur.com/bLQcX.png" alt="enter image description here"></a></p>
0
2016-09-09T06:16:43Z
39,541,161
<p>You can use the python code available <a href="https://kylo_ren@bitbucket.org/kylo_ren/big_data_json_to_excel_converter.git" rel="nofollow">here</a></p>
0
2016-09-16T22:58:36Z
[ "python", "json", "excel" ]
opening a gnome terminal via python doesn't seem to work when opening a specific directory
39,405,035
<p>If I run the following from a gnome terminal:</p> <pre><code>gnome-terminal --working-directory="/home/users" </code></pre> <p>I get a new shell in the '/home/users' directory.</p> <p>If I run the following in python:</p> <pre><code>import subprocess subprocess.Popen(['gnome-terminal', '--working-directory="/home/users"']) </code></pre> <p>I get a shell opened in my home directory - not in '/home/users'?</p>
2
2016-09-09T06:21:50Z
39,405,236
<p>In my case when i just remove <code>""</code> from argument it's seems to work:</p> <pre><code>import subprocess subprocess.call(['gnome-terminal', '--working-directory=/home/test']) </code></pre> <p>Also <code>/home/test</code> exist in my case. </p>
1
2016-09-09T06:34:56Z
[ "python", "subprocess", "gnome-terminal" ]
how to call a function in python with different number of attributes and with another logic?
39,405,071
<p>I have a function in python that has 2 arguments: for example </p> <pre><code> def get_shiff(instance): total=0 if instance.x: total+=instance.x/2 elif instance.y: total.+=instance.y*40 return total </code></pre> <p>Can I call this function in python in another file as this:</p> <pre><code> def get_shiff(instance,type) # the same thing for total but add this logic if type=="standard" : total+=instance.z*100 return total </code></pre>
-2
2016-09-09T06:23:58Z
39,405,606
<p>Short answer Yes, but maybe not as you expect. Have a look at the folowing:</p> <pre><code>def fn(a, b, c= None): if c is not None: return a+b+c else: return a+b print fn(1,2,3) &gt;&gt; 6 print fn(1,2) &gt;&gt; 3 </code></pre> <p>Applying this to your example:</p> <pre><code>def get_shiff(instance, shift=None): total=0 if shift is None: if instance.x: total+=instance.x/2 elif instance.y: total.+=instance.y*40 return total elif type=="standard" : total+=instance.z*100 return total else: return 0 </code></pre>
1
2016-09-09T07:00:19Z
[ "python", "django" ]
Can't import subprocess module into python3
39,405,118
<p>Im trying to import subprocess. However Im unable to even import subprocess.</p> <p>Currently, my file (throwaway.py) consists of only one line:</p> <pre><code>import subprocess </code></pre> <p>but it returns the error:</p> <pre><code>Traceback (most recent call last): File "throwaway.py", line 1, in &lt;module&gt; import subprocess ImportError: bad magic number in 'subprocess': b'\x03\xf3\r\n' Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook from apport.fileutils import likely_packaged, get_recent_crashes File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in &lt;module&gt; from apport.report import Report File "/usr/lib/python3/dist-packages/apport/report.py", line 12, in &lt;module&gt; import subprocess, tempfile, os.path, re, pwd, grp, os, time ImportError: bad magic number in 'subprocess': b'\x03\xf3\r\n' Original exception was: Traceback (most recent call last): File "throwaway.py", line 1, in &lt;module&gt; import subprocess ImportError: bad magic number in 'subprocess': b'\x03\xf3\r\n' </code></pre> <p>What are magic number errors? I read that they occur when you accidentally give a file the .pyc extention rather than .py? </p>
0
2016-09-09T06:26:52Z
39,405,211
<p>In this case the error occurs because for some reason your code is importing <strong>Python 2.7</strong> <code>subprocess.pyc</code> into Python 3. Python 2.7 <code>.pyc</code>s start with <code>b'\x03\xf3\r\n'</code>. Perhaps you've created one virtualenv for both Python 2 and 3 (it <strong>wouldn't work</strong>), or are using a wrong <code>PYTHONPATH</code>.</p>
3
2016-09-09T06:33:19Z
[ "python", "subprocess" ]
Can't import subprocess module into python3
39,405,118
<p>Im trying to import subprocess. However Im unable to even import subprocess.</p> <p>Currently, my file (throwaway.py) consists of only one line:</p> <pre><code>import subprocess </code></pre> <p>but it returns the error:</p> <pre><code>Traceback (most recent call last): File "throwaway.py", line 1, in &lt;module&gt; import subprocess ImportError: bad magic number in 'subprocess': b'\x03\xf3\r\n' Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook from apport.fileutils import likely_packaged, get_recent_crashes File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in &lt;module&gt; from apport.report import Report File "/usr/lib/python3/dist-packages/apport/report.py", line 12, in &lt;module&gt; import subprocess, tempfile, os.path, re, pwd, grp, os, time ImportError: bad magic number in 'subprocess': b'\x03\xf3\r\n' Original exception was: Traceback (most recent call last): File "throwaway.py", line 1, in &lt;module&gt; import subprocess ImportError: bad magic number in 'subprocess': b'\x03\xf3\r\n' </code></pre> <p>What are magic number errors? I read that they occur when you accidentally give a file the .pyc extention rather than .py? </p>
0
2016-09-09T06:26:52Z
39,405,538
<p>Use <code>pyclean</code> and try to import it again. </p> <pre><code>pyclean &lt;path&gt; </code></pre> <p>will remove all <code>pyc</code> files in path you'll provide (recursively), so there won't be compiled files, so no conflict.</p>
0
2016-09-09T06:56:45Z
[ "python", "subprocess" ]
How to save plots from multiple python scripts using an interactive C# process command?
39,405,252
<p>I've been trying to save plots(multiple) from different scripts using an interactive C# process command.</p> <p><strong>Objective:</strong> My aim is to save plots by executing multiple scripts in a single interactive python shell and that too from C#.</p> <p>Here's the code which I've tried from my end.</p> <p><strong>Code snippet:</strong></p> <pre><code>class Program { static string data = string.Empty; static void Main(string[] args) { Process pythonProcess = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe", "/c" + "python.exe -i"); startInfo.WorkingDirectory = "C:\\python"; startInfo.CreateNoWindow = true; startInfo.UseShellExecute = false; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; pythonProcess.StartInfo = startInfo; pythonProcess.ErrorDataReceived += Process_ErrorDataReceived; pythonProcess.OutputDataReceived += Process_OutputDataReceived; pythonProcess.Start(); pythonProcess.BeginErrorReadLine(); pythonProcess.BeginOutputReadLine(); Thread.Sleep(5000); while (data != string.Empty) { if (data == "Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.") { pythonProcess.StandardInput.WriteLine("execfile('script1.py')"); pythonProcess.StandardInput.WriteLine("execfile('script2.py')"); break; } } pythonProcess.WaitForExit(); } private static void Process_OutputDataReceived(object sender, DataReceivedEventArgs e) { data = e.Data; } private static void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e) { data = e.Data; } } </code></pre> <p><strong>Scripts:</strong></p> <p><em>script1.py</em></p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 5, 0.1); y = np.sin(x) plt.plot(x, y) plt.savefig('script1.png') </code></pre> <p><em>script2.py</em></p> <pre><code>import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.savefig('script2.png') </code></pre> <p>From the above C# code, you could see that I've tried to execute both the scripts. But, during the execution, the plot from the first script (<em>script1.py</em>) alone gets saved, whereas the second one (<em>script2.py</em>) doesn't. </p> <p>All I need to know is, how come the second script plot doesn't gets saved and what's the reason behind this ?</p> <p>Thanks in advance :)</p>
16
2016-09-09T06:36:14Z
39,444,207
<p>Since you are opening a python shell and then sending it the commands:</p> <pre><code>execfile('script1.py') execfile('script2.py') </code></pre> <p>Immediately one after the other I suspect that the second command is being sent during time taken to load <code>numpy</code> and <code>matplotlib</code> - you need to check the output from the first <code>execfile</code> to make sure that it has <strong>finished</strong> before issuing the second, or you need to use a different thread for each - at the moment you have a single thread attempting to perform two separate actions almost at once.</p> <p>Note that once you have finished with your python shell it is a <strong>very</strong> good idea to exit it by sending <code>exit()</code> to the process stdin and calling <code>process.WaitForExit()</code>.</p> <p>Also note that using a shell to call python code and execute external threads is classed as a security vulnerability in addition to being slow, reliant on the user having python installed, etc., you might be better off looking at using <a href="http://ironpython.net/" rel="nofollow">IronPython</a> - but the only actively maintained plotting library that <strong><em>I</em></strong> was able to find is the <em>non-free</em> <a href="http://ilnumerics.net/visualization-engine.html" rel="nofollow">ILNumerics Visualization Engine</a>.</p>
1
2016-09-12T06:06:19Z
[ "c#", "python", "plot", "command-line", "python.net" ]
How do I check if x has more or less than seven integers?
39,405,316
<pre><code>x = [] y = int(input("Hello, please enter your date of birth in this format: DDMMYYYY")) x.append(y) b = len.x() if b &gt; 7: input("Please enter your date of birth correctly in the above format") elif b &lt; 7: input("Please enter your date of birth correctly in the above format") </code></pre> <p>At the moment I'm getting this error: </p> <blockquote> <p>b = len.x() </p> <p>AttributeError: 'builtin_function_or_method' object has no attribute 'x'</p> </blockquote> <p>Sorry, I'm quite new to python, thanks for all the help!</p>
-4
2016-09-09T06:39:38Z
39,405,459
<p>Python'a <code>len()</code> is a <strong>function</strong>. It does not work like you think it does. What you doing is incorrect. Instead of this:</p> <p><code>b = len.x()</code></p> <p>Do this:</p> <p><code>b = len(str(x))</code></p> <p>You seem to be confused about the <code>len()</code> function. I suggest you read the <a href="https://docs.python.org/3/library/functions.html#len" rel="nofollow">Python documentation</a> about it.</p>
0
2016-09-09T06:50:36Z
[ "python", "python-3.x" ]
How do I check if x has more or less than seven integers?
39,405,316
<pre><code>x = [] y = int(input("Hello, please enter your date of birth in this format: DDMMYYYY")) x.append(y) b = len.x() if b &gt; 7: input("Please enter your date of birth correctly in the above format") elif b &lt; 7: input("Please enter your date of birth correctly in the above format") </code></pre> <p>At the moment I'm getting this error: </p> <blockquote> <p>b = len.x() </p> <p>AttributeError: 'builtin_function_or_method' object has no attribute 'x'</p> </blockquote> <p>Sorry, I'm quite new to python, thanks for all the help!</p>
-4
2016-09-09T06:39:38Z
39,405,710
<p>You can checkout the solution given in the below thread if you are dealing with date and time.</p> <p><a href="http://stackoverflow.com/questions/15581629/getting-input-date-from-the-user-in-python-using-datetime-datetime">Getting input date from the user in python using datetime.datetime</a></p>
2
2016-09-09T07:06:21Z
[ "python", "python-3.x" ]
How do i save many to many fields objects using django rest framework
39,405,326
<p>I have three models Blogs, Posted, Tags. In Blogs model I have fields 'postedin' as foreign key to Posted model and 'tags' as manytomany fields to Tags model.</p> <p>models.py:</p> <pre><code>class Posted(models.Model): name = models.CharField(_('Posted In'),max_length=255, unique=True) class Tags(models.Model): name = models.CharField(_('Tag Name'),max_length=255, unique=True) class Blogs(models.Model): author = models.ForeignKey(CustomUser) title=models.CharField(max_length=100) postedin=models.ForeignKey(Posted) tags= models.ManyToManyField(Tags) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) </code></pre> <p>views.py:</p> <pre><code>class BlogViewSet(viewsets.ModelViewSet): queryset=Blogs.objects.order_by('-created_at') serializer_class= BlogsSerializer def get_permissions(self): if self.request.method in permissions.SAFE_METHODS: return (permissions.AllowAny(),) return (permissions.IsAuthenticated(),IsAuthorOfBlog()) def perform_create(self,serializer): serializer.save(author=self.request.user) return super(BlogViewSet,self).perform_create(serializer) </code></pre> <p>serializers.py:</p> <pre><code>class TagsSerializer(serializers.ModelSerializer): class Meta: model = Tags fields = ('pk','name') read_only_fields=('pk','name') class PostedSerializer(serializers.ModelSerializer): class Meta: model = Posted fields = ('pk','name') read_only_fields=('pk','name') class BlogsSerializer(serializers.ModelSerializer): author = AccountSerializer(read_only=True,required=False) tags=TagsSerializer(read_only=True,many=True) tags_id = serializers.PrimaryKeyRelatedField(queryset=Tags.objects.all(), write_only=True) postedin = PostedSerializer(read_only=True) postedin_id = serializers.PrimaryKeyRelatedField(queryset=Posted.objects.all(), write_only=True) class Meta: model = Blogs fields = ('pk','author','title','tags','tags_id','postedin','postedin_id','content','created_at','updated_at') read_only_fields=('pk','created_at','updated_at') def get_validation_exclusions(self, *args, **kwargs): exclusions = super(BlogsSerializer, self).get_validation_exclusions() return exclusions + ['author'] def create(self, validated_data): postedin = validated_data.pop('postedin_id') tags = validated_data.pop('tags_id') blogs = Blogs.objects.create(tags=tags,postedin=postedin, **validated_data) return blogs </code></pre> <p>Request sent:</p> <p>{title: "nvnbv", postedin_id: "1", tags_id: ["2", "5", "1", "4"], content: "nmvmvjm"}</p> <p>response receive:</p> <p>{tags_id: ["Incorrect type. Expected pk value, received list."]}</p> <p>I am beginner in Django-rest-framework.How to solve this error.</p> <p>Thanks in advance ! </p>
0
2016-09-09T06:40:56Z
39,406,265
<p>thanks @Abdulafaja for your suggestion.</p> <p>Finally I got solution</p> <p>BlogsSerializer should be</p> <pre><code>class BlogsSerializer(serializers.ModelSerializer): author = AccountSerializer(read_only=True,required=False) tags=TagsSerializer(read_only=True,many=True) tags_id = serializers.PrimaryKeyRelatedField(queryset=Tags.objects.all(), write_only=True,many=True) postedin = PostedSerializer(read_only=True) postedin_id = serializers.PrimaryKeyRelatedField(queryset=Posted.objects.all(), write_only=True) class Meta: model = Blogs fields = ('pk','author','title','tags','tags_id','postedin','postedin_id','content','created_at','updated_at') read_only_fields=('pk','created_at','updated_at') def get_validation_exclusions(self, *args, **kwargs): exclusions = super(BlogsSerializer, self).get_validation_exclusions() return exclusions + ['author'] def create(self, validated_data): postedin = validated_data.pop('postedin_id') tags = validated_data.pop('tags_id') blogs = Blogs.objects.create(postedin=postedin, **validated_data) for tg in tags: blogs.tags.add(tg) return blogs </code></pre>
0
2016-09-09T07:38:02Z
[ "python", "django", "django-rest-framework" ]
run django projact from another python program
39,405,376
<p>are anyway to run django project from another python program without useing subprocess or os.system.</p> <p>im trying to use :</p> <pre><code>os.system("python manage.py runserver") </code></pre> <p>and : </p> <pre><code>subprocess.call("python", "manage.py", "runserver") </code></pre> <p>but i want to run it from kivy in android and android don't have python builtin</p> <p>django local server is using as serverside of webwiew.</p> <p>i find runpy module but it can't run django.</p> <p>how can i do this ?</p> <p>edit 1 :</p> <p>i do it like that Tomasz Jakub Rup say but not work and give below error :</p> <pre><code> Python 3.5.1 (default, Mar 3 2016, 09:29:07) [GCC 5.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; import django &gt;&gt;&gt; os.environ['DJANGO_SETTINGS_MODULE'] = 'sample.settings' &gt;&gt;&gt; if hasattr(django, 'setup'): ... django.setup() ... &gt;&gt;&gt; from django.core.management import call_command &gt;&gt;&gt; call_command('runserver') /usr/bin/python: can't find '__main__' module in '' </code></pre>
-1
2016-09-09T06:44:35Z
39,405,748
<p>First You must init <code>django</code>:</p> <pre><code>import os import django os.environ['DJANGO_SETTINGS_MODULE'] = 'testapp.settings' if hasattr(django, 'setup'): django.setup() from django.core.management import call_command </code></pre> <p>And run command:</p> <pre><code>call_command('runserver') </code></pre>
0
2016-09-09T07:07:50Z
[ "android", "python", "django", "server", "kivy" ]
run django projact from another python program
39,405,376
<p>are anyway to run django project from another python program without useing subprocess or os.system.</p> <p>im trying to use :</p> <pre><code>os.system("python manage.py runserver") </code></pre> <p>and : </p> <pre><code>subprocess.call("python", "manage.py", "runserver") </code></pre> <p>but i want to run it from kivy in android and android don't have python builtin</p> <p>django local server is using as serverside of webwiew.</p> <p>i find runpy module but it can't run django.</p> <p>how can i do this ?</p> <p>edit 1 :</p> <p>i do it like that Tomasz Jakub Rup say but not work and give below error :</p> <pre><code> Python 3.5.1 (default, Mar 3 2016, 09:29:07) [GCC 5.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; import django &gt;&gt;&gt; os.environ['DJANGO_SETTINGS_MODULE'] = 'sample.settings' &gt;&gt;&gt; if hasattr(django, 'setup'): ... django.setup() ... &gt;&gt;&gt; from django.core.management import call_command &gt;&gt;&gt; call_command('runserver') /usr/bin/python: can't find '__main__' module in '' </code></pre>
-1
2016-09-09T06:44:35Z
39,405,889
<p>Built in development server of django is fine initially but down the line you might want to use uwsgi or gunicorn to serve your application. They are efficient and can also be made to run on startup in the background rather than launching the shell and you having to run the command manually. You can check more about it here.</p> <p><a href="http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html" rel="nofollow">http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html</a></p>
0
2016-09-09T07:16:20Z
[ "android", "python", "django", "server", "kivy" ]
Ansible playbook, set environment variables not working
39,405,457
<p>I have to install psycopg to an old python (2.4). Everything works fine, except setting the environment variables -> LD_LIBRARY_PATH.</p> <pre><code>- name: install psycopg shell: "{{ item }}" environment: CPPFLAGS: "-I/my_python/lib/python2.4/site-packages/mx/DateTime/mxDateTime" LD_LIBRARY_PATH: "/path_to_postgresql/lib" args: chdir: "/path_to_psycopg_src/" with_items: - ./configure --prefix=/my_python --with-python=/my_python/bin/python --with-postgres-libraries=/path_to_postgresql/lib --with-postgres-includes=/path_postgresql/include --with-mxdatetime-includes=/my_python/lib/python2.4/site-packages/mx/DateTime/mxDateTime - make - make install </code></pre> <p>After successfull installation I get the following error:</p> <pre><code>&gt;&gt;&gt; import psycopg ImportError: libpq.so.4: cannot open shared object file: No such file or directory </code></pre> <p>When I export it manually, it works fine:</p> <pre><code>export LD_LIBRARY_PATH="/path_postgresql/lib" &gt;&gt;&gt; import psycopg &gt;&gt;&gt; psycopg &lt;module 'psycopg' from '/my_python/lib/python2.4/site-packages/psycopgmodule.so'&gt; </code></pre>
0
2016-09-09T06:50:30Z
39,405,647
<p>Because you set the <code>LD_LIBRARY_PATH</code> just for <code>install psycopg</code> task. If you want to set an environment variable not just for task/playbook I think you need to edit <code>/etc/environment</code></p>
1
2016-09-09T07:02:32Z
[ "python", "ansible", "ansible-playbook" ]
How to deal with xmlns values while parsing an XML file?
39,405,542
<p>I have the following toy example of an XML file. I have thousands of these. I have difficulty parsing this file. </p> <p>Look at the text in second line. All my original files contain this text. When I delete <code>i:type="Record" xmlns="http://schemas.datacontract.org/Storage"</code> from second line (retaining the remaining text), I am able to get <code>accelx</code> and <code>accely</code> values using the code given below. </p> <p>How can I parse this file with the original text? </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;ArrayOfRecord xmlns:i="http://www.w3.org/2001/XMLSchema-instance" i:type="Record" xmlns="http://schemas.datacontract.org/Storage"&gt; &lt;AvailableCharts&gt; &lt;Accelerometer&gt;true&lt;/Accelerometer&gt; &lt;Velocity&gt;false&lt;/Velocity&gt; &lt;/AvailableCharts&gt; &lt;Trics&gt; &lt;Trick&gt; &lt;EndOffset&gt;PT2M21.835S&lt;/EndOffset&gt; &lt;Values&gt; &lt;TrickValue&gt; &lt;Acceleration&gt;26.505801694441629&lt;/Acceleration&gt; &lt;Rotation&gt;0.023379150593228679&lt;/Rotation&gt; &lt;/TrickValue&gt; &lt;/Values&gt; &lt;/Trick&gt; &lt;/Trics&gt; &lt;Values&gt; &lt;SensorValue&gt; &lt;accelx&gt;-3.593643144&lt;/accelx&gt; &lt;accely&gt;7.316485176&lt;/accely&gt; &lt;/SensorValue&gt; &lt;SensorValue&gt; &lt;accelx&gt;0.31103436&lt;/accelx&gt; &lt;accely&gt;7.70408184&lt;/accely&gt; &lt;/SensorValue&gt; &lt;/Values&gt; &lt;/ArrayOfRecord&gt; </code></pre> <p>Code to parse the data: </p> <pre><code>import lxml.etree as etree tree = etree.parse(r"C:\testdel.xml") root = tree.getroot() val_of_interest = root.findall('./Values/SensorValue') for sensor_val in val_of_interest: print sensor_val.find('accelx').text print sensor_val.find('accely').text </code></pre> <p>I asked related question here: <a href="http://stackoverflow.com/questions/39402388/how-to-extract-data-from-xml-file-that-is-deep-down-the-tag">How to extract data from xml file that is deep down the tag</a> </p> <p>Thanks </p>
0
2016-09-09T06:56:54Z
39,406,031
<p>The confusion was caused by the following <em>default namespace</em> (namespace declared without prefix) :</p> <pre><code>xmlns="http://schemas.datacontract.org/Storage" </code></pre> <p>Note that descendants elements without prefix inherit default namespace from ancestor, implicitly. Now, to reference element in namespace, you need to map a prefix to the namespace URI, and use that prefix in your XPath :</p> <pre><code>ns = {'d': 'http://schemas.datacontract.org/Storage' } val_of_interest = root.findall('./d:Values/d:SensorValue', ns) for sensor_val in val_of_interest: print sensor_val.find('d:accelx', ns).text print sensor_val.find('d:accely', ns).text </code></pre>
2
2016-09-09T07:25:16Z
[ "python", "xml" ]
Django Postgres ArrayField __contain lookup does not behave expectedly
39,405,782
<p>This is my <em>models.py</em>:</p> <pre><code>class Dog(models.Model): name = models.CharField(max_length=200) data = JSONField() def __unicode__(self): return self.name </code></pre> <p>I did this in the django shell:</p> <pre><code>Dog.objects.create(name='Rufus', data={ 'breed': 'labrador', 'owner': { 'name': 'Bob', 'other_pets': [{ 'name': 'Fishy', }], }, }) Dog.objects.create(name='Meg', data={'breed': 'collie'}) Dog.objects.filter(data__breed__contains='l') </code></pre> <p>However when I did the last command it gave me an empy queryset return:</p> <pre><code>&lt;QuerySet []&gt; </code></pre> <p>The two objects <em>(Meg and Rufus)</em> should have both returned because they both contain l</p> <p>This is my query:</p> <pre><code>SELECT "post_tagging_dog"."id", "post_tagging_dog"."name", "post_tagging_dog"."data" FROM "post_tagging_dog" WHERE "post_tagging_dog"."data" -&gt; 'breed' @&gt; '"l"' </code></pre>
-1
2016-09-09T07:10:03Z
39,406,586
<p>try simply <code>for + if</code>:</p> <pre><code>for obj in Dog.objects: if 'l' in obj.data['breed']: return obj </code></pre>
-1
2016-09-09T07:56:09Z
[ "python", "django" ]
SQLAlchemy: Lost connection to MySQL server during query
39,405,808
<p>There are a couple of related questions regarding this, but in my case, all those solutions is not working out. Thats why I thought of asking again. I am getting this error while I am firing below query using sqlalchemy orm.</p> <pre><code>Traceback (most recent call last): File "MyFile.py", line 1010, in &lt;module&gt; handler.handle(line.split('\t')) File "MyFile.py", line 849, in handle self.getRecord(whatIfFlag, id) File "MyFile.py", line 143, in getRecord newRecord = self.recordSearcher.getRecordByParams(name, pId) File "abc.py", line 67, in getRecord File "/opt/product/python/prod/bin/2.7.6/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/orm/query.py", line 2361, in one ret = list(self) File "/opt/product/python/prod/bin/2.7.6/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/orm/query.py", line 2404, in __iter__ return self._execute_and_instances(context) File "/opt/product/python/prod/bin/2.7.6/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/orm/query.py", line 2419, in _execute_and_instances result = conn.execute(querycontext.statement, self._params) File "/opt/product/python/prod/bin/2.7.6/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/engine/base.py", line 720, in execute return meth(self, multiparams, params) File "/opt/product/python/prod/bin/2.7.6/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/sql/elements.py", line 317, in _execute_on_connection return connection._execute_clauseelement(self, multiparams, params) File "/opt/product/python/prod/bin/2.7.6/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/engine/base.py", line 817, in _execute_clauseelement compiled_sql, distilled_params File "/opt/product/python/prod/bin/2.7.6/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/engine/base.py", line 947, in _execute_context context) File "/opt/product/python/prod/bin/2.7.6/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1108, in _handle_dbapi_exception exc_info File "/opt/product/python/prod/bin/2.7.6/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/util/compat.py", line 185, in raise_from_cause reraise(type(exception), exception, tb=exc_tb) File "/opt/product/python/prod/bin/2.7.6/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/engine/base.py", line 940, in _execute_context context) File "/opt/product/python/prod/bin/2.7.6/lib/python2.7/site-packages/SQLAlchemy-0.9.4-py2.7-linux-x86_64.egg/sqlalchemy/engine/default.py", line 435, in do_execute cursor.execute(statement, parameters) File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py", line 205, in execute File "build/bdist.linux-x86_64/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler sqlalchemy.exc.OperationalError: (OperationalError) (2013, 'Lost connection to MySQL server during query') .... query = self.__session.query(MyTable).filter(and_(MyTable.NAME == name,MyTable.P_ID == p_id) try: record = query.one() except NoResultFound: new_record = MyTable(params) self.__session.add(new_record) self.__session.commit() self.__session.close() </code></pre> <p>It is expected to return only one record. This is how I create my session.</p> <pre><code>sqlEngine = sqlalchemy.create_engine(self.getMySQLURI(), pool_recycle=10800, echo=False, echo_pool=False) session = scoped_session(sessionmaker(autoflush=True, autocommit=False, bind=sqlEngine, expire_on_commit=False)) </code></pre> <p>These are my mysql configurations: interactive_timeout and wait_timeout is set to 28800 ~ 8 hours. net_write_timeout is set to 3600 ~ 60 mins and net_read_timeout is set 300 ~ 5 mins.</p> <p>Any help is highly appreciated.</p>
0
2016-09-09T07:11:41Z
39,510,454
<p>It is turned out to be problem with the tcp_connect_timeout between the application server and the database server. The tcp connect timeout was default of 1 hour and my pool recycle settings was 3 hrs. So anything between 1 and 3 were failing. Posting the answer to help others who might face this later.</p>
0
2016-09-15T11:57:26Z
[ "python", "mysql", "sqlalchemy" ]