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': Tr...
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': Tr...
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],...
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,...
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> ...
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...
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> ...
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 s...
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</...
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 ...
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
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/late...
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 l...
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>....
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(), ...
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.djangop...
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><c...
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><c...
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><c...
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, whi...
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...
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...
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...
-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
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 w...
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 d...
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>...
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(li...
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...
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...
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>...
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 a...
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 = ...
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, the...
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>E...
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 da...
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>E...
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 de...
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>E...
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 r...
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 nice...
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_sessio...
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 usin...
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_wid...
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 usin...
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 ca...
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 usin...
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="...
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...
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...
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 d...
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...
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("testdo...
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 item...
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-coordinat...
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...
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 /Li...
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 em...
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...
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 advis...
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 wheth...
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 advis...
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__</...
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 ...
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...
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 inter...
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 ...
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 inter...
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><...
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 inter...
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...
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> <...
-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 ME...
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] ...
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...
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] ...
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. </...
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] ...
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-t...
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_b...
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> w...
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 opera...
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 secon...
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.], [...
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 secon...
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., ...
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.getlin...
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 a...
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 ...
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...
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 ...
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([]) fo...
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 ...
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...
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>...
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.1...
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>...
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/228642...
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>...
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 insta...
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 <co...
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 insta...
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 ...
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 insta...
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:/...
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-k...
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-...
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-k...
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 reque...
-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 automatical...
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> :</h...
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 automatical...
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) </co...
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)...
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\proje...
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 no...
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...
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 Pyt...
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)...
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: ...
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: typ...
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 ca...
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 rang...
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>an...
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 -&g...
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".st...
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 -&g...
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 pare...
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 -&g...
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...
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 tab...
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>:...
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 tab...
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 fo...
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 clas...
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,dia...
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 clas...
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...
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 clas...
0
2016-09-09T06:16:43Z
39,541,161
<p>You can use the python code available <a href="https://[email protected]/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="/hom...
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:</...
-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_shif...
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;modu...
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>),...
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;modu...
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><...
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...
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>...
-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 yo...
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>...
-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.Mode...
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.Primar...
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 f...
-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') </...
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 f...
-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...
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:...
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 th...
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 ...
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'...
-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;modul...
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" ]