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
in Python, are statements objects?
39,570,317
<p>As far as I understand, everything in python is an object or a reference. For example: in <code>x = 1</code>, <code>x</code> is a reference to the integer object <code>1</code>. If I write <code>print type(x)</code>, then Python will tell me the object that x is referencing is an integer. </p> <p>So what about statements such as <code>if</code>?</p> <p>if I try <code>print type(if)</code>, unsurprisingly, I get a syntax error. I can speculate on why this is the case. Maybe <code>if</code> is a static method of a class, or maybe it has somehow been weirdly defined as non returnable, etc. I just don't know.</p> <p>Ultimately, I suspect that <code>if</code> has nothing to do with an object or a reference. However, that would surely go against the idea of everything being an object or a reference? </p>
0
2016-09-19T09:58:05Z
39,570,581
<p>When they say "everything is an object or a reference" they are referring specifically to data. So this naturally does not apply to statements. Of course, all expressions will result in data. For example <code>a == b</code> is <code>&lt;class 'bool'&gt;</code> because it is an expression.</p> <p>There are some languages where <code>if</code> is an expression but python is not one of them.</p>
2
2016-09-19T10:12:00Z
[ "python", "object", "if-statement", "reference", "conditional" ]
Naming conventions for Python scripts without classes
39,570,320
<p>I've searched around for an answer specific to my use case, but can't find one, so apologies if this specific case has been answered before.</p> <p>I run a number of isolated scripts which perform different functions, like assessing specific data from APIs and sending email alerts. Whilst the scripts themselves use appropriately named modules for shared functionality - e.g. sending emails - they don't themselves have functionality which will need to be shared.</p> <p>As a result I have a directory/script structure that feels too generic:</p> <pre><code>{script1 purpose} - go.py {script2 purpose} - go.py {script3 purpose} - go.py </code></pre> <p>e.g.</p> <pre><code>Spend Monitor - go.py </code></pre> <p>Where `Spend Monitor' is a relevant directory name, with the script starting the execution called go.py in each directory.</p> <p>This has not caused any problems so far, but it feels like bad practice. However, I can't find reference to this specific case - should the go.py files be renamed? To what?</p>
0
2016-09-19T09:58:09Z
39,571,484
<p>This is the only reference I know about module names (scripts are themselves modules so it applies to them too):</p> <blockquote> <p>Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability.</p> </blockquote> <p><a href="https://www.python.org/dev/peps/pep-0008/#package-and-module-names" rel="nofollow">https://www.python.org/dev/peps/pep-0008/#package-and-module-names</a></p> <p>Now if the way you are naming things feels to you like bad practice and you can think of some other way that feels like less bad practice, it is probably worth the change.</p>
0
2016-09-19T10:56:49Z
[ "python", "naming-conventions" ]
applying a mask on a nested numpy array - numpy - python
39,570,335
<p>a bit embarassing to ask since the heavy documentation on Numpy but I was stuck doing this simple task, that is getting all the records for which a mask is true in a nested numpy representation (equivalent to the <code>dataframe.loc[cond]</code> in <code>pandas</code>):</p> <pre><code>import numpy as np a1 = np.array([1,2,3]) a2 = np.array(['a','b','c']) a3 = np.array(['luca','paolo','francesco']) a4 = np.array([True, False,False], dtype='bool') combination = np.array([a1,a2,a3,a4]) print(combination) # slice for a4 == True combination[combination[3] == 'True'] </code></pre> <p>but the result is not what I want.</p> <p>in fact from <code>combination</code> :</p> <pre><code>[['1' '2' '3'] ['a' 'b' 'c'] ['luca' 'paolo' 'francesco'] ['True' 'False' 'False']] </code></pre> <p>it yields with <code>combination[combination[3] == 'True']</code>:</p> <pre><code>array([['1', '2', '3']], dtype='&lt;U11') </code></pre> <p>when in reality I want:</p> <pre><code>[['1'] ['a' ] ['luca'] ['True' ]] </code></pre> <p>any ideas on what I am doing wrong?</p> <p>P.S.: no i can't do it in pandas because pandas has my RAM exploding when converting this to a <code>pandas.Dataframe</code> </p>
1
2016-09-19T09:58:45Z
39,570,777
<p>I believe you're simply missing the indexes of the other dimension:</p> <pre><code>combination[combination[3] == 'True'] </code></pre> <p>should be</p> <pre><code>combination[:, combination[3] == 'True'] </code></pre> <p>Note the colon.</p> <p>This yields a new ndarray indexed over all of the first dimension and only 0 in the second.</p>
2
2016-09-19T10:21:13Z
[ "python", "arrays", "numpy", "indexing", "slice" ]
Install opencv-python under python3 ubunto 14.04
39,570,381
<p>I want to use opencv under python 3 in Ubunto 14.04. I plan to use the PyCharm IDE to develop my program. </p> <p>Inside PyCharm I choose, I set:</p> <p><strong>File/Settings/Project:HelloWorld/Project Interpreter/3.4.3(/usr/bin/python3.4)</strong> </p> <p>Python 3.4.3 is the default version of python in Ubunto 14.04.</p> <p>Then I try to add <strong>opencv-python</strong> package:</p> <p><strong>File/Settings/Project:HelloWorld/Project Interpreter/+</strong> (where you add the package)</p> <p>and the system gives me this error:</p> <pre><code> Executed command: pip install opencv-python Try to run this command from the system terminal. Make sure that you use the correct version of 'pip' installed for your Python interpreter located at '/usr/bin/python3.4'. DEPRECATION: --no-install, --no-download, --build, and --no-clean are deprecated. See https://github.com/pypa/pip/issues/906. Downloading/unpacking opencv-python Could not find any downloads that satisfy the requirement opencv-python Cleaning up... No distributions at all found for opencv-python Storing debug log for failure in /root/.pip/pip.log </code></pre> <p>the error is the same when I run the command from terminal. I believe the problem is related to installing opencv under python3 but I am not sure I know if I can fix it. Please let me know your opinion. </p> <p>Thanks</p>
1
2016-09-19T10:01:38Z
39,570,487
<p>As far as I can see from querying pip (using <code>pip search opencv</code>) there is no package called <code>opencv-python</code> I think the one you're looking for is <code>pyopencv</code>.</p> <p><a href="http://stackoverflow.com/questions/25215102/installing-opencv-for-python-on-ubuntu-getting-importerror-no-module-named-cv2">this issue appears to be almost identical</a></p>
1
2016-09-19T10:07:06Z
[ "python", "opencv" ]
Using Python regex find and replace to add HTML tags around raw text
39,570,504
<p>I'm building a simple web app using Flask and I want to know if it is possible to use regex to find and replace the numbers in Fe2O3 + CO -> Fe + CO2 and surround them with the sub HTML tag so it becomes Fe<sub>2</sub>O<sub>3</sub> + CO -> Fe + CO<sub>2</sub> when displayed in HTML.</p>
-4
2016-09-19T10:07:20Z
39,570,893
<p>Try something like this, Here <code>a</code> is your input string. Implemented without using regex.</p> <pre><code>In [1]: a = 'Fe2O3 + CO -&gt; Fe + CO2' In [2]: ''.join(['&lt;sub&gt;'+i+'&lt;/sub&gt;' if i.isdigit() else i for i in a]) Out[1]: 'Fe&lt;sub&gt;2&lt;/sub&gt;O&lt;sub&gt;3&lt;/sub&gt; + CO -&gt; Fe + CO&lt;sub&gt;2&lt;/sub&gt;' </code></pre>
0
2016-09-19T10:26:03Z
[ "python", "regex" ]
split-apply-combine to sklearn pipeline
39,570,578
<p>I am trying to generate a pipeline using sklearn, and am not really sure how to go about it. Here is a minimal example:</p> <pre><code>def numFeat(data): return data[['AGE', 'WASTGIRF']] def catFeat(data): return pd.get_dummies(data[['PAI', 'smokenow1']]) features = FeatureUnion([('f1',FunctionTransformer(numFeat)), ('f2',FunctionTransformer(catFeat)) ] ) pipeline = Pipeline( [('f', features), ('lm',LinearRegression())] ) data = pd.DataFrame({'AGE':[1,2,3,4], 'WASTGIRF': [23,5,43,1], 'PAI':['a','b','a','d'], 'smokenow1': ["lots", "some", "none", "some"]}) pipeline.fit(data, y) print pipeline.transform(data) </code></pre> <p>In the above example, <code>data</code> is a Pandas DataFrame that contains the columns <code>['AGE', 'WASTGIRF', 'PAI', 'smokenow1']</code> among others. </p> <p>Of course, in the <code>FeatureUnion</code> example, I want to supply many more transformation operations, but, all of them take a Pandas DataFrame and return another Pandas DataFrame. So in effect, I want to do something like this ...</p> <pre><code>data --+--&gt;num features--&gt;num transforms--+--&gt;FeatureUnion--&gt;model | | +--&gt;cat features--&gt;cat transforms--+ </code></pre> <p>How do I go about doing this?</p> <p>For the example above, the error i get is ...</p> <pre><code>TypeError: float() argument must be a string or a number </code></pre>
0
2016-09-19T10:11:49Z
39,583,770
<p>You need to initialise <code>FunctionTransformer</code> with <code>validate=False</code> (IMO this is a bad default that should be changed):</p> <pre><code>features = FeatureUnion([('f1',FunctionTransformer(numFeat, validate=False)), ('f2',FunctionTransformer(catFeat, validate=False))] ) </code></pre> <p>See also <a href="http://stackoverflow.com/questions/39001956/sklearn-pipeline-how-to-apply-different-transformations-on-different-coluns/39009125">sklearn pipeline - how to apply different transformations on different columns</a></p>
1
2016-09-20T00:02:09Z
[ "python", "scikit-learn" ]
ImportError: No module named requests using two versions of python
39,570,633
<p>I've python 3.4.1 installed, and need to run python 2 script. I've installed python 2.7.5 by running <code>make install</code>. When i run my script it writes:</p> <pre><code>Traceback (most recent call last): File "/root/roseltorg/run.py", line 2, in &lt;module&gt; import requests ImportError: No module named requests </code></pre> <p>Then I'm trying to install requests module but:</p> <pre><code>pip install requests Requirement already satisfied (use --upgrade to upgrade): requests in /usr/local/lib/python3.4/site-packages/requests-2.11.1-py3.4.egg Cleaning up... </code></pre> <p>How to force install this module for python 2.7?</p>
0
2016-09-19T10:15:01Z
39,570,783
<p>I prefer using virtualenv in such scenario. </p> <pre><code>virtualenv -p path_to_python2.7 .(current dir) source bin/activate pip install requests </code></pre>
1
2016-09-19T10:21:27Z
[ "python", "python-2.7", "pip", "python-3.4" ]
ImportError: No module named requests using two versions of python
39,570,633
<p>I've python 3.4.1 installed, and need to run python 2 script. I've installed python 2.7.5 by running <code>make install</code>. When i run my script it writes:</p> <pre><code>Traceback (most recent call last): File "/root/roseltorg/run.py", line 2, in &lt;module&gt; import requests ImportError: No module named requests </code></pre> <p>Then I'm trying to install requests module but:</p> <pre><code>pip install requests Requirement already satisfied (use --upgrade to upgrade): requests in /usr/local/lib/python3.4/site-packages/requests-2.11.1-py3.4.egg Cleaning up... </code></pre> <p>How to force install this module for python 2.7?</p>
0
2016-09-19T10:15:01Z
39,571,170
<p>It is installing to python 3.4 with <code>pip</code> which means <code>pip</code> pointing to <code>pip3</code>. Try doing this</p> <pre><code>pip2 install requests </code></pre>
1
2016-09-19T10:40:23Z
[ "python", "python-2.7", "pip", "python-3.4" ]
How to read columns from CSV file in Python
39,570,849
<pre><code>def rowfilter(): field_data = {} try: csv_read = csv.reader(open('sample.csv', ), delimiter=',', quotechar='|') for row in csv_read: for field in row[7]: print(field) except FileNotFoundError: print("File not found") rowfilter() </code></pre> <p>This code runs successfully but I want this code to print data prior to the user_input. e.g. if user enter 5 then its should print all the details from 1 to 5, along with all the column associated with it.</p>
-2
2016-09-19T10:24:20Z
39,571,210
<pre><code>def rowfilter(col1, col2): try: csv_read = csv.reader(open('items.csv'), delimiter=',', quotechar='|') for row in csv_read: print(row[int(cols[0]):int(cols[1])]) except FileNotFoundError: print("File not found") inputrows = input("Enter columns in the format: col1 col2 ") rowfilter(inputrows.split())) </code></pre> <p>I have edited this answer as per your comment, it is possible to treat the csv row as a list once the csv reader has read it. Therefore this method will print columns from col1 to col2. Note that python is 0 indexed.</p>
0
2016-09-19T10:42:59Z
[ "python", "python-3.x", "csv" ]
How to read columns from CSV file in Python
39,570,849
<pre><code>def rowfilter(): field_data = {} try: csv_read = csv.reader(open('sample.csv', ), delimiter=',', quotechar='|') for row in csv_read: for field in row[7]: print(field) except FileNotFoundError: print("File not found") rowfilter() </code></pre> <p>This code runs successfully but I want this code to print data prior to the user_input. e.g. if user enter 5 then its should print all the details from 1 to 5, along with all the column associated with it.</p>
-2
2016-09-19T10:24:20Z
39,571,533
<p>This is almost certainly a job for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">pandas</a></p> <pre><code>import pandas as pd df = pd.read_csv('sample.csv', delimiter=',', quotechar='|') #you can get the 7th column like this df_seven = df[df.columns[7]] #Then slice the dataframe as you see fit df_seven[0:5] # first five rows df_seven[4:9] # rows 4 to 9... etc </code></pre>
0
2016-09-19T10:59:38Z
[ "python", "python-3.x", "csv" ]
Python bitarray manipulation
39,571,128
<p>I want to remove the least significant 2 bits of every 16-bit integer from a bitarray. They're stored like this:</p> <pre><code>010101**00**10010101101100**00**10101010..... </code></pre> <p>(The zeroes between the asterisks will be removed. There are two of them every 16 bits (ignoring the very first)).</p> <p>I can simply eliminate them with a regular for loop checking indexes (the 7th and 8th after every 16 bits). </p> <p>But... is there another more <em>pythonic</em> way to do this? I'm thinking about some slice notation or maybe comprehension lists. Perhaps I could divide every number by 4 and encode every one with 14 bits (if there's a way to do that).</p>
-1
2016-09-19T10:38:05Z
39,571,450
<p>You can clear bits quite easily with masking. If you want to clear bits 8 and 7 you can do it like this:</p> <pre><code>a = int('10010101101100',2) mask = ~((1 &lt;&lt; 7) | (1 &lt;&lt; 8)) bin(a&amp;mask) </code></pre> <p>more information about masking from <a href="https://wiki.python.org/moin/BitManipulation" rel="nofollow">here!</a></p>
2
2016-09-19T10:55:25Z
[ "python", "arrays", "list", "bit-manipulation", "bitarray" ]
How do you open specific text files on python?
39,571,134
<p>I want to open specific lines from an ordinary text file in python. is there anyway to do this? and how?</p>
-1
2016-09-19T10:38:23Z
39,571,218
<p>presuming that you want the line <code>m</code> and the name file is <code>file.txt</code></p> <pre><code>with open('file.txt') as f: line = f.read().splitlines()[m] print(line) </code></pre> <p><code>line</code> is the line that you want.</p>
2
2016-09-19T10:43:28Z
[ "python" ]
How do you open specific text files on python?
39,571,134
<p>I want to open specific lines from an ordinary text file in python. is there anyway to do this? and how?</p>
-1
2016-09-19T10:38:23Z
39,571,267
<p>If the lines are selected by line numbers which follow a consistent pattern, use <a href="https://docs.python.org/3.6/library/itertools.html#itertools.islice" rel="nofollow"><code>itertools.islice</code></a>.</p> <p>E.g. To select every second line from line 3 up to but not including line 10:</p> <pre><code>import itertools with open('my_file.txt') as f: for line in itertools.islice(f, 3, 10, 2): print(line) </code></pre>
1
2016-09-19T10:46:00Z
[ "python" ]
How do you open specific text files on python?
39,571,134
<p>I want to open specific lines from an ordinary text file in python. is there anyway to do this? and how?</p>
-1
2016-09-19T10:38:23Z
39,574,220
<p>First lets see how to open a file to write:</p> <pre><code>f = open(‘filename.txt’, ‘w’) </code></pre> <p>Now we have opened a file named filename, in write mode. Write mode is indicated using ‘w’. If a file of that particular name is not present then a new file would be created.</p> <p>It has created an object of that particular file and we can do all our operations on that particular object. Now we have created an object for writing. The command to write is:</p> <pre><code>text = “Hello Python” f.write(text) ## or f.write(“Hello Python”) </code></pre> <p>After doing all our required operations, we need to close the file. The command to close the file is as follows:</p> <pre><code>f.close() </code></pre> <p>This will save the file and close it. Now lets see how to read a file.</p> <pre><code>f = open(‘filename.txt’, ‘r’) </code></pre> <p>Same like write, but only the mode is changed to ‘r’. Now we have opened a file named filename, in read mode. Read mode is indicated using ‘r’. If a file of that particular name is not present then an error will be raised</p> <pre><code>Traceback (most recent call last): File "", line 1, in IOError: [Errno 2] No such file or directory: 'filename.txt' </code></pre> <p>If the file is present, then it would create an object of that particular file and we can do all our operations on that particular object. Now we have created an object for reading. The command to read is:</p> <pre><code>text = f.read() print text </code></pre> <p>All the contents of the file object is now read and stored in the variable text. Text holds the entire contents of the file.</p> <p>After doing all our required operations, we need to close the file. The command to close the file is as follows:</p> <pre><code>f.close() </code></pre> <p>In the above examples we have opened the file separately and close it separately, there is a better way to do it using with function. The modified code will be</p> <pre><code>with open(‘filename.txt’, ‘r’) as f: text = f.read() print text </code></pre> <p>When it comes out of the with block it will automatically close the file.</p>
0
2016-09-19T13:18:17Z
[ "python" ]
How can I manipulate an array declared as `self.tab[('_',0)]` without explicitly knowing what it contains?
39,571,169
<p>I am writing a code in python that will be reading each character from a file and save its number of occurrences. As it is a homework assignement, I am not allowed to change the way the array was declared.</p> <p>The array was declared in this way:</p> <pre><code> def __init__(self): self.tab = [('_', 0)] * 100 self.size = 0 </code></pre> <p>Now, every time I read a character, I check wheter I already had noticed it or not:</p> <pre><code> def add(self, c): # c is the character that was read for i in range(0,self.size): if self.tab[i] == (c, ): # this is where my problem occurs. #How should should I check if the #character given as an argument is #present in the array I declared #before? self.tab[i] = ? #Here I want to add 1 to the number #of occurrences of the character. #How should I do it? else: pass </code></pre> <p>As I said in the question, I don't know what the character equals to and what is the number does the second column equals to. I want to be able to add 1 to the number of occurrences without knowing how many occurrences there was.</p> <p>I don't expect an answer that will give me the exact solution to my particular situation. All I need is a set of rules and exemples on how to work in such cases. </p>
2
2016-09-19T10:40:18Z
39,572,005
<p>To check if your character is already present in the tab, you can use something like:</p> <pre><code>found_char = [arr_item for arr_item in self.tab if arr_item[0]==c] </code></pre> <p>and check the returned value:</p> <pre><code>if found_char == []: # add a new entry in your tab using the self.size attribute. else: # use self.tab.index(...) to find the corresponding tupple in self.tab and # replace it by a modified one as tupple are immutable. </code></pre>
0
2016-09-19T11:23:16Z
[ "python", "arrays" ]
How can I manipulate an array declared as `self.tab[('_',0)]` without explicitly knowing what it contains?
39,571,169
<p>I am writing a code in python that will be reading each character from a file and save its number of occurrences. As it is a homework assignement, I am not allowed to change the way the array was declared.</p> <p>The array was declared in this way:</p> <pre><code> def __init__(self): self.tab = [('_', 0)] * 100 self.size = 0 </code></pre> <p>Now, every time I read a character, I check wheter I already had noticed it or not:</p> <pre><code> def add(self, c): # c is the character that was read for i in range(0,self.size): if self.tab[i] == (c, ): # this is where my problem occurs. #How should should I check if the #character given as an argument is #present in the array I declared #before? self.tab[i] = ? #Here I want to add 1 to the number #of occurrences of the character. #How should I do it? else: pass </code></pre> <p>As I said in the question, I don't know what the character equals to and what is the number does the second column equals to. I want to be able to add 1 to the number of occurrences without knowing how many occurrences there was.</p> <p>I don't expect an answer that will give me the exact solution to my particular situation. All I need is a set of rules and exemples on how to work in such cases. </p>
2
2016-09-19T10:40:18Z
39,572,083
<p>As I mentioned in the comment, this is <em>not</em> a great data structure to use for this problem. </p> <p>Firstly, tuples are immutable, i.e., they can't be updated. To change a string or integer in one of those <code>self.tab</code> tuples you basically need to create a new tuple and replace the original one. So there's really not much point in initialising the list with 100 tuples that are going to be discarded. Secondly, it's not efficient to do a linear scan over a list to look for matching characters.</p> <p>The sensible way to do this task in Python would be to use the Counter class defined in the collections module. However, it's also quite easy to implement this using a plain dictionary, or a defaultdict.</p> <p>But anyway, here's one way to do it using the data structure given in the question.</p> <pre><code>class CharCounter(object): def __init__(self): self.tab = [('_', 0)] * 100 self.size = 0 def add(self, c): # c is the character that was read for i in range(1 + self.size): ch, count = self.tab[i] if ch == c: self.tab[i] = (c, count + 1) break else: self.tab[self.size] = (c, 1) self.size += 1 # test counter = CharCounter() for c in 'this is a test': counter.add(c) for i in range(counter.size): print(i, counter.tab[i]) </code></pre> <p><strong>output</strong></p> <pre><code>0 ('t', 3) 1 ('h', 1) 2 ('i', 2) 3 ('s', 3) 4 (' ', 3) 5 ('a', 1) 6 ('e', 1) </code></pre> <p>Note that this code does <em>not</em> add any <code>_</code> chars found in the input. Presumably, <code>_</code> is being used to indicate an empty table slot; it would be more usual in Python to use an empty string, <code>None</code>, or perhaps a sentinel object (eg an instance of <code>object</code>).</p>
4
2016-09-19T11:27:42Z
[ "python", "arrays" ]
Scraping data from interactive graph
39,571,193
<p>There is a <a href="https://opensignal.com/reports/2016/02/state-of-lte-q4-2015/" rel="nofollow">website</a> with a couple of interactive charts from which I would like to extract data. I've written a couple of web scrapers before in python using selenium webdriver, but this seems to be a different problem. I've looked at a couple of similar questions on stackoverflow. From those it seems that the solution could be to download data directly from a json file. I looked at the source code of the website and identified a couple of json files, but upon inspection they don't seem to contain the data.</p> <p>Does anyone know how to download the data from those graphs? In particular I am interested in this bar chart: <code>.//*[@id='network_download']</code></p> <p>Thanks</p> <p>edit: I should add that when I inspected the website using Firebug I saw that itis possible to get data in the following format. But this is obviously not helpful as it doesn't include any labels.</p> <pre><code>&lt;circle fill="#8CB1AA" cx="713.4318516666667" cy="5.357142857142858" r="4.5" style="opacity: 0.983087;"&gt; &lt;circle fill="#8CB1AA" cx="694.1212663333334" cy="10.714285714285715" r="4.5" style="opacity: 0.983087;"&gt; &lt;circle fill="#CEA379" cx="626.4726493333333" cy="16.071428571428573" r="4.5" style="opacity: 0.983087;"&gt; &lt;circle fill="#B0B359" cx="613.88416" cy="21.42857142857143" r="4.5" style="opacity: 0.983087;"&gt; &lt;circle fill="#D1D49E" cx="602.917665" cy="26.785714285714285" r="4.5" style="opacity: 0.983087;"&gt; &lt;circle fill="#A5E0B5" cx="581.5437366666666" cy="32.142857142857146" r="4.5" style="opacity: 0.983087;"&gt; </code></pre>
0
2016-09-19T10:41:51Z
39,650,363
<p>SVG charts like this tend to be a bit tough to scrape. The numbers you want aren't displayed until you actually hover the individual elements with your mouse.</p> <p>To get the data you need to</p> <ol> <li>Find a list of all dots</li> <li>For each dot in dots_list, click or hover (action chains) the dot</li> <li>Scrape the values in the tooltip that pops up</li> </ol> <p>This works for me:</p> <pre><code>from __future__ import print_function from pprint import pprint as pp from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains def main(): driver = webdriver.Chrome() ac = ActionChains(driver) try: driver.get("https://opensignal.com/reports/2016/02/state-of-lte-q4-2015/") dots_css = "div#network_download g g.dots_container circle" dots_list = driver.find_elements_by_css_selector(dots_css) print("Found {0} data points".format(len(dots_list))) download_speeds = list() for index, _ in enumerate(dots_list, 1): # Because this is an SVG chart, and because we need to hover it, # it is very likely that the elements will go stale as we do this. For # that reason we need to require each dot element right before we click it single_dot_css = dots_css + ":nth-child({0})".format(index) dot = driver.find_element_by_css_selector(single_dot_css) dot.click() # Scrape the text from the popup popup_css = "div#network_download div.tooltip" popup_text = driver.find_element_by_css_selector(popup_css).text pp(popup_text) rank, comp_and_country, speed = popup_text.split("\n") company, country = comp_and_country.split(" in ") speed_dict = { "rank": rank.split(" Globally")[0].strip("#"), "company": company, "country": country, "speed": speed.split("Download speed: ")[1] } download_speeds.append(speed_dict) # Hover away from the tool tip so it clears hover_elem = driver.find_element_by_id("network_download") ac.move_to_element(hover_elem).perform() pp(download_speeds) finally: driver.quit() if __name__ == "__main__": main() </code></pre> <p>Sample Output:</p> <pre><code>(.venv35) ➜ stackoverflow python svg_charts.py Found 182 data points '#1 Globally\nSingTel in Singapore\nDownload speed: 40 Mbps' '#2 Globally\nStarHub in Singapore\nDownload speed: 39 Mbps' '#3 Globally\nSaskTel in Canada\nDownload speed: 35 Mbps' '#4 Globally\nOrange in Israel\nDownload speed: 35 Mbps' '#5 Globally\nolleh in South Korea\nDownload speed: 34 Mbps' '#6 Globally\nVodafone in Romania\nDownload speed: 33 Mbps' '#7 Globally\nVodafone in New Zealand\nDownload speed: 32 Mbps' '#8 Globally\nTDC in Denmark\nDownload speed: 31 Mbps' '#9 Globally\nT-Mobile in Hungary\nDownload speed: 30 Mbps' '#10 Globally\nT-Mobile in Netherlands\nDownload speed: 30 Mbps' '#11 Globally\nM1 in Singapore\nDownload speed: 29 Mbps' '#12 Globally\nTelstra in Australia\nDownload speed: 29 Mbps' '#13 Globally\nTelenor in Hungary\nDownload speed: 29 Mbps' &lt;...&gt; [{'company': 'SingTel', 'country': 'Singapore', 'rank': '1', 'speed': '40 Mbps'}, {'company': 'StarHub', 'country': 'Singapore', 'rank': '2', 'speed': '39 Mbps'}, {'company': 'SaskTel', 'country': 'Canada', 'rank': '3', 'speed': '35 Mbps'} ... ] </code></pre> <p>It should be noted that the values you referenced in the question, in the circle elements, aren't particularly useful, as those just specify how to draw the dots within the SVG chart.</p>
0
2016-09-22T23:30:53Z
[ "python", "json", "selenium" ]
Python multiprocess lists of images
39,571,222
<p>I want to use multi process to stack many images. Each stack consists of 5 images, which means I have a list of images with a sublist of the images which should be combined:</p> <blockquote> <p>img_lst = [[01_A, 01_B, 01_C, 01_D, 01_E], [02_A, 02_B, 02_C, 02_D, 02_E], [03_A, 03_B, 03_C, 03_D, 03_E]]</p> </blockquote> <p>At them moment I call my function do_stacking(sub_lst) with a loop:</p> <pre><code>for sub_lst in img_lst: # example: do_stacking([01_A, 01_B, 01_C, 01_D, 01_E]) do_stacking(sub_lst) </code></pre> <p>I want to speed up with multiprocessing but I am not sure how to call pool.map function:</p> <pre><code>if __name__ == '__main__': from multiprocessing import Pool # I store my lists in a file f_in = open(stacking_path + "stacks.txt", 'r') f_stack = f_in.readlines() for data in f_stack: data = data.strip() data = data.split('\t') # data is now my sub_lst # Not sure what to do here, set the sublist, f_stack? pool = Pool() pool.map(do_stacking, ???) pool.close() pool.join() </code></pre> <p><strong>Edit</strong>:</p> <p>I have a list of list:</p> <p>[</p> <p>[01_A, 01_B, 01_C, 01_D, 01_E],</p> <p>[02_A, 02_B, 02_C, 02_D, 02_E], </p> <p>[03_A, 03_B, 03_C, 03_D, 03_E]</p> <p>]</p> <p>Each sublist should be passed to a function called do_stacking(sublist). I only want to proceed with the sublist and not with the entire list.</p> <p>My question is how to handle the loop of the list (for x in img_lst)? Should I create a loop for each Pool?</p>
0
2016-09-19T10:43:38Z
39,571,704
<p><code>Pool.map</code> works like the builtin <code>map</code> function.It fetch one element from the second argument each time and pass it to the function that represent by the first argument.</p> <pre><code>if __name__ == '__main__': from multiprocessing import Pool # I store my lists in a file f_in = open(stacking_path + "stacks.txt", 'r') f_stack = f_in.readlines() img_list = [] for data in f_stack: data = data.strip() data = data.split('\t') # data is now my sub_lst img_list.append(data) print img_list # check if the img_list is right? # Not sure what to do here, set the sublist, f_stack? pool = Pool() pool.map(do_stacking, img_list) pool.close() pool.join() </code></pre>
1
2016-09-19T11:07:28Z
[ "python", "multiprocessing" ]
HTML/CSS center for all resolutions without % (percentage)
39,571,232
<p>I was wondering, is it possible to make this central box be "in the very" center of the page without using %?</p> <p>I'm using VPS and I have some Python going on there, so I don't know how to use % sizes in order to get it right. But this is how far I came up only to hear that this isn't centered on 1280x1024:</p> <p><a href="https://s18.postimg.org/vta0qfd5l/2809583a0f43627d0fc1b428863b3faa.jpg" rel="nofollow">https://s18.postimg.org/vta0qfd5l/2809583a0f43627d0fc1b428863b3faa.jpg</a></p> <p>This is the code I have used:</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-css lang-css prettyprint-override"><code>h2 { margin: 0; } body { background-color: #121212; background-image: url("https://app.box.com/shared/static/vgfs65li424fk8h4n5e23pm7070yrewq.jpg"); background-size: contain; background-repeat: no-repeat; background-attachment: fixed; background-position: center; background-height: auto; max width: 1200px; } table { display: inline-block; position: absolute; max-width: 350px; max-height: 265px; border: 5px ridge yellow; top: 0; bottom: 0; margin: auto; left: 0; right: 0; padding-left: 90px; padding-right: 90px; background: rgba(255, 255, 255, 0.8); } div { text-align: center; align: center; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;table&gt; &lt;/table&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>So, any idea what I can improve to "nail it"? I've noticed that if I add more to max-width complete box moves to the left. Maybe if I can solve this, I would solve the first problem as well?</p> <p>This question is unique because I can't use percentage in order to align table properly, so I just want to know if this is possible at all.</p> <p>Thanks!</p>
0
2016-09-19T10:44:14Z
39,571,417
<p>You can position it using absolute positions in CSS and measurements in px. If you are using Jquery then you can get the document sizes using</p> <pre><code>$(document).height(); $(document).width(); </code></pre> <p>or $(window).height(); // for the viewport.</p> <p>Some quick JavaScript calculations should allow you to dynamically position something anywhere you want. Don't forget to bind .resize() events to adapt to user adjusting browser size. Heres a nice article on getting window sizes etc.</p> <p><a href="https://andylangton.co.uk/blog/development/get-viewportwindow-size-width-and-height-javascript" rel="nofollow">https://andylangton.co.uk/blog/development/get-viewportwindow-size-width-and-height-javascript</a></p>
0
2016-09-19T10:54:17Z
[ "python", "html", "css", "center" ]
HTML/CSS center for all resolutions without % (percentage)
39,571,232
<p>I was wondering, is it possible to make this central box be "in the very" center of the page without using %?</p> <p>I'm using VPS and I have some Python going on there, so I don't know how to use % sizes in order to get it right. But this is how far I came up only to hear that this isn't centered on 1280x1024:</p> <p><a href="https://s18.postimg.org/vta0qfd5l/2809583a0f43627d0fc1b428863b3faa.jpg" rel="nofollow">https://s18.postimg.org/vta0qfd5l/2809583a0f43627d0fc1b428863b3faa.jpg</a></p> <p>This is the code I have used:</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-css lang-css prettyprint-override"><code>h2 { margin: 0; } body { background-color: #121212; background-image: url("https://app.box.com/shared/static/vgfs65li424fk8h4n5e23pm7070yrewq.jpg"); background-size: contain; background-repeat: no-repeat; background-attachment: fixed; background-position: center; background-height: auto; max width: 1200px; } table { display: inline-block; position: absolute; max-width: 350px; max-height: 265px; border: 5px ridge yellow; top: 0; bottom: 0; margin: auto; left: 0; right: 0; padding-left: 90px; padding-right: 90px; background: rgba(255, 255, 255, 0.8); } div { text-align: center; align: center; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;table&gt; &lt;/table&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>So, any idea what I can improve to "nail it"? I've noticed that if I add more to max-width complete box moves to the left. Maybe if I can solve this, I would solve the first problem as well?</p> <p>This question is unique because I can't use percentage in order to align table properly, so I just want to know if this is possible at all.</p> <p>Thanks!</p>
0
2016-09-19T10:44:14Z
39,573,142
<p>If your page is served as a HTML webpage, you <em>should</em> be able to use JS, HTML, and CSS without your backend mucking it up. If you apply the following styles to <strong>any</strong> element, it will be centered:</p> <pre><code> position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); </code></pre> <p>There were some errors as well which would pretty much frag the remaining styles you might've expected:</p> <pre><code>background-height </code></pre> <p>Does not exist.</p> <pre><code>min width: </code></pre> <p>should be:</p> <pre><code>&gt; min-width: </code></pre> <p>and</p> <pre><code>align: center; </code></pre> <p>doesn't exist either.</p> <p>In this Snippet I corrected the previously mentioned errors and refactored a substantial amount. You have a div framing the table, so it made more sense to center the div and make sure that the table stays within the div. Let me know if I'm close to expected results or not.</p> <h3>SNIPPET 1</h3> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>h2 { margin: 0; } body { background-color: #121212; background-image: url("https://app.box.com/shared/static/vgfs65li424fk8h4n5e23pm7070yrewq.jpg"); background-size: contain; background-repeat: no-repeat; background-attachment: fixed; background-position: center; height: auto; max-width: 1200px; } table { position: absolute; top: 0; left: 0; margin: 0 auto; background: rgba(255, 255, 255, 0.8); width: 100%; height: 100%; } div { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 100%; height: 100%; max-width: 350px; max-height: 265px; border: 5px ridge yellow; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;table&gt; &lt;/table&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>This solution should work, but if you insist on not using percentages for reasons beyond my comprehension, then consider the viewport measurement unit.</p> <pre><code>100vw = 100% of viewport width 100vh = 100% of viewport height </code></pre> <p>The big difference between percentage unit of measure and viewport unit of measure is that percentage lengths are determined by whatever contains the subject element being measured. While a viewport length is determined by the dimensions of your viewable area of the screen. See the following Snippet to see the difference, view it in full page mode and resize to test the demonstration at different dimensions. For more on <code>vw</code> and <code>vh</code> refer to this <a href="http://thenewcode.com/660/Using-vw-and-vh-Measurements-In-Modern-Site-Design" rel="nofollow">article</a>.</p> <h3>SNIPPET 2</h3> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background: black; color: white; } #A { border: 3px dotted red; width: 500px; height: 250px; background: rgba(255, 0, 0, .4); } #B { border: 2px dashed blue; width: 50%; height: 50%; background: rgba(0, 0, 255, .4); } #C { border: 2px dashed yellow; width: 50vw; height: 50vh; background: rgba(0, 255, 255, .4); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p&gt;Viewable area of browser is viewport. View this in Full page mode and resize the browser at various sizes. Div B (blue) doesn't change. Div C (yellow) does.&lt;/p&gt; &lt;div id='A'&gt; A width: 500px height: 250px &lt;div id='B'&gt;B width: 50% height: 50%&lt;/div&gt; &lt;div id='C'&gt;C width: 50vw height: 50vh&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
1
2016-09-19T12:26:06Z
[ "python", "html", "css", "center" ]
HTML/CSS center for all resolutions without % (percentage)
39,571,232
<p>I was wondering, is it possible to make this central box be "in the very" center of the page without using %?</p> <p>I'm using VPS and I have some Python going on there, so I don't know how to use % sizes in order to get it right. But this is how far I came up only to hear that this isn't centered on 1280x1024:</p> <p><a href="https://s18.postimg.org/vta0qfd5l/2809583a0f43627d0fc1b428863b3faa.jpg" rel="nofollow">https://s18.postimg.org/vta0qfd5l/2809583a0f43627d0fc1b428863b3faa.jpg</a></p> <p>This is the code I have used:</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-css lang-css prettyprint-override"><code>h2 { margin: 0; } body { background-color: #121212; background-image: url("https://app.box.com/shared/static/vgfs65li424fk8h4n5e23pm7070yrewq.jpg"); background-size: contain; background-repeat: no-repeat; background-attachment: fixed; background-position: center; background-height: auto; max width: 1200px; } table { display: inline-block; position: absolute; max-width: 350px; max-height: 265px; border: 5px ridge yellow; top: 0; bottom: 0; margin: auto; left: 0; right: 0; padding-left: 90px; padding-right: 90px; background: rgba(255, 255, 255, 0.8); } div { text-align: center; align: center; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;table&gt; &lt;/table&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>So, any idea what I can improve to "nail it"? I've noticed that if I add more to max-width complete box moves to the left. Maybe if I can solve this, I would solve the first problem as well?</p> <p>This question is unique because I can't use percentage in order to align table properly, so I just want to know if this is possible at all.</p> <p>Thanks!</p>
0
2016-09-19T10:44:14Z
39,577,817
<p>thank you for your help, but I talked to a friend meanwhile and we came up to satisfying solution, so here's the final code and what we did</p> <ol> <li>I removed the table from the body and other non-necessary items (forgive me, as I'm a newbie)</li> <li>Instead of max height and width we used height and width - we had to fine tune height so that all browsers can display content properly and I have tested this out on cellphone, iPad, several monitors, everything is shown in a way I would like to.</li> <li>Except for IE8... but honestly, it doesn't matter :)</li> </ol> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>&lt;style&gt;h2 { margin: 0; } body { background-color: #121212; background-image: url("https://app.box.com/shared/static/vgfs65li424fk8h4n5e23pm7070yrewq.jpg"); background-size: contain; background-repeat: no-repeat; background-attachment: fixed; background-position: center; } .FormBody { display: inline-block; position: absolute; width: 380px; height: 305px; border: 5px ridge gold; top: 0; bottom: 0; margin: auto; left: 0; right: 0; padding-left: 90px; padding-right: 90px; text-align: center; background: rgba(255, 255, 255, 0.8); } &lt;/style&gt;</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;meta charset="utf-8"&gt; &lt;head&gt; &lt;title&gt;CTLServer REGISTRACIJA&lt;/title&gt; &lt;/head&gt; &lt;script src="/md5.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script&gt; function makeHash() { a = document.getElementById('serial').value; a = a.replace(/^\s+/, '').replace(/\s+$/, '').replace(/-/g, '').toUpperCase(); if (!a.match(/^[A-Z0-9]{20}$/)) { alert('Neispravan serijski broj.'); return false; } document.getElementById('serial').value = a; while (a.length &lt; 36) { a += '\0'; } u = document.getElementById('username').value; u = u.replace(/^\s+/, '').replace(/\s+$/, ''); if (u.length &lt; 3 || !u.match(/^[0-9a-zA-Z]+$/)) { alert('Zabranjeno ime za korisnika - dozvoljeno 3-36 alfa-numerička znaka (0-9 | a-z | A-Z).'); return false; } p = document.getElementById('password').value; if (p.length &lt; 3) { alert('Lozinka je kratka - minimum 3 alfa-numerička znaka (0-9 | a-z | A-Z)'); return false; } document.getElementById('hash').value = hex_md5(a + u + '-' + p); return true; } &lt;/script&gt; &lt;div class="FormBody"&gt; &lt;br /&gt; &lt;h2&gt;&lt;u&gt;• CTLServer REGISTRACIJA •&lt;/h2&gt; &lt;/u&gt; &lt;strong&gt;&lt;a href="https://app.box.com/shared/static/krtchlikkjw48u21aywx"&gt;LINK za HOST&lt;/a&gt;&lt;br /&gt;&lt;/strong&gt; &lt;br /&gt; &lt;form name="registration" action="/register" method="POST"&gt; &lt;input type="hidden" name="nonce" id="nonce" value="%(nonce)s" /&gt; &lt;input type="hidden" name="hash" id="hash" size="32" value="" /&gt; &lt;strong&gt;Serijski Broj:&lt;/strong&gt; &lt;br /&gt; &lt;input type="text" name="serial" id="serial" size="40" value="%(serial)s" onkeydown="if (event.keyCode == 13) {document.getElementById('btnGen').click(); return false;}" /&gt; &lt;br /&gt; &lt;br /&gt; &lt;strong&gt;Korisničko Ime:&lt;/strong&gt; &lt;br /&gt; &lt;input type="text" name="user" id="username" size="40" value="%(username)s" onkeydown="if (event.keyCode == 13) {document.getElementById('btnGen').click(); return false;}" /&gt; &lt;br /&gt; &lt;/form&gt; &lt;strong&gt;Lozinka:&lt;/strong&gt; &lt;br /&gt; &lt;input type="password" id="password" size="40" value="" onkeydown="if (event.keyCode == 13) {document.getElementById('btnGen').click(); return false;}" /&gt; &lt;br /&gt; &lt;p&gt; &lt;input class="button" type="button" id="btnGen" value="Registruj se" onclick="if (makeHash()) {document.forms['registration'].submit();}" /&gt; &lt;/p&gt; &lt;/div&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>So once again, thanks for all your help, especially @zer00ne I will definitely read your post briefly couple of times as I think there is a lot I can understand from there. And as a matter of fact I think I'm gonna try other methods as well, just to make it work in case I'm gonna need them at some point.</p>
0
2016-09-19T16:27:13Z
[ "python", "html", "css", "center" ]
Django forms: Error message display all the time, not only after errors
39,571,245
<p>I'm building my own site with Django's Framework. I made a form for creating a new account. It works well but I have a problem with my errors messages.</p> <p>All my errors are already display when I first arrive on the page. After submit, if a field is wrong, the page newly updated display only the wanted messages.</p> <p><a href="http://i.stack.imgur.com/tfOkK.png" rel="nofollow">Here is a view of my page at my first arrival</a></p> <p>So, my question is: How can I do for display the message only if a field is wrong ? I already succeed to personalize each messages.</p> <p>I paste you my different django files:</p> <p><strong>views.py</strong></p> <pre><code>@csrf_exempt def create_new_user(request): form = UserCreateForm(request.POST) if request.method=="POST": if form.is_valid(): user = form.save() messages.info(request, "Merci pour votre enregistrement, vous etes maintenant connecte") new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'] ) login(request, new_user) return HttpResponseRedirect('/') return render_to_response('lejeudesbars/register.html', RequestContext(request, {'form': form})) else: return render(request, 'lejeudesbars/register.html', {'form': form}) </code></pre> <p><strong>forms.py</strong></p> <pre><code>class UserCreateForm(UserCreationForm): captcha = ReCaptchaField(error_messages={'required': 'Captcha: Validation obligatoire'}) email = forms.EmailField(required=True) username = forms.CharField(error_messages={'required': 'Pseudo: Champ obligatoire'}) email = forms.EmailField(error_messages={'required': 'Email: Champ obligatoire'}) password1 = forms.CharField(widget=forms.PasswordInput(), error_messages={'required': 'Mot de passe: Champ obligatoire'}) password2 = forms.CharField(widget=forms.PasswordInput(), error_messages={'required': 'Mot de passe: Confirmation obligatoire'}) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(UserCreateForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() return user` </code></pre> <p><strong>index.html</strong></p> <pre><code> &lt;form method="post" action="/accounts/register/"&gt; {% csrf_token %} &lt;h1&gt;S'enregistrer&lt;/h1&gt; {{ form.username }} {% if form.errors %} &lt;p class="error-msg-register"&gt;{{ form.username.errors }}&lt;/p&gt; {% endif %} {{ form.email }} {% if form.errors %} &lt;p class="error-msg-register"&gt;{{ form.email.errors }}&lt;/p&gt; {% endif %} {{ form.password1 }} {% if form.errors %} &lt;p class="error-msg-register"&gt;{{ form.password1.errors }}&lt;/p&gt; {% endif %} {{ form.password2 }} {% if form.errors %} &lt;p class="error-msg-register"&gt;{{ form.password2.errors }}&lt;/p&gt; {% endif %} {{ form.captcha }} {% if form.errors %} &lt;p class="error-msg-register"&gt;{{ form.captcha.errors }}&lt;/p&gt; {% endif %} &lt;input style="padding: 10px" type="submit" value="Créer mon compte" /&gt; &lt;input type="hidden" name="next" value="{{ next }}" /&gt; &lt;/form&gt;` </code></pre> <p>Thank you in advance for helping me !</p> <p>(sorry for my bad english)</p> <hr> <p>Thanks to Daniel Roseman, I've resolved my problem. Here is my updated views.py:</p> <p><strong>views.py</strong></p> <pre><code>@csrf_exempt def create_new_user(request): if request.method=="POST": form = UserCreateForm(request.POST) if form.is_valid(): user = form.save() messages.info(request, "Merci pour votre enregistrement, vous etes maintenant connecte") new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'] ) login(request, new_user) else: form = UserCreateForm() return render(request, 'lejeudesbars/register.html', {'form': form}) </code></pre>
0
2016-09-19T10:44:59Z
39,571,297
<p>In each field you have {% if form.errors %} - so when there is at least one error, you are going to display it everywhere.</p> <p>change it to <code>{% if form.field_name.errors %}</code> and then html should render only the errors associated with that specific field</p>
0
2016-09-19T10:47:49Z
[ "python", "django", "forms" ]
Django forms: Error message display all the time, not only after errors
39,571,245
<p>I'm building my own site with Django's Framework. I made a form for creating a new account. It works well but I have a problem with my errors messages.</p> <p>All my errors are already display when I first arrive on the page. After submit, if a field is wrong, the page newly updated display only the wanted messages.</p> <p><a href="http://i.stack.imgur.com/tfOkK.png" rel="nofollow">Here is a view of my page at my first arrival</a></p> <p>So, my question is: How can I do for display the message only if a field is wrong ? I already succeed to personalize each messages.</p> <p>I paste you my different django files:</p> <p><strong>views.py</strong></p> <pre><code>@csrf_exempt def create_new_user(request): form = UserCreateForm(request.POST) if request.method=="POST": if form.is_valid(): user = form.save() messages.info(request, "Merci pour votre enregistrement, vous etes maintenant connecte") new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'] ) login(request, new_user) return HttpResponseRedirect('/') return render_to_response('lejeudesbars/register.html', RequestContext(request, {'form': form})) else: return render(request, 'lejeudesbars/register.html', {'form': form}) </code></pre> <p><strong>forms.py</strong></p> <pre><code>class UserCreateForm(UserCreationForm): captcha = ReCaptchaField(error_messages={'required': 'Captcha: Validation obligatoire'}) email = forms.EmailField(required=True) username = forms.CharField(error_messages={'required': 'Pseudo: Champ obligatoire'}) email = forms.EmailField(error_messages={'required': 'Email: Champ obligatoire'}) password1 = forms.CharField(widget=forms.PasswordInput(), error_messages={'required': 'Mot de passe: Champ obligatoire'}) password2 = forms.CharField(widget=forms.PasswordInput(), error_messages={'required': 'Mot de passe: Confirmation obligatoire'}) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(UserCreateForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() return user` </code></pre> <p><strong>index.html</strong></p> <pre><code> &lt;form method="post" action="/accounts/register/"&gt; {% csrf_token %} &lt;h1&gt;S'enregistrer&lt;/h1&gt; {{ form.username }} {% if form.errors %} &lt;p class="error-msg-register"&gt;{{ form.username.errors }}&lt;/p&gt; {% endif %} {{ form.email }} {% if form.errors %} &lt;p class="error-msg-register"&gt;{{ form.email.errors }}&lt;/p&gt; {% endif %} {{ form.password1 }} {% if form.errors %} &lt;p class="error-msg-register"&gt;{{ form.password1.errors }}&lt;/p&gt; {% endif %} {{ form.password2 }} {% if form.errors %} &lt;p class="error-msg-register"&gt;{{ form.password2.errors }}&lt;/p&gt; {% endif %} {{ form.captcha }} {% if form.errors %} &lt;p class="error-msg-register"&gt;{{ form.captcha.errors }}&lt;/p&gt; {% endif %} &lt;input style="padding: 10px" type="submit" value="Créer mon compte" /&gt; &lt;input type="hidden" name="next" value="{{ next }}" /&gt; &lt;/form&gt;` </code></pre> <p>Thank you in advance for helping me !</p> <p>(sorry for my bad english)</p> <hr> <p>Thanks to Daniel Roseman, I've resolved my problem. Here is my updated views.py:</p> <p><strong>views.py</strong></p> <pre><code>@csrf_exempt def create_new_user(request): if request.method=="POST": form = UserCreateForm(request.POST) if form.is_valid(): user = form.save() messages.info(request, "Merci pour votre enregistrement, vous etes maintenant connecte") new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'] ) login(request, new_user) else: form = UserCreateForm() return render(request, 'lejeudesbars/register.html', {'form': form}) </code></pre>
0
2016-09-19T10:44:59Z
39,571,358
<p>You should only pass request.POST into the field if it actually is a POST. So:</p> <pre><code>def create_new_user(request): if request.method=="POST": form = UserCreateForm(request.POST) if form.is_valid(): ... else: form = UserCreateForm() return render(request, 'lejeudesbars/register.html', {'form': form}) </code></pre> <p>You also don't need that intermediate <code>return render_to_response(...)</code>.</p>
3
2016-09-19T10:51:14Z
[ "python", "django", "forms" ]
BadRequestError: BLOB, ENITY_PROTO or TEXT property concise_topics must be in a raw_property field
39,571,299
<p>Here is the code for my model. </p> <pre><code>from google.appengine.ext import ndb from modules.admin.models.Author import Author from modules.hod.models.Concept import Concept class Post(ndb.Model): author_key = ndb.KeyProperty(kind=Author) content = ndb.StringProperty(indexed=False) created = ndb.DateTimeProperty(auto_now_add=True) title = ndb.StringProperty(indexed=True) topics = ndb.StructuredProperty(Concept, repeated=True) def get_important_topics(self): return filter(lambda x: x.occurrences &gt; 1, self.topics) concise_topics = ndb.ComputedProperty(get_important_topics, repeated=True) </code></pre> <p>Here is the route which creates the model.</p> <pre><code>@admin_home_routes.route('/SavePost', methods=['POST']) @authenticate_admin def save_new_post(): post_data = request.form['newpost'] new_post = Post(parent=posts_key()) author = get_author_by_email(users.get_current_user().email()) if len(author) &gt; 0: new_post.author_key = author[0].key else: author = Author(parent=author_key()) author.email = users.get_current_user().email() author.name = users.get_current_user().email() author.identity = users.get_current_user().user_id() key = author.put() new_post.author_key = key new_post.content = post_data concepts = get_topics(post_data) _concepts = [] if len(concepts) &gt; 0: for concept in concepts['concepts']: temp_concept = Concept(name=concept['concept'], occurrences=concept['occurrences']) _concepts.append(temp_concept) new_post.topics = _concepts new_post.put() return redirect('/Admin/Posts') </code></pre> <p>The error I get is </p> <pre><code>WARNING 2016-09-19 20:44:47,227 urlfetch_stub.py:540] Stripped prohibited headers from URLFetch request: ['Host', 'Content-Length'] WARNING 2016-09-19 10:44:48,937 tasklets.py:468] suspended generator _put_tasklet(context.py:358) raised BadRequestError(BLOB, ENITY_PROTO or TEXT property concise_topics must be in a raw_property field) WARNING 2016-09-19 10:44:48,937 tasklets.py:468] suspended generator put(context.py:824) raised BadRequestError(BLOB, ENITY_PROTO or TEXT property concise_topics must be in a raw_property field) ERROR 2016-09-19 10:44:48,941 app.py:1587] Exception on /Admin/SavePost [POST] Traceback (most recent call last): File "C:\Code\zion-alpha\lib\flask\app.py", line 1988, in wsgi_app response = self.full_dispatch_request() File "C:\Code\zion-alpha\lib\flask\app.py", line 1641, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Code\zion-alpha\lib\flask\app.py", line 1544, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Code\zion-alpha\lib\flask\app.py", line 1639, in full_dispatch_request rv = self.dispatch_request() File "C:\Code\zion-alpha\lib\flask\app.py", line 1625, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "C:\Code\zion-alpha\modules\admin\decorators\authentication.py", line 16, in authenticate_and_call return func(*args, **kwargs) File "C:\Code\zion-alpha\modules\admin\routes\admin_routes.py", line 72, in save_new_post new_post.put() File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\ndb\model.py", line 3451, in _put return self._put_async(**ctx_options).get_result() File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\ndb\tasklets.py", line 383, in get_result self.check_success() File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\ndb\tasklets.py", line 427, in _help_tasklet_along value = gen.throw(exc.__class__, exc, tb) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\ndb\context.py", line 824, in put key = yield self._put_batcher.add(entity, options) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\ndb\tasklets.py", line 427, in _help_tasklet_along value = gen.throw(exc.__class__, exc, tb) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\ndb\context.py", line 358, in _put_tasklet keys = yield self._conn.async_put(options, datastore_entities) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\ndb\tasklets.py", line 513, in _on_rpc_completion result = rpc.get_result() File "C:\Program Files (x86)\Google\google_appengine\google\appengine\api\apiproxy_stub_map.py", line 613, in get_result return self.__get_result_hook(self) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\datastore\datastore_rpc.py", line 1881, in __put_hook self.check_rpc_success(rpc) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\datastore\datastore_rpc.py", line 1373, in check_rpc_success raise _ToDatastoreError(err) BadRequestError: BLOB, ENITY_PROTO or TEXT property concise_topics must be in a raw_property field INFO 2016-09-19 20:44:49,036 module.py:788] default: "POST /Admin/SavePost HTTP/1.1" 500 291 INFO 2016-09-19 20:45:04,424 module.py:402] [default] Detected file changes: </code></pre>
0
2016-09-19T10:47:52Z
39,571,546
<p>I would use <code>_pre_put_hook</code> instead of <code>ComputedProperty</code></p> <pre><code>topics = ndb.StructuredProperty(Concept, repeated=True) concise_topics = ndb.StructuredProperty(Concept, repeated=True) def _pre_put_hook(self): self.concise_topics = filter(lambda x: x.occurrences &gt; 1, self.topics) </code></pre>
0
2016-09-19T11:00:14Z
[ "python", "python-2.7", "google-app-engine" ]
How can I use two keys with defaultdict?
39,571,543
<p>I am trying to create a defaultdict with nested keys. Here is the view that I wrote, but apparently multiple keys don't work in defaultdict.</p> <pre><code>def routine_view(request, klass_id): days = Routine.DAYS periods = Routine.PERIODS class_details = defaultdict(list) classes = Routine.objects.filter(klass_id=klass_id) for cls in classes: class_details[cls.day][cls.period].append(cls) context = { "days": days, "periods": periods, "class_details": class_details } return render(request, "routine/routine_view.html", context) </code></pre> <p>When I run this view I get the following error:</p> <pre><code>IndexError at /routine/1/ list index out of range </code></pre>
0
2016-09-19T11:00:04Z
39,571,619
<p>Your question isn't totally clear, but I think you want a defaultdict which itself contains a defaultdict of lists. So:</p> <pre><code>class_details = defaultdict(lambda: defaultdict(list)) </code></pre> <p>Alternatively, you may not need a nested dict at all; you could instead use the original defauldict with key that is a tuple:</p> <pre><code>class_details[(cls.day, cls.period)].append(cls) </code></pre>
1
2016-09-19T11:03:07Z
[ "python", "django", "defaultdict" ]
openpyxl: Gives error on load_workbook()
39,571,560
<p>The following code was executing fine, until I setup the development environment on a different computer. </p> <pre><code>workbook_obj = load_workbook(filename=xl_file, data_only=True, use_iterators=True) </code></pre> <p>I get the following error: </p> <pre><code>TypeError: load_workbook() got an unexpected keyword argument 'use_iterators' </code></pre> <p>A <code>pip freeze</code> command shows that I was using <code>openpyxl 2.3.5</code> previously when the code worked fine. My current version is <code>2.4.0</code>.</p> <p>Is this a bug in <code>openpyxl</code>? </p>
-1
2016-09-19T11:00:54Z
39,572,032
<p>The <code>use_iterators</code> keyword <a href="https://openpyxl.readthedocs.io/en/default/changes.html?highlight=use_iterators#id14" rel="nofollow">was removed</a> since 2.4.0. Use <code>read_only=True</code> instead.</p>
3
2016-09-19T11:24:37Z
[ "python", "openpyxl" ]
Post data from html to another html
39,571,659
<p>I want to post data from html to another html</p> <p>I know how to post data html->python and python-> html</p> <p>I have dictionary in the html (I get it from python - <code>return render_to_response('page.html', locals()</code>)</p> <p>how can I use with the dictionary in the second html file?</p>
0
2016-09-19T11:05:05Z
39,576,661
<p>you can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage" rel="nofollow">window.postMessage</a> and window.addEventListener as described in this <a href="http://stackoverflow.com/questions/13545883/can-i-communicate-between-two-local-html-files-using-javascript">example</a> .</p>
0
2016-09-19T15:18:07Z
[ "javascript", "python", "html" ]
Python sorting by attributes that can be None
39,571,738
<p>Let's say I have a list of items I want to sort: <code>items = [ item1, item2, item3 ]</code>. The attribute I want to use to sort them is <code>item.data.value</code>, so I'd normally go:</p> <pre><code>sorted(items, key=attrgetter('data.value')) </code></pre> <p>And that'd work just fine. However, <code>data</code> can actually be <code>None</code> so obviously I couldn't access <code>value</code>.</p> <p>How do you usually deal with scenarios like this?</p> <p>PS: neither <a href="http://stackoverflow.com/questions/12971631/sorting-list-by-an-attribute-that-can-be-none">this question</a> nor <a href="http://stackoverflow.com/questions/39085672/sorting-by-multiple-values-that-can-be-none">this one</a> helped.</p>
2
2016-09-19T11:09:01Z
39,571,933
<p>just filter for the None before sorting</p> <pre><code>sorted(filter(None, items), key=attrgetter('data.value')) </code></pre>
0
2016-09-19T11:19:06Z
[ "python", "python-2.7", "sorting" ]
Python sorting by attributes that can be None
39,571,738
<p>Let's say I have a list of items I want to sort: <code>items = [ item1, item2, item3 ]</code>. The attribute I want to use to sort them is <code>item.data.value</code>, so I'd normally go:</p> <pre><code>sorted(items, key=attrgetter('data.value')) </code></pre> <p>And that'd work just fine. However, <code>data</code> can actually be <code>None</code> so obviously I couldn't access <code>value</code>.</p> <p>How do you usually deal with scenarios like this?</p> <p>PS: neither <a href="http://stackoverflow.com/questions/12971631/sorting-list-by-an-attribute-that-can-be-none">this question</a> nor <a href="http://stackoverflow.com/questions/39085672/sorting-by-multiple-values-that-can-be-none">this one</a> helped.</p>
2
2016-09-19T11:09:01Z
39,571,937
<p>If you do not have a function handy that returns the key you want then just write your own.</p> <pre><code>def item_key(item): try: return item.data.value except AttributeError: return None sorted(items, key=item_key) </code></pre>
0
2016-09-19T11:19:14Z
[ "python", "python-2.7", "sorting" ]
Python sorting by attributes that can be None
39,571,738
<p>Let's say I have a list of items I want to sort: <code>items = [ item1, item2, item3 ]</code>. The attribute I want to use to sort them is <code>item.data.value</code>, so I'd normally go:</p> <pre><code>sorted(items, key=attrgetter('data.value')) </code></pre> <p>And that'd work just fine. However, <code>data</code> can actually be <code>None</code> so obviously I couldn't access <code>value</code>.</p> <p>How do you usually deal with scenarios like this?</p> <p>PS: neither <a href="http://stackoverflow.com/questions/12971631/sorting-list-by-an-attribute-that-can-be-none">this question</a> nor <a href="http://stackoverflow.com/questions/39085672/sorting-by-multiple-values-that-can-be-none">this one</a> helped.</p>
2
2016-09-19T11:09:01Z
39,571,950
<p>Just filter the None values first before sending them to sorted.</p> <pre><code>sorted(filter(None, items), key=attrgetter('data.value')) </code></pre> <p>And if you really want the None items too, you can do something like this:</p> <pre><code># items already defined with values new_items_list = sorted(filter(None, items), key=attrgetter('data.value')) new_items_list.extend([None] * (len(items) - len(new_items_list))) </code></pre> <p>However, I am not sure whether you really need the None items.</p> <p>EDIT: Fixed the end code which will retain the None items.</p>
0
2016-09-19T11:20:24Z
[ "python", "python-2.7", "sorting" ]
Python sorting by attributes that can be None
39,571,738
<p>Let's say I have a list of items I want to sort: <code>items = [ item1, item2, item3 ]</code>. The attribute I want to use to sort them is <code>item.data.value</code>, so I'd normally go:</p> <pre><code>sorted(items, key=attrgetter('data.value')) </code></pre> <p>And that'd work just fine. However, <code>data</code> can actually be <code>None</code> so obviously I couldn't access <code>value</code>.</p> <p>How do you usually deal with scenarios like this?</p> <p>PS: neither <a href="http://stackoverflow.com/questions/12971631/sorting-list-by-an-attribute-that-can-be-none">this question</a> nor <a href="http://stackoverflow.com/questions/39085672/sorting-by-multiple-values-that-can-be-none">this one</a> helped.</p>
2
2016-09-19T11:09:01Z
39,572,023
<pre><code>sorted(items, key=lambda i: i.data.value if i.data else 0) </code></pre>
0
2016-09-19T11:24:22Z
[ "python", "python-2.7", "sorting" ]
Python sorting by attributes that can be None
39,571,738
<p>Let's say I have a list of items I want to sort: <code>items = [ item1, item2, item3 ]</code>. The attribute I want to use to sort them is <code>item.data.value</code>, so I'd normally go:</p> <pre><code>sorted(items, key=attrgetter('data.value')) </code></pre> <p>And that'd work just fine. However, <code>data</code> can actually be <code>None</code> so obviously I couldn't access <code>value</code>.</p> <p>How do you usually deal with scenarios like this?</p> <p>PS: neither <a href="http://stackoverflow.com/questions/12971631/sorting-list-by-an-attribute-that-can-be-none">this question</a> nor <a href="http://stackoverflow.com/questions/39085672/sorting-by-multiple-values-that-can-be-none">this one</a> helped.</p>
2
2016-09-19T11:09:01Z
39,572,117
<p>Use as key a <em>tuple</em>, like <code>(False, value)</code>. If value is None, then the tuple should be <code>(True, None)</code>.</p> <p>Tuples are compared by their first element first, then the second, et cetera. False sorts before True. So all None values will be sorted to the end.</p> <pre><code>def none_to_end_key(item): value = item.data.value if item.data else None return (value is None, value) sorted(items, key=none_to_end_key) </code></pre> <p>Will sort all None values to the end.</p> <p>I see now that you have tagged your question Python-2.7, then this is probably overkill. In Python 3, comparing None to an integer or string raises an exception, so you can't simply sort a list with None and other values, and something like this is needed.</p>
2
2016-09-19T11:29:54Z
[ "python", "python-2.7", "sorting" ]
Find longest path with BFS
39,571,825
<p>I have a list with 794 three-letter long words. My task is to find the word(s) with the longest path to a given word. </p> <p><strong>Definition (children):</strong><br> Children to a parent word are the parent word with one and only one letter replaced. </p> <p><strong>Example:</strong><br> 'can', 'run', 'rap' etcetera are children to the word 'ran' (given that those words exist in the list).</p> <p><strong>Definition (path):</strong><br> A path is a series of words where each word is generated by exchanging a single letter in the previous.</p> <pre><code>#Pseudo code Given a word Put the word in a queue Keep a list with all visited words As long as the queue is not empty Get the first word in the queue Generate a list with all the children to this word For every children in that list If the child is not in the list of visited words Append the child to the list of visited words Put the child in the queue Print the path to the last grandchild. </code></pre> <p>My idea is that this will give the longest path since we continue to generate new children until we run out of possible children (that is, children that hasn't already been visited). </p> <p><strong>Question:</strong><br> Is my idea valid? How can I test if it actually works? </p> <hr> <p>The actual code can be viewed below, but it might not make any sense without comments. </p> <p><strong>Edit</strong><br> Since trees and lists can be a bit slow, I replaced them with sets. </p> <pre><code>from Queue import Queuenode; import Bintree with open('word3',encoding='utf-8') as f: lista=f.readlines() lista=[x.strip('\n') for x in lista] alfabet='abcdefghijklmnopqrstuvwxyzåäö' class Word: def __init__(self, w, f = None): self.word = w self.parent = f children=Bintree.Bintree() for i in lista: children.put(i) def barn(far): barnlista=[] for i in range(3): for j in range(29): empty='' empty+=far[0:i]+alfabet[j]+far[i+1:] if empty!=far and children._exists(empty): barnlista+=[empty] return barnlista ko=Queuenode() def vag(item): start=item counter=0 while start!=None: counter+=1 print(start.word) start=start.parent print(counter) def bfsx(startord): ko.put(Word(startord)) besokta=[startord] while not ko.isempty(): first=ko.get() lista=barn(first.word) for child in lista: if child not in besokta: besokta+=[child] ko.put(Word(child,first)) vag(first) </code></pre>
2
2016-09-19T11:13:48Z
39,572,240
<p>IIUC, this is not guaranteed to work (in fact, you can build cases where it doesn't).</p> <p>Suppose you start at node <em>a</em>; there is a direct path <em>a &rarr; b</em>; there are also a direct path <em>a &rarr; c</em> and an indirect path <em>c &rArr; b</em>. </p> <p>Suppose that when you iterate over the children of <em>a</em>, you encounter <em>b</em> before <em>c</em>. You deal with <em>b</em> and mark it as visited. At some point later you encounter <em>c</em>, and eventually reconsider <em>b</em> again. At that point, however, <em>b</em> is already considered visited, so your algorithm will consider the shorter subpath <em>a &rarr; b</em> rather than the longer one <em>a &rarr; c &rArr; b</em>. </p> <p>You cannot also get rid of the "visited" mark, as the story behind your graph makes it clear it is not a DAG. If you remove the "visited" logic, you will encounter infinite loops. </p>
1
2016-09-19T11:36:38Z
[ "python", "python-3.x", "python-3.5" ]
How to row-wise concatenate several columns containing strings?
39,571,832
<p>I have a specific series of datasets which come in the following general form:</p> <pre><code>import pandas as pd import random df = pd.DataFrame({'n': random.sample(xrange(1000), 3), 't0':['a', 'b', 'c'], 't1':['d','e','f'], 't2':['g','h','i'], 't3':['i','j', 'k']}) </code></pre> <p>The number of <em>tn</em> columns (<em>t0, t1, t2 ... tn</em>) <strong>varies depending on the dataset</strong>, but is always &lt;30. My aim is to merge content of the <em>tn</em> columns for each row so that I achieve this result (note that for readability I need to keep the whitespace between elements):</p> <pre><code>df['result'] = df.t0 +' '+df.t1+' '+df.t2+' '+ df.t3 </code></pre> <p><a href="http://i.stack.imgur.com/eEl4x.png" rel="nofollow"><img src="http://i.stack.imgur.com/eEl4x.png" alt="enter image description here"></a></p> <p>So far so good. This code may be simple but it becomes clumsy and inflexible as soon as I receive another dataset, where the number of <em>tn</em> columns goes up. This where my question comes in:</p> <p><strong>Is there any other syntax to merge the content across multiple columns?</strong> Something agnostic to the number columns, akin to:</p> <pre><code>df['result'] = ' '.join(df.ix[:,1:]) </code></pre> <p>Basically I want to achieve the same as the OP in the link below, but with whitespace between the strings: <a href="http://stackoverflow.com/questions/6308933/r-concatenate-row-wise-across-specific-columns-of-dataframe">R - concatenate row-wise across specific columns of dataframe</a></p>
3
2016-09-19T11:14:07Z
39,573,438
<p>Here is a slightly alternative solution:</p> <pre><code>In [57]: df['result'] = df.filter(regex=r'^t').apply(lambda x: x.add(' ')).sum(axis=1).str.strip() In [58]: df Out[58]: n t0 t1 t2 t3 result 0 92 a d g i a d g i 1 916 b e h j b e h j 2 363 c f i k c f i k </code></pre>
2
2016-09-19T12:39:40Z
[ "python", "pandas", "dataframe", "multiple-columns", "string-concatenation" ]
Size issues with Python shelve module
39,571,859
<p>I want to store a few dictionaries using the shelve module, however, I am running into a problem with the size. I use Python 3.5.2 and the latest shelve module.</p> <p>I have a list of words and I want to create a map from the bigrams (character level) to the words. The structure will look something like this:</p> <pre><code>'aa': 'aardvark', 'and', ... 'ab': 'absolute', 'dab', ... ... </code></pre> <p>I read in a large file consisting of approximately 1.3 million words. So the dictionary gets pretty large. This is the code:</p> <pre><code>self.bicharacters // part of class def _create_bicharacters(self): ''' Creates a bicharacter index for calculating Jaccard coefficient. ''' with open('wordlist.txt', encoding='ISO-8859-1') as f: for line in f: word = line.split('\t')[2] for i in range(len(word) - 1): bicharacter = (word[i] + word[i+1]) if bicharacter in self.bicharacters: get = self.bicharacters[bicharacter] get.append(word) self.bicharacters[bicharacter] = get else: self.bicharacters[bicharacter] = [word] </code></pre> <p>When I ran this code using a regular Python dictionary, I did not run into issues, but I can't spare those kinds of memory resources due to the rest of the program also having quite a large memory footprint. </p> <p>So I tried using the shelve module. However, when I run the code above using shelve the program stops after a while due to no more memory on disk, the shelve db that was created was around 120gb, and it had still not read even half the 1.3M word list from the file. What am I doing wrong here?</p>
0
2016-09-19T11:15:37Z
39,574,975
<p>The problem here is not so much the number of keys, but that each key references a list of words.</p> <p>While in memory as one (huge) dictionary, this isn't that big a problem as the words are simply shared between the lists; each list is simply a sequence of references to other objects and here many of those objects are the same, as only one string per word needs to be referenced.</p> <p>In <code>shelve</code>, however, each value is pickled and stored separately, meaning that a <em>concrete copy</em> of the words in a list will have to be stored <em>for each value</em>. Since your setup ends up adding a given word to a large number of lists, this multiplies your data needs rather drastically.</p> <p>I'd switch to using a SQL database here. Python comes with bundled with <a href="https://docs.python.org/3/library/sqlite3.html" rel="nofollow"><code>sqlite3</code></a>. If you create one table for individual words, and second table for each possible bigram, and a third that simply links between the two (a many-to-many mapping, linking bigram row id to word row id), this can be done very efficiently. You can then do very efficient lookups as SQLite is quite adept managing memory and indices for you.</p>
2
2016-09-19T13:55:23Z
[ "python", "dictionary", "shelve" ]
Part II: Counting how many times in a row the result of a sum is positive (or negative)
39,572,089
<p><strong>Second part</strong> First part can be found here: <a href="http://stackoverflow.com/questions/39514202/counting-how-many-times-in-a-row-the-result-of-a-sum-is-positive-or-negative">Click me</a></p> <p>Hi all, I have been practising with the gg function that you guys help me create -- see part one. Now, I realized that the output of the function are not unique series, yet a sum: for instance, a series of 3 positives in a row is also shown as 2 series of two positives in a row and as 3 single positives.</p> <p>Let's say I got this:</p> <pre><code>df = pd.DataFrame(np.random.rand(15, 2), columns=["open", "close"]) df['test'] = df.close-df.open &gt; 0 open close test 0 0.769829 0.261478 False 1 0.770246 0.128516 False 2 0.266448 0.346099 True 3 0.302941 0.065790 False 4 0.747712 0.730082 False 5 0.382923 0.751792 True 6 0.028505 0.083543 True 7 0.137558 0.243148 True 8 0.456349 0.649780 True 9 0.041046 0.163488 True 10 0.291495 0.617486 True 11 0.046561 0.038747 False 12 0.782994 0.150166 False 13 0.435168 0.080925 False 14 0.679253 0.478050 False df.test Out[113]: 0 False 1 False 2 True 3 False 4 False 5 True 6 True 7 True 8 True 9 True 10 True 11 False 12 False 13 False 14 False </code></pre> <p>As output, I would like the unique number of series of True in a row; something like:</p> <pre><code>1: 1 2: 0 3: 0 4: 0 5: 0 6: 1 7: 0 8: 0 </code></pre> <p>What I've tried so far:</p> <pre><code>(green.rolling(x).sum()&gt;x-1).sum() #gives me how many times there is a series of x True in a row; yet, this is not unique as explained beforehand </code></pre> <p>However, I do not feel the rolling is the solution over here...</p> <p>Thank you again for your help, CronosVirus00</p>
0
2016-09-19T11:28:03Z
39,573,123
<p>What you are looking for are the <code>groupby</code> function <strong>from <code>itertools</code></strong> and <code>Counter</code> from <code>collections</code>. Here is how to achieve what you want :</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.rand(15, 2), columns=["open", "close"]) df['test'] = df.close-df.open &gt; 0 from itertools import groupby from collections import Counter #we group each sequence of True and False seq_len=[(k,len(list(g))) for k, g in groupby(list(df['test']))] #we filter to keep only True sequence lenght true_seq_len= [n for k,n in seq if k == True] #we count each length true_seq_count = Counter(true_seq_len) </code></pre> <p>Output :</p> <pre><code>&gt;&gt;&gt; print(df['test']) 0 True 1 True 2 False 3 True 4 True 5 False 6 True 7 False 8 True 9 True 10 True 11 True 12 False 13 False 14 True &gt;&gt;&gt;print(seq_len) [(True, 2), (False, 1), (True, 2), (False, 1), (True, 1), (False, 1), (True, 4), (False, 2), (True, 1)] &gt;&gt;&gt;print(true_seq_count) Counter({1: 2, 2: 2, 4: 1}) </code></pre>
1
2016-09-19T12:24:56Z
[ "python", "pandas", "numpy" ]
Run tests in celery workers
39,572,178
<p>I'm looking for a Python test-suite that takes tests, converts them into celery tasks which are run on workers, gathers the results and prints them as if the tests were running normally.</p> <p>Searching only came up with ways of testing celery tasks. I don't want to test celery tasks, I want celery tasks to test other things.</p> <p>Is there anything like that?</p>
0
2016-09-19T11:32:45Z
39,572,311
<p>I'm not aware of any library that uses celery to distribute tests, but there are libraries for both pytest and nose that do something similar.</p> <ul> <li><a href="https://pypi.python.org/pypi/pytest-xdist" rel="nofollow">https://pypi.python.org/pypi/pytest-xdist</a></li> <li><a href="https://github.com/dlanger/nose-parallel" rel="nofollow">https://github.com/dlanger/nose-parallel</a></li> </ul>
0
2016-09-19T11:39:49Z
[ "python", "testing", "celery" ]
How to replace code block in a source file using shell script or python or perl
39,572,195
<p>In my source file there are multiple if clause with same check . I want to make one of the conditional block executed all the time by commenting out conditional statement which is based on text defined after if statement. </p> <pre><code>if [ "${SVR_GRP}" = "obi" ] ; then EXTRA_JAVA_PROPERTIES="-Doracle.fusion.appsMode=true ${EXTRA_JAVA_PROPERTIES}" export EXTRA_JAVA_PROPERTIES fi if [ "${SVR_GRP}" = "obi" ] ; then EXTRA_JAVA_PROPERTIES="-DUseSunHttpHandler=true ${EXTRA_JAVA_PROPERTIES}" export EXTRA_JAVA_PROPERTIES fi </code></pre> <p>replace with </p> <pre><code>if [ "${SVR_GRP}" = "obi" ] ; then EXTRA_JAVA_PROPERTIES="Doracle.fusion.appsMode=true ${EXTRA_JAVA_PROPERTIES}" export EXTRA_JAVA_PROPERTIES fi #if [ "${SVR_GRP}" = "obi" ] ; then EXTRA_JAVA_PROPERTIES="-DUseSunHttpHandler=true ${EXTRA_JAVA_PROPERTIES}" export EXTRA_JAVA_PROPERTIES #fi </code></pre> <p>Can you please suggest me how can I do this using perl/python or shell script?</p> <p>I tried perl command that doesn't work for me,</p> <pre><code>perl -0pe '/if [ "${SVR_GRP}" = "obi" ] ; then\nEXTRA_JAVA_PROPERTIES="-DUseSunHttpHandler=true ${EXTRA_JAVA_PROPERTIES}"/#if [ "${SVR_GRP}" = "obi" ] ; then\nEXTRA_JAVA_PROPERTIES="-DUseSunHttpHandler=true ${EXTRA_JAVA_PROPERTIES}" </code></pre> <p>Python program which works as expected but considered it as work around, feel there can be better solution. I am not good at shell script and perl.</p> <pre><code>file_loc = 'D:/official/workspace/pythontest/test/oops/test.sh' new_file_loc = 'D:/official/workspace/pythontest/test/oops/test1.sh' def modify(): file = open(file_loc) file2 = open(new_file_loc, 'w') lines = [] count = -1; found = False for line in file: if str(line).strip() == 'if [ "${SVR_GRP}" = "obi" ] ; then': count = 3; lines.append(line) else: if str(line).strip() == 'EXTRA_JAVA_PROPERTIES="-DUseSunHttpHandler=true ${EXTRA_JAVA_PROPERTIES}"': found = True lines.append(line) count = count - 1; if (count == 0): writeIntoFile(file2, lines, found) found = False count = -1 lines = [] elif count &lt; 0: lines = [] file2.write(line) def writeIntoFile(file, lines, found): for line in lines: if found == False: file.write(line) elif str(line).strip() == 'if [ "${SVR_GRP}" = "obi" ] ; then' or str(line).strip() == 'fi': file.write('#' + line); else: file.write(line) modify() </code></pre>
1
2016-09-19T11:33:50Z
39,574,395
<blockquote> <p>I want comment out condition based on second line text value</p> </blockquote> <p>I'm afraid this is a very unclear specification. Please try harder to explain what needs to happen to your text.</p> <p>This Perl code transforms your sample input into your sample output, but given the vagueness of your question it's impossible to know if it's making the right transformations for the right reasons.</p> <p>It's a Unix filter (it reads from STDIN and writes to STDOUT).</p> <pre><code>#!/usr/bin/perl use strict; use warnings; local $/ = ''; # Paragraph mode my %seen; while (&lt;&gt;) { my $first_line = (split /\n/)[0]; if ($seen{$first_line}++) { s/^if\b/#if/m; s/^fi\b/#fi/m; } print; } </code></pre>
0
2016-09-19T13:27:05Z
[ "python", "perl", "shell", "python-2.4" ]
Pyomo's parameter estimation in an ODE system with missing values in time series
39,572,201
<p>I have an ODE system of 7 equations for explaining a particular set of microorganisms dynamics of the form:</p> <p><img src="http://latex.codecogs.com/gif.latex?%5Cbegin%7Balign*%7D&space;%5Cfrac%7BdX_1%7D%7Bdt%7D&amp;=-Y_1%5C,.%5C,v_1-Y_2%5C,.%5C,v_3%5C%5C[4pt]&space;%5Cfrac%7BdX_2%7D%7Bdt%7D&amp;=v_1-v_2%5C%5C[4pt]&space;%5Cfrac%7BdX_3%7D%7Bdt%7D&amp;=Y_3%5C,.%5C,v_1-Y_4%5C,.%5C,v_5%5C%5C[4pt]&space;%5Cfrac%7BdX_4%7D%7Bdt%7D&amp;=v_3-v_4%5C%5C[4pt]&space;%5Cfrac%7BdX_5%7D%7Bdt%7D&space;&amp;=Y_5%5C,.%5C,v_3%5C%5C[4pt]&space;%5Cfrac%7BdX_6%7D%7Bdt%7D&space;&amp;=&space;v_3-v_6%5C%5C[4pt]&space;%5Cfrac%7BdX_7%7D%7Bdt%7D&amp;=Y_6%5C,.%5C,v_5%5C%5C[4pt]&space;%5Cend%7Balign*%7D" title="\begin{align*} \frac{dX_1}{dt}&amp;=-Y_1\,.\,v_1-Y_2\,.\,v_3\\[4pt] \frac{dX_2}{dt}&amp;=v_1-v_2\\[4pt] \frac{dX_3}{dt}&amp;=Y_3\,.\,v_1-Y_4\,.\,v_5\\[4pt] \frac{dX_4}{dt}&amp;=v_3-v_4\\[4pt] \frac{dX_5}{dt} &amp;=Y_5\,.\,v_3\\[4pt] \frac{dX_6}{dt} &amp;= v_3-v_6\\[4pt] \frac{dX_7}{dt}&amp;=Y_6\,.\,v_5\\[4pt] \end{align*}" /></p> <p>Where the <img src="http://latex.codecogs.com/gif.latex?X_n" title="X_n" /> are the different chemical and microorganisms species involved (even sub-indexes for chemical compounds), the <img src="http://latex.codecogs.com/gif.latex?Y_n" title="Y_n" /> are the yield coefficients and the <img src="http://latex.codecogs.com/gif.latex?v_n" title="v_n" /> are the pseudo-reactions:</p> <p><img src="http://latex.codecogs.com/gif.latex?%5Cbegin%7Balign*%7D&space;v_1&amp;=%5Cfrac%7Bk_1%5C,.%5C,X_1%7D%7Bk_2&plus;X_1%7D%5C,.%5C,X_2%5C%5C[4pt]&space;v_2&amp;=k_7%5C,.%5C,X_3%5C,.%5C,X_2%5C%5C[4pt]&space;v_3&amp;=%5Cfrac%7Bk_3%5C,.%5C,X_1%7D%7Bk_4&plus;X_1%7D%5C,.%5C,X_4%5C%5C[4pt]&space;v_4&amp;=k_8%5C,.%5C,X_3%5C,.%5C,X_4%5C%5C[4pt]&space;v_5&amp;=%5Cfrac%7Bk_5%5C,.%5C,X_3%7D%7Bk_6&plus;X_3%7D%5C,.%5C,X_5%5C%5C[4pt]&space;v_6&amp;=k_9%5C,.%5C,X_5%5C%5C[4pt]&space;%5Cend%7Balign*%7D" title="\begin{align*} v_1&amp;=\frac{k_1\,.\,X_1}{k_2+X_1}\,.\,X_2\\[4pt] v_2&amp;=k_7\,.\,X_3\,.\,X_2\\[4pt] v_3&amp;=\frac{k_3\,.\,X_1}{k_4+X_1}\,.\,X_4\\[4pt] v_4&amp;=k_8\,.\,X_3\,.\,X_4\\[4pt] v_5&amp;=\frac{k_5\,.\,X_3}{k_6+X_3}\,.\,X_5\\[4pt] v_6&amp;=k_9\,.\,X_5\\[4pt] \end{align*}" /></p> <p>I am using Pyomo for the estimation of all my unknown parameters, which are basically all the yield coefficients and kinetic constants (15 in total).</p> <p>The following code works perfectly when is used with complete experimental time series for each of the dynamical variables:</p> <pre><code>from pyomo.environ import * from pyomo.dae import * m = AbstractModel() m.t = ContinuousSet() m.MEAS_t = Set(within=m.t) # Measurement times, must be subset of t m.x1_meas = Param(m.MEAS_t) m.x2_meas = Param(m.MEAS_t) m.x3_meas = Param(m.MEAS_t) m.x4_meas = Param(m.MEAS_t) m.x5_meas = Param(m.MEAS_t) m.x6_meas = Param(m.MEAS_t) m.x7_meas = Param(m.MEAS_t) m.x1 = Var(m.t,within=PositiveReals) m.x2 = Var(m.t,within=PositiveReals) m.x3 = Var(m.t,within=PositiveReals) m.x4 = Var(m.t,within=PositiveReals) m.x5 = Var(m.t,within=PositiveReals) m.x6 = Var(m.t,within=PositiveReals) m.x7 = Var(m.t,within=PositiveReals) m.k1 = Var(within=PositiveReals) m.k2 = Var(within=PositiveReals) m.k3 = Var(within=PositiveReals) m.k4 = Var(within=PositiveReals) m.k5 = Var(within=PositiveReals) m.k6 = Var(within=PositiveReals) m.k7 = Var(within=PositiveReals) m.k8 = Var(within=PositiveReals) m.k9 = Var(within=PositiveReals) m.y1 = Var(within=PositiveReals) m.y2 = Var(within=PositiveReals) m.y3 = Var(within=PositiveReals) m.y4 = Var(within=PositiveReals) m.y5 = Var(within=PositiveReals) m.y6 = Var(within=PositiveReals) m.x1dot = DerivativeVar(m.x1,wrt=m.t) m.x2dot = DerivativeVar(m.x2,wrt=m.t) m.x3dot = DerivativeVar(m.x3,wrt=m.t) m.x4dot = DerivativeVar(m.x4,wrt=m.t) m.x5dot = DerivativeVar(m.x5,wrt=m.t) m.x6dot = DerivativeVar(m.x6,wrt=m.t) m.x7dot = DerivativeVar(m.x7,wrt=m.t) def _init_conditions(m): yield m.x1[0] == 51.963 yield m.x2[0] == 6.289 yield m.x3[0] == 0 yield m.x4[0] == 6.799 yield m.x5[0] == 0 yield m.x6[0] == 4.08 yield m.x7[0] == 0 m.init_conditions=ConstraintList(rule=_init_conditions) def _x1dot(m,i): if i==0: return Constraint.Skip return m.x1dot[i] == - m.y1*m.k1*m.x1[i]*m.x2[i]/(m.k2+m.x1[i]) - m.y2*m.k3*m.x1[i]*m.x4[i]/(m.k4+m.x1[i]) m.x1dotcon = Constraint(m.t, rule=_x1dot) def _x2dot(m,i): if i==0: return Constraint.Skip return m.x2dot[i] == m.k1*m.x1[i]*m.x2[i]/(m.k2+m.x1[i]) - m.k7*m.x2[i]*m.x3[i] m.x2dotcon = Constraint(m.t, rule=_x2dot) def _x3dot(m,i): if i==0: return Constraint.Skip return m.x3dot[i] == m.y3*m.k1*m.x1[i]*m.x2[i]/(m.k2+m.x1[i]) - m.y4*m.k5*m.x3[i]*m.x6[i]/(m.k6+m.x3[i]) m.x3dotcon = Constraint(m.t, rule=_x3dot) def _x4dot(m,i): if i==0: return Constraint.Skip return m.x4dot[i] == m.k3*m.x1[i]*m.x4[i]/(m.k4+m.x1[i]) - m.k8*m.x4[i]*m.x3[i] m.x4dotcon = Constraint(m.t, rule=_x4dot) def _x5dot(m,i): if i==0: return Constraint.Skip return m.x5dot[i] == m.y5*m.k3*m.x1[i]*m.x4[i]/(m.k4+m.x1[i]) m.x5dotcon = Constraint(m.t, rule=_x5dot) def _x6dot(m,i): if i==0: return Constraint.Skip return m.x6dot[i] == m.k5*m.x3[i]*m.x6[i]/(m.k6+m.x3[i]) - m.k9*m.x6[i]*m.x7[i] m.x6dotcon = Constraint(m.t, rule=_x6dot) def _x7dot(m,i): if i==0: return Constraint.Skip return m.x7dot[i] == m.y6*m.k5*m.x3[i]*m.x6[i]/(m.k6+m.x3[i]) m.x7dotcon = Constraint(m.t, rule=_x7dot) def _obj(m): return sum((m.x1[i]-m.x1_meas[i])**2+(m.x2[i]-m.x2_meas[i])**2+(m.x3[i]-m.x3_meas[i])**2+(m.x4[i]-m.x4_meas[i])**2+(m.x5[i]-m.x5_meas[i])**2+(m.x6[i]-m.x6_meas[i])**2+(m.x7[i]-m.x7_meas[i])**2 for i in m.MEAS_t) m.obj = Objective(rule=_obj) m.pprint() instance = m.create_instance('exp.dat') instance.t.pprint() discretizer = TransformationFactory('dae.collocation') discretizer.apply_to(instance,nfe=30)#,ncp=3) solver=SolverFactory('ipopt') results = solver.solve(instance,tee=True) </code></pre> <p>However, I am trying to run the same estimation routine in another experimental data that have missing values at the end of one or maximum two time series of some of the dynamical variables.</p> <p>In other words, these complete experimental data looks like (in the .dat file):</p> <pre><code>set t := 0 6 12 18 24 30 36 42 48 54 60 66 72 84 96 120 144; set MEAS_t := 0 6 12 18 24 30 36 42 48 54 60 66 72 84 96 120 144; param x1_meas := 0 51.963 6 43.884 12 24.25 18 26.098 24 11.871 30 4.607 36 1.714 42 4.821 48 5.409 54 3.701 60 3.696 66 1.544 72 4.428 84 1.086 96 2.337 120 2.837 144 3.486 ; param x2_meas := 0 6.289 6 6.242 12 7.804 18 7.202 24 6.48 30 5.833 36 6.644 42 5.741 48 4.568 54 4.252 60 5.603 66 5.167 72 4.399 84 4.773 96 4.801 120 3.866 144 3.847 ; param x3_meas := 0 0 6 2.97 12 9.081 18 9.62 24 6.067 30 11.211 36 16.213 42 10.215 48 20.106 54 22.492 60 5.637 66 5.636 72 13.85 84 4.782 96 9.3 120 4.267 144 7.448 ; param x4_meas := 0 6.799 6 7.73 12 7.804 18 8.299 24 8.208 30 8.523 36 8.507 42 8.656 48 8.49 54 8.474 60 8.203 66 8.127 72 8.111 84 8.064 96 6.845 120 6.721 144 6.162 ; param x5_meas := 0 0 6 0.267 12 0.801 18 1.256 24 1.745 30 5.944 36 3.246 42 7.787 48 7.991 54 6.943 60 8.593 66 8.296 72 6.85 84 8.021 96 7.667 120 7.209 144 8.117 ; param x6_meas := 0 4.08 6 4.545 12 4.784 18 4.888 24 5.293 30 5.577 36 5.802 42 5.967 48 6.386 54 6.115 60 6.625 66 6.835 72 6.383 84 6.605 96 5.928 120 5.354 144 4.975 ; param x7_meas := 0 0 6 0.152 12 1.616 18 0.979 24 4.033 30 5.121 36 2.759 42 3.541 48 4.278 54 4.141 60 6.139 66 3.219 72 5.319 84 4.328 96 3.621 120 4.208 144 5.93 ; </code></pre> <p>While one of my incomplete data sets could have all time series complete, but one like this:</p> <pre><code>param x6_meas := 0 4.08 6 4.545 12 4.784 18 4.888 24 5.293 30 5.577 36 5.802 42 5.967 48 6.386 54 6.115 60 6.625 66 6.835 72 6.383 84 6.605 96 5.928 120 5.354 144 . ; </code></pre> <p>I have knowledge that one can specify to Pyomo to take the derivative of certain variables with respect to a different time serie. However, after tried it, it hadn't worked, and I guess that is because that these are coupled ODE. So basically my question is if there is a way to overcome this issue in Pyomo.</p> <p>Thanks in advance.</p>
0
2016-09-19T11:34:04Z
39,575,258
<p>I think all you need to do is slightly modify your objective function like this:</p> <pre><code>def _obj(m): sum1 = sum((m.x1[i]-m.x1_meas[i])**2 for i in m.MEAS_t if i in m.x1_meas.keys()) sum2 = sum((m.x2[i]-m.x2_meas[i])**2 for i in m.MEAS_t if i in m.x2_meas.keys()) sum3 = sum((m.x3[i]-m.x3_meas[i])**2 for i in m.MEAS_t if i in m.x3_meas.keys()) sum4 = sum((m.x4[i]-m.x4_meas[i])**2 for i in m.MEAS_t if i in m.x4_meas.keys()) sum5 = sum((m.x5[i]-m.x5_meas[i])**2 for i in m.MEAS_t if i in m.x5_meas.keys()) sum6 = sum((m.x6[i]-m.x6_meas[i])**2 for i in m.MEAS_t if i in m.x6_meas.keys()) sum7 = sum((m.x7[i]-m.x7_meas[i])**2 for i in m.MEAS_t if i in m.x7_meas.keys()) return sum1+sum2+sum3+sum4+sum5+sum6+sum7 m.obj = Objective(rule=_obj) </code></pre> <p>This double checks that <em>i</em> is a valid index for each set of measurements before adding that index to the sum. If you knew apriori which measurement sets were missing data then you could simplify this function by only doing this check on those sets and summing over the others like you were before. </p>
1
2016-09-19T14:09:23Z
[ "python", "ode", "pyomo" ]
How to execute python scripts with a custom name without .py extension
39,572,325
<p>Lets say I have a python script that makes an http request and prints the response code to the screen and exits.</p> <pre><code># check_app_status.py import requests r = requests.get("https://someapp.com") print r.status_code </code></pre> <p>Now i can run it by </p> <pre><code>$ python check_app_status.py 200 </code></pre> <p>What do I need to set up to be able to run it like this </p> <pre><code>$ check-app 200 </code></pre>
1
2016-09-19T11:40:54Z
39,572,364
<p>Assuming you're on a unixoid system, you just need to add a shebang line:</p> <pre><code>#!/usr/local/bin/python import requests ... </code></pre> <p>The exact location of the python executable may vary, so you can alternatively also use the shebang line <code>#!/usr/bin/env python</code>, which should always work.</p> <p>Then, set the executable bit (<code>chmod +x check-app</code>). Finally, if you want to be able to call it from any location, put it somewhere in your $PATH. I would recommend extending your <code>$PATH</code> with a custom directory where you put your scripts (in this case <code>~/bin</code>). To do that, put this in your <code>.bashrc</code> (or similar):</p> <p><code>export PATH=$PATH:$HOME/bin</code></p>
3
2016-09-19T11:43:15Z
[ "python" ]
Scrapy - How to keep track of start url
39,572,599
<p>Given a pool of start urls I would like to identify in the parse_item() function the origin url.</p> <p>As far as I'm concerned the scrapy spiders start crawling from the initial pool of start urls, but when parsing there is no trace of which of those urls was the initial one. How it would be possible to keep track of the starting point?</p>
0
2016-09-19T11:56:22Z
39,575,584
<p>If you need a parsing url inside the spider, just use response.url:</p> <pre><code>def parse_item(self, response): print response.url </code></pre> <p>but in case you need it outside spider I can think of following ways:</p> <ol> <li>Use <a href="http://doc.scrapy.org/en/latest/topics/api.html" rel="nofollow">scrapy core api</a></li> <li>You can also call scrapy from an external python module with OS command (which apparently is not recommended):</li> </ol> <p>in scrapycaller.py</p> <pre><code>from subprocess import call urls = 'url1,url2' cmd = 'scrapy crawl myspider -a myurls={}'.format(urls) call(cmd, shell=True) </code></pre> <p>Inside myspider:</p> <pre><code>class mySpider(scrapy.Spider): def __init__(self, myurls=''): self.start_urls = myurls.split(",") </code></pre>
0
2016-09-19T14:25:46Z
[ "python", "scrapy", "web-crawler" ]
Using graphframes with PyCharm
39,572,603
<p>I have spent almost 2 days scrolling the internet and I was unable to sort out this problem. I am trying to install the <a href="https://spark-packages.org/package/graphframes/graphframes" rel="nofollow">graphframes package</a> (Version: 0.2.0-spark2.0-s_2.11) to run with spark through PyCharm, but, despite my best efforts, it's been impossible.</p> <p>I have tried almost everything. Please, know that I have checked this site <a href="https://developer.ibm.com/clouddataservices/2016/07/15/intro-to-apache-spark-graphframes/" rel="nofollow">here</a> as well before posting an answer. </p> <p>Here is the code I am trying to run:</p> <pre><code># IMPORT OTHER LIBS -------------------------------------------------------- import os import sys import pandas as pd # IMPORT SPARK ------------------------------------------------------------------------------------# # Path to Spark source folder USER_FILE_PATH = "/Users/&lt;username&gt;" SPARK_PATH = "/PycharmProjects/GenesAssociation" SPARK_FILE = "/spark-2.0.0-bin-hadoop2.7" SPARK_HOME = USER_FILE_PATH + SPARK_PATH + SPARK_FILE os.environ['SPARK_HOME'] = SPARK_HOME # Append pySpark to Python Path sys.path.append(SPARK_HOME + "/python") sys.path.append(SPARK_HOME + "/python" + "/lib/py4j-0.10.1-src.zip") try: from pyspark import SparkContext from pyspark import SparkConf from pyspark.sql import SQLContext from pyspark.graphframes import GraphFrame except ImportError as ex: print "Can not import Spark Modules", ex sys.exit(1) # GLOBAL VARIABLES --------------------------------------------------------- -----------------------# SC = SparkContext('local') SQL_CONTEXT = SQLContext(SC) # MAIN CODE ---------------------------------------------------------------------------------------# if __name__ == "__main__": # Main Path to CSV files DATA_PATH = '/PycharmProjects/GenesAssociation/data/' FILE_NAME = 'gene_gene_associations_50k.csv' # LOAD DATA CSV USING PANDAS -----------------------------------------------------------------# print "STEP 1: Loading Gene Nodes -------------------------------------------------------------" # Read csv file and load as df GENES = pd.read_csv(USER_FILE_PATH + DATA_PATH + FILE_NAME, usecols=['OFFICIAL_SYMBOL_A'], low_memory=True, iterator=True, chunksize=1000) # Concatenate chunks into list &amp; convert to dataFrame GENES_DF = pd.DataFrame(pd.concat(list(GENES), ignore_index=True)) # Remove duplicates GENES_DF_CLEAN = GENES_DF.drop_duplicates(keep='first') # Name Columns GENES_DF_CLEAN.columns = ['gene_id'] # Output dataFrame print GENES_DF_CLEAN # Create vertices VERTICES = SQL_CONTEXT.createDataFrame(GENES_DF_CLEAN) # Show some vertices print VERTICES.take(5) print "STEP 2: Loading Gene Edges -------------------------------------------------------------" # Read csv file and load as df EDGES = pd.read_csv(USER_FILE_PATH + DATA_PATH + FILE_NAME, usecols=['OFFICIAL_SYMBOL_A', 'OFFICIAL_SYMBOL_B', 'EXPERIMENTAL_SYSTEM'], low_memory=True, iterator=True, chunksize=1000) # Concatenate chunks into list &amp; convert to dataFrame EDGES_DF = pd.DataFrame(pd.concat(list(EDGES), ignore_index=True)) # Name Columns EDGES_DF.columns = ["src", "dst", "rel_type"] # Output dataFrame print EDGES_DF # Create vertices EDGES = SQL_CONTEXT.createDataFrame(EDGES_DF) # Show some edges print EDGES.take(5) g = gf.GraphFrame(VERTICES, EDGES) </code></pre> <p>Needless to say, I have tried including the graphframes directory (look <a href="https://github.com/graphframes/graphframes/tree/master/python/graphframes" rel="nofollow">here</a> to understand what I did) into spark's pyspark directory. But it seems like this not enough... Anything else I have tried just failed. Would appreciate some help with this. You can see below the error message I am getting:</p> <pre><code>Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties Setting default log level to "WARN". To adjust logging level use sc.setLogLevel(newLevel). 16/09/19 12:46:02 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable 16/09/19 12:46:03 WARN Utils: Service 'SparkUI' could not bind on port 4040. Attempting port 4041. STEP 1: Loading Gene Nodes ------------------------------------------------------------- gene_id 0 MAP2K4 1 MYPN 2 ACVR1 3 GATA2 4 RPA2 5 ARF1 6 ARF3 8 XRN1 9 APP 10 APLP1 11 CITED2 12 EP300 13 APOB 14 ARRB2 15 CSF1R 16 PRRC2A 17 LSM1 18 SLC4A1 19 BCL3 20 ADRB1 21 BRCA1 25 ARVCF 26 PCBD1 27 PSEN2 28 CAPN3 29 ITPR1 30 MAGI1 31 RB1 32 TSG101 33 ORC1 ... ... 49379 WDR26 49380 WDR5B 49382 NLE1 49383 WDR12 49385 WDR53 49386 WDR59 49387 WDR61 49409 CHD6 49422 DACT1 49424 KMT2B 49438 SMARCA1 49459 DCLRE1A 49469 F2RL1 49472 SENP8 49475 TSPY1 49479 SERPINB5 49521 HOXA11 49548 SYF2 49553 FOXN3 49557 MLANA 49608 REPIN1 49609 GMNN 49670 HIST2H2BE 49767 BCL7C 49797 SIRT3 49810 KLF4 49858 RHO 49896 MAGEA2 49907 SUV420H2 49958 SAP30L [6025 rows x 1 columns] 16/09/19 12:46:08 WARN TaskSetManager: Stage 0 contains a task of very large size (107 KB). The maximum recommended task size is 100 KB. [Row(gene_id=u'MAP2K4'), Row(gene_id=u'MYPN'), Row(gene_id=u'ACVR1'), Row(gene_id=u'GATA2'), Row(gene_id=u'RPA2')] STEP 2: Loading Gene Edges ------------------------------------------------------------- src dst rel_type 0 MAP2K4 FLNC Two-hybrid 1 MYPN ACTN2 Two-hybrid 2 ACVR1 FNTA Two-hybrid 3 GATA2 PML Two-hybrid 4 RPA2 STAT3 Two-hybrid 5 ARF1 GGA3 Two-hybrid 6 ARF3 ARFIP2 Two-hybrid 7 ARF3 ARFIP1 Two-hybrid 8 XRN1 ALDOA Two-hybrid 9 APP APPBP2 Two-hybrid 10 APLP1 DAB1 Two-hybrid 11 CITED2 TFAP2A Two-hybrid 12 EP300 TFAP2A Two-hybrid 13 APOB MTTP Two-hybrid 14 ARRB2 RALGDS Two-hybrid 15 CSF1R GRB2 Two-hybrid 16 PRRC2A GRB2 Two-hybrid 17 LSM1 NARS Two-hybrid 18 SLC4A1 SLC4A1AP Two-hybrid 19 BCL3 BARD1 Two-hybrid 20 ADRB1 GIPC1 Two-hybrid 21 BRCA1 ATF1 Two-hybrid 22 BRCA1 MSH2 Two-hybrid 23 BRCA1 BARD1 Two-hybrid 24 BRCA1 MSH6 Two-hybrid 25 ARVCF CDH15 Two-hybrid 26 PCBD1 CACNA1C Two-hybrid 27 PSEN2 CAPN1 Two-hybrid 28 CAPN3 TTN Two-hybrid 29 ITPR1 CA8 Two-hybrid ... ... ... ... 49969 SAP30 HDAC3 Affinity Capture-Western 49970 BRCA1 RBBP8 Co-localization 49971 BRCA1 BRCA1 Biochemical Activity 49972 SET TREX1 Co-purification 49973 SET TREX1 Reconstituted Complex 49974 PLAGL1 EP300 Reconstituted Complex 49975 PLAGL1 CREBBP Reconstituted Complex 49976 EP300 PLAGL1 Affinity Capture-Western 49977 MTA1 ESR1 Reconstituted Complex 49978 SIRT2 EP300 Affinity Capture-Western 49979 EP300 SIRT2 Affinity Capture-Western 49980 EP300 HDAC1 Affinity Capture-Western 49981 EP300 SIRT2 Biochemical Activity 49982 MIER1 CREBBP Reconstituted Complex 49983 SMARCA4 SIN3A Affinity Capture-Western 49984 SMARCA4 HDAC2 Affinity Capture-Western 49985 ESR1 NCOA6 Affinity Capture-Western 49986 ESR1 TOP2B Affinity Capture-Western 49987 ESR1 PRKDC Affinity Capture-Western 49988 ESR1 PARP1 Affinity Capture-Western 49989 ESR1 XRCC5 Affinity Capture-Western 49990 ESR1 XRCC6 Affinity Capture-Western 49991 PARP1 TOP2B Affinity Capture-Western 49992 PARP1 PRKDC Affinity Capture-Western 49993 PARP1 XRCC5 Affinity Capture-Western 49994 PARP1 XRCC6 Affinity Capture-Western 49995 SIRT3 XRCC6 Affinity Capture-Western 49996 SIRT3 XRCC6 Reconstituted Complex 49997 SIRT3 XRCC6 Biochemical Activity 49998 HDAC1 PAX3 Affinity Capture-Western [49999 rows x 3 columns] 16/09/19 12:46:11 WARN TaskSetManager: Stage 1 contains a task of very large size (1211 KB). The maximum recommended task size is 100 KB. [Row(src=u'MAP2K4', dst=u'FLNC', rel_type=u'Two-hybrid'), Row(src=u'MYPN', dst=u'ACTN2', rel_type=u'Two-hybrid'), Row(src=u'ACVR1', dst=u'FNTA', rel_type=u'Two-hybrid'), Row(src=u'GATA2', dst=u'PML', rel_type=u'Two-hybrid'), Row(src=u'RPA2', dst=u'STAT3', rel_type=u'Two-hybrid')] Traceback (most recent call last): File "/Users/username/PycharmProjects/GenesAssociation/__init__.py", line 99, in &lt;module&gt; g = gf.GraphFrame(VERTICES, EDGES) File "/Users/username/PycharmProjects/GenesAssociation/spark-2.0.0-bin-hadoop2.7/python/pyspark/graphframes/graphframe.py", line 62, in __init__ self._jvm_gf_api = _java_api(self._sc) File "/Users/username/PycharmProjects/GenesAssociation/spark-2.0.0-bin-hadoop2.7/python/pyspark/graphframes/graphframe.py", line 34, in _java_api return jsc._jvm.Thread.currentThread().getContextClassLoader().loadClass(javaClassName) \ File "/Users/username/PycharmProjects/GenesAssociation/spark-2.0.0-bin-hadoop2.7/python/lib/py4j-0.10.1-src.zip/py4j/java_gateway.py", line 933, in __call__ File "/Users/username/PycharmProjects/GenesAssociation/spark-2.0.0-bin-hadoop2.7/python/pyspark/sql/utils.py", line 63, in deco return f(*a, **kw) File "/Users/username/PycharmProjects/GenesAssociation/spark-2.0.0-bin-hadoop2.7/python/lib/py4j-0.10.1-src.zip/py4j/protocol.py", line 312, in get_return_value py4j.protocol.Py4JJavaError: An error occurred while calling o50.loadClass. : java.lang.ClassNotFoundException: org.graphframes.GraphFramePythonAPI at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:280) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:128) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:211) at java.lang.Thread.run(Thread.java:745) Process finished with exit code 1 </code></pre> <p>Thanks in advance.</p>
0
2016-09-19T11:56:31Z
39,575,317
<p>You can set <code>PYSPARK_SUBMIT_ARGS</code> either in your code</p> <pre><code>os.environ["PYSPARK_SUBMIT_ARGS"] = ( "--packages graphframes:graphframes:0.2.0-spark2.0-s_2.11 pyspark-shell" ) spark = SparkSession.builder.getOrCreate() </code></pre> <p>or in PyCharm edit run configuration (<kbd>Run</kbd> -> <kbd>Edit configuration</kbd> -> <kbd>Choose configuration</kbd> -> <kbd>Select configuration tab</kbd> -> <kbd>Choose Environment variables</kbd> -> <kbd>Add PYSPARK_SUBMIT_ARGS</kbd>):</p> <p><a href="http://i.stack.imgur.com/n1UGL.png" rel="nofollow"><img src="http://i.stack.imgur.com/n1UGL.png" alt="enter image description here"></a></p> <p>with a minimal working example:</p> <pre><code>import os import sys SPARK_HOME = ... os.environ["SPARK_HOME"] = SPARK_HOME # os.environ["PYSPARK_SUBMIT_ARGS"] = ... If not set in PyCharm config sys.path.append(os.path.join(SPARK_HOME, "python")) sys.path.append(os.path.join(SPARK_HOME, "python/lib/py4j-0.10.3-src.zip")) from pyspark.sql import SparkSession spark = SparkSession.builder.getOrCreate() v = spark.createDataFrame([("a", "foo"), ("b", "bar"),], ["id", "attr"]) e = spark.createDataFrame([("a", "b", "foobar")], ["src", "dst", "rel"]) from graphframes import * g = GraphFrame(v, e) g.inDegrees.show() spark.stop() </code></pre> <p>You could also add the <code>packages</code> or <code>jars</code> to your <code>spark-defaults.conf</code>.</p> <p>If you use Python 3 there is a known issue with extracting Python libraries from JAR so you'll have to do it manually. You can for example download JAR file, unzip it, and make sure that root directory with <code>graphframes</code> is on your Python path.</p>
2
2016-09-19T14:12:24Z
[ "python", "install", "pycharm", "pyspark", "graphframes" ]
Python XML parse issues
39,572,648
<p>Currently trying to parse some XML using python, so far I've managed to get the name of the tag however I can't figure out how to get the data from inside this.</p> <pre><code> &lt;Fragment name="Located At"&gt;Sector 121212&lt;/Fragment&gt; </code></pre> <p>The above is an example of the XML file, I can get the "Located At" part out but not the "Sector 165658" I am currently using the following:</p> <pre><code>xmldoc = minidom.parse('file.xml') itemlist = xmldoc.getElementsByTagName('Fragment') for items in itemlist: print (items.attributes['name'].value) </code></pre> <p>I can't for the life of me remember that the "name" for the section is I feel like this is going to be a simple answer and I'm going to look like an idiot but we shall see.</p>
0
2016-09-19T11:59:19Z
39,572,756
<p>According to the <a href="https://docs.python.org/2/library/xml.dom.minidom.html" rel="nofollow"><code>minidom</code> docs</a>, it looks like <code>.childNodes</code> might be the thing you're looking for.</p>
1
2016-09-19T12:05:37Z
[ "python", "xml", "python-2.7" ]
How do I roll a dice and store the total number using Python3.4
39,572,664
<pre><code>import tkinter import random def rollDice(): x=random.randint(1,6) total=0 if x == 1: total+=1 .... print(total) </code></pre> <p>I would like to add each number I roll in <code>.rollDice</code> and store into <code>total</code> , and maximum is 50. How can I do that?</p>
-2
2016-09-19T12:00:34Z
39,572,968
<p>As @PaulRooney says, i am not sure what <code>tkinter</code> has to do with this. From what i understand, you want to roll a dice until your <code>total</code> reaches or exceeds 50.. So here is my take on this:</p> <pre><code>from random import randint def rollDice(): return randint(1,6) total = 0 while total &lt; 50: new_roll = rollDice() total += new_roll print('You rolled a {}. The new total is {}'.format(new_roll, total)) # You rolled a 3. The new total is 3 # You rolled a 3. The new total is 6 # You rolled a 4. The new total is 10 # You rolled a 6. The new total is 16 # You rolled a 2. The new total is 18 # You rolled a 1. The new total is 19 # You rolled a 5. The new total is 24 # You rolled a 5. The new total is 29 # You rolled a 4. The new total is 33 # You rolled a 5. The new total is 38 # You rolled a 2. The new total is 40 # You rolled a 3. The new total is 43 # You rolled a 4. The new total is 47 # You rolled a 6. The new total is 53 </code></pre>
0
2016-09-19T12:16:05Z
[ "python", "tkinter" ]
Thread in python-
39,572,769
<p>I want to use threads to get better performance in python.</p> <p>My program need to return value from each function the thread does.</p> <p>And I need to know when the thread is finished.</p> <p>There are 3 ways I tried to execute this little program.</p> <pre><code>import thread import datetime from threading import Thread import threading from multiprocessing.pool import ThreadPool def func1(word): i=0 while i&lt;100000: if 1&lt;2: i=i+1 return "func1" def func2(): i=0 while i&lt;100000: if 1&lt;2: i=i+1 return "func2" word="hiiii" """ #--------------------------------example1-------------------------------- pool = ThreadPool(processes=2) print str(datetime.datetime.now().time()) async_result1 = pool.apply_async(func1, (word, )) async_result2 = pool.apply_async(func2) print async_result1.get() print async_result2.get() print str(datetime.datetime.now().time()) print func1(word) print func2() print str(datetime.datetime.now().time()) #with threads-71000 #without threads- 40000 #--------------------------------example1-------------------------------- """ """ #--------------------------------example2-------------------------------- t1 = Thread(target=func1, args=(word,)) t2 = Thread(target=func2, args=()) print str(datetime.datetime.now().time()) t1.start() t2.start() t1.join() t2.join() print str(datetime.datetime.now().time()) func1(word) func2() print str(datetime.datetime.now().time()) #with threads-75000 #without threads-42000 #--------------------------------example2-------------------------------- """ """ #--------------------------------example3 without sending value-------------------------------- print str(datetime.datetime.now().time()) t1 = threading.Thread(name=func1,target=func1) t2= threading.Thread(name=func2,target=func2) t1.start() t2.start() t1.join() t2.join() print str(datetime.datetime.now().time()) func1() func2() print str(datetime.datetime.now().time()) #with threads- 73000 #without threads- 42000 #--------------------------------example3 without sending value------------- ------------------- """ </code></pre> <p>But, you can see that the better way to run is without threads! why?? what do I do wrong? How to use threads?</p>
2
2016-09-19T12:05:59Z
39,572,927
<p>Threading is primarily of use when you have multiple tasks contending for CPU but spending most of their time waiting for some external event like a network read or a database write.</p> <p>With multiple threads active, every (some number) of opcodes it spends time deciding to switch to another thread (assuming there are other runnable threads). If neither of your threads ever does anything but compute then there is effectively no time to be saved by switching between threads. Because all threads run in the same process, and a Python process cannot (normally) take advantage of multiple CPUs, you won't see any speed-up (and, indeed, may observe slow-down due to thread-switching activity).</p> <p><strong>tl;dr</strong>: CPU-bound tasks cannot be sped up by multi-threading.</p>
3
2016-09-19T12:14:04Z
[ "python", "multithreading", "python-2.7", "threadpool" ]
Thread in python-
39,572,769
<p>I want to use threads to get better performance in python.</p> <p>My program need to return value from each function the thread does.</p> <p>And I need to know when the thread is finished.</p> <p>There are 3 ways I tried to execute this little program.</p> <pre><code>import thread import datetime from threading import Thread import threading from multiprocessing.pool import ThreadPool def func1(word): i=0 while i&lt;100000: if 1&lt;2: i=i+1 return "func1" def func2(): i=0 while i&lt;100000: if 1&lt;2: i=i+1 return "func2" word="hiiii" """ #--------------------------------example1-------------------------------- pool = ThreadPool(processes=2) print str(datetime.datetime.now().time()) async_result1 = pool.apply_async(func1, (word, )) async_result2 = pool.apply_async(func2) print async_result1.get() print async_result2.get() print str(datetime.datetime.now().time()) print func1(word) print func2() print str(datetime.datetime.now().time()) #with threads-71000 #without threads- 40000 #--------------------------------example1-------------------------------- """ """ #--------------------------------example2-------------------------------- t1 = Thread(target=func1, args=(word,)) t2 = Thread(target=func2, args=()) print str(datetime.datetime.now().time()) t1.start() t2.start() t1.join() t2.join() print str(datetime.datetime.now().time()) func1(word) func2() print str(datetime.datetime.now().time()) #with threads-75000 #without threads-42000 #--------------------------------example2-------------------------------- """ """ #--------------------------------example3 without sending value-------------------------------- print str(datetime.datetime.now().time()) t1 = threading.Thread(name=func1,target=func1) t2= threading.Thread(name=func2,target=func2) t1.start() t2.start() t1.join() t2.join() print str(datetime.datetime.now().time()) func1() func2() print str(datetime.datetime.now().time()) #with threads- 73000 #without threads- 42000 #--------------------------------example3 without sending value------------- ------------------- """ </code></pre> <p>But, you can see that the better way to run is without threads! why?? what do I do wrong? How to use threads?</p>
2
2016-09-19T12:05:59Z
39,573,328
<p>To append the other answer:</p> <p>The reason the threaded version can actually be slower in a CPU-bound operation is (as mentioned) GIL, the Global Interpreter Lock. GIL works as a mutex, allowing only a single thread to access it at a time. So threading is only useful when waiting for IO-operations.</p> <p>However, there is a way to actually execute code in multiple cores, bypassing the issue with GIL. The solution is to use <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">multiprocessing</a> library.</p> <p>So in your case:</p> <pre><code>process1 = multiprocessing.Process(target=func1, args=(word,)) process1.start() process2 = multiprocessing.Process(target=func2) process2.start() process.join() process2.join() </code></pre> <p>The two processes should start in different cores, effectively making the program execute faster. For me it almost halved the execution time. Note that spawning more processes than you have cores will again make it run slower.</p>
1
2016-09-19T12:34:35Z
[ "python", "multithreading", "python-2.7", "threadpool" ]
Python - check if it's prime number
39,572,815
<p>I know that this question was asked way too many times, but I'm not searching for the fastest algorithm. I'd only like to know what I'm doing wrong with my code since it's faulty.</p> <pre><code>import math def is_prime(number): for i in range (2, 1+ int(math.sqrt(number))): if number % i == 0: return 0 else: return 1 choice = int(input("Check if it's prime: ")) if is_prime(choice): print ("{} is a prime number".format(choice)) else: print ("{} is not a prime number".format(choice)) </code></pre> <p>If I test this program for most numbers it will return correct response, but if I check any square number it will say that it's a prime. So any suggestions what I'm doing wrong?</p>
0
2016-09-19T12:08:20Z
39,572,861
<p>You are returning immediately in the first iteration of the loop ... always.</p> <p>Instead only return immediately when you know it is not a prime, else keep going:</p> <pre><code>def is_prime(number): for i in range (2, 1+ int(math.sqrt(number))): if number % i == 0: return 0 return 1 </code></pre>
4
2016-09-19T12:11:04Z
[ "python" ]
Python, using threading with multiprocessing
39,572,941
<p>Can someone explain why threading don't work in multiprocessing.Process.</p> <p>I've attached some example to explain my problem.</p> <p>I have a process that executed every second and write to file. When I run it from shell, it works as expected.</p> <p><strong>stat_collect.py</strong></p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- from threading import Timer from os import path from datetime import datetime STAT_DATETIME_FMT = '%Y-%m-%d %H:%M:%S' def collect_statistics(): my_file = 'test.file' if not path.exists(my_file): with open(my_file, 'w') as fp: fp.write(datetime.now().strftime(STAT_DATETIME_FMT) + '\n') else: with open(my_file, 'a') as fp: fp.write(datetime.now().strftime(STAT_DATETIME_FMT) + '\n') Timer(1, collect_statistics).start() if __name__ == '__main__': collect_statistics() </code></pre> <p>When I try to run it from other script (to work in background):</p> <pre><code>#!/usr/bin/env python from multiprocessing import Process from stat_collect import collect_statistics # logger sc if __name__ == '__main__': # This don't work p = Process(target=collect_statistics) p.start() while True: pass </code></pre> <p>Method collect_statistics executed only once, but if I use Thread(target=collect_statistics).start() it works as if I run it from shell. Why this is happen?</p>
2
2016-09-19T12:14:53Z
39,617,461
<p>Here is what is going on:</p> <ol> <li>You start your process </li> <li><code>collect_statistics</code> runs</li> <li>Timer is started</li> <li>now the function called in the process(<code>collect_statistics</code>) is finished, so the process quit, killing the timer in the same time.</li> </ol> <p>Here is how to fix it :</p> <p><strong>stat_collect.py</strong></p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- from threading import Timer from os import path from datetime import datetime import time STAT_DATETIME_FMT = '%Y-%m-%d %H:%M:%S' def collect_statistics(): while True: my_file = 'test.file' if not path.exists(my_file): with open(my_file, 'w') as fp: fp.write(datetime.now().strftime(STAT_DATETIME_FMT) + '\n') else: with open(my_file, 'a') as fp: fp.write(datetime.now().strftime(STAT_DATETIME_FMT) + '\n') time.sleep(1) if __name__ == '__main__': collect_statistics() </code></pre> <p>And for the calling script :</p> <pre><code>#!/usr/bin/env python from multiprocessing import Process from stat_collect import collect_statistics # logger sc if __name__ == '__main__': # This don't work p = Process(target=collect_statistics) p.start() p.join() # wait until process is over, e.g forever </code></pre> <p><code>p.join()</code> is just here to replace you infinite while loop, which is taking a lot of ressource for nothing.</p>
1
2016-09-21T13:07:36Z
[ "python", "multithreading", "python-multiprocessing" ]
Tuples in python to 3D matrix
39,573,129
<p>I have a list of lists in python that contains the score of users in a game with different courses and levels. My tuple (users, courses, levels, scores). I ve got 20 users 4 courses and 10 levels. What I want is to create a 3D matrix which will have as dimensions users-courses-levels and as a value user score. My tuples are as of the following:</p> <pre><code>(110, u'Math', 1, 5) (110, u'Sports', 1, 5) (110, u'Geography', 1, 10) (112, u'History', 1, 9) (112, u'History', 2, 10) ... ... ... ... ... ... .. </code></pre> <p>How can I create the 3D matrix (putting zero in the fields that I dont have data)? </p>
1
2016-09-19T12:25:15Z
39,575,380
<p>If you really need the data in that form, you could do something like:</p> <pre><code>data = [(110, 'Math', 1, 5), (110, 'Sports', 1, 5), (110, 'Geography', 1, 10), (112, 'History', 1, 9), (112, 'History', 2, 10)] #I'm using Python 3 -- u'' is superfluous dataDict = {(x,y,z):w for x,y,z,w in data} users = [110,112] #extend as needed. Also -- easily grabbed by code subjects = ['Math', 'Sports', 'Geography', 'History'] #etc levels = [1,2] #etc. #first create a matrix of the right shape initialized to zeros: dataMatrix = [[[0 for k in range(len(levels))] for j in range(len(subjects))] for i in range(len(users))] #then load the nonzeros: for i,u in enumerate(users): for j,s in enumerate(subjects): for k,l in enumerate(levels): if (u,s,l) in dataDict: dataMatrix[i][j][k] = dataDict[u,s,l] </code></pre> <p>To view it, do something like:</p> <pre><code>&gt;&gt;&gt; for layer in dataMatrix: print(layer) [[5, 0], [5, 0], [10, 0], [0, 0]] [[0, 0], [0, 0], [0, 0], [9, 10]] </code></pre> <p>the first layer is the 2-D matrix corresponding to the first user, etc.</p> <p>Having done all this -- I really don't see any reason anybody would want to use <code>dataMatrix</code> rather than <code>dataDict</code>.</p>
1
2016-09-19T14:15:43Z
[ "python" ]
Django validate what user sends from admin panel
39,573,167
<p>I am kind of new to Django, and i am trying to make sort of a news website where users can submit articles(with an account) but the admin needs to check them before they can be posted. Is that possible?</p>
1
2016-09-19T12:27:08Z
39,573,262
<p>Yes, it is. </p> <p>The simplest approach would be creating simple flag in model let's say a Boolean field named <code>verified</code>, which by default would be False. You could add permissions. So in the end you could overwrite a function in your admin form, and show the field for superuser only.</p> <pre><code>class MyUserAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): self.exclude = [] if not request.user.is_superuser: self.exclude.append('Permissions') #here! return super(MyUserAdmin, self).get_form(request, obj, **kwargs) </code></pre>
2
2016-09-19T12:31:23Z
[ "python", "django", "frameworks", "website" ]
Output Projection in Seq2Seq model Tensorflow
39,573,188
<p>I'm going through the translation code implemented by <code>tensorflow</code> using <code>seq2seq</code> model. I'm following <code>tensorflow</code> tutorial about <a href="https://www.tensorflow.org/versions/r0.10/tutorials/seq2seq/index.html" rel="nofollow"><code>seq2seq</code> model</a>.</p> <p>In that tutorial there is a part explaining a concept called <a href="https://www.tensorflow.org/versions/r0.10/tutorials/seq2seq/index.html#sampled-softmax-and-output-projection" rel="nofollow">output projection</a> which they have implemented in <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/rnn/translate/seq2seq_model.py" rel="nofollow">seq2seq_model.py</a> code. I understand the code. But I don't understand what this <strong>output projection</strong> part is doing.</p> <p>It would be great if someone can explain me what is going on behind this output projection thing..?</p> <p>Thank You!!</p>
0
2016-09-19T12:27:58Z
39,578,266
<p>Internally, a neural network operates on dense vectors of some size, often 256, 512 or 1024 floats (let's say 512 for here). But at the end it needs to predict a word from the vocabulary which is often much larger, e.g., 40000 words. Output projection is the final linear layer that converts (projects) from the internal representation to the larger one. So, for example, it can consist of a 512 x 40000 parameter matrix and a 40000 parameter for the bias vector. The reason it is kept separate in seq2seq code is that some loss functions (e.g., the sampled softmax loss) need direct access to the final 512-sized vector and the output projection matrix. Hope that helps!</p>
1
2016-09-19T16:52:10Z
[ "python", "tensorflow" ]
why using matplotlib text alignent with string format functions works wrong?
39,573,252
<p>I am trying to align my texts to right in matplotlib bars. The following codes works just fine:</p> <pre><code>colors = ['red', 'blue', 'green', 'yellow'] for color in colors: print('{:&gt;15}'.format(color)) </code></pre> <p>output:</p> <pre><code> red blue green yellow </code></pre> <p>However, the same string format doesn't work in plt.text functions:</p> <pre><code>fig, ax = plt.subplots() bar_band = ax.barh(range(len(colors)), np.ones(len(colors)), height=1) for i in range(len(colors)): bar_band[i].set_color(colors[i]) ax.text(0.1, i+0.4, "{:&gt;15}".format(colors[i])) ax.set_axis_off() plt.show() </code></pre> <p>I got texts aligns to center instead. Can any one help me on this?</p> <p><a href="http://i.stack.imgur.com/mki3f.png" rel="nofollow">enter image description here</a></p>
0
2016-09-19T12:31:02Z
39,573,344
<p><a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.text" rel="nofollow"><code>ax.text()</code></a> creates a matplotlib <code>Text</code> object, which have the option <a href="http://matplotlib.org/api/text_api.html#matplotlib.text.Text.set_horizontalalignment" rel="nofollow"><code>horizontalalignment</code></a> (or <code>ha</code> for short). This can help you to align the text to your desired position.</p> <p>Accepted options are <code>'left'</code>, <code>'right'</code> and <code>'center'</code></p> <p>So, you might try: </p> <pre><code>ax.text(0.1, i+0.4, "{:&gt;15}".format(colors[i]), ha='right') </code></pre>
0
2016-09-19T12:35:25Z
[ "python", "string", "matplotlib", "plot", "text-alignment" ]
How to create field named «from» in WTForms?
39,573,284
<p>I want to make a form for selecting an interval with two fields: <code>from</code> and <code>to</code>. But since <code>from</code> is a keyword in Python, I can't just write:</p> <pre class="lang-python prettyprint-override"><code>class MyForm(Form): from = DateField() to = DateField() </code></pre> <p>This means that I have to name the field in Python differently but I still want to name the field in GET query exactly <code>from</code>. Is it possible with WTForms?</p>
1
2016-09-19T12:32:27Z
39,673,889
<p>You can use Python's built in function <code>setattr</code>:</p> <pre><code>class MyForm(Form): to = DateField() setattr(MyForm, 'from', DateField()) myform = MyForm() </code></pre> <p>You can access the field again with <code>getattr</code>:</p> <pre><code>from_ = getattr(myform, 'from') </code></pre>
1
2016-09-24T07:46:10Z
[ "python", "wtforms" ]
Deploy Python executable to Azure Service Fabric
39,573,315
<p>I am looking for helpful solutions to deploy <code>Python</code> executable to <code>Azure Service Fabric</code></p> <p>There is documentation for <code>node js</code> <a href="https://azure.microsoft.com/en-us/documentation/articles/service-fabric-deploy-multiple-apps/" rel="nofollow">here</a> but I could not find anything related to <code>python</code></p>
1
2016-09-19T12:33:55Z
39,599,956
<p>This shouldn't be any different for Python, as long as you either install the Python requirements directly on the nodes through a script extension (for Azure). Or call the Python installer as the SetupEntryPoint.</p>
0
2016-09-20T17:04:41Z
[ "python", "azure", "web-deployment" ]
find all words in list/file that begin/ends with a specific prefix/suffix
39,573,394
<p>The below code gives the words which begin/ends with a specific prefix/suffix.</p> <pre><code>string_list = [line.strip() for line in open("file.txt", 'r')] for word in string_list: if word[-1] == "a": print word string_list = [line.strip() for line in open("file.txt", 'r')] for word in string_list: if word[0] == "fi": print word </code></pre> <p>How can i optimize it to be real fast on huge data. also how can i pass the param like</p> <pre><code>python test.py --prefix fi python test.py --suffix o </code></pre> <p>Thanks in advance.</p>
1
2016-09-19T12:37:31Z
39,573,479
<p>If <code>word</code> is a string, then <code>word[0] == "fi"</code> does not do what you think it does. </p> <p>You can instead use <code>startswith</code> and <code>endswith</code> to check for <em>multicharacter</em> suffixes and prefixes.</p> <pre><code>string_list = open("file.txt", 'r') for word in string_list: if word.startswith("fi") or word.endswith('a'): print word </code></pre> <hr> <p>To pass the suffix/ prefix as a parameter to your script, have a look at <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow"><code>argparse</code></a></p>
1
2016-09-19T12:41:40Z
[ "python", "regex", "prefix", "suffix" ]
find all words in list/file that begin/ends with a specific prefix/suffix
39,573,394
<p>The below code gives the words which begin/ends with a specific prefix/suffix.</p> <pre><code>string_list = [line.strip() for line in open("file.txt", 'r')] for word in string_list: if word[-1] == "a": print word string_list = [line.strip() for line in open("file.txt", 'r')] for word in string_list: if word[0] == "fi": print word </code></pre> <p>How can i optimize it to be real fast on huge data. also how can i pass the param like</p> <pre><code>python test.py --prefix fi python test.py --suffix o </code></pre> <p>Thanks in advance.</p>
1
2016-09-19T12:37:31Z
39,574,034
<p>If you need speed, you could simply use <a href="https://en.wikipedia.org/wiki/Grep" rel="nofollow">GREP</a>, which is written in a lowlevel language and is bound to be faster than a python loop by leaps and bounds. </p> <p>It is also portable and runs just fine on Linux/Windows/OSX/...</p>
0
2016-09-19T13:09:04Z
[ "python", "regex", "prefix", "suffix" ]
Update default value Entry Widget
39,573,459
<p>I have a toplevel window containing a simple entry widget and two buttons. (Class opc)</p> <p>The entry widget has assigned a default value "test". What I´m trying to do is update this default value when the user input a new value, and show this as default in new instances of the window.</p> <p>When I change the value and save changes, new instances of the windows always show "test" and not the new input.</p> <p>What is the best way to do this? Should I use "Stringvar"?</p> <pre><code>import tkinter as tk from tkinter import ttk class TEP(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) self.parent = parent label=tk.LabelFrame(self, text="REFERENCIAS", height=180, labelanchor="n",borderwidth="2",relief="groove") label.pack(fill="x",padx=10,pady=10) class opc(tk.Frame): def __init__(self, parent,*args, **kwargs): tk.Frame.__init__(self, parent,*args, **kwargs) self.parent = parent self.grid() datlab = tk.LabelFrame(self.parent, text="Información", labelanchor="nw",borderwidth="2",relief="groove") datlab.grid(column=0,row=0,padx=5,pady=3,ipadx=5,ipady=5) labelproy=tk.Label(datlab,text="Proyecto:",padx=5,pady=5) labelproy.grid(column=0, row=0, sticky=tk.W) self.entrproy=tk.Entry(datlab,width=27) self.entrproy.insert(0,"Test") self.entrproy.grid(row=0,column=1,sticky=tk.W,padx=5) self.ok = ttk.Button(self.parent, text="OK", command=self.getdata) self.ok.grid(column=0,row=4,sticky=tk.W,padx=50,pady=7) self.cancel = ttk.Button(self.parent, text="Cancelar", command=self.parent.destroy) self.cancel.grid(column=0,row=4,sticky=tk.E,padx=50,pady=7) self.parent.bind('&lt;Return&gt;',self.getdata) def getdata(self,*args): self.Proyecto=self.entrproy.get() print(self.Proyecto) self.parent.destroy() def main(): root = tk.Tk() app = TEP(root) app.pack(side="top", fill="both", expand = True) menubar=MenuBar(root) menubar.add root.config(menu=menubar) root.title("App") root.focus_force() # root.wm_state('zoomed') root.minsize(width=1000, height=420) root.columnconfigure(0,weight=1) root.rowconfigure(0,weight=1) root.mainloop() if __name__ == '__main__': main() </code></pre>
0
2016-09-19T12:40:34Z
39,587,366
<p>One option is to create a list owned by the class, i.e.:</p> <pre><code>class classname(object): defaultvalue=[100] #Default is 100 def dostuff(self): self.defaultvalue[0]=self.entryname.get() </code></pre> <p>The basic idea is that each class has the same value for defaultvalue: a link to a spot in memory where '100' is stored. If you change the value at that location, it will update it for future instances of the class.</p>
0
2016-09-20T06:44:09Z
[ "python", "tkinter" ]
How to ignore lower as well upper case of a word in python?
39,573,486
<p>I want to find <strong>Andy</strong> in the list. Either <strong>Andy</strong> comes in upper or lower case in string the program should return <code>True</code> </p> <pre><code>String1 ='Andy is an awesome bowler' String2 ='andy is an awesome bowler' String3 ='ANDY is an awesome bowler' </code></pre> <p>I am doing in this way</p> <pre><code>if 'Andy' in String1: print ('success') else: print("Nothing") </code></pre> <p>But it is working only for <code>Andy</code> not for <code>andy</code> or <code>ANDY</code>. I do not want to use <code>Pattern</code> matching. By using <code>lower()</code> the <code>Andy</code> can be converted to lower case but I need both at a time ignoring lower as well as upper case. Is it possible? </p>
-1
2016-09-19T12:42:09Z
39,573,564
<p>You can convert the string to uppercase or lowercase first:</p> <pre><code>String1 ='Andy is an awesome bowler' String2 ='andy is an awesome bowler' String3 ='ANDY is an awesome bowler' if 'andy' in String1.lower(): # or this could be if 'ANDY' in String1.upper(): print('success') else: print('Nothing') </code></pre>
3
2016-09-19T12:46:14Z
[ "python" ]
How to ignore lower as well upper case of a word in python?
39,573,486
<p>I want to find <strong>Andy</strong> in the list. Either <strong>Andy</strong> comes in upper or lower case in string the program should return <code>True</code> </p> <pre><code>String1 ='Andy is an awesome bowler' String2 ='andy is an awesome bowler' String3 ='ANDY is an awesome bowler' </code></pre> <p>I am doing in this way</p> <pre><code>if 'Andy' in String1: print ('success') else: print("Nothing") </code></pre> <p>But it is working only for <code>Andy</code> not for <code>andy</code> or <code>ANDY</code>. I do not want to use <code>Pattern</code> matching. By using <code>lower()</code> the <code>Andy</code> can be converted to lower case but I need both at a time ignoring lower as well as upper case. Is it possible? </p>
-1
2016-09-19T12:42:09Z
39,573,750
<p>If you are sure that you string contains only ascii characters, use the following approach: </p> <pre><code>if 'andy' in string1.lower(): do something </code></pre> <p>If your comparision strings involve unicodedata: </p> <pre><code>import unicodedata def normalize_caseless(text): return unicodedata.normalize("any_string", text.casefold()) def caseless_equal(left, right): return normalize_caseless(left) == normalize_caseless(right) </code></pre>
1
2016-09-19T12:54:35Z
[ "python" ]
How to detect logic gates from scanned images of hand drawn circuits?
39,573,527
<p>we started with scanned images of proper drawn diagrams of logic circuit we were able to separate the logic gates from the scanned image of the circuit however we were not able detect and how to proceed further,we had use python open cv for this ,our code for the above is</p> <pre><code>import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('logic.png',0) ret,img2 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV) # converting the image into binary image. kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(100,3)) # kernel to detect vertical lines vertical = cv2.morphologyEx(img2, cv2.MORPH_OPEN, kernel) # applying morphological opening operation to detect vertical lines vertical = cv2.dilate(vertical,kernel,iterations = 1) #dilate the vertical lines obtained kernel2 = cv2.getStructuringElement(cv2.MORPH_RECT,(3,100)) # kernel to detect horizontal lines horizontal = cv2.morphologyEx(img2, cv2.MORPH_OPEN, kernel2) # applying morphological opening operation to detect horizontal lines horizontal = cv2.dilate(horizontal,kernel2,iterations = 1) #dilate the horizontal lines obtained cv2.imshow('d',vertical) # show the vertical imag cv2.imshow('b',horizontal) # show the horizontal image img = img2 -horizontal - vertical # subtracting horizontal and vertical lines from original image cv2.imwrite('horizontal.png',horizontal) cv2.imwrite('vertical.png',vertical) cv2.imwrite('result.png',img) cv2.imshow('last',img) # show the resulted image after subtraction kerne = np.ones((3,3),np.uint8) # kernel to remove the noise from the last image opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kerne) # applying opening morphological operation to remove the noise from the image cv2.imshow('opening',opening) # show the resulted image after removing noise cv2.imwrite('noise_removal.png',opening) cv2.waitKey(0) </code></pre> <p>Check the result below and advise how to proceed further to detect the logic gates from the scanned images of hand drawn circuits?</p> <p>The result of the code is below : <br></p> <p><strong>1)</strong> Input Image : <br> <img src="http://i.stack.imgur.com/9oLC9.png"/></p> <p><strong>2)</strong> Output Image (code result) : <br><br> <img src="http://i.stack.imgur.com/MKUjF.jpg"/></p>
1
2016-09-19T12:44:42Z
39,603,383
<p>The logic doors all have the same size. I would do that:</p> <ol> <li>Connected component labeling of white areas.</li> <li>Separate/isolate</li> <li>Filter the labels by the size.</li> <li>(optional) All the logic doors will touch a tiny white pattern/label on the right.</li> </ol>
0
2016-09-20T20:42:11Z
[ "python", "opencv", "image-processing", "image-recognition", "morphological-analysis" ]
Project Euler #13 Python. Incorrect carry over
39,573,554
<p>This problem asks to sum up 100 numbers, each 50 digits long. <a href="http://code.jasonbhill.com/python/project-euler-problem-13/" rel="nofollow">http://code.jasonbhill.com/python/project-euler-problem-13/</a></p> <p>We can replace <code>\n</code> with "\n+" in Notepad++ yielding</p> <pre><code>a=37107287533902102798797998220837590246510135740250 +46376937677490009712648124896970078050417018260538 ... +20849603980134001723930671666823555245252804609722 +53503534226472524250874054075591789781264330331690 print(a) </code></pre> <p><code>&gt;&gt;37107287533902102798797998220837590246510135740250</code> (incorrect)</p> <p>We can as well replace <code>\n</code> with <code>\na+=</code> yielding </p> <pre><code>a=37107287533902102798797998220837590246510135740250 a+=46376937677490009712648124896970078050417018260538 ... a+=20849603980134001723930671666823555245252804609722 a+=53503534226472524250874054075591789781264330331690 print(a) </code></pre> <p><code>&gt;&gt;553...</code> (correct)</p> <p>This seems to be a feature of BigInteger arithmetic. Under which conditions a sum of all numbers (Method 1) yields different result from an iterative increment (Method 2)?</p>
0
2016-09-19T12:45:52Z
39,573,694
<p>Python source code lines are terminated by newline characters. The subsequent lines in the first example are separate expression statements consisting of a single integer with a unary plus operator in front, but they don't do anything. They evaluate the expression (resulting in the integer constant itself), and then ignore the result. If you put all numbers on a single line, or use parentheses around the addition, the simple sum will work as well.</p>
0
2016-09-19T12:52:06Z
[ "python" ]
Project Euler #13 Python. Incorrect carry over
39,573,554
<p>This problem asks to sum up 100 numbers, each 50 digits long. <a href="http://code.jasonbhill.com/python/project-euler-problem-13/" rel="nofollow">http://code.jasonbhill.com/python/project-euler-problem-13/</a></p> <p>We can replace <code>\n</code> with "\n+" in Notepad++ yielding</p> <pre><code>a=37107287533902102798797998220837590246510135740250 +46376937677490009712648124896970078050417018260538 ... +20849603980134001723930671666823555245252804609722 +53503534226472524250874054075591789781264330331690 print(a) </code></pre> <p><code>&gt;&gt;37107287533902102798797998220837590246510135740250</code> (incorrect)</p> <p>We can as well replace <code>\n</code> with <code>\na+=</code> yielding </p> <pre><code>a=37107287533902102798797998220837590246510135740250 a+=46376937677490009712648124896970078050417018260538 ... a+=20849603980134001723930671666823555245252804609722 a+=53503534226472524250874054075591789781264330331690 print(a) </code></pre> <p><code>&gt;&gt;553...</code> (correct)</p> <p>This seems to be a feature of BigInteger arithmetic. Under which conditions a sum of all numbers (Method 1) yields different result from an iterative increment (Method 2)?</p>
0
2016-09-19T12:45:52Z
39,573,705
<p>As you can see in the result, the first set of instruction is not computing the sum. It preserved the first assignment. Since <code>+N</code> is on its own a valid instruction, the next lines after the assignment do nothing. Thus</p> <pre><code>a=42 +1 print a </code></pre> <p>prints <code>42</code></p> <p>To write an instruction over two lines, you need to escape the ending newline <code>\n</code> :</p> <pre><code>a=42\ +1 </code></pre> <p>43</p>
1
2016-09-19T12:52:38Z
[ "python" ]
How to compare four columns of pandas dataframe at a time?
39,573,574
<p>I have one dataframe. </p> <p><strong>Dataframe :</strong> </p> <pre><code> Symbol1 BB Symbol2 CC 0 ABC 1 ABC 1 1 PQR 1 PQR 1 2 CPC 2 CPC 0 3 CPC 2 CPC 1 4 CPC 2 CPC 2 </code></pre> <p>I want to compare <code>Symbol1</code> with <code>Symbol2</code> and <code>BB</code> with <code>CC</code>, if they are same then I want that rows only other rows must be removed from the dataframe.</p> <p><strong>Expected Result :</strong></p> <pre><code>Symbol1 BB Symbol2 CC 0 ABC 1 ABC 1 1 PQR 1 PQR 1 2 CPC 2 CPC 2 </code></pre> <p>If comparison between two rows then I'm using : </p> <pre><code>df = df[df['BB'] == '2'].copy() </code></pre> <p>It will work fine.</p> <pre><code>df = df[df['BB'] == df['offset'] and df['Symbol1'] == df['Symbol2']].copy() </code></pre> <p>It is giving me error.</p> <p><strong>Error :</strong> </p> <pre><code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). </code></pre> <p>How I can compare and get expected result?</p>
3
2016-09-19T12:46:48Z
39,573,631
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing"><code>boolean indexing</code></a> and compare with <code>&amp;</code> instead <a href="http://stackoverflow.com/a/21415990/2901002"><code>and</code></a>:</p> <pre><code>print ((df.Symbol1 == df.Symbol2) &amp; (df.BB == df.CC)) 0 True 1 True 2 False 3 False 4 True dtype: bool print (df[(df.Symbol1 == df.Symbol2) &amp; (df.BB == df.CC)]) Symbol1 BB Symbol2 CC 0 ABC 1 ABC 1 1 PQR 1 PQR 1 4 CPC 2 CPC 2 </code></pre>
6
2016-09-19T12:49:19Z
[ "python", "pandas", "indexing", "dataframe", "condition" ]
How to compare four columns of pandas dataframe at a time?
39,573,574
<p>I have one dataframe. </p> <p><strong>Dataframe :</strong> </p> <pre><code> Symbol1 BB Symbol2 CC 0 ABC 1 ABC 1 1 PQR 1 PQR 1 2 CPC 2 CPC 0 3 CPC 2 CPC 1 4 CPC 2 CPC 2 </code></pre> <p>I want to compare <code>Symbol1</code> with <code>Symbol2</code> and <code>BB</code> with <code>CC</code>, if they are same then I want that rows only other rows must be removed from the dataframe.</p> <p><strong>Expected Result :</strong></p> <pre><code>Symbol1 BB Symbol2 CC 0 ABC 1 ABC 1 1 PQR 1 PQR 1 2 CPC 2 CPC 2 </code></pre> <p>If comparison between two rows then I'm using : </p> <pre><code>df = df[df['BB'] == '2'].copy() </code></pre> <p>It will work fine.</p> <pre><code>df = df[df['BB'] == df['offset'] and df['Symbol1'] == df['Symbol2']].copy() </code></pre> <p>It is giving me error.</p> <p><strong>Error :</strong> </p> <pre><code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). </code></pre> <p>How I can compare and get expected result?</p>
3
2016-09-19T12:46:48Z
39,574,920
<p>Here is an alternative way, which is bit nicer, but it's also bit slower:</p> <pre><code>In [65]: df.query('Symbol1 == Symbol2 and BB == CC') Out[65]: Symbol1 BB Symbol2 CC 0 ABC 1 ABC 1 1 PQR 1 PQR 1 4 CPC 2 CPC 2 </code></pre>
3
2016-09-19T13:52:56Z
[ "python", "pandas", "indexing", "dataframe", "condition" ]
share variables by PHP, python, bash
39,573,614
<p>I have project that uses same initial variables on same server by different programming languages. they are PHP, python and bash. i need all languages to access those variable and I cannot exclude any language.</p> <p>for now I keep 3 places to store variables: for php I have Mysql storage, for python and bash 2 separate files</p> <p>if initial value of any variable changes, i need to change it at 3 locations</p> <p>i want to simplify that now. lest assume all systems can access Mysql. is there the way define initial variables in Mysql instead of files? or what is the best practice to share variables in my case?</p>
1
2016-09-19T12:48:37Z
39,580,897
<p>OK, I think the best approach for me here would be to limit variable storages from 3 to at least 2 and make python script deal with bash tasks over os.system. To use 2 storages is somehow manageable</p>
0
2016-09-19T19:43:45Z
[ "php", "python", "bash", "variables", "share" ]
Python - Can't connect to MS SQL
39,573,669
<p>When I try to connect to MS SQL, I got this error:</p> <pre><code>&gt; pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC Driver 13 for SQL &gt; Server]SQL Server Network Interfaces: Error Locating Server/Instance &gt; Specified [xFFFFFFFF]. (-1) (SQLDriverConnect); [HYT00] &gt; [Microsoft][ODBC Driver 13 for SQL Server]Login timeout expired (0); &gt; [08001] [Microsoft][ODBC Driver 13 for SQL Server]A network-related or &gt; instance-specific error has occurred while establishing a connection &gt; to SQL Server. Server is not found or not accessible. Check if &gt; instance name is correct and if SQL Server is configured to allow &gt; remote connections. For more information see SQL Server Books Online. &gt; (-1)') </code></pre> <p>How can I resolve this error and finally connect to the database? </p>
1
2016-09-19T12:51:10Z
39,573,670
<p>In my case, it was solved by activating <code>SQL Server (SQLEXPRESS)</code> in services. It turns out, it doesn't turn on automatically when the computer starts.</p> <p><a href="http://i.stack.imgur.com/D6hsT.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/D6hsT.jpg" alt="enter image description here"></a></p>
1
2016-09-19T12:51:10Z
[ "python", "sql-server", "database", "database-connection", "pyodbc" ]
How do I get the filepath of an uploaded file?
39,573,710
<p>I'm having difficulty passing the path of a file to a library called Textract.</p> <pre><code>def file_to_string(filepath): text = textract.process(filepath) print text return text </code></pre> <p>Here is my upload form in views.py</p> <pre><code>if request.method == 'POST': upload_form = UploadFileForm(request.POST, request.FILES) if upload_form.is_valid(): file = request.FILES['file'] filetosave = File(file=file, filename=file.name) filetosave.save() if validate_file_extension(file): request.session['text'] = file_to_string(file) # something in here else: upload_form=UploadFileForm() </code></pre> <p>models.py</p> <pre><code>class File(models.Model): filename = models.CharField(max_length=200) file = models.FileField(upload_to='files/%Y/%m/%d') upload_date=models.DateTimeField(auto_now_add =True) status = models.CharField(max_length=200) def __unicode__(self): return self.filename </code></pre> <p>Now Textract expects a path to go into <code>file_to_string(filepath)</code>. If I try to pass in the file object it gives me an error: <code>"coercing to Unicode: need string or buffer, InMemoryUploadedFile found"</code>.</p> <p>But if it is an InMemoryUploadedFile type, how do I get the path? I understand this is stored in memory and doesn't have a path.</p> <p>How should I handle this -- should I save the file object first and then try to access it? If I save the file and then try <code>request.session['text'] = file_to_string(file.name)</code> it gives a <code>MissingFileError</code>, though the docs say that this should give the name of the file including the relative path from MEDIA_ROOT.</p> <p>Thanks a lot in advance.</p>
0
2016-09-19T12:52:55Z
39,574,121
<p>Try using <code>file_to_string(file.name)</code>.</p> <p>Docs: <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.fields.files.FieldFile.name" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.fields.files.FieldFile.name</a></p>
0
2016-09-19T13:13:41Z
[ "python", "django", "django-models", "django-uploads" ]
How do I get the filepath of an uploaded file?
39,573,710
<p>I'm having difficulty passing the path of a file to a library called Textract.</p> <pre><code>def file_to_string(filepath): text = textract.process(filepath) print text return text </code></pre> <p>Here is my upload form in views.py</p> <pre><code>if request.method == 'POST': upload_form = UploadFileForm(request.POST, request.FILES) if upload_form.is_valid(): file = request.FILES['file'] filetosave = File(file=file, filename=file.name) filetosave.save() if validate_file_extension(file): request.session['text'] = file_to_string(file) # something in here else: upload_form=UploadFileForm() </code></pre> <p>models.py</p> <pre><code>class File(models.Model): filename = models.CharField(max_length=200) file = models.FileField(upload_to='files/%Y/%m/%d') upload_date=models.DateTimeField(auto_now_add =True) status = models.CharField(max_length=200) def __unicode__(self): return self.filename </code></pre> <p>Now Textract expects a path to go into <code>file_to_string(filepath)</code>. If I try to pass in the file object it gives me an error: <code>"coercing to Unicode: need string or buffer, InMemoryUploadedFile found"</code>.</p> <p>But if it is an InMemoryUploadedFile type, how do I get the path? I understand this is stored in memory and doesn't have a path.</p> <p>How should I handle this -- should I save the file object first and then try to access it? If I save the file and then try <code>request.session['text'] = file_to_string(file.name)</code> it gives a <code>MissingFileError</code>, though the docs say that this should give the name of the file including the relative path from MEDIA_ROOT.</p> <p>Thanks a lot in advance.</p>
0
2016-09-19T12:52:55Z
39,574,169
<p><code>request.session['text'] = file_to_string(filetosave.file.path)</code> should do the trick</p>
0
2016-09-19T13:16:13Z
[ "python", "django", "django-models", "django-uploads" ]
Django - dropdown form with multiple select
39,573,772
<p><strong>I need guidance building a django <em>dropdown</em> <code>forms.Form</code> field in which I can select <em>multiple</em> choices. I need to select multiple locations on the <code>office</code> field of the form.</strong></p> <p>When submitted, the form needs to return a <code>list</code> of the chosen offices (e.g. <code>["New York", "Los Angeles"]</code> or <code>["Austin"]</code>). Returning a <code>tuple</code> is also acceptable.</p> <hr> <p>The best I can do right now is build a <a href="https://docs.djangoproject.com/en/1.10/ref/forms/fields/#multiplechoicefield" rel="nofollow">multipleChoiceField</a> for <code>office</code> with the following:</p> <pre><code>from django import forms class my_Form(forms.Form): OPTIONS = [ ("0", "*ALL"), ("1", "New York"), ("2", "Los Angeles"), ] office = forms.MultipleChoiceField( choices=OPTIONS, initial='0', widget=forms.SelectMultiple(), required=True, label='Office', ) </code></pre> <p>resulting in this form field layout:</p> <p><a href="http://i.stack.imgur.com/7OZIH.png" rel="nofollow"><img src="http://i.stack.imgur.com/7OZIH.png" alt="enter image description here"></a></p> <hr> <p>However, I would like this field to be a dropdown, to take up less space on the page.</p> <p>I found this <a href="https://djangosnippets.org/snippets/747/" rel="nofollow">djangosnippet</a> but (1) a few people have mentioned it appears out of date (I can't confirm), and (2) I first want to check if a built-in django form/widget setup can fulfill this task before using custom code.</p>
0
2016-09-19T12:55:54Z
39,573,931
<p>"Dropdown" boxes don't support multiple selection in HTML; browsers will always render it as a flat box as your image shows.</p> <p>You probably want to use some kind of JS widget - <a href="https://select2.github.io/" rel="nofollow">Select2</a> is a popular one. There are a couple of Django projects - <a href="https://github.com/applegrew/django-select2" rel="nofollow">django-select2</a>, <a href="https://github.com/asyncee/django-easy-select2" rel="nofollow">django-easy-select</a> - that aim to make it simple to integrate that into your form; I have no experience with either of them.</p> <p>(And yes, that snippet - like many things on Djangosnippets - is massively out of date; "newforms" was renamed to "forms" even before version 1.0 of Django.)</p>
1
2016-09-19T13:03:33Z
[ "python", "django", "forms" ]
Django - dropdown form with multiple select
39,573,772
<p><strong>I need guidance building a django <em>dropdown</em> <code>forms.Form</code> field in which I can select <em>multiple</em> choices. I need to select multiple locations on the <code>office</code> field of the form.</strong></p> <p>When submitted, the form needs to return a <code>list</code> of the chosen offices (e.g. <code>["New York", "Los Angeles"]</code> or <code>["Austin"]</code>). Returning a <code>tuple</code> is also acceptable.</p> <hr> <p>The best I can do right now is build a <a href="https://docs.djangoproject.com/en/1.10/ref/forms/fields/#multiplechoicefield" rel="nofollow">multipleChoiceField</a> for <code>office</code> with the following:</p> <pre><code>from django import forms class my_Form(forms.Form): OPTIONS = [ ("0", "*ALL"), ("1", "New York"), ("2", "Los Angeles"), ] office = forms.MultipleChoiceField( choices=OPTIONS, initial='0', widget=forms.SelectMultiple(), required=True, label='Office', ) </code></pre> <p>resulting in this form field layout:</p> <p><a href="http://i.stack.imgur.com/7OZIH.png" rel="nofollow"><img src="http://i.stack.imgur.com/7OZIH.png" alt="enter image description here"></a></p> <hr> <p>However, I would like this field to be a dropdown, to take up less space on the page.</p> <p>I found this <a href="https://djangosnippets.org/snippets/747/" rel="nofollow">djangosnippet</a> but (1) a few people have mentioned it appears out of date (I can't confirm), and (2) I first want to check if a built-in django form/widget setup can fulfill this task before using custom code.</p>
0
2016-09-19T12:55:54Z
39,722,350
<p>You can choose multiple choices by using Django select2. Include below code in your respective HTML file.</p> <pre><code>&lt;link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" /&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"&gt;&lt;/script&gt; &lt;select class="select_field_class" multiple="multiple" name="option" id="option"&gt; &lt;option value=""&gt;Enter the option&lt;/option&gt; {% for option in options %} &lt;option value="{{ option.id }}"&gt;{{ option.name }}&lt;/option&gt; {% endfor %} &lt;/select&gt; $('.select_field_class').select2( { placeholder: "Select here", maximumSelectionSize: 100 } ); </code></pre>
0
2016-09-27T10:30:50Z
[ "python", "django", "forms" ]
python - Convert list of dicts to hierarchy/multiple nested dicts - issue with orders
39,573,845
<p>Currently I have these input:</p> <pre><code>query = [{'id': 1, 'desc': 'desc_father', 'parent_id': None} ,{'id': 2, 'desc': 'desc_child_1', 'parent_id': 10} ,{'id': 3, 'desc': 'desc_child_2', 'parent_id': 2} ,{'id': 4, 'desc': 'desc_child_5', 'parent_id': 5} ,{'id': 5, 'desc': 'desc_child_6', 'parent_id': 6} ,{'id': 6, 'desc': 'desc_child_1', 'parent_id': 1}] </code></pre> <p>This is my recursive function:</p> <pre><code>def recursive(parent_list, child_dict, parent_id): for l in parent_list: if parent_id in l.values(): if 'children' not in l: l['children'] = [] l['children'].append(child_dict) break else: for i in l: if isinstance(l[i], list): recursive(d[i], child_dict, parent_id) return parent_list </code></pre> <p>This is my main code:</p> <pre><code>results = [] for q in query: dict_item = {} dict_item['id'] = q['id'] dict_item['desc'] = q['desc'] if q['parent_id'] is None: results.append(dict_item) else: results= recursive(results, dict_item, q['parent_id']) return results </code></pre> <p>So, with above given data and the code, I have the result as below:</p> <pre><code>[{ 'desc' : 'desc_father', 'id' : 1, 'children' : [{ 'desc' : 'desc_child_1', 'id' : 2, 'children' : [{ 'desc' : 'desc_child_2', 'id' : 3 } ] }, { 'desc' : 'desc_child_1', 'id' : 6 } ] } ] </code></pre> <p>This result is as you could see missing the items with <code>id = 4</code> and <code>id = 5</code> because during the loops, the parents of these items haven't been created yet (the items with <code>id = 5</code> &amp; <code>id = 6</code>). I am having difficulties in fixing this problem as I don't know how to traverse back or forward the list to create the father item before the children ones. Help is appreciated. Thanks in advance. </p> <p><strong><em>UPDATED</em></strong></p> <p>I have added in one case for my query, which is the item with <code>id = 2</code>, this time the item is updated its parent_id to 10 (<code>parent_id = 10</code>), since we do not have the item with <code>id = 10</code> as parent in our return result, so this <code>id = 2</code> item will also be a root. </p> <p>My new code based on Scott Hunter guidance but I still could not make it to work. I must have misunderstood somewhere:</p> <pre><code>new_dict = {} for q in query: q['Children'] = [] new_dict[q['id']] = q for k, v in new_dict.iteritems(): print k, v if v['parent_id'] is not None and v['parent_id'] in new_dict: new_dict[k]['Children'].append(v) print new_dict </code></pre> <p><strong><em>UPDATED-2</em></strong></p> <p>Now I make it to work, based on Scott Hunter suggestion, please see my below code. However the code looks ugly with too many for, is there anyway that I could perfect this? Thanks a lot for your support, just one more step and it will be done!</p> <pre><code>new_dict = {} for q in query: q['children'] = [] q['parent'] = 1 new_dict[q['id']] = q for k, v in new_dict.iteritems(): p_id = v['parent_id'] for kk, vv in new_dict.iteritems(): if kk == p_id: v['parent'] = 0 vv['children'].append(v) results = [] for d_id, d_item in new_dict.iteritems(): if d_item['parent'] == 1: results.append(d_item) print results </code></pre>
1
2016-09-19T12:59:09Z
39,573,941
<p>This does not require recursion.</p> <p>First create a dictionary of nodes, one for each item using <code>id</code> as the key, which includes an empty list of children. Then you can scan that dictionary, and add each node to the list of children for its parent (skipping those whose parent is <code>None</code>). Once this scan is complete, every node that isn't a root will be in the child list of its parent, and thus all trees will be complete.</p> <p>The roots of the forrest are the nodes that have <code>None</code> for a parent.</p>
2
2016-09-19T13:04:19Z
[ "python", "dictionary", "recursion", "parent-child" ]
python - Convert list of dicts to hierarchy/multiple nested dicts - issue with orders
39,573,845
<p>Currently I have these input:</p> <pre><code>query = [{'id': 1, 'desc': 'desc_father', 'parent_id': None} ,{'id': 2, 'desc': 'desc_child_1', 'parent_id': 10} ,{'id': 3, 'desc': 'desc_child_2', 'parent_id': 2} ,{'id': 4, 'desc': 'desc_child_5', 'parent_id': 5} ,{'id': 5, 'desc': 'desc_child_6', 'parent_id': 6} ,{'id': 6, 'desc': 'desc_child_1', 'parent_id': 1}] </code></pre> <p>This is my recursive function:</p> <pre><code>def recursive(parent_list, child_dict, parent_id): for l in parent_list: if parent_id in l.values(): if 'children' not in l: l['children'] = [] l['children'].append(child_dict) break else: for i in l: if isinstance(l[i], list): recursive(d[i], child_dict, parent_id) return parent_list </code></pre> <p>This is my main code:</p> <pre><code>results = [] for q in query: dict_item = {} dict_item['id'] = q['id'] dict_item['desc'] = q['desc'] if q['parent_id'] is None: results.append(dict_item) else: results= recursive(results, dict_item, q['parent_id']) return results </code></pre> <p>So, with above given data and the code, I have the result as below:</p> <pre><code>[{ 'desc' : 'desc_father', 'id' : 1, 'children' : [{ 'desc' : 'desc_child_1', 'id' : 2, 'children' : [{ 'desc' : 'desc_child_2', 'id' : 3 } ] }, { 'desc' : 'desc_child_1', 'id' : 6 } ] } ] </code></pre> <p>This result is as you could see missing the items with <code>id = 4</code> and <code>id = 5</code> because during the loops, the parents of these items haven't been created yet (the items with <code>id = 5</code> &amp; <code>id = 6</code>). I am having difficulties in fixing this problem as I don't know how to traverse back or forward the list to create the father item before the children ones. Help is appreciated. Thanks in advance. </p> <p><strong><em>UPDATED</em></strong></p> <p>I have added in one case for my query, which is the item with <code>id = 2</code>, this time the item is updated its parent_id to 10 (<code>parent_id = 10</code>), since we do not have the item with <code>id = 10</code> as parent in our return result, so this <code>id = 2</code> item will also be a root. </p> <p>My new code based on Scott Hunter guidance but I still could not make it to work. I must have misunderstood somewhere:</p> <pre><code>new_dict = {} for q in query: q['Children'] = [] new_dict[q['id']] = q for k, v in new_dict.iteritems(): print k, v if v['parent_id'] is not None and v['parent_id'] in new_dict: new_dict[k]['Children'].append(v) print new_dict </code></pre> <p><strong><em>UPDATED-2</em></strong></p> <p>Now I make it to work, based on Scott Hunter suggestion, please see my below code. However the code looks ugly with too many for, is there anyway that I could perfect this? Thanks a lot for your support, just one more step and it will be done!</p> <pre><code>new_dict = {} for q in query: q['children'] = [] q['parent'] = 1 new_dict[q['id']] = q for k, v in new_dict.iteritems(): p_id = v['parent_id'] for kk, vv in new_dict.iteritems(): if kk == p_id: v['parent'] = 0 vv['children'].append(v) results = [] for d_id, d_item in new_dict.iteritems(): if d_item['parent'] == 1: results.append(d_item) print results </code></pre>
1
2016-09-19T12:59:09Z
39,575,135
<p>This would be my solution:</p> <pre><code>#! /usr/bin/env python3 from pprint import pprint query = [{'id': 1, 'desc': 'desc_father', 'parent_id': None} ,{'id': 2, 'desc': 'desc_child_1', 'parent_id': 1} ,{'id': 3, 'desc': 'desc_child_2', 'parent_id': 2} ,{'id': 4, 'desc': 'desc_child_5', 'parent_id': 5} ,{'id': 5, 'desc': 'desc_child_6', 'parent_id': 6} ,{'id': 6, 'desc': 'desc_child_1', 'parent_id': 1}] def rec(query, parent): parent['children'] = [] for item in query: if item['parent_id'] == parent['id']: parent['children'].append(item) rec(query, item) root = {'id': None} rec(query, root) pprint(root, indent=4) </code></pre> <p>It gives me the output (The keys are out of order, but that's what you get when you use a dictionary)</p> <pre><code>maurice@ubuntu:~/Dev/random$ python recursion_tree.py { 'children': [ { 'children': [ { 'children': [], 'desc': 'desc_child_2', 'id': 3, 'parent_id': 2}], 'desc': 'desc_child_1', 'id': 2, 'parent_id': 1}, { 'children': [ { 'children': [ { 'children': [ ], 'desc': 'desc_child_5', 'id': 4, 'parent_id': 5}], 'desc': 'desc_child_6', 'id': 5, 'parent_id': 6}], 'desc': 'desc_child_1', 'id': 6, 'parent_id': 1}], 'desc': 'desc_father', 'id': 1, 'parent_id': None} </code></pre> <p>This should even work with multiple root nodes (there will be a dummy Node with the id <code>None</code> at the top though)</p>
1
2016-09-19T14:03:42Z
[ "python", "dictionary", "recursion", "parent-child" ]
Building HTML table from list of dictionaries
39,573,901
<p>I have a list containing dictionaries that I would like to output into an HTML table.</p> <p>My list looks like this:</p> <pre><code>[{'description': 'KA8ts5', 'password': 'KA8ts5', 'username': 'test4'}, {'description': '5j6mEF', 'password': '5j6mEF', 'username': 'test5'}] </code></pre> <p>I am trying to make it look as follows:</p> <pre><code>&lt;tr&gt;&lt;td&gt;test4&lt;/td&gt;&lt;td&gt;KA8ts5&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;test5&lt;/td&gt;&lt;td&gt;5j6mEF&lt;/td&gt;&lt;/tr&gt; </code></pre> <p>But I am unsure how to get these values as well as format them accordingly.</p>
0
2016-09-19T13:02:07Z
39,574,046
<p>You could use an example supplied in the docs for <a href="https://docs.python.org/3/library/contextlib.html" rel="nofollow"><code>contextlib</code></a> and build it accordingly.</p> <p>Essentially, create a context manager with <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" rel="nofollow"><code>@contextmanager</code></a> that adds initial and closing tags and print out the required values in the <code>with</code> block. The context manager, as found in the docs:</p> <pre><code>from contextlib import contextmanager @contextmanager def tag(name): print("&lt;%s&gt;" % name, end='') yield print("&lt;/%s&gt;" % name, end='') </code></pre> <p>and, the actual sample that uses it:</p> <pre><code>l = [{'description': 'KA8ts5', 'password': 'KA8ts5', 'username': 'test4'}, {'description': '5j6mEF', 'password': '5j6mEF', 'username': 'test5'}] for d in l: with tag('tr'): with tag('td'): print(d['username'], end='') with tag('td'): print(d['password'], end='') print() </code></pre> <p>Outputs:</p> <pre><code>&lt;tr&gt;&lt;td&gt;test4&lt;/td&gt;&lt;td&gt;KA8ts5&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;test5&lt;/td&gt;&lt;td&gt;5j6mEF&lt;/td&gt;&lt;/tr&gt; </code></pre>
0
2016-09-19T13:09:23Z
[ "python", "python-3.x" ]
Building HTML table from list of dictionaries
39,573,901
<p>I have a list containing dictionaries that I would like to output into an HTML table.</p> <p>My list looks like this:</p> <pre><code>[{'description': 'KA8ts5', 'password': 'KA8ts5', 'username': 'test4'}, {'description': '5j6mEF', 'password': '5j6mEF', 'username': 'test5'}] </code></pre> <p>I am trying to make it look as follows:</p> <pre><code>&lt;tr&gt;&lt;td&gt;test4&lt;/td&gt;&lt;td&gt;KA8ts5&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;test5&lt;/td&gt;&lt;td&gt;5j6mEF&lt;/td&gt;&lt;/tr&gt; </code></pre> <p>But I am unsure how to get these values as well as format them accordingly.</p>
0
2016-09-19T13:02:07Z
39,574,130
<p>I would use a <em>template engine</em> like <a href="http://www.makotemplates.org/" rel="nofollow"><code>mako</code></a> or <a href="http://jinja.pocoo.org/docs/dev/" rel="nofollow"><code>jinja2</code></a>.</p> <p>Example using <code>mako</code>:</p> <pre><code>from mako.template import Template template = """ &lt;table&gt; % for user in users: &lt;tr&gt; &lt;td&gt;${user['username']}&lt;/td&gt; &lt;td&gt;${user['description']}&lt;/td&gt; &lt;/tr&gt; % endfor &lt;/table&gt; """ users = [ {'description': 'KA8ts5', 'password': 'KA8ts5', 'username': 'test4'}, {'description': '5j6mEF', 'password': '5j6mEF', 'username': 'test5'} ] result = Template(template).render(users=users) print(result) </code></pre> <p>Prints:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;test4&lt;/td&gt; &lt;td&gt;KA8ts5&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;test5&lt;/td&gt; &lt;td&gt;5j6mEF&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre>
1
2016-09-19T13:14:16Z
[ "python", "python-3.x" ]
How does one create an generalise AttrDict Mixin for a python "dict-style" class?
39,573,949
<p>Basically I want to be able to take <code>class</code> that <em>quacks</em> like a <code>dict</code> (eg my example <code>DICT</code> below) and add a <code>MixIn</code> that allows me to access the <code>DICT</code>'s values as attributes... eg </p> <pre><code>print purchase.price # instead of purchase["price"] </code></pre> <p>Background: I have a various different database tables (not just the <code>DICT</code> example) that look (&amp; <em>quack</em>) like a <code>dict</code> (eg. <code>bsddb</code>) and I want define (then use) a standard <code>AttrDictMixIn</code>. (And so avoid using a boilerplate cut/paste of code)</p> <pre><code># First try using a std dict class AttrDict(dict): def __init__(self, *args, **kwargs): self.__dict__ = self super(AttrDict, self).__init__(*args, **kwargs) test1=AttrDict() test1.x="111" print 1,test1 # Next derive a crude UPPER dict class DICT(dict): # EXAMPLE ONLY def __getitem__(self,key): return super(DICT,self).__getitem__(key.upper()) def __setitem__(self,key,value): return super(DICT,self).__setitem__(key.upper(),value) test2=DICT() test2["x"]="222" print 2,test2 # Next define a AttrDict MixIn class AttrDictMixIn(object): # This is what I want to work... def __init__(self, *args, **kwargs): self.__dict__ = self return super(AttrDict, self).__init__(*args, **kwargs) # Apply the MixIn to DICT class AttrDICT(DICT,AttrDictMixIn): pass test3=AttrDICT() test3.x="333.xxx" test3["y"]="333.yyy" print 3,test3,"X is missing" print 4,"test3.x:",test3.x,"OK" print 5,"test3['y']:",test3["y"],"OK" print 6,"test3.y:",test3.y,"DUD" print 7,"test3['x']:",test3["x"],"DUD" </code></pre> <p>Output:</p> <pre><code>1 {'x': '111'} 2 {'X': '222'} 3 {'Y': '333.yyy'} X is missing 4 test3.x: 333.xxx OK 5 test3['y']: 333.yyy OK 6 test3.y: Traceback (most recent call last): File "x.py", line 39, in &lt;module&gt; print 6,"test3.y:",test3.y,"DUD" AttributeError: 'AttrDICT' object has no attribute 'y' </code></pre> <p>I suspect I am doing something trivial wrong... Hints welcome. (And pointers to some reference examples of similar python MixIns may also help)</p> <p>edit: an explanation of why the line <code>self.__dict__ = self</code> breaks multiple inheritance would be appreciated.</p>
0
2016-09-19T13:04:37Z
39,576,145
<p>Implement it like so:</p> <pre><code>class AttrDictMixin(object): def __getattr__(self, name): return self[name] def __setattr__(self, name, value): self[name] = value def __delattr__(self, name): del self[name] </code></pre> <p>Upon attribute access, setting, or deleting - <code>__getattr__</code>, <code>__setattr__</code> and <code>__delattr__</code> are called accordingly.</p> <p>Keep in mind mixins should come before the base class in the inheritance:</p> <pre><code>class AttrDict(AttrDictMixin, DICT): pass </code></pre>
0
2016-09-19T14:52:34Z
[ "python", "class", "dictionary", "attributes", "multiple-inheritance" ]
Xgboost crossvalidated model access
39,574,014
<p>Is there any way I can access the trained <code>xgboost</code> model from <code>xgboost.cv</code> directly? Or do I manually have to loop over the folds and perform a fit in this case?</p> <pre><code>xgb.cv(param, dtrain, num_round, nfold = 5, seed = 0, obj = logregobj, feval=evalerror) </code></pre>
0
2016-09-19T13:07:51Z
39,664,355
<p>First, you cross-validate xgboost as you indicate:</p> <p><code>xgb.cv_m &lt;- xgb.cv(param, dtrain, num_round, nfold = 5, seed = 0, obj = logregobj, feval=evalerror)</code></p> <p>Then, the number of rounds needed corresponds to the best AUC (the AUC train and test means and std resulted from cross-validation are saved in the data frame 'dt' - check out <code>names(xgb_cv_m)</code>):</p> <p><code>nr &lt;- which(xgb_cv_m$dt$test.auc.mean == max(xgb_cv_m$dt$test.auc.mean))</code></p> <p>Next, when you fit the final model using 'xgboost' you use nrounds=nr</p> <p>If you wish, you can also visually inspect the performance at every round by: <code>plot(xgb_cv_m$dt$test.auc.mean)</code></p>
1
2016-09-23T15:22:25Z
[ "python", "data-science", "xgboost" ]
How to delete pages from pdf file using Python?
39,574,096
<p>I have some .pdf files with more than 500 pages, but I need only a few pages in each file. It is necessary to preserve document`s title pages. I know exactly the numbers of the pages that program should remove. How I can do it using Python 2.7 Environment, which is installed upon MS Visual Studio?</p>
0
2016-09-19T13:12:17Z
39,574,216
<p>Use pyPDF2:</p> <p><a href="https://github.com/mstamy2/PyPDF2" rel="nofollow">https://github.com/mstamy2/PyPDF2</a></p> <p>Documentation is at:</p> <p><a href="https://pythonhosted.org/PyPDF2/" rel="nofollow">https://pythonhosted.org/PyPDF2/</a></p> <p>It seems pretty intuitive.</p>
0
2016-09-19T13:18:00Z
[ "python", "pdf" ]
How to delete pages from pdf file using Python?
39,574,096
<p>I have some .pdf files with more than 500 pages, but I need only a few pages in each file. It is necessary to preserve document`s title pages. I know exactly the numbers of the pages that program should remove. How I can do it using Python 2.7 Environment, which is installed upon MS Visual Studio?</p>
0
2016-09-19T13:12:17Z
39,574,231
<p>Try using <a href="https://pypi.python.org/pypi/PyPDF2/1.26.0" rel="nofollow">PyPDF2</a>. Some sample code (adapted from <a href="https://www.binpress.com/tutorial/manipulating-pdfs-with-python/167" rel="nofollow">here</a>).</p> <pre><code>pages_to_keep = [1,2,10] from PyPDF2 import PdfFileWriter, PdfFileReader infile = PdfFileReader('source.pdf', 'rb') output = PdfFileWriter() for i in xrange(infile.getNumPages()): p = infile.getPage(i) if i in pages_to_keep: # getContents is None if page is blank output.addPage(p) with open('newfile.pdf', 'wb') as f: output.write(f) </code></pre>
1
2016-09-19T13:18:45Z
[ "python", "pdf" ]
Missing menuBar in PyQt5
39,574,105
<p>I've been developing a GUI using PyQt5 and wanted to include a menu bar. When I went to code this feature, however, my menu wouldn't appear. Figuring my understanding on how to implement menu bars in PyQt5 was off, I looked for a pre-existing example online. With some tweaking I developed the following test case:</p> <pre><code>import sys from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QApplication, QMainWindow, QMenuBar, QAction, qApp class Example(QMainWindow): def __init__(self): super().__init__() exitAction = QAction(QIcon('exit.png'), '&amp;Exit', self) exitAction.triggered.connect(qApp.quit) menubar = self.menuBar() fileMenu = menubar.addMenu('&amp;Testmenu') fileMenu.addAction(exitAction) self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) </code></pre> <p>When I run this, however, <code>Testmenu</code> is nowhere to be found.</p> <p>I have also tried creating the menu bar (and the rest of my GUI layout) in QTCreator before converting the .ui file to an importable .py using pyuic5. I thought this would eliminate some programming mistake on my end, but the menubar still won't show. Any thoughts? </p> <p>Edit:</p> <p>Im running this code using Python 3.5 (Anaconda 4.1) from within a Jupyter notebook, version 4.1. I'm also using a Macbook running os 10.1l, PyQt 5.7 and Qt version 5.7.0.</p> <p>I've realized that the menu bar will become responsive if I click off the application window and then click back onto the window - effectively unfocusing and the focusing the application. Armed with this information I realized that I am not the first to notice this problem (see <a href="https://github.com/robotology/yarp/issues/457" rel="nofollow">https://github.com/robotology/yarp/issues/457</a>). Unfortunately, I'm still not sure how to resolve the issue.</p>
2
2016-09-19T13:12:49Z
39,574,279
<p>try this:</p> <pre><code>menubar = QMenuBar() self.setMenuBar(menubar) </code></pre> <p>instead of <code>menubar = self.menuBar()</code></p>
0
2016-09-19T13:20:57Z
[ "python", "osx", "pyqt", "pyqt5", "menubar" ]
Missing menuBar in PyQt5
39,574,105
<p>I've been developing a GUI using PyQt5 and wanted to include a menu bar. When I went to code this feature, however, my menu wouldn't appear. Figuring my understanding on how to implement menu bars in PyQt5 was off, I looked for a pre-existing example online. With some tweaking I developed the following test case:</p> <pre><code>import sys from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QApplication, QMainWindow, QMenuBar, QAction, qApp class Example(QMainWindow): def __init__(self): super().__init__() exitAction = QAction(QIcon('exit.png'), '&amp;Exit', self) exitAction.triggered.connect(qApp.quit) menubar = self.menuBar() fileMenu = menubar.addMenu('&amp;Testmenu') fileMenu.addAction(exitAction) self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) </code></pre> <p>When I run this, however, <code>Testmenu</code> is nowhere to be found.</p> <p>I have also tried creating the menu bar (and the rest of my GUI layout) in QTCreator before converting the .ui file to an importable .py using pyuic5. I thought this would eliminate some programming mistake on my end, but the menubar still won't show. Any thoughts? </p> <p>Edit:</p> <p>Im running this code using Python 3.5 (Anaconda 4.1) from within a Jupyter notebook, version 4.1. I'm also using a Macbook running os 10.1l, PyQt 5.7 and Qt version 5.7.0.</p> <p>I've realized that the menu bar will become responsive if I click off the application window and then click back onto the window - effectively unfocusing and the focusing the application. Armed with this information I realized that I am not the first to notice this problem (see <a href="https://github.com/robotology/yarp/issues/457" rel="nofollow">https://github.com/robotology/yarp/issues/457</a>). Unfortunately, I'm still not sure how to resolve the issue.</p>
2
2016-09-19T13:12:49Z
39,603,054
<p>Have you tried the most simple example in the following link <a href="https://www.tutorialspoint.com/pyqt/qmenubar_qmenu_qaction_widgets.htm" rel="nofollow">tutorialspoint</a>.</p> <p>Here is the most simple example.</p> <pre><code>import sys from PyQt5.QtWidgets import QHBoxLayout, QAction, QApplication, QMainWindow class menudemo(QMainWindow): def __init__(self, parent = None): super(menudemo, self).__init__(parent) bar = self.menuBar() file = bar.addMenu("File") file.addAction("New") save = QAction("Save",self) save.setShortcut("Ctrl+S") file.addAction(save) edit = file.addMenu("Edit") edit.addAction("copy") edit.addAction("paste") quit = QAction("Quit",self) file.addAction(quit) file.triggered[QAction].connect(self.processtrigger) self.setWindowTitle("menu demo") def processtrigger(self, q): print(q.text()+" is triggered") def main(): app = QApplication(sys.argv) ex = menudemo() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() </code></pre>
0
2016-09-20T20:16:35Z
[ "python", "osx", "pyqt", "pyqt5", "menubar" ]
xpath cant select only one html tag
39,574,222
<p>I am trying to get some data from a website, but when i use the following code it's return all of the matched elements, i want to return only 1st match! I've tried extract_first but it returned none!</p> <pre><code># -*- coding: utf-8 -*- import scrapy from gumtree.items import GumtreeItem class FlatSpider(scrapy.Spider): name = "flat" allowed_domains = ["gumtree.com"] start_urls = ( 'https://www.gumtree.com/flats-for-sale', ) def parse(self, response): item = GumtreeItem() item['title'] = response.xpath('//*[@class="listing-title"][1]/text()').extract() return item </code></pre> <p>How to select only one element with xpath selector ? </p>
1
2016-09-19T13:18:20Z
39,574,339
<p>This is because the first element is actually empty - filter out the non-empty values only and use <code>extract_first()</code> - works for me:</p> <pre><code>$ scrapy shell "https://www.gumtree.com/flats-for-sale" -s USER_AGENT="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.113 Safari/537.36" In [1]: response.xpath('//*[@class="listing-title"][1]/text()[normalize-space(.)]').extract_first().strip() Out[1]: u'REDUCED to sell! Stunning Hove sea view flat.' </code></pre>
1
2016-09-19T13:24:01Z
[ "python", "python-3.x", "xpath", "web-scraping", "scrapy" ]
xpath cant select only one html tag
39,574,222
<p>I am trying to get some data from a website, but when i use the following code it's return all of the matched elements, i want to return only 1st match! I've tried extract_first but it returned none!</p> <pre><code># -*- coding: utf-8 -*- import scrapy from gumtree.items import GumtreeItem class FlatSpider(scrapy.Spider): name = "flat" allowed_domains = ["gumtree.com"] start_urls = ( 'https://www.gumtree.com/flats-for-sale', ) def parse(self, response): item = GumtreeItem() item['title'] = response.xpath('//*[@class="listing-title"][1]/text()').extract() return item </code></pre> <p>How to select only one element with xpath selector ? </p>
1
2016-09-19T13:18:20Z
39,646,519
<p>Strictly speaking it should be <code>response.xpath('(//*[@class="listing-title"])[1]/text()')</code> but if what you want is to grab the title of each ad (to create an item for example) you should probably do this instead:</p> <pre><code>for article in response.xpath('//article[@data-q]'): item = GumtreeItem() item['title'] = article.css('.listing-title::text').extract_first() yield item </code></pre>
0
2016-09-22T18:36:35Z
[ "python", "python-3.x", "xpath", "web-scraping", "scrapy" ]
Override builtin type __str__ method in python
39,574,286
<p>I need to port some code from Python2 to Python3 and the main problem seems to be in bytes type, because str(bytes) gives me "b'%s'" result, but '%s' is needed, so I decided to override __str__() method of bytes class to print exactly what I want.</p> <p>I tried to patch builtins.bytes with class inherited from bytes, but that seem to work only for one file and not for the whole project and also does not affect on bytesliterals (b'').</p> <p>If there are any other ways (less painful) to port from py2 to py3, it would be nice to see them.</p> <p>Using .decode('UTF-8') is not acceptable, because the project is more than 4k lines and adding decode method to all necessary places would result in progressive bugs count, and also some of those .decode places are in 3-rd party libraries.</p> <p>I tried to do something like this:</p> <pre><code>import builtins class StrBytes(builtins.bytes): def __str__(self): return self.decode('UTF-8') builtins.bytes = StrBytes </code></pre> <p>Then if I use bytes() it creates StrBytes object and str(bytes()) is exactly what I want. This way is bad because it does not cover constructing bytes object from bytesliteral:</p> <pre><code>&gt;&gt;&gt; type(bytes()) &lt;class 'StrBytes'&gt; &gt;&gt;&gt; type(b'') &lt;class 'bytes'&gt; </code></pre> <p>And I am not certain if it works for the whole project, not only one file.</p> <p>In many different places of my code, I have something like this:</p> <pre><code>return b''.join(some_extra_values) keys = [b'1', b'2', b'3'] # actually keys are given from another part of code for key in keys: some_dict[key] = some_value some_dict['1'] # works in py2, not in py3, KeyError </code></pre>
2
2016-09-19T13:21:19Z
39,574,509
<p>The rule with text is "decode on input, encode on output." Although a lot of work has been done to make it easier to write code that is compatible between v2 and v3, there are always going to be some discrepancies and the fact that Python 3 no longer defines the <code>unicode</code> symbol is one of them.</p> <p>It isn't a good idea to try and patch the built-in types in Python. Because they are defined in C there is no effective way to patch their methods.</p> <p>One possibly useful tool is</p> <pre><code>from __future__ import unicode_literals </code></pre> <p>when, when inserted at the beginning of the program will interpret all string literals as Unicode strings rather than bytestrings.</p> <p>Another way to adapt your code is to use the fact that Python 3 doesn't implement the <code>unicode</code> name to drive feature detection. So you might write, for example</p> <pre><code>try: unicode = unicode # RHS raises NameError on Python 3 except NameError: unicode = str </code></pre> <p>Then you can check for text types by writing</p> <pre><code>if type(s) is unicode: ... </code></pre> <p>and the comparisons should work in both v2 and v3.</p> <p>You should NOT have to insert many calls to decode if you correctly decode on input, and should only need to encode when the string has to be communicated to an external tool of some kind.</p>
2
2016-09-19T13:32:17Z
[ "python", "decode", "2to3", "builtins" ]
Match the last occurrence of delimiter in the expect function of pexpect
39,574,329
<p>I utilize pexpect for automation. The delimiter for the command prompt is '>'. However it so happens that sometimes the output itself contain a '>' sign causing the expect function to delimit at that precise location rather than taking all the output till the command prompt. Is there any way to make expect function pick the last occurrence of the delimiter character?</p>
0
2016-09-19T13:23:27Z
39,607,336
<p>Pexpect cannot tell which <code>&gt;</code> is the last one because the spawned process may keep outputting something. To solve your problem you can customize the shell prompt and then you just expect your own shell prompt. For example:</p> <pre class="lang-none prettyprint-override"><code>[STEP 101] # cat pexp.py import pexpect, sys prompt = 'my-ugly-prompt' ssh = pexpect.spawn('ssh localhost') ssh.logfile_read = sys.stdout ssh.expect('password:') ssh.sendline('password') ssh.expect('bash-') ssh.sendline('PS1="[%s] # "' % prompt) ssh.expect(prompt) ssh.sendline('echo hello world') ssh.expect(prompt) ssh.sendline('exit') ssh.expect(pexpect.EOF) [STEP 102] # python pexp.py root@localhost's password: bash-4.4# PS1="[my-ugly-prompt] # " [my-ugly-prompt] # echo hello world hello world [my-ugly-prompt] # exit exit Connection to localhost closed. [STEP 103] # </code></pre>
0
2016-09-21T04:01:36Z
[ "python", "shell", "automation", "command-line-interface", "pexpect" ]
Python urllib2 request exploiting Active Directory authentication
39,574,388
<p>I've got a Windows server (Navision) offering web access to its APIs through Active Directory authentication.<br/> I'm trying to make a request to the web server through Active Directory authentication, by using an external Linux based host.</p> <p>I successfully authenticated by using <code>python-ldap</code> library.</p> <pre><code>import ldap import urllib2 DOMAINHOST='domain_ip_host' USERNAME='administrator@mydomain' PASSWORD='mycleanpassword' URL='http://...' conn = ldap.open(DOMAINHOST) ldap.set_option(ldap.OPT_REFERRALS, 0) try: print conn.simple_bind_s(USERNAME, PASSWORD) except ldap.INVALID_CREDENTIALS: user_error_msg('wrong password provided') </code></pre> <p>The output is in this case:</p> <pre><code>(97, [], 1, []) </code></pre> <p>representing a successful authentication.</p> <p>I'd need to exploit this successful authentication to communicate to the Navision web service, e.g. by using <code>urllib2</code> library.</p> <pre><code>req = urllib2.Request(URL) res = urllib2.urlopen(req) </code></pre> <p>Of course, since authentication is not exploited/adopted, the request fails with a <code>401 Unauthorized</code> error.</p> <p>I also tried to use <code>python-ntlm</code> library:</p> <pre><code>passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, URL, USERNAME, PASSWORD) # create the NTLM authentication handler auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman) # other authentication handlers auth_basic = urllib2.HTTPBasicAuthHandler(passman) auth_digest = urllib2.HTTPDigestAuthHandler(passman) # disable proxies (if you want to stay within the corporate network) proxy_handler = urllib2.ProxyHandler({}) # create and install the opener opener = urllib2.build_opener(proxy_handler, auth_NTLM, auth_digest, auth_basic) urllib2.install_opener(opener) # retrieve the result response = urllib2.urlopen(url) print(response.read()) </code></pre> <p>Also in this case, a <code>401 Unauthorized</code> error is provided.</p> <p>How can I successfully make a web request by authenticating the user against Active Directory?</p>
0
2016-09-19T13:26:48Z
39,589,376
<p>If it's a Dynamics NAV Webservice you want to trigger (didn't see that from code but from tag) you have to activcate ntlm on your NST. Just change the Property 'ServicesUseNTLMAuthentication' from False to True in your CustomSettings.config or just use the Microsoft Dynamics NAV Administration MMC. Don't forget to restart the service after changing.</p>
0
2016-09-20T08:39:03Z
[ "python", "active-directory", "windows-authentication", "ntlm", "navision" ]
Run Length Encoding in python
39,574,474
<p>i got homework to do "Run Length Encoding" in python and i wrote a code but it is print somthing else that i dont want. it prints just the string(just like he was written) but i want that it prints the string and if threre are any characthers more than one time in this string it will print the character just one time and near it the number of time that she appeard in the string. how can i do this? </p> <p>For example:</p> <p>the string : 'lelamfaf"</p> <p>the result : 'l2ea2mf2</p> <pre><code>def encode(input_string): count = 1 prev = '' lst = [] for character in input_string: if character != prev: if prev: entry = (prev, count) lst.append(entry) #print lst count = 1 prev = character else: count += 1 else: entry = (character, count) lst.append(entry) return lst def decode(lst): q = "" for character, count in lst: q += character * count return q def main(): s = 'emanuelshmuel' print decode(encode(s)) if __name__ == "__main__": main() </code></pre>
-2
2016-09-19T13:30:22Z
39,575,637
<p>Three remarks:</p> <ol> <li>You should use the existing method <code>str.count</code> for the <code>encode</code> function.</li> <li>The <code>decode</code> function will print <code>count</code> times a character, not the character and its counter.</li> <li>Actually the <code>decode(encode(string))</code> combination is a coding function since you do not retrieve the starting string from the encoding result.</li> </ol> <p>Here is a working code:</p> <pre><code>def encode(input_string): characters = [] result = '' for character in input_string: # End loop if all characters were counted if set(characters) == set(input_string): break if character not in characters: characters.append(character) count = input_string.count(character) result += character if count &gt; 1: result += str(count) return result def main(): s = 'emanuelshmuel' print encode(s) assert(encode(s) == 'e3m2anu2l2sh') s = 'lelamfaf' print encode(s) assert(encode(s) == 'l2ea2mf2') if __name__ == "__main__": main() </code></pre>
0
2016-09-19T14:28:10Z
[ "python" ]
Run Length Encoding in python
39,574,474
<p>i got homework to do "Run Length Encoding" in python and i wrote a code but it is print somthing else that i dont want. it prints just the string(just like he was written) but i want that it prints the string and if threre are any characthers more than one time in this string it will print the character just one time and near it the number of time that she appeard in the string. how can i do this? </p> <p>For example:</p> <p>the string : 'lelamfaf"</p> <p>the result : 'l2ea2mf2</p> <pre><code>def encode(input_string): count = 1 prev = '' lst = [] for character in input_string: if character != prev: if prev: entry = (prev, count) lst.append(entry) #print lst count = 1 prev = character else: count += 1 else: entry = (character, count) lst.append(entry) return lst def decode(lst): q = "" for character, count in lst: q += character * count return q def main(): s = 'emanuelshmuel' print decode(encode(s)) if __name__ == "__main__": main() </code></pre>
-2
2016-09-19T13:30:22Z
39,575,748
<p>Came up with this quickly, maybe there's room for optimization (for example, if the strings are too large and there's enough memory, it would be better to use a set of the letters of the original string for look ups rather than the list of characters itself). But, does the job fairly efficiently:</p> <pre><code>text = 'lelamfaf' counts = {s:text.count(s) for s in text} char_lst = [] for l in text: if l not in char_lst: char_lst.append(l) if counts[l] &gt; 1: char_lst.append(str(counts[l])) encoded_str = ''.join(char_lst) print encoded_str </code></pre>
0
2016-09-19T14:33:33Z
[ "python" ]
Python Pandas calculate time until output reaches 0
39,574,497
<p>I have a pandas dataframe in python with several columns and a datetime stamp. One of the columns has a true/false variable. I'd like to calculate time until that column is false.</p> <p>Ideally it would look something like this:</p> <pre><code>datetime delivered secondsuntilfailure 2014-05-01 01:00:00 True 3 2014-05-01 01:00:01 True 2 2014-05-01 01:00:02 True 1 2014-05-01 01:00:03 False 0 2014-05-01 01:00:04 True ? </code></pre> <p>Thanks in advance!!</p>
0
2016-09-19T13:31:48Z
39,574,725
<p>You can first change order by <code>[::-1]</code>, then find <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofollow"><code>diff</code></a> and count <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cumsum.html" rel="nofollow"><code>cumsum</code></a> if values are <code>True</code>:</p> <pre><code>df = df[::-1] print (df.datetime.diff().astype('timedelta64[s]')) 4 NaN 3 -1.0 2 -1.0 1 -1.0 0 -1.0 Name: datetime, dtype: float64 df['new'] = df.delivered.where(~df.delivered,df.datetime.diff().astype('timedelta64[s]')) .cumsum().fillna(0).astype(int).mul(-1) df = df[::-1] print (df) datetime delivered secondsuntilfailure new 0 2014-05-01 01:00:00 True 3 3 1 2014-05-01 01:00:01 True 2 2 2 2014-05-01 01:00:02 True 1 1 3 2014-05-01 01:00:03 False 0 0 4 2014-05-01 01:00:04 True ? 0 </code></pre>
0
2016-09-19T13:43:22Z
[ "python", "datetime", "pandas" ]
Python Pandas calculate time until output reaches 0
39,574,497
<p>I have a pandas dataframe in python with several columns and a datetime stamp. One of the columns has a true/false variable. I'd like to calculate time until that column is false.</p> <p>Ideally it would look something like this:</p> <pre><code>datetime delivered secondsuntilfailure 2014-05-01 01:00:00 True 3 2014-05-01 01:00:01 True 2 2014-05-01 01:00:02 True 1 2014-05-01 01:00:03 False 0 2014-05-01 01:00:04 True ? </code></pre> <p>Thanks in advance!!</p>
0
2016-09-19T13:31:48Z
39,575,552
<p>Count the seconds:</p> <pre><code>cumsecs = df.datetime.diff().astype('timedelta64[s]').cumsum().fillna(value=0.0) </code></pre> <p>Copy the cumulative value whenever delivered fails, and fill any preceeding values:</p> <pre><code>undeliv_secs = cumsecs.where(~df['delivered']).fillna(method='bfill') </code></pre> <p>Seconds until failure is just the difference between the two:</p> <pre><code>df['secondsuntilfailure'] = undeliv_secs - cumsecs print(df) datetime delivered secondsuntilfailure 0 2014-05-01 01:00:00 True 3.0 1 2014-05-01 01:00:01 True 2.0 2 2014-05-01 01:00:02 True 1.0 3 2014-05-01 01:00:03 False 0.0 4 2014-05-01 01:00:04 True NaN </code></pre>
0
2016-09-19T14:23:53Z
[ "python", "datetime", "pandas" ]
Reset a python mock generator return value
39,574,537
<p>How can I "reset" a method that returns a generator. If I mock this method but use the parent class twice in a method under test, the first call consumes the generator and the second call has no data. Sample code below. The two calls to get_values should return the same (mocked) list.</p> <pre><code>import mock class MyTestClass(object): def __init__(self, param): self.param = param def get_values(self): return self.param class MyTestRunner(object): def __init__(self): pass def run(self): cls = MyTestClass(2) print list(cls.get_values()) cls = MyTestClass(3) print list(cls.get_values()) with mock.patch.object(MyTestClass, 'get_values') as mock_class: mock_class.return_value = ({'a': '10', 'b': '20'}).iteritems() m = MyTestRunner() m.run() </code></pre> <p>Expected:</p> <pre><code>[('a', '10'), ('b', '20')] [('a', '10'), ('b', '20')] </code></pre> <p>Actual:</p> <pre><code>[('a', '10'), ('b', '20')] [] </code></pre>
1
2016-09-19T13:33:24Z
39,575,889
<p>How's this?</p> <pre><code>mock_class.side_effect = lambda x: {'a': '10', 'b': '20'}.iteritems() </code></pre> <p>Side effect occurs every call thus recreates every time.</p> <p>You can even set the dict before like so</p> <pre><code>my_dict = {'a': '10', 'b': '20'} mock_class.side_effect = lambda x: my_dict.iteritems() </code></pre> <p>The return value of side_effect is the result of the call.</p>
2
2016-09-19T14:40:15Z
[ "python", "mocking" ]
text document sorting to sides
39,574,541
<p>I'm currently learning python and I am supposed to write a program which asks a user for input of name and then input of age, It is supposed to look like this "<a href="http://i.imgur.com/hcMTJuK.png" rel="nofollow">http://i.imgur.com/hcMTJuK.png</a>" Sorry i cannot add pictures yet since I don't have 10 rep yet, but it looks like this for me "<a href="http://i.imgur.com/w9YDAYB.png" rel="nofollow">http://i.imgur.com/w9YDAYB.png</a>" Please help as soon as you can, I'll highly appreciate it.</p>
0
2016-09-19T13:33:46Z
39,574,820
<p>I am currently learning Python, too. I am excited because I think I can help you.</p> <p>So what I would try and do is to put "Name" and "Age" on the same line and assign it to the variable "title". What I think will also help you is if you use a variable called "space" so that you'll be able to control the formatting. You can type in something like this:</p> <p>space = " "</p> <p>title = "Name" + space * 10 + "Age"</p> <p>I just put the 10 in there as an estimate, but you might want to play around with the numbers to get the look you want. After that, you can just have the program print out the title, then the inputs with formatting and I think you're all set!</p> <p>I hope that steers you in the right direction. Like I said, I am learning, too, and I haven't gotten to that part where I can call up lists yet -- but I remember it from my previous programming classes. Please let me know if you need anything else!</p>
0
2016-09-19T13:47:45Z
[ "python", "project" ]
Django redirect after logout
39,574,559
<p>I'm using Django and to authenticate my user, I have a custom OAuth2 provider. I had to write the login and logout view myself because they are doing some very specific things.</p> <p>I would like to be redirected to the same url after logout. If you are on a page that require to be authenticated, I would like to redirect to the homepage. I didn't find any resource to know if a view/endpoint is using the decorator <code>login_required</code> </p>
0
2016-09-19T13:34:42Z
39,574,655
<p>The <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#the-login-required-decorator" rel="nofollow"><code>login_required</code></a> decorator takes a parameter to redirect users. You could use this.</p> <p>As of Django 1.9, you could also use the <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#redirecting-unauthorized-requests-in-class-based-views" rel="nofollow"><code>AccessMixin</code></a>. </p> <p>Unless I misunderstand your question, all the information you need is in the docs. Are you using an older version of Django?</p>
0
2016-09-19T13:39:32Z
[ "python", "django" ]
Django redirect after logout
39,574,559
<p>I'm using Django and to authenticate my user, I have a custom OAuth2 provider. I had to write the login and logout view myself because they are doing some very specific things.</p> <p>I would like to be redirected to the same url after logout. If you are on a page that require to be authenticated, I would like to redirect to the homepage. I didn't find any resource to know if a view/endpoint is using the decorator <code>login_required</code> </p>
0
2016-09-19T13:34:42Z
39,574,865
<p>Sure, just use query string parameter <code>next</code>, e.g.: </p> <pre><code>&lt;a href="{% url 'users:user_logout' %}?next={% url 'some_url' %}"&gt;Log out&lt;/a&gt; </code></pre> <p>The rest is only a matter of arranging template hierarchy, so you will use different urls in different templates without repetition.</p>
0
2016-09-19T13:49:47Z
[ "python", "django" ]
Acessing a variable as a string in a module
39,574,560
<p>Following other posts here, I have a function that prints out information about a variable based on its name. I would like to move it into a module.</p> <pre><code>#python 2.7 import numpy as np def oshape(name): #output the name, type and shape/length of the input variable(s) #for array or list x=globals()[name] if type(x) is np.array or type(x) is np.ndarray: print('{:20} {:25} {}'.format(name, repr(type(x)), x.shape)) elif type(x) is list: print('{:20} {:25} {}'.format(name, repr(type(x)), len(x))) else: print('{:20} {:25} X'.format(name, type(t))) a=np.array([1,2,3]) b=[4,5,6] oshape('a') oshape('b') </code></pre> <p>Output:</p> <pre><code>a &lt;type 'numpy.ndarray'&gt; (3,) b &lt;type 'list'&gt; 3 </code></pre> <p>I would like to put this function oshape() into a module so that it can be reused. However, placing in a module does not allow access to the globals from the main module. I have tried things like 'import __main__ ' and even storing the function globals() and passing it into the submodule. The problem is that globals() is one function, which specifically returns the globals of the module it is called from, not a different function for each module.</p> <pre><code>import numpy as np import olib a=np.array([1,2,3]) b=[4,5,6] olib.oshape('a') olib.oshape('b') </code></pre> <p>Gives me:</p> <pre><code>KeyError: 'a' </code></pre> <p>Extra information: The goal is to reduce redundant typing. With a slight modification (I took it out to make it simpler for the question), oshape could report on a list of variables, so I could use it like:</p> <pre><code>oshape('a', 'b', 'other_variables_i_care_about') </code></pre> <p>So solutions that require typing the variable names in twice are not really what I am looking for. Also, just passing in the variable does not allow the name to be printed. Think about using this in a long log file to show the results of computations &amp; checking variable sizes.</p>
5
2016-09-19T13:34:43Z
39,574,697
<p>The actual problem you have here is a namespace problem.</p> <p>You could write your method this way:</p> <pre><code>def oshape(name, x): # output the name, type and shape/length of the input variable(s) # for array or list if type(x) in (np.array, np.ndarray): print('{:20} {:25} {}'.format(name, repr(type(x)), x.shape)) elif type(x) is list: print('{:20} {:25} {}'.format(name, repr(type(x)), len(x))) else: print('{:20} {:25} X'.format(name, type(x))) </code></pre> <p>and use it like this:</p> <pre><code>import numpy as np import olib a=np.array([1,2,3]) b=[4,5,6] olib.oshape('a', a) olib.oshape('b', b) </code></pre> <p>but it's looks very redundant to have the variable and its name in the arguments.</p> <p>Another solution would be to give the <code>globals()</code> dict to the method and keep your code.</p> <p>Have a look at <a href="http://stackoverflow.com/questions/15959534/python-visibility-of-global-variables-in-imported-modules">this answer</a> about the visibility of the global variables through modules.</p>
2
2016-09-19T13:41:53Z
[ "python", "python-2.7" ]
Acessing a variable as a string in a module
39,574,560
<p>Following other posts here, I have a function that prints out information about a variable based on its name. I would like to move it into a module.</p> <pre><code>#python 2.7 import numpy as np def oshape(name): #output the name, type and shape/length of the input variable(s) #for array or list x=globals()[name] if type(x) is np.array or type(x) is np.ndarray: print('{:20} {:25} {}'.format(name, repr(type(x)), x.shape)) elif type(x) is list: print('{:20} {:25} {}'.format(name, repr(type(x)), len(x))) else: print('{:20} {:25} X'.format(name, type(t))) a=np.array([1,2,3]) b=[4,5,6] oshape('a') oshape('b') </code></pre> <p>Output:</p> <pre><code>a &lt;type 'numpy.ndarray'&gt; (3,) b &lt;type 'list'&gt; 3 </code></pre> <p>I would like to put this function oshape() into a module so that it can be reused. However, placing in a module does not allow access to the globals from the main module. I have tried things like 'import __main__ ' and even storing the function globals() and passing it into the submodule. The problem is that globals() is one function, which specifically returns the globals of the module it is called from, not a different function for each module.</p> <pre><code>import numpy as np import olib a=np.array([1,2,3]) b=[4,5,6] olib.oshape('a') olib.oshape('b') </code></pre> <p>Gives me:</p> <pre><code>KeyError: 'a' </code></pre> <p>Extra information: The goal is to reduce redundant typing. With a slight modification (I took it out to make it simpler for the question), oshape could report on a list of variables, so I could use it like:</p> <pre><code>oshape('a', 'b', 'other_variables_i_care_about') </code></pre> <p>So solutions that require typing the variable names in twice are not really what I am looking for. Also, just passing in the variable does not allow the name to be printed. Think about using this in a long log file to show the results of computations &amp; checking variable sizes.</p>
5
2016-09-19T13:34:43Z
39,575,206
<p>Your logic is way over complicated, you should just pass the arrays themselves as you are also already passing the variable name as a string so you are not looking up something you don't have access to. But if you wanted to make your code work exactly as is you could set an attibute on the module:</p> <pre><code>import numpy as np import olib a = np.array([1, 2, 3]) b = [4, 5, 6] olib.a = a olib.b = b olib.oshape('a') olib.oshape('b') </code></pre> <p>This will take any args and search the module the code is run from for the attrs:</p> <pre><code>import numpy as np import sys from os.path import basename import imp def oshape(*args): # output the name, type and shape/length of the input variable(s) # for array or list file_name = sys.argv[0] mod = basename(file_name).split(".")[0] if mod not in sys.modules: mod = imp.load_source(mod, file_name) for name in args: x = getattr(mod, name) if type(x) is np.array or type(x) is np.ndarray: print('{:20} {:25} {}'.format(name, repr(type(x)), x.shape)) elif type(x) is list: print('{:20} {:25} {}'.format(name, repr(type(x)), len(x))) else: print('{} {} X'.format(name, type(x))) </code></pre> <p>Just pass the variable name strings:</p> <pre><code>:~/$ cat t2.py import numpy as np from olib import oshape a = np.array([1, 2, 3]) b = [4, 5, 6] c = "a str" oshape("a", "b", "c") :$ python t2.py a &lt;type 'numpy.ndarray'&gt; (3,) b &lt;type 'list'&gt; 3 c &lt;type 'str'&gt; X </code></pre>
1
2016-09-19T14:06:47Z
[ "python", "python-2.7" ]
merge() missing 1 required positional argument: 'right'
39,574,571
<p>I am doing a tutorial and I have a problem: <strong>My code:</strong></p> <pre><code>import html5lib import quandl import pandas as pd import pickle pd.read_html("https://simple.wikipedia.org/wiki/List_of_U.S._states") main_df = pd.DataFrame() fiddy_states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states') for abbv in fiddy_states[0][0][1:]: query = "FMAC/HPI_"+str(abbv) df = quandl.get(query) if main_df.empty: main_df = df else: main_df = pd.merge (main_df , df, how = "right") print(pd.merge(main_df)) </code></pre> <p><strong>and my error is</strong>: </p> <pre><code>TypeError: merge() missing 1 required positional argument: 'right' </code></pre> <p>what's wrong? </p>
0
2016-09-19T13:35:26Z
39,577,959
<pre><code>main_df.merge(df, how = "right") </code></pre>
0
2016-09-19T16:35:19Z
[ "python", "pandas" ]
How to create a custom field in python jira
39,574,585
<p>I'd like to store some extra information in a custom field. So I create a dictionary for my issue:</p> <pre><code> issue_dict = { 'project': 'PROJECT-TITLE', 'summary': 'issue title', 'description': 'issue description', 'assignee': 'issue assignee', 'issuetype': {'name': 'Bug'}, 'customfield': {'extra info'} } </code></pre> <p>and import it to jira like this:</p> <pre><code>new_issue = self.jira.create_issue(fields=issue_dict) </code></pre> <p>The error I get is: </p> <pre><code>TypeError: set(['extra info']) is not JSON serializable </code></pre>
1
2016-09-19T13:36:14Z
39,589,103
<p>One workaround that I found was to store the information in a comment instead and parsing <code>comment body</code>instead. It ain't pretty though.</p>
0
2016-09-20T08:24:39Z
[ "python", "python-jira" ]
ImportError: cannot import name 'QtCore'
39,574,639
<p>I am getting the below error with the following imports. It seems to be related to pandas import. I am unsure how to debug/solve this.</p> <p>Imports:</p> <pre><code>import pandas as pd import numpy as np import pdb, math, pickle import matplotlib.pyplot as plt </code></pre> <p>Error:</p> <pre><code>In [1]: %run NN.py --------------------------------------------------------------------------- ImportError Traceback (most recent call last) /home/abhishek/Desktop/submission/a1/new/NN.py in &lt;module&gt;() 2 import numpy as np 3 import pdb, math, pickle ----&gt; 4 import matplotlib.pyplot as plt 5 6 class NN(object): /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/pyplot.py in &lt;module&gt;() 112 113 from matplotlib.backends import pylab_setup --&gt; 114 _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() 115 116 _IP_REGISTERED = None /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/backends/__init__.py in pylab_setup() 30 # imports. 0 means only perform absolute imports. 31 backend_mod = __import__(backend_name, ---&gt; 32 globals(),locals(),[backend_name],0) 33 34 # Things we pull in from all backends /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt4agg.py in &lt;module&gt;() 16 17 ---&gt; 18 from .backend_qt5agg import FigureCanvasQTAggBase as _FigureCanvasQTAggBase 19 20 from .backend_agg import FigureCanvasAgg /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt5agg.py in &lt;module&gt;() 14 15 from .backend_agg import FigureCanvasAgg ---&gt; 16 from .backend_qt5 import QtCore 17 from .backend_qt5 import QtGui 18 from .backend_qt5 import FigureManagerQT /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt5.py in &lt;module&gt;() 29 figureoptions = None 30 ---&gt; 31 from .qt_compat import QtCore, QtGui, QtWidgets, _getSaveFileName, __version__ 32 from matplotlib.backends.qt_editor.formsubplottool import UiSubplotTool 33 /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/backends/qt_compat.py in &lt;module&gt;() 135 # have been changed in the above if block 136 if QT_API in [QT_API_PYQT, QT_API_PYQTv2]: # PyQt4 API --&gt; 137 from PyQt4 import QtCore, QtGui 138 139 try: ImportError: cannot import name 'QtCore' </code></pre> <p>Debugging:</p> <pre><code>$ python -c "import PyQt4" $ python -c "from PyQt4 import QtCore" Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; ImportError: cannot import name 'QtCore' $ conda list | grep qt jupyter-qtconsole-colorschemes 0.7.1 &lt;pip&gt; pyqt 5.6.0 py35_0 qt 5.6.0 0 qtawesome 0.3.3 py35_0 qtconsole 4.2.1 py35_0 qtpy 1.0.2 py35_0 </code></pre> <p>I found other answers but all related to Windows. I am using ubuntu 16.04 with anaconda distribution of python 3.</p>
11
2016-09-19T13:38:41Z
39,577,184
<p>Downgrading pyqt version 5.6.0 to 4.11.4, and qt from version 5.6.0 to 4.8.7 fixes this:</p> <pre><code>$ conda install pyqt=4.11.4 $ conda install qt=4.8.7 </code></pre> <p>The issue itself is being resolved here: <a href="https://github.com/ContinuumIO/anaconda-issues/issues/1068">https://github.com/ContinuumIO/anaconda-issues/issues/1068</a></p>
11
2016-09-19T15:50:01Z
[ "python", "anaconda", "python-import", "qtcore" ]
ImportError: cannot import name 'QtCore'
39,574,639
<p>I am getting the below error with the following imports. It seems to be related to pandas import. I am unsure how to debug/solve this.</p> <p>Imports:</p> <pre><code>import pandas as pd import numpy as np import pdb, math, pickle import matplotlib.pyplot as plt </code></pre> <p>Error:</p> <pre><code>In [1]: %run NN.py --------------------------------------------------------------------------- ImportError Traceback (most recent call last) /home/abhishek/Desktop/submission/a1/new/NN.py in &lt;module&gt;() 2 import numpy as np 3 import pdb, math, pickle ----&gt; 4 import matplotlib.pyplot as plt 5 6 class NN(object): /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/pyplot.py in &lt;module&gt;() 112 113 from matplotlib.backends import pylab_setup --&gt; 114 _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() 115 116 _IP_REGISTERED = None /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/backends/__init__.py in pylab_setup() 30 # imports. 0 means only perform absolute imports. 31 backend_mod = __import__(backend_name, ---&gt; 32 globals(),locals(),[backend_name],0) 33 34 # Things we pull in from all backends /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt4agg.py in &lt;module&gt;() 16 17 ---&gt; 18 from .backend_qt5agg import FigureCanvasQTAggBase as _FigureCanvasQTAggBase 19 20 from .backend_agg import FigureCanvasAgg /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt5agg.py in &lt;module&gt;() 14 15 from .backend_agg import FigureCanvasAgg ---&gt; 16 from .backend_qt5 import QtCore 17 from .backend_qt5 import QtGui 18 from .backend_qt5 import FigureManagerQT /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt5.py in &lt;module&gt;() 29 figureoptions = None 30 ---&gt; 31 from .qt_compat import QtCore, QtGui, QtWidgets, _getSaveFileName, __version__ 32 from matplotlib.backends.qt_editor.formsubplottool import UiSubplotTool 33 /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/backends/qt_compat.py in &lt;module&gt;() 135 # have been changed in the above if block 136 if QT_API in [QT_API_PYQT, QT_API_PYQTv2]: # PyQt4 API --&gt; 137 from PyQt4 import QtCore, QtGui 138 139 try: ImportError: cannot import name 'QtCore' </code></pre> <p>Debugging:</p> <pre><code>$ python -c "import PyQt4" $ python -c "from PyQt4 import QtCore" Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; ImportError: cannot import name 'QtCore' $ conda list | grep qt jupyter-qtconsole-colorschemes 0.7.1 &lt;pip&gt; pyqt 5.6.0 py35_0 qt 5.6.0 0 qtawesome 0.3.3 py35_0 qtconsole 4.2.1 py35_0 qtpy 1.0.2 py35_0 </code></pre> <p>I found other answers but all related to Windows. I am using ubuntu 16.04 with anaconda distribution of python 3.</p>
11
2016-09-19T13:38:41Z
39,756,863
<p>To avoid downgrading you can also (as was suggested by tacaswell in the issue) set the backend to use <code>Qt5Agg</code> using one of the methods here: <a href="http://matplotlib.org/faq/usage_faq.html#what-is-a-backend" rel="nofollow">http://matplotlib.org/faq/usage_faq.html#what-is-a-backend</a></p> <p>E.g., you can modify the matplotlibrc file located in <code>/your/path/to/anaconda3/envs/yourenv/lib/python3.5/site-packages/matplotlib/mpl-data/matplotlibrc</code> and change the backend line to <code>backend : Qt5Agg</code>. This will make the <code>Qt5Agg</code> backend the default throughout the <code>yourenv</code> conda environment.</p>
1
2016-09-28T20:15:42Z
[ "python", "anaconda", "python-import", "qtcore" ]
ImportError: cannot import name 'QtCore'
39,574,639
<p>I am getting the below error with the following imports. It seems to be related to pandas import. I am unsure how to debug/solve this.</p> <p>Imports:</p> <pre><code>import pandas as pd import numpy as np import pdb, math, pickle import matplotlib.pyplot as plt </code></pre> <p>Error:</p> <pre><code>In [1]: %run NN.py --------------------------------------------------------------------------- ImportError Traceback (most recent call last) /home/abhishek/Desktop/submission/a1/new/NN.py in &lt;module&gt;() 2 import numpy as np 3 import pdb, math, pickle ----&gt; 4 import matplotlib.pyplot as plt 5 6 class NN(object): /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/pyplot.py in &lt;module&gt;() 112 113 from matplotlib.backends import pylab_setup --&gt; 114 _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() 115 116 _IP_REGISTERED = None /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/backends/__init__.py in pylab_setup() 30 # imports. 0 means only perform absolute imports. 31 backend_mod = __import__(backend_name, ---&gt; 32 globals(),locals(),[backend_name],0) 33 34 # Things we pull in from all backends /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt4agg.py in &lt;module&gt;() 16 17 ---&gt; 18 from .backend_qt5agg import FigureCanvasQTAggBase as _FigureCanvasQTAggBase 19 20 from .backend_agg import FigureCanvasAgg /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt5agg.py in &lt;module&gt;() 14 15 from .backend_agg import FigureCanvasAgg ---&gt; 16 from .backend_qt5 import QtCore 17 from .backend_qt5 import QtGui 18 from .backend_qt5 import FigureManagerQT /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt5.py in &lt;module&gt;() 29 figureoptions = None 30 ---&gt; 31 from .qt_compat import QtCore, QtGui, QtWidgets, _getSaveFileName, __version__ 32 from matplotlib.backends.qt_editor.formsubplottool import UiSubplotTool 33 /home/abhishek/anaconda3/lib/python3.5/site-packages/matplotlib/backends/qt_compat.py in &lt;module&gt;() 135 # have been changed in the above if block 136 if QT_API in [QT_API_PYQT, QT_API_PYQTv2]: # PyQt4 API --&gt; 137 from PyQt4 import QtCore, QtGui 138 139 try: ImportError: cannot import name 'QtCore' </code></pre> <p>Debugging:</p> <pre><code>$ python -c "import PyQt4" $ python -c "from PyQt4 import QtCore" Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; ImportError: cannot import name 'QtCore' $ conda list | grep qt jupyter-qtconsole-colorschemes 0.7.1 &lt;pip&gt; pyqt 5.6.0 py35_0 qt 5.6.0 0 qtawesome 0.3.3 py35_0 qtconsole 4.2.1 py35_0 qtpy 1.0.2 py35_0 </code></pre> <p>I found other answers but all related to Windows. I am using ubuntu 16.04 with anaconda distribution of python 3.</p>
11
2016-09-19T13:38:41Z
40,113,906
<p>Updating matplotlib did the trick for me: </p> <pre><code>conda install matplotlib </code></pre>
1
2016-10-18T16:52:03Z
[ "python", "anaconda", "python-import", "qtcore" ]