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
Matplotlib - How to plot a high resolution graph?
39,870,642
<p>I've used matplotlib for plotting some experimental results (discussed it in here: <a href="http://stackoverflow.com/questions/39676294/looping-over-files-and-plotting-python/" title="Looping over files and plotting &#40;Python&#41;">Looping over files and plotting</a>. However, saving the picture by clicking right ...
2
2016-10-05T09:45:40Z
39,870,773
<p>use <code>plt.figure(dpi=1200)</code> before all your <code>plt.plot...</code> and at the end use <code>plt.savefig(...</code> see: <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figure" rel="nofollow">http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figure</a> and <a href="http://ma...
0
2016-10-05T09:51:33Z
[ "python", "matplotlib" ]
Matplotlib - How to plot a high resolution graph?
39,870,642
<p>I've used matplotlib for plotting some experimental results (discussed it in here: <a href="http://stackoverflow.com/questions/39676294/looping-over-files-and-plotting-python/" title="Looping over files and plotting &#40;Python&#41;">Looping over files and plotting</a>. However, saving the picture by clicking right ...
2
2016-10-05T09:45:40Z
39,871,404
<p>At the end of your <em>for()</em> loop, you can use the <code>savefig()</code> function instead of <em>plt.show()</em> and set the name, dpi and format of your figure. </p> <p>E.g. 1000 dpi and eps format are quite a good quality, and if you want to save every picture at folder <em>./</em> with names 'Sample1.eps',...
0
2016-10-05T10:22:09Z
[ "python", "matplotlib" ]
Max, len, split Python
39,870,749
<p>I'm trying to find all combinations of A,B repeated 3 times. Once I've done this I would like to count how many A's there are in a row, by splitting the string and returning the len.max value. However this is going crazy on me. I must have misunderstood the len(max(tmp.split="A")</p> <p>Can anyone explain what this...
2
2016-10-05T09:50:33Z
39,871,238
<p><strong>Edit</strong>: Count only consecutive B's</p> <pre><code>import re import itertools li = list(itertools.product(["A", "B"], repeat=3)) count = 0; for i in li: count += 1 s = ''.join(i) if i.count('B') &gt; 0: var = max(len(s) for s in re.findall(r'B+', s)) else: var = 0 ...
-1
2016-10-05T10:13:40Z
[ "python", "itertools" ]
Max, len, split Python
39,870,749
<p>I'm trying to find all combinations of A,B repeated 3 times. Once I've done this I would like to count how many A's there are in a row, by splitting the string and returning the len.max value. However this is going crazy on me. I must have misunderstood the len(max(tmp.split="A")</p> <p>Can anyone explain what this...
2
2016-10-05T09:50:33Z
39,871,549
<p>You can use <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> to find groups of identical elements in an iterable. <code>groupby</code> generates a sequence of (key, group) tuples, where <code>key</code> is the value of the elements in the ...
3
2016-10-05T10:30:09Z
[ "python", "itertools" ]
Difference between logarithm in numpy and theano.tensor
39,870,912
<p>What is the difference between numpy.log and theano.tensor.log? Do they perform the same?</p>
1
2016-10-05T09:57:48Z
39,877,452
<p>It is likely that <code>numpy.log</code> will be faster. You can compare them both on your CPU and your data.</p> <pre><code>import theano import theano.tensor as T import numpy as x = T.vector('x') theano_log = theano.function([x], T.log(x)) a = np.random.rand(1000).astype(np.float32) # test data assert np.all...
0
2016-10-05T14:58:45Z
[ "python", "numpy", "theano" ]
Most elegant way to calculate completion times for a list of jobs in Python
39,870,925
<p>I have a list of jobs in form of <code>[(weight, length)]</code>, e.g.</p> <pre><code>[(99, 1), (100, 3), (100, 3), (99, 2), (99, 2)] </code></pre> <p>But much larger. </p> <p>And i've written a function that schedules them according to different keys that I pass as a parameter. This means that for each job I cal...
1
2016-10-05T09:58:43Z
39,871,204
<p>You want to use the <a href="https://docs.python.org/3/library/itertools.html#itertools.accumulate" rel="nofollow"><code>itertools.accumulate()</code> iterable</a> to produce the acumulative weight of your lengths:</p> <pre><code>from itertools import accumulate def schedule(jobs_list, sort_key): sorted_jobs ...
3
2016-10-05T10:12:06Z
[ "python", "list", "python-3.x", "list-comprehension" ]
Parsing XML in Python with multiple tags
39,870,942
<p>I'm trying to parse an XML file.<br> I succeeded at parsing tags at the upper layer, but now I have a tag within a tag and I'm not getting the correct output.</p> <p><strong>XML FILE:</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Stations&gt; &lt;Station&gt; &lt;Code&gt;HT&lt...
1
2016-10-05T09:59:12Z
39,872,817
<p>something like this (note: I have used <code>.fromstring()</code> in this example, but you can modify this for your own use with files)</p> <pre><code>import xml.etree.ElementTree xmlstring = "&lt;root&gt;&lt;synoniemen&gt;&lt;synoniem&gt;A&lt;/synoniem&gt;&lt;synoniem&gt;B&lt;/synoniem&gt;&lt;/synoniemen&gt;&lt;/r...
2
2016-10-05T11:31:26Z
[ "python", "python-3.x" ]
OpenCV/Python: Colorbar in fft magnitude
39,870,953
<p>I'm using opencv in python 2.7.</p> <ol> <li>The colormap is oversized. How to shrink it to has the same length as the image?</li> <li>How do I explain the value/range of magnitude?</li> </ol> <p>This is my code:</p> <pre><code>import numpy as np import cv2 from matplotlib import pyplot as plt img = cv2.imread('...
0
2016-10-05T09:59:50Z
39,871,734
<p>I found the solution.</p> <p>To resize the <code>colorbar</code> I use <code>fraction</code> parameter and it's corresponding value in <code>colorbar</code>. Thanks to <a href="http://stackoverflow.com/questions/18195758/set-matplotlib-colorbar-size-to-match-graph/26720422#26720422">bejota's answer</a>.</p> <p>Reg...
0
2016-10-05T10:38:32Z
[ "python", "opencv", "fft", "magnitude" ]
Django how to send a argument in handler404?
39,871,189
<p>How to override <code>handler404</code> to pass arguments into view?</p> <p>Need to pass the arguments <code>text</code> and <code>error</code></p> <pre><code># views.py def handler404(request, error, text): response = render_to_response('error/40X.html', {'error': error, 'text':text}) response.status_code...
0
2016-10-05T10:11:37Z
39,871,516
<p>I don't think you need a custom <code>handler404</code> view here. Django's <code>page_not_found</code> view does what you want.</p> <p>In Django 1.9+, you can include <code>{{ exception }}</code> in the 404 template.</p> <p>In your view, you could set the message when raising the exception, for example:</p> <pre...
0
2016-10-05T10:28:23Z
[ "python", "django", "python-3.x", "django-views", "python-3.5" ]
Is it possible to def a function with a dotted name in Python?
39,871,227
<p>In the question <a href="https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do"><em>What does the "yield" keyword do?</em></a>, I found a Python syntax being used that I didn't expect to be valid. The question is old and has a huge number of votes, so I'm surprised nobody at least left a comment ...
7
2016-10-05T10:13:12Z
39,871,459
<p>No, the syntax is not valid. It is easy to prove by checking the documentation. In Python 2, an identifier is constructed by the following <a href="https://docs.python.org/2/reference/lexical_analysis.html#identifiers" rel="nofollow">rules</a>:</p> <pre><code>identifier ::= (letter|"_") (letter | digit | "_")* let...
4
2016-10-05T10:25:20Z
[ "python", "function", "syntax-error" ]
Is it possible to def a function with a dotted name in Python?
39,871,227
<p>In the question <a href="https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do"><em>What does the "yield" keyword do?</em></a>, I found a Python syntax being used that I didn't expect to be valid. The question is old and has a huge number of votes, so I'm surprised nobody at least left a comment ...
7
2016-10-05T10:13:12Z
39,871,509
<p>As in my comment you cannot, the valid identifiers for python3 are in the <a href="https://docs.python.org/3/reference/lexical_analysis.html#identifiers" rel="nofollow">docs</a>:</p> <p><em>Identifiers (also referred to as names) are described by the following lexical definitions.</em></p> <p><em>The syntax of ide...
2
2016-10-05T10:27:50Z
[ "python", "function", "syntax-error" ]
Unordered collection for mutable objects in Python
39,871,281
<p>The task I have at hand is to parse a large text (several 100K rows) file and accumulate some statistics based which will be then visualized in plots. Each row contains results of some prior analysis. </p> <p>I wrote a custom class to define the objects that are to be accumulated. The class contains 2 string fields...
-2
2016-10-05T10:15:40Z
39,871,545
<p>You could also try an <a href="https://pypi.python.org/pypi/ordered-set" rel="nofollow">ordered-set</a>. Which is a set and ordered.</p>
0
2016-10-05T10:29:51Z
[ "python", "python-3.x", "collections" ]
process Builder java cannot run some of the python code in java. How to solve?
39,871,474
<p>I am using java to create ProcessBuilder to run python. </p> <p>Both of the two py can be run sucessfully in the python program. (the two py have no issue with the code)</p> <p>input.py:</p> <pre><code>print 'hello' number=[3,5,2,0,6] print number number.sort() print number number.append(0) print numb...
0
2016-10-05T10:26:01Z
39,871,834
<p>Your script runs, but it does not reach "Step 2", so </p> <pre><code>gUpdate.parse("BBCOntology.rdf" ) </code></pre> <p>will be the source of the problem. Possibly it is because the file <code>BBCOntology.rdf</code> is not in the current working directory of the Python process. Or it could be that the Python proce...
2
2016-10-05T10:43:13Z
[ "java", "python", "parsing", "rdf", "processbuilder" ]
process Builder java cannot run some of the python code in java. How to solve?
39,871,474
<p>I am using java to create ProcessBuilder to run python. </p> <p>Both of the two py can be run sucessfully in the python program. (the two py have no issue with the code)</p> <p>input.py:</p> <pre><code>print 'hello' number=[3,5,2,0,6] print number number.sort() print number number.append(0) print numb...
0
2016-10-05T10:26:01Z
39,886,173
<pre><code>gUpdate = Graph() print ".&gt; Step....1" gUpdate.parse("D:\\Desktop\\searchTestJava\\BBCOntology.rdf" ) print ".&gt; Step....2" </code></pre> <p>The BBCOntology.rdf is in the current working directory of the Python process. So the program can work in python even if I wrote as (gUpdate.parse("BBCOnt...
0
2016-10-06T01:38:05Z
[ "java", "python", "parsing", "rdf", "processbuilder" ]
Apache Spark 2.0.0 PySpark manual dataframe creation head scratcher
39,871,496
<p>When I assemble a one row data frame as follows my method successfully brings back the expected data frame.</p> <pre><code>def build_job_finish_data_frame(sql_context, job_load_id, is_success): job_complete_record_schema = StructType( [ StructField("job_load_id", IntegerType(), False), ...
1
2016-10-05T10:27:08Z
39,873,305
<p>Why the name changes things? The problem is that <code>Row</code> is a <code>tuple</code> <strong>sorted</strong> by <code>__fields__</code>. So the first case creates </p> <pre><code>from pyspark.sql import Row from datetime import datetime x = Row(job_load_id=1, terminate_datetime=datetime.now(), was_success=Tru...
1
2016-10-05T11:56:38Z
[ "python", "apache-spark", "dataframe" ]
Update a Value in Python
39,871,507
<p>Hello I am trying to write a program that reads a CSV file of different animals of various breeds. Various animals, named differently, can be of the same breed. (Imagine two cats named bob and sam)</p> <p>The breeds are in one column and the names are in another.</p> <p>I want to be able to go over all the animals...
0
2016-10-05T10:27:40Z
39,871,692
<p>As the comments point out, indentation matters in python. The <code>else</code> is not on the same indentation level as the <code>if</code> and thus you get an error.</p> <p>as for the counting, the <code>+=</code> operator is useful for that, so your if/else block could be like this:</p> <pre><code>if row[4] in b...
2
2016-10-05T10:37:15Z
[ "python", "arrays", "csv", "dictionary" ]
Update a Value in Python
39,871,507
<p>Hello I am trying to write a program that reads a CSV file of different animals of various breeds. Various animals, named differently, can be of the same breed. (Imagine two cats named bob and sam)</p> <p>The breeds are in one column and the names are in another.</p> <p>I want to be able to go over all the animals...
0
2016-10-05T10:27:40Z
39,871,699
<p>Your <code>else</code> block is insufficiently indented (<code>else</code> can pair with <code>for</code>, but it's uncommon, and the logic of your code says its an error here).</p> <p>Even if you fix that though, you can't have an empty block in Python, because Python needs at least one indented line of code to de...
0
2016-10-05T10:37:29Z
[ "python", "arrays", "csv", "dictionary" ]
Remove columns from data frame with hashing
39,871,559
<p>Given two pandas dataframes:</p> <pre><code>df1 = pd.read_csv(file1, names=['col1','col2','col3']) df2 = pd.read_csv(file2, names=['col1','col2','col3']) </code></pre> <p>I'd like to remove all the rows in df2 where the values of either <code>col1</code> or <code>col2</code> (or both) do not exist in df1. </p> <p...
1
2016-10-05T10:30:45Z
39,871,596
<p>I think you can try <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a>:</p> <pre><code>df2 = df2[(df2['col1'].isin(df1['col1'])) &amp; (df2['col2'].isin(df1['col2']))] df1 = pd.DataFrame({'col1':[1,2,3,3], 'col2':[4,5,6,2...
2
2016-10-05T10:32:06Z
[ "python", "pandas", "indexing", "merge", "multiple-columns" ]
Is there a way to get the sonar result per class or per module
39,871,632
<p>I want to get the sonar result in the class wise classification or modularized format. I am using python and the sonar web API. Apart from the basic APIs are there any other APIs which give me the results per class</p>
1
2016-10-05T10:34:16Z
39,873,031
<p>SonarQube doesn't know the concept of "class". This is a logical element, whereas SonarQube manages only "physical" components like files or folders. The consequence is that the Web API allows you to query only components that are "physical".</p>
2
2016-10-05T11:41:58Z
[ "python", "sonarqube" ]
Executing Interactive shell script in python
39,872,088
<p>I have a shell script with ask for the user input. Consider a below example</p> <p>Test.sh</p> <pre><code>#!/bin/bash echo -n "Enter name &gt; " read text echo "You entered: $text" echo -n "Enter age &gt; " read text echo "You entered: $text" echo -n "Enter location &gt; " read text echo "You entered: $text" </cod...
-1
2016-10-05T10:55:42Z
39,872,331
<p>Your code is working, but since you mention <code>stdout=subprocess.PIPE</code> the content is going to <code>stdout</code> variable you defined in <code>stdout,stderr = proc.communicate()</code>. Remove <code>stdout=subprocess.PIPE</code> argument from your <code>Popen()</code> call and you will see the output.</p>...
2
2016-10-05T11:07:51Z
[ "python", "python-2.7", "shell", "python-3.x" ]
Executing Interactive shell script in python
39,872,088
<p>I have a shell script with ask for the user input. Consider a below example</p> <p>Test.sh</p> <pre><code>#!/bin/bash echo -n "Enter name &gt; " read text echo "You entered: $text" echo -n "Enter age &gt; " read text echo "You entered: $text" echo -n "Enter location &gt; " read text echo "You entered: $text" </cod...
-1
2016-10-05T10:55:42Z
39,872,483
<p>Actually the subprocess does work - but you are not seeing the prompts because the standard out of the child process is being captured by <code>proc.communicate()</code>. You can confirm this by entering values for the 3 prompts and you should finally see the prompts and your input echoed.</p> <p>Just remove the <c...
1
2016-10-05T11:15:41Z
[ "python", "python-2.7", "shell", "python-3.x" ]
ttk.Widget.state() TclError: Invalid state name
39,872,172
<p>I try change ttk.button state (at the beggining of mainloop) in tkinter like in this <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-Widget.html" rel="nofollow">manual</a> [actualization: actually <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-state-spec.html" rel="nofollow">here</a>.]...
1
2016-10-05T10:59:50Z
39,872,173
<pre><code>colored_btn.state(('pressed',)) </code></pre> <p>From <a href="https://docs.python.org/3.4/library/tkinter.ttk.html?highlight=ttk%20style#tkinter.ttk.Widget.state" rel="nofollow">Python Documentation</a>:</p> <blockquote> <p>statespec will usually be a list or a tuple.</p> </blockquote> <p>I suppose thi...
1
2016-10-05T10:59:50Z
[ "python", "tkinter", "tk", "ttk" ]
Communication Loop with a GUI
39,872,222
<p>I am making a GUI in Python for a machine. My python program runs on a Raspberry Pi 3 and it is communicating by serial with an Arduino UNO.</p> <p>I've made a protocol; the arduino sends a "1". The raspberry knows the "1" stands for Run/Stop, and gives back the value of the RunStop variable (which is either 0 or 1...
-2
2016-10-05T11:01:56Z
39,872,771
<p>Use the Tkinter .after method to periodically call the code that you use to read data from the serial port.</p> <p><a href="http://effbot.org/tkinterbook/widget.htm" rel="nofollow">http://effbot.org/tkinterbook/widget.htm</a></p> <p><a href="http://stackoverflow.com/questions/25753632/tkinter-how-to-use-after-meth...
1
2016-10-05T11:28:57Z
[ "python", "tkinter", "arduino", "pyserial", "raspberry-pi3" ]
Communication Loop with a GUI
39,872,222
<p>I am making a GUI in Python for a machine. My python program runs on a Raspberry Pi 3 and it is communicating by serial with an Arduino UNO.</p> <p>I've made a protocol; the arduino sends a "1". The raspberry knows the "1" stands for Run/Stop, and gives back the value of the RunStop variable (which is either 0 or 1...
-2
2016-10-05T11:01:56Z
39,876,188
<p><strong>Assuming you can do a non-blocking read on the serial port</strong>, you can write a function that reads the serial port, and then schedules itself to be called again after a delay. </p> <p>For example:</p> <pre><code>def poll_serial(root): uartIn = ser.read() if uartIn: process_value_from...
0
2016-10-05T14:06:38Z
[ "python", "tkinter", "arduino", "pyserial", "raspberry-pi3" ]
execute curl command in python
39,872,317
<p>I have already gone through few StackOverflow existing links for this query, did not help me.</p> <p>I would like to run few curl command(4) and each curl commands give output. From that output, I would like to parse the few group ids for next command.</p> <pre><code>curl --basic -u admin:admin -d \'{ "name" : "te...
0
2016-10-05T11:07:04Z
39,872,990
<p>You can use os.popen with</p> <pre><code>fh = os.popen(bash_com, 'r') data = fh.read() fh.close() </code></pre> <p>Or you can use subprocess like this</p> <pre><code>cmds = ['ls', '-l', ] try: output = subprocess.check_output(cmds, stderr=subprocess.STDOUT) retcode = 0 except subprocess.CalledProcessErro...
0
2016-10-05T11:40:11Z
[ "python", "curl", "esb" ]
execute curl command in python
39,872,317
<p>I have already gone through few StackOverflow existing links for this query, did not help me.</p> <p>I would like to run few curl command(4) and each curl commands give output. From that output, I would like to parse the few group ids for next command.</p> <pre><code>curl --basic -u admin:admin -d \'{ "name" : "te...
0
2016-10-05T11:07:04Z
39,873,420
<p>Better output using os.open(bash_com,'r') and then fh.read()</p> <h1>python api.py</h1> <p>% Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 199 172 0 172 0 27 3948 619 --:--:-- --:--:-- --:-...
0
2016-10-05T12:02:16Z
[ "python", "curl", "esb" ]
execute curl command in python
39,872,317
<p>I have already gone through few StackOverflow existing links for this query, did not help me.</p> <p>I would like to run few curl command(4) and each curl commands give output. From that output, I would like to parse the few group ids for next command.</p> <pre><code>curl --basic -u admin:admin -d \'{ "name" : "te...
0
2016-10-05T11:07:04Z
39,909,997
<p>I am trying to redirect the curl commands output to text file and then parse the file via JSON. All I am trying to get "id" from about output.</p> <pre><code>fh = os.popen(bash_com,'r') data = fh.read() newf = open("/var/tmp/t1.txt",'w') sys.stdout = newf print data with open("/var/tmp/t1.txt") as json_data: ...
0
2016-10-07T05:23:57Z
[ "python", "curl", "esb" ]
No module named sqlite
39,872,465
<p>i am a beginner i need to create a python virtual_environment for installing Django. I am using the following steps for installing python and virtualenv </p> <pre><code>cd /usr/src/ wget http://www.python.org/ftp/python/3.5.1./Python-3.5.1.tgz tar zxf Python-3.5.1.tgz cd python-3.5.1 mkdir /usr/local/python-3.5 ./c...
-2
2016-10-05T11:14:52Z
39,872,597
<p>The python-bundled sqlite package is called <code>sqlite3</code>: <a href="https://docs.python.org/3.6/library/sqlite3.html" rel="nofollow">https://docs.python.org/3.6/library/sqlite3.html</a></p> <p>So, just do </p> <pre><code>import sqlite3 </code></pre> <p>and you should be good.</p> <p><strong>EDIT</strong><...
1
2016-10-05T11:20:52Z
[ "python", "django", "virtualenv" ]
No module named sqlite
39,872,465
<p>i am a beginner i need to create a python virtual_environment for installing Django. I am using the following steps for installing python and virtualenv </p> <pre><code>cd /usr/src/ wget http://www.python.org/ftp/python/3.5.1./Python-3.5.1.tgz tar zxf Python-3.5.1.tgz cd python-3.5.1 mkdir /usr/local/python-3.5 ./c...
-2
2016-10-05T11:14:52Z
39,879,388
<p>Any reason you are not using the <a href="https://fedoraproject.org/wiki/EPEL" rel="nofollow">EPEL Repository</a> to install python?</p>
0
2016-10-05T16:33:13Z
[ "python", "django", "virtualenv" ]
Convert image into 4x4 non-overlapping blocks
39,872,556
<p>I want to divide an image into 4x4 non-overlapping blocks in python and then convert that block into array of 16 element.</p>
-1
2016-10-05T11:19:09Z
39,872,931
<p>I recommend using a quality-library like <a href="http://scikit-image.org/" rel="nofollow">scikit-image</a>, especially if there are more steps needed in the future. It is based on numpy/scipy.</p> <p>A kind of minimal example (<a href="http://scikit-image.org/docs/dev/auto_examples/numpy_operations/plot_view_as_bl...
0
2016-10-05T11:36:56Z
[ "python", "image-processing" ]
How to execute multi query from list at once time in Python?
39,872,583
<p>I'm using Tornado and Postgres, I have some queries (4 or 5) that I appended to the list during program and now I want to execute all of them at once time! </p> <p>when I tried to execute I got error that was: </p> <pre><code>"DummyFuture does not support blocking for results" </code></pre> <p>I executed this c...
0
2016-10-05T11:20:03Z
39,874,471
<p>Don't call <code>result()</code> on a Future in a Tornado coroutine. Get results like this:</p> <pre><code>@gen.coroutine def method(self): result = yield self.db.execute('...') </code></pre> <p>Also, I don't think it will work to just join your queries as strings. The outcome won't be valid SQL. Instead:</p> ...
1
2016-10-05T12:51:17Z
[ "python", "postgresql", "tornado" ]
how to remove rows and count it in same file opening
39,872,614
<p>I am trying to open CSV file and remove some rows from it according to given list, on same progress I want to count those rows for future usage. </p> <p>Each file opening works great on separately, how can I combine them on same open file progress? </p> <p>My current code is : </p> <pre><code># read latest file a...
-1
2016-10-05T11:21:44Z
39,872,819
<p>according to your initial description of the problem this could be one solution, although it can surely be optimized</p> <pre><code>excluded = ['your excluded list here'] deleted_rows = 0 with open(file) as read: with open(file2) as write: w = csv.writer(write) r = csv.reader(read) for r...
0
2016-10-05T11:31:32Z
[ "python", "csv" ]
How to set text into a DOM element
39,872,860
<p>I'm trying to set text into a DOM element. I create the element.</p> <pre><code>svg_doc = minidom.parse('PATH_TO_SVG_FILE.svg') category = svg_doc.createElement('category') </code></pre> <p>Then I try to set the <code>nodeValue</code>:</p> <pre><code>category.nodeValue = 'Design' </code></pre> <p>But I get:</p> ...
0
2016-10-05T11:33:47Z
39,875,869
<p>I think this should work:</p> <pre><code>category.createTextNode('Design') </code></pre> <p>See: <a href="https://docs.python.org/2/library/xml.dom.minidom.html" rel="nofollow">https://docs.python.org/2/library/xml.dom.minidom.html</a></p>
1
2016-10-05T13:51:51Z
[ "python", "xml", "dom", "svg", "minidom" ]
Pass command line arguments to nose via "python setup.py test"
39,872,880
<h1>Package Settings</h1> <p>I have built a Python package which uses <a href="http://nose.readthedocs.io/en/latest/" rel="nofollow">nose</a> for testing. Therefore, <a class='doc-link' href="http://stackoverflow.com/documentation/python/1381/creating-python-packages#t=201610051128088238533"><code>setup.py</code></a> ...
0
2016-10-05T11:34:51Z
39,874,096
<p>Nose provides its own setuptools command (<code>nosetests</code>) which accepts command line arguments:</p> <pre><code>python setup.py nosetests --with-xunit </code></pre> <p>More information can be found here: <a href="http://nose.readthedocs.io/en/latest/setuptools_integration.html" rel="nofollow">http://nose.re...
1
2016-10-05T12:33:53Z
[ "python", "command-line-arguments", "nose", "setup.py" ]
How to install GLPK on Alpine Linux?
39,872,907
<p>The installation of <code>swiglpk</code> package on Alpine Linux fails with the following trace:</p> <pre><code>Collecting swiglpk&gt;=1.2.14; extra == "all" (from cameo[all]==0.6.3-&gt;-r requirements.txt (line 1)) Downloading swiglpk-1.2.14.tar.gz Complete output from command python setup.py egg_info: which: n...
0
2016-10-05T11:35:43Z
39,892,738
<p>Cause there is no <code>glpk</code> package for Alpine yet, it can be installed from source</p> <pre><code>wget ftp://ftp.gnu.org/gnu/glpk/glpk-4.55.tar.gz tar -xzvf glpk-4.55.tar.gz cd glpk-4.55 ./configure make install </code></pre> <p>To make sure it worked, run <code>which glpsol</code></p>
0
2016-10-06T09:47:45Z
[ "python", "linux", "installation", "glpk", "alpine" ]
Efficient way for calculating selected differences in array
39,872,981
<p>I have two arrays as an output from a simulation script where one contains IDs and one times, i.e. something like:</p> <pre><code>ids = np.array([2, 0, 1, 0, 1, 1, 2]) times = np.array([.1, .3, .3, .5, .6, 1.2, 1.3]) </code></pre> <p>These arrays are always of the same size. Now I need to calculate the differences...
3
2016-10-05T11:39:48Z
39,873,410
<p>You can use <code>array.argsort()</code> and ignore the values corresponding to change in ids:</p> <pre><code>&gt;&gt;&gt; id_ind = ids.argsort(kind='mergesort') &gt;&gt;&gt; times_diffs = np.diff(times[id_ind]) array([ 0.2, -0.2, 0.3, 0.6, -1.1, 1.2]) </code></pre> <p>To see which values you need to discard, y...
3
2016-10-05T12:01:54Z
[ "python", "arrays", "numpy" ]
Efficient way for calculating selected differences in array
39,872,981
<p>I have two arrays as an output from a simulation script where one contains IDs and one times, i.e. something like:</p> <pre><code>ids = np.array([2, 0, 1, 0, 1, 1, 2]) times = np.array([.1, .3, .3, .5, .6, 1.2, 1.3]) </code></pre> <p>These arrays are always of the same size. Now I need to calculate the differences...
3
2016-10-05T11:39:48Z
39,873,434
<p>Say you <code>np.argsort</code> by <code>ids</code>:</p> <pre><code>inds = np.argsort(ids, kind='mergesort') &gt;&gt;&gt; array([1, 3, 2, 4, 5, 0, 6]) </code></pre> <p>Now sort <code>times</code> by this, <code>np.diff</code>, and prepend a <code>nan</code>:</p> <pre><code>diffs = np.concatenate(([np.nan], np.dif...
2
2016-10-05T12:02:58Z
[ "python", "arrays", "numpy" ]
Efficient way for calculating selected differences in array
39,872,981
<p>I have two arrays as an output from a simulation script where one contains IDs and one times, i.e. something like:</p> <pre><code>ids = np.array([2, 0, 1, 0, 1, 1, 2]) times = np.array([.1, .3, .3, .5, .6, 1.2, 1.3]) </code></pre> <p>These arrays are always of the same size. Now I need to calculate the differences...
3
2016-10-05T11:39:48Z
39,874,178
<p>I'm adding another answer, since, even though these things are possible in <code>numpy</code>, I think that the higher-level <a href="http://pandas.pydata.org/" rel="nofollow"><code>pandas</code></a> is much more natural for them.</p> <p>In <code>pandas</code>, you could do this in one step, after creating a DataFr...
0
2016-10-05T12:37:11Z
[ "python", "arrays", "numpy" ]
Efficient way for calculating selected differences in array
39,872,981
<p>I have two arrays as an output from a simulation script where one contains IDs and one times, i.e. something like:</p> <pre><code>ids = np.array([2, 0, 1, 0, 1, 1, 2]) times = np.array([.1, .3, .3, .5, .6, 1.2, 1.3]) </code></pre> <p>These arrays are always of the same size. Now I need to calculate the differences...
3
2016-10-05T11:39:48Z
39,874,828
<p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) contains efficient and flexible functionality for these kind of grouping operations:</p> <pre><code>import numpy_indexed as npi unique_ids, diffed_time_groups = npi.group_by(...
1
2016-10-05T13:06:53Z
[ "python", "arrays", "numpy" ]
Offer user the option to re-run code
39,873,002
<pre><code>print ("Welcome to my Area Calculator") i=raw_input("Please enter the shape whose Area you want to calculate(square/rectangle/right angled triangle/rhombus/parallelogram): ") my_list=["square","rectangle","triangle","right angled triangle","rhombus","parallelogram"] if i in my_list: if i=="square": ...
-6
2016-10-05T11:40:24Z
39,873,070
<p>Ask for the user if he wants to continue, put it in a boolean variable, put all your code in a while loop with this boolean as a condition<br> Don't forget to init this boolean to true</p>
0
2016-10-05T11:43:49Z
[ "python" ]
Offer user the option to re-run code
39,873,002
<pre><code>print ("Welcome to my Area Calculator") i=raw_input("Please enter the shape whose Area you want to calculate(square/rectangle/right angled triangle/rhombus/parallelogram): ") my_list=["square","rectangle","triangle","right angled triangle","rhombus","parallelogram"] if i in my_list: if i=="square": ...
-6
2016-10-05T11:40:24Z
39,873,085
<p>Make your entire program became a function, then execute it inside while loop.</p> <pre><code>while(option != 'yes'): Program() userInput() </code></pre>
2
2016-10-05T11:44:32Z
[ "python" ]
SQL error 1054, "Unknown column 'xxxxx' in 'field list'" in Python with placeholders
39,873,064
<p>I am new to mySQL with Python and I am getting the common 1054 error when I try to execute a pre-prepared SQL INSERT statement with Python friendly placeholders ('%s')</p> <p>I understand the normal solution is to add quotes in place of back-ticks, or add them if they're missing for the inserted values, however I h...
0
2016-10-05T11:43:40Z
39,873,521
<p>Seems you are asking how to trouble shoot the issue?</p> <pre><code>INSERT INTO Parameters ({0}) VALUES ({1}) </code></pre> <p>The error reporting that in your ({0}), you has one field called "ColumnName", but it is not defined in your table Parameters.</p> <p>Try:</p> <pre><code>SHOW CREATE TABLE parameters; </...
0
2016-10-05T12:06:38Z
[ "python", "mysql", "sql", "mariadb", "pymysql" ]
SQL error 1054, "Unknown column 'xxxxx' in 'field list'" in Python with placeholders
39,873,064
<p>I am new to mySQL with Python and I am getting the common 1054 error when I try to execute a pre-prepared SQL INSERT statement with Python friendly placeholders ('%s')</p> <p>I understand the normal solution is to add quotes in place of back-ticks, or add them if they're missing for the inserted values, however I h...
0
2016-10-05T11:43:40Z
39,891,520
<p>Thanks @Gordon Linoff and @Shuo for all your help. It turned out my dumbed down version of the SQL statement was misleading. I played around with manually adding columns directly using SQL command line to find the answer. </p> <p>It turned out some of my column names exceeded the 64 character limit imposed by SQ...
0
2016-10-06T08:46:10Z
[ "python", "mysql", "sql", "mariadb", "pymysql" ]
max() of big nested lists
39,873,114
<p>I encountered a quite odd problem while dealing with the max of a long list of lists of of pairs, such as</p> <pre><code>[ [(0, 1), (1, 1), (2, 1), (3, 4), (4, 1), (5, 1), (6, 1),...,(141,3)], ..., [(12, 1), (36, 1), (91, 1), (92, 1), (110, 1),..., (180, 1)] ] </code></pre> <p>I am trying to get the m...
-1
2016-10-05T11:46:07Z
39,873,205
<p>You have an empty list among your list of lists, at index 280. Slicing up to <code>[:280]</code> excludes it, and it is included with <code>[:281]</code>.</p> <p>This is easily reproduced with a shorter sample:</p> <pre><code>&gt;&gt;&gt; lsts = [ ... [(0, 1), (1, 1)], ... [(2, 1), (3, 4)], ... [(4, 1)...
5
2016-10-05T11:51:22Z
[ "python", "list", "max", "nested-lists" ]
max() of big nested lists
39,873,114
<p>I encountered a quite odd problem while dealing with the max of a long list of lists of of pairs, such as</p> <pre><code>[ [(0, 1), (1, 1), (2, 1), (3, 4), (4, 1), (5, 1), (6, 1),...,(141,3)], ..., [(12, 1), (36, 1), (91, 1), (92, 1), (110, 1),..., (180, 1)] ] </code></pre> <p>I am trying to get the m...
-1
2016-10-05T11:46:07Z
39,873,318
<p>Why not just this?</p> <pre><code>max([max([t[0] for t in sl if t]) for sl in l if sl]) </code></pre> <p>You can extract the first item from the beginning. Empty lists and tuples are ignored.</p> <p>EDIT</p> <pre><code>max([max([t for t in sl if t]) for sl in l if sl])[0] </code></pre> <p>is more efficient.</p...
0
2016-10-05T11:57:24Z
[ "python", "list", "max", "nested-lists" ]
How to calculate SHA from a string with the Github api in python?
39,873,507
<p>I want to update a file with the Github API and commit it into a branch. I have troubles creating the commit. The SHA does not match the expected one.</p> <pre><code>{ 'documentation_url': 'https://developer.github.com/enterprise/2.7/v3/repos/contents/', 'message': 'pom.xml does not match de42fdd980f9b8067a...
0
2016-10-05T12:06:08Z
39,874,235
<p>GitHub calculates hashes as followes:</p> <pre><code>sha1("blob " + filesize + "\0" + data) </code></pre> <p>so use this code:</p> <pre><code>with open(filepath, 'rb') as file_for_hash: data = file_for_hash.read() filesize = len(data) sha = hashlib.sha1("blob " + filesize + "\0" + data).hexdigest() </code...
0
2016-10-05T12:40:05Z
[ "python", "git", "github-api" ]
How to calculate SHA from a string with the Github api in python?
39,873,507
<p>I want to update a file with the Github API and commit it into a branch. I have troubles creating the commit. The SHA does not match the expected one.</p> <pre><code>{ 'documentation_url': 'https://developer.github.com/enterprise/2.7/v3/repos/contents/', 'message': 'pom.xml does not match de42fdd980f9b8067a...
0
2016-10-05T12:06:08Z
39,874,911
<p>You don't need to calculate the SHA for the new file. Instead you must supply the SHA of the file that is being <em>replaced</em>. You can obtain that by performing a <a href="https://developer.github.com/enterprise/2.7/v3/repos/contents/#get-contents" rel="nofollow">get contents</a> on the file using <code>request...
2
2016-10-05T13:10:35Z
[ "python", "git", "github-api" ]
OOP: best way to code relations between objects of different classes
39,873,713
<p>Let's say we have two classes <code>Basket</code> and <code>Item</code>. Each basket contains a list of items. I can store in the basket the <code>id</code>s of the items, or directly the items objects. Which is the best solution, and why (in terms of memory usage, covenience, etc...)?</p> <p><strong>CASE A</strong...
0
2016-10-05T12:16:19Z
39,873,813
<p>You should store the items directly. As previously mentioned there is no resource issue with doing it and then it provides the basket with direct access to the items. Say you wanted to know how much the basket weighs? well if you add a .weight method to your items class then you can have your basket iterate throu...
3
2016-10-05T12:21:19Z
[ "python", "oop" ]
OOP: best way to code relations between objects of different classes
39,873,713
<p>Let's say we have two classes <code>Basket</code> and <code>Item</code>. Each basket contains a list of items. I can store in the basket the <code>id</code>s of the items, or directly the items objects. Which is the best solution, and why (in terms of memory usage, covenience, etc...)?</p> <p><strong>CASE A</strong...
0
2016-10-05T12:16:19Z
39,873,929
<p>I would prefer storing objects, not IDs. Because each time you would have to do something with your Items you would have to first somehow get/load this object by ID. But this is a general case.</p> <p>In case of you will have tons of Items and no operations with full list (e.g. basket will only perform actions on a...
1
2016-10-05T12:26:09Z
[ "python", "oop" ]
OOP: best way to code relations between objects of different classes
39,873,713
<p>Let's say we have two classes <code>Basket</code> and <code>Item</code>. Each basket contains a list of items. I can store in the basket the <code>id</code>s of the items, or directly the items objects. Which is the best solution, and why (in terms of memory usage, covenience, etc...)?</p> <p><strong>CASE A</strong...
0
2016-10-05T12:16:19Z
39,873,988
<p>Option B is usually the best option because this is how <strong>Object Oriented Programming</strong> works. Because you are using the objects directly you can also access them directly in you code. If you use the link option then in order to access a given <code>Item</code> later you would have to do some sort of qu...
1
2016-10-05T12:29:02Z
[ "python", "oop" ]
OOP: best way to code relations between objects of different classes
39,873,713
<p>Let's say we have two classes <code>Basket</code> and <code>Item</code>. Each basket contains a list of items. I can store in the basket the <code>id</code>s of the items, or directly the items objects. Which is the best solution, and why (in terms of memory usage, covenience, etc...)?</p> <p><strong>CASE A</strong...
0
2016-10-05T12:16:19Z
39,874,782
<p><strong>everything</strong> in python is an object, including integers used as IDs for other objects. So in both Case A and Case B you are appending references to objects to the <code>Basket._items</code> list.</p> <p>So what is the difference between A and B? If you only store the IDs then how will you reference t...
1
2016-10-05T13:04:56Z
[ "python", "oop" ]
I want to appoint array in insert sentence
39,873,794
<p>I use pyorient. The following things want to make it, but can register nothing.</p> <pre><code>lst = ['10', '20', '30'] var = 2016 client.command("insert into class1 (datet, price) values(var, lst[0])") </code></pre>
-2
2016-10-05T12:20:26Z
39,874,656
<p>You could use</p> <pre><code>lst = ['10', '20', '30'] var = 2016 client.command("insert into class1 set datet='%d', price='%s'" % (var,lst[0])); </code></pre> <p>or</p> <pre><code>client.command("insert into class1 (datet,price) values ('%d','%s')" % (var,lst[0])) </code></pre> <p>Hope it helps.</p>
0
2016-10-05T12:59:22Z
[ "python", "orientdb" ]
How to prevent a particular string from being printed in find_all()?
39,873,820
<p>How to exclude a substring from being printed in object <code>obj</code></p> <pre><code>obj = soup.find_all('tag') if "string" not in obj.text: print obj.text </code></pre> <p>But due to the use of find_all() method for object obj nothing is being printed. What should be done so that we print only the wanted s...
-1
2016-10-05T12:21:35Z
39,873,971
<p>You need to loop through the list returned by <code>find_all()</code>:</p> <pre><code>for i in soup.find_all('tag'): txt = i.text if 'string' not in txt: print txt </code></pre> <p>Alternatively, you could create another list where the unwanted tags are filtered out:</p> <pre><code>filtered_lst = ...
0
2016-10-05T12:27:59Z
[ "python", "web-scraping" ]
heroku: no default language could be detected for this app
39,873,920
<p>First time using Heroku. Trying to push. I have run the command:</p> <p><code>heroku create --buildpack heroku/pyhon</code> and it displayed</p> <p><code>$ heroku create --buildpack heroku/python Creating app... done, glacial-reef-7599 Setting buildpack to heroku/python... done https://glacial-reef-7599.herokuapp....
0
2016-10-05T12:25:50Z
39,876,229
<p>You need to create a runtime.txt file. On the command line, in the same folder as your requirements.txt file, enter <code>echo "python-3.5.1" &gt; runtime.txt</code>. Of course, make sure to switch the 3.5.1 with whichever version of Python you are using.</p>
0
2016-10-05T14:08:25Z
[ "python", "heroku" ]
How to iterate over pandas dataframe and create new column
39,873,995
<p>I have a pandas dataframe that has 2 columns. I want to loop through it's rows and based on a string from column 2 I would like to add a string in a newly created 3th column. I tried:</p> <pre><code>for i in df.index: if df.ix[i]['Column2']==variable1: df['Column3'] = variable2 elif df.ix[i]['Column...
2
2016-10-05T12:29:19Z
39,874,053
<p>I think you can use double <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>, what is faster as loop:</p> <pre><code>df['Column3'] = np.where(df['Column2']==variable1, variable2, np.where(df['Column2']==variable3, varia...
2
2016-10-05T12:31:38Z
[ "python", "loops", "pandas", "condition", "multiple-columns" ]
How to iterate over pandas dataframe and create new column
39,873,995
<p>I have a pandas dataframe that has 2 columns. I want to loop through it's rows and based on a string from column 2 I would like to add a string in a newly created 3th column. I tried:</p> <pre><code>for i in df.index: if df.ix[i]['Column2']==variable1: df['Column3'] = variable2 elif df.ix[i]['Column...
2
2016-10-05T12:29:19Z
39,874,167
<p>You can also try this (if you want to keep the <code>for</code> loop you use) :</p> <pre><code>new_column = [] for i in df.index: if df.ix[i]['Column2']==variable1: new_column.append(variable2) elif df.ix[i]['Column2']==variable3: new_column.append(variable4) else : #if both conditions ...
0
2016-10-05T12:36:38Z
[ "python", "loops", "pandas", "condition", "multiple-columns" ]
How to iterate over pandas dataframe and create new column
39,873,995
<p>I have a pandas dataframe that has 2 columns. I want to loop through it's rows and based on a string from column 2 I would like to add a string in a newly created 3th column. I tried:</p> <pre><code>for i in df.index: if df.ix[i]['Column2']==variable1: df['Column3'] = variable2 elif df.ix[i]['Column...
2
2016-10-05T12:29:19Z
39,874,196
<p>Firstly, there is no need to loop through each and every index, just use pandas built in <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#the-where-method-and-masking" rel="nofollow">boolean indexing</a>. First line here, we gather all of the values in <code>Column2</code> that are the same as <cod...
0
2016-10-05T12:37:55Z
[ "python", "loops", "pandas", "condition", "multiple-columns" ]
How can I install pip requirements?
39,874,121
<p>I am installing a requirements package list using</p> <pre><code>pip install -r requirements.txt </code></pre> <p>but I am getting the error</p> <pre><code> Using cached alabaster-0.7.8-py2.py3-none-any.whl Collecting anaconda-client==1.4.0 (from -r requirements.txt (line 2)) Could not find a version that satis...
-1
2016-10-05T12:34:43Z
39,875,122
<p>Pip is basically used to install the latest version of the files available on server Pip install filename Maybe the file you are installing is not on server till now</p>
1
2016-10-05T13:19:52Z
[ "python", "pip", "anaconda" ]
'Subclassing' a Function in Python?
39,874,269
<p>I'm working with the <code>docx</code> library in Python, and I was hoping to create a subclass <code>NewStyleDoc</code> of the <code>Document</code> class from <code>docx</code>. I attempted to do this as follows:</p> <pre><code>from docx import Document class NewStyleDocument(Document): # stuff </code></pre>...
0
2016-10-05T12:41:55Z
39,874,466
<p>This is from the documentation. Your issue seems to be you are using a constructor built into the module, not into the object.</p> <pre><code>Document objects¶ class docx.document.Document[source] WordprocessingML (WML) document. Not intended to be constructed directly. Use docx.Document() to open or creat...
0
2016-10-05T12:51:06Z
[ "python", "inheritance", "docx" ]
'Subclassing' a Function in Python?
39,874,269
<p>I'm working with the <code>docx</code> library in Python, and I was hoping to create a subclass <code>NewStyleDoc</code> of the <code>Document</code> class from <code>docx</code>. I attempted to do this as follows:</p> <pre><code>from docx import Document class NewStyleDocument(Document): # stuff </code></pre>...
0
2016-10-05T12:41:55Z
39,874,559
<p>The simplest method (as <code>docx.Document</code>) appears to be a factory function is probably to just let it do what it needs to so you don't repeat, and wrap around it:</p> <pre><code>from docx import Document def NewStyleDocument(docx=None): document = Document(docx) document.add_heading('Document Tit...
2
2016-10-05T12:54:45Z
[ "python", "inheritance", "docx" ]
Date with a time zone specified as a string is parsed as naive
39,874,396
<p>I'm curious why the timezone in this example, <code>GMT</code>, is not parsed as a valid one:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; import pytz &gt;&gt;&gt; b = 'Mon, 3 Oct 2016 21:24:17 GMT' &gt;&gt;&gt; fmt = '%a, %d %b %Y %H:%M:%S %Z' &gt;&gt;&gt; datetime.strptime(b, fmt).astime...
-1
2016-10-05T12:47:47Z
39,874,625
<p>Use <code>.replace()</code> method with <code>datetime</code> object to update the time zone info.</p> <pre><code>&gt;&gt;&gt; datetime.strptime(b, fmt).replace(tzinfo=pytz.utc) datetime.datetime(2016, 10, 3, 21, 24, 17, tzinfo=&lt;UTC&gt;) </code></pre> <p>Since you mentioned, <code>.astimezone()</code> is workin...
0
2016-10-05T12:57:51Z
[ "python", "datetime" ]
Get column names for max values over a certain row in a pandas DataFrame
39,874,501
<p>In the DataFrame</p> <pre><code>import pandas as pd df=pd.DataFrame({'col1':[1,2,3],'col2':[3,2,1],'col3':[1,1,1]},index= ['row1','row2','row3']) print df col1 col2 col3 row1 1 3 1 row2 2 2 1 row3 3 1 1 </code></pre> <p>I want to get the column names of the cells with ...
1
2016-10-05T12:52:05Z
39,874,583
<p>If not duplicates, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmax.html" rel="nofollow"><code>idxmax</code></a>, but it return only first column of <code>max</code> value:</p> <pre><code>print (df.idxmax(1)) row1 col2 row2 col1 row3 col1 dtype: object def...
1
2016-10-05T12:55:50Z
[ "python", "pandas" ]
Get column names for max values over a certain row in a pandas DataFrame
39,874,501
<p>In the DataFrame</p> <pre><code>import pandas as pd df=pd.DataFrame({'col1':[1,2,3],'col2':[3,2,1],'col3':[1,1,1]},index= ['row1','row2','row3']) print df col1 col2 col3 row1 1 3 1 row2 2 2 1 row3 3 1 1 </code></pre> <p>I want to get the column names of the cells with ...
1
2016-10-05T12:52:05Z
39,874,650
<p>you could also use apply and create a method such has:</p> <pre><code>def returncolname(row, colnames): return colnames[np.argmax(row.values)] df['colmax'] = df.apply(lambda x: returncolname(x, df.columns), axis=1) Out[62]: row1 col2 row2 col1 row3 col1 dtype: object </code></pre> <p>an you can use...
2
2016-10-05T12:59:12Z
[ "python", "pandas" ]
How to parse Python set-inside-list structure into text?
39,874,541
<p>I have the following strange format I am trying to parse. </p> <p>The data structure I am trying to parse is a "set" of key-value pairs in a list:</p> <pre><code>[{'key1:value1', 'key2:value2', 'key3:value3',...}] </code></pre> <p>That's the only data I have, and it needs to be processed. I don't think this can ...
-3
2016-10-05T12:54:04Z
39,874,598
<pre><code>', '.join('{0}:{1}'.format(key, value) for key, value in my_dict.iteritems() for my_dict in my_list) </code></pre> <p>where my_list is name of your list variable</p>
1
2016-10-05T12:56:42Z
[ "python", "regex", "string", "python-3.x" ]
How to parse Python set-inside-list structure into text?
39,874,541
<p>I have the following strange format I am trying to parse. </p> <p>The data structure I am trying to parse is a "set" of key-value pairs in a list:</p> <pre><code>[{'key1:value1', 'key2:value2', 'key3:value3',...}] </code></pre> <p>That's the only data I have, and it needs to be processed. I don't think this can ...
-3
2016-10-05T12:54:04Z
39,874,620
<p>I would use itertools </p> <pre><code>d = {'key1':'value1', 'key2':'value2', 'key3':'value3'} for k, v in d.iteritems(): print k + v + ',', </code></pre>
0
2016-10-05T12:57:40Z
[ "python", "regex", "string", "python-3.x" ]
How to parse Python set-inside-list structure into text?
39,874,541
<p>I have the following strange format I am trying to parse. </p> <p>The data structure I am trying to parse is a "set" of key-value pairs in a list:</p> <pre><code>[{'key1:value1', 'key2:value2', 'key3:value3',...}] </code></pre> <p>That's the only data I have, and it needs to be processed. I don't think this can ...
-3
2016-10-05T12:54:04Z
39,874,733
<p>Try this,</p> <pre><code>print ', '.join(i for x in list_of_set for i in x) </code></pre> <p>If it's <code>set</code> there is no issue with the parsing. The code is equals to </p> <pre><code>output = '' for x in list of_set: for i in x: output += i print output </code></pre>
0
2016-10-05T13:02:21Z
[ "python", "regex", "string", "python-3.x" ]
How to parse Python set-inside-list structure into text?
39,874,541
<p>I have the following strange format I am trying to parse. </p> <p>The data structure I am trying to parse is a "set" of key-value pairs in a list:</p> <pre><code>[{'key1:value1', 'key2:value2', 'key3:value3',...}] </code></pre> <p>That's the only data I have, and it needs to be processed. I don't think this can ...
-3
2016-10-05T12:54:04Z
39,874,761
<p>So, you have a list whose only element is a dictionary, and you want to get all the keys-value pairs from that dictionary and put them into a string?</p> <p>If so, try something like this:</p> <pre><code>d = yourList[0] s = "" for key in d.keys(): s += key + ":" + d[key] + ", " s = s[:-2] #To trim off the last...
0
2016-10-05T13:03:43Z
[ "python", "regex", "string", "python-3.x" ]
How to parse Python set-inside-list structure into text?
39,874,541
<p>I have the following strange format I am trying to parse. </p> <p>The data structure I am trying to parse is a "set" of key-value pairs in a list:</p> <pre><code>[{'key1:value1', 'key2:value2', 'key3:value3',...}] </code></pre> <p>That's the only data I have, and it needs to be processed. I don't think this can ...
-3
2016-10-05T12:54:04Z
39,874,967
<p>Iterating over <code>.items()</code> and formatting differently then previous answers.</p> <p>If your data is the following: <code>list</code> of <code>dict</code> objects then</p> <pre><code>&gt;&gt;&gt; data = [{'key1':'value1', 'key2':'value2', 'key3':'value3'}] &gt;&gt;&gt; ', '.join('{0}:{1}'.format(*item) f...
1
2016-10-05T13:13:20Z
[ "python", "regex", "string", "python-3.x" ]
How to parse Python set-inside-list structure into text?
39,874,541
<p>I have the following strange format I am trying to parse. </p> <p>The data structure I am trying to parse is a "set" of key-value pairs in a list:</p> <pre><code>[{'key1:value1', 'key2:value2', 'key3:value3',...}] </code></pre> <p>That's the only data I have, and it needs to be processed. I don't think this can ...
-3
2016-10-05T12:54:04Z
39,875,064
<p>Since your structure (let's call it <code>myStruct</code>) is a <code>set</code> rather than a <code>dict</code>, the following code should do what you want:</p> <pre><code>result = ", ".join([x for x in myStruct[0]]) </code></pre> <p>Beware, a <code>set</code> is not ordered, so you might end up with something li...
1
2016-10-05T13:17:32Z
[ "python", "regex", "string", "python-3.x" ]
Python - replace a line by its column in file
39,874,600
<p>Sorry for posting such an easy question, but i couldn't find an answer on google. I wish my code to do something like this code:</p> <pre><code>lines = open("Bal.txt").write lines[1] = new_value lines.close() </code></pre> <p>p.s i wish to replace the line in a file with a value</p>
-1
2016-10-05T12:56:51Z
39,876,489
<p>xxx.dat before:</p> <pre><code>ddddddddddddddddd EEEEEEEEEEEEEEEEE fffffffffffffffff with open('xxx.txt','r') as f: x=f.readlines() x[1] = "QQQQQQQQQQQQQQQQQQQ\n" with open('xxx.txt','w') as f: f.writelines(x) </code></pre> <p>xxx.dat after:</p> <pre><code>ddddddddddddddddd QQQQQQQQQQQQQQQQQQQ ffffffffff...
0
2016-10-05T14:19:02Z
[ "python", "file" ]
python list is out of range at iteration 14?
39,874,762
<p>i have a list of indexes that point a term in database</p> <p>Here is my code:</p> <pre><code>for doc in TSS: tokens = word_tokenize(doc[1]) tokens = [token.lower() for token in tokens if len(token) &gt; 2] tokens = [token for token in tokens if token not in words] tokens = [stemmer.stem(token) for...
-2
2016-10-05T13:03:44Z
39,874,975
<p>The way the list "id" is declared is wrong. I didnt get what you are doing there. But if want to store all the values returned by fetchall() function then use for loop for doing it. Declare an empty list id. id = [ ] Use a for loop for taking all the values. And to save the value in list use id.append(value)</p>
0
2016-10-05T13:13:40Z
[ "python" ]
How to convert Odoo/Python code from old to new APIs?
39,874,787
<p>I am convert my whole Odoo Python code from the old API to the new API. So when I create new API this error is generated. How to solve it?</p> <pre><code>File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 380, in dumps return _default_encoder.encode(obj) File "/usr/lib/python2.7/dist-packages/simp...
-3
2016-10-05T13:05:07Z
39,875,356
<p>Somewhere in your code you are passing an object ( flight.itinerary(18,) ) you probably are assigning a value like this.</p> <pre><code>flight_itinerary = self.env['flight.itinerary'].browse([18]) something_else = flight_itinerary </code></pre> <p>Try </p> <pre><code>something_else = flight_itinerary.id </code><...
1
2016-10-05T13:30:16Z
[ "python", "openerp", "odoo-8" ]
How do I get the computer to guess by enumeration?
39,874,868
<p>I've only just started using Python so please excuse how bad my code is!</p> <p>So the computer is playing a game with itself where it has guessed a number between 0 and 100 (target) and it's trying to guess what that number was but it can only guess by enumeration ie. 1,2,3 etc. (i know this isn't the best way for...
-1
2016-10-05T13:08:26Z
39,874,991
<p>Put the <code>guess = 0</code> before your <code>for</code> loop: you are reseting <code>guess</code> at each iteration. Also, <code>count</code> and <code>guess</code> do exactly the same thing, you can just replace one of them by the other. Finally, the <code>break</code> is not correctly indented, it should be at...
1
2016-10-05T13:14:30Z
[ "python", "python-2.7" ]
How do I get the computer to guess by enumeration?
39,874,868
<p>I've only just started using Python so please excuse how bad my code is!</p> <p>So the computer is playing a game with itself where it has guessed a number between 0 and 100 (target) and it's trying to guess what that number was but it can only guess by enumeration ie. 1,2,3 etc. (i know this isn't the best way for...
-1
2016-10-05T13:08:26Z
39,875,129
<p><code>gess</code> is always equal to <code>1</code> in the while loop, to solve it just move <code>guess=0</code> outside: </p> <pre><code>... guess = 0 while True: guess +=1 .... </code></pre>
1
2016-10-05T13:20:12Z
[ "python", "python-2.7" ]
JSONEncoder not handling lists
39,875,038
<p>I have a deeply nested data structure with extensive lists. I want to count the lists instead of displaying all the contents.</p> <pre><code>class SummaryJSONEncoder(json.JSONEncoder): """ Simple extension to JSON encoder to handle date or datetime objects """ def default(self, obj): func =...
1
2016-10-05T13:16:37Z
39,875,880
<p>This seems to work</p> <pre><code>class SummaryJSONEncoder(json.JSONEncoder): """ Simple extension to JSON encoder to handle date or datetime objects """ def default(self, obj): if isinstance(obj, (datetime.datetime, datetime.date,)): return obj.isoformat() if isinstance(obj, (list, tuple, set,)): ...
0
2016-10-05T13:52:18Z
[ "python", "json", "list", "set", "encode" ]
Member of a CBV in Django
39,875,057
<p>I'm, trying to implement a LoginRequiredMixin. For example, if user goes to /post/6 and he isn't logged in, he is redirected to /auth/login/?next=/post/6. I'm trying to make a function that will redirect user either to /post/* (according to next in the url) or to the / if there is no next in the url. I tried to get ...
0
2016-10-05T13:17:13Z
39,917,875
<p>I think your safest bet is to use <a href="https://django-braces.readthedocs.io/" rel="nofollow"><code>braces</code></a>:</p> <h2>Installation</h2> <pre><code>$ pip install braces </code></pre> <h2>Usage</h2> <p>The <a href="https://django-braces.readthedocs.io/en/latest/access.html#loginrequiredmixin" rel="nofo...
0
2016-10-07T12:57:07Z
[ "python", "django", "django-views" ]
Merging two dic in python3 using Unpacking Generalisations in Python3.5
39,875,061
<p>There are two dictionaries as follow which I want to merge them, my point is to select those keys that I am interested in, for example I am interested in all the keys except county. Solution I 've used is using <code>del</code> function after creating your new dictionary, however I am sure there are more ways that a...
-1
2016-10-05T13:17:22Z
39,875,335
<p>why would you want to do it using argument unpacking? just do:</p> <pre><code>from itertools import chain d = {key:value for key, value in chain(d1.iteritems(), d2.iteritems()) if key not in keys_to_ignore} </code></pre> <p>where keys_to_ignore is list/set/tuple of keys you want to ignore</p>
1
2016-10-05T13:29:31Z
[ "python", "python-3.5", "argument-unpacking" ]
Merging two dic in python3 using Unpacking Generalisations in Python3.5
39,875,061
<p>There are two dictionaries as follow which I want to merge them, my point is to select those keys that I am interested in, for example I am interested in all the keys except county. Solution I 've used is using <code>del</code> function after creating your new dictionary, however I am sure there are more ways that a...
-1
2016-10-05T13:17:22Z
39,875,385
<blockquote> <p>How can I solve this problem without del function using UNPACKING ARGUMENT?</p> </blockquote> <p>Yes, you can. But you should not. Ideal way should be:</p> <pre><code>d1.update(d2) # values will be updated in d1 dict del d1['country'] </code></pre> <p>There no direct way to meet your conditions:<...
1
2016-10-05T13:31:01Z
[ "python", "python-3.5", "argument-unpacking" ]
Merging two dic in python3 using Unpacking Generalisations in Python3.5
39,875,061
<p>There are two dictionaries as follow which I want to merge them, my point is to select those keys that I am interested in, for example I am interested in all the keys except county. Solution I 've used is using <code>del</code> function after creating your new dictionary, however I am sure there are more ways that a...
-1
2016-10-05T13:17:22Z
39,875,454
<p>If you don't want to use <code>del</code>, you can replace it by <code>.pop(key)</code>. For example, using unpacking argument too:</p> <pre><code>d = dict(d1, **d2) d.pop("country") </code></pre> <p>Notice that <code>.pop</code> returns the value too (here "Japan").</p>
1
2016-10-05T13:34:08Z
[ "python", "python-3.5", "argument-unpacking" ]
Python - TypeError: unbound method error
39,875,067
<p>Please help, I am new to python and now getting below error </p> <p>"<em>TypeError: unbound method assertEqual() must be called with ExampleScript14 instance as first argument (got str instance instead)</em>"</p> <p><strong>for the below code:</strong></p> <p>from selenium import webdriver from selenium.webdriver...
-1
2016-10-05T13:17:38Z
39,875,141
<p>You <code>test_click_the_username</code> should not be a <code>classmethod</code>. Just delete <code>@classmethod</code> decorator and it should work.</p>
1
2016-10-05T13:20:54Z
[ "python", "selenium" ]
Run the urls in python
39,875,212
<p>I would like to download some datasets from a webpage X. Links to my datasets are included on the webpage. This is my code (I changed the name of the webpage)</p> <pre><code>import urllib2 from BeautifulSoup import * import webbrowser link = urllib2.urlopen('http://www.x.com/html/tlc/html/about/abcd.shtml').read()...
-1
2016-10-05T13:24:12Z
39,875,363
<p>Since this seems to be a problem of your computer/browser, you could try to not download them all at once.</p> <p>Have a look at this: <a href="http://stackoverflow.com/questions/24533951/wait-for-download-completion-in-python">Wait for download completion in Python</a></p> <p>This uses the urllib without opening ...
-1
2016-10-05T13:30:24Z
[ "python", "beautifulsoup" ]
Python script stops after a few minutes
39,875,272
<p>I'm building a python script to check the price of an amazon item every 5-10 seconds. Problem is, the script stops 'working' after a few minutes. There is no output to the console but it shows up as 'running' in my processes.</p> <p>I'm using requests sessions for making http requests and time to display the time o...
3
2016-10-05T13:26:43Z
39,876,241
<p>The timeout argument to the <code>s.get()</code> function is tricky. <a href="http://docs.python-requests.org/en/latest/user/quickstart/#timeouts" rel="nofollow">Here</a> I found a good explanation for its unusual behavior. The <code>timeout</code> will stop the process if the requested url does not respond but it w...
0
2016-10-05T14:08:59Z
[ "python" ]
Insertion sort doesn't sort
39,875,273
<p>I have attempted to create an insertion sort in python, however the list returned is not sorted. What is the problem with my code?</p> <p>Argument given: [3, 2, 1, 4, 5, 8, 7, 9, 6]</p> <p>Result: 2 1 3 6 4 7 5 8 9</p> <p>Python code:</p> <pre><code>def insertion_sort(mylist): sorted_list = [] for i in m...
2
2016-10-05T13:26:48Z
39,875,453
<p>You need to change <code>sorted_list.insert(j-1, i)</code> to be <code>sorted_list.insert(j, i)</code> to insert before position <code>j</code>. </p> <p><code>insert(j-1, ..)</code> will insert before the <em>previous</em> element, and in the case where <code>j=0</code> it'll wrap around and insert before the last...
4
2016-10-05T13:34:08Z
[ "python", "algorithm", "insertion-sort" ]
Insertion sort doesn't sort
39,875,273
<p>I have attempted to create an insertion sort in python, however the list returned is not sorted. What is the problem with my code?</p> <p>Argument given: [3, 2, 1, 4, 5, 8, 7, 9, 6]</p> <p>Result: 2 1 3 6 4 7 5 8 9</p> <p>Python code:</p> <pre><code>def insertion_sort(mylist): sorted_list = [] for i in m...
2
2016-10-05T13:26:48Z
39,875,475
<p>As often, it was a off-by-one error, the code below is fixed. I also made some parts a bit prettier.</p> <pre><code>def insertion_sort(mylist): sorted_list = [] for i in mylist: for index, j in enumerate(sorted_list): if j &gt; i: sorted_list.insert(index, i) #put the num...
1
2016-10-05T13:35:01Z
[ "python", "algorithm", "insertion-sort" ]
Insertion sort doesn't sort
39,875,273
<p>I have attempted to create an insertion sort in python, however the list returned is not sorted. What is the problem with my code?</p> <p>Argument given: [3, 2, 1, 4, 5, 8, 7, 9, 6]</p> <p>Result: 2 1 3 6 4 7 5 8 9</p> <p>Python code:</p> <pre><code>def insertion_sort(mylist): sorted_list = [] for i in m...
2
2016-10-05T13:26:48Z
39,875,722
<p>As Efferalgan &amp; tzaman have mentioned your core problem is due to an off-by-one error. To catch these sorts of errors it's useful to print <code>i</code>, <code>j</code> and <code>sorted_list</code> on each loop iteration to make sure they contain what you think they contain.</p> <p>Here are a few versions of y...
2
2016-10-05T13:46:21Z
[ "python", "algorithm", "insertion-sort" ]
how to send application/x-www-form-urlencoded JSON string in python botlle server
39,875,519
<p>I want to post a JSON string in the format of </p> <pre><code>application/x-www-form-urlencoded </code></pre> <p>using python's bottle</p> <p>Here's the web service I had written</p> <pre><code>import json from bottle import route, run, request @route('/ocr_response2', method='POST') def ocr_response2(): wo...
-1
2016-10-05T13:36:51Z
39,876,141
<p>use <code>request.forms.get('spam')</code></p> <p>also in <code>requests.post</code> url should be <code>http://XX.XX.XX.XXX:8080/ocr_response2</code></p>
1
2016-10-05T14:04:27Z
[ "python", "bottle" ]
When i run this command " cascPath = sys.argv[1] " i get error IndexError: list index out of range
39,875,587
<p>I am using a Raspberry Pi 3 Model B, with Raspbian, opencv 2.x and Python 3 installed.</p> <p>I want to access my USB Webcam and take a picture with it. I've found tons of code but none are of any use. I found one which is better but when I run the command</p> <pre><code>cascPath = sys.argv[1] </code></pre> <p>I...
-3
2016-10-05T13:40:07Z
39,875,673
<p><code>sys.argv[1]</code> is the first CLI parameter and if you don't provide any CLI parameter, <code>len(sys.argv)=1</code> so you can only access sys.argv[0] which is the script name.</p> <p>What you need to do is provide a CLI parameter which is for <code>cascPath</code>.</p> <p>The Cascade is a xml file contai...
0
2016-10-05T13:44:14Z
[ "python", "opencv", "webcam", "raspberry-pi3", "getpicture" ]
Python regex words boundary with unexpected results
39,875,620
<pre><code>import re sstring = "ON Any ON Any" regex1 = re.compile(r''' \bON\bANY\b''', re.VERBOSE) regex2 = re.compile(r'''\b(ON)?\b(Any)?''', re.VERBOSE) regex3 = re.compile(r'''\b(?:ON)?\b(?:Any)?''', re.VERBOSE) for a in regex1.findall(sstring): print(a) print("----------") for a in regex2.findall(sstring): print(a...
1
2016-10-05T13:41:22Z
39,876,126
<p>Note that to match <code>ON ANY</code> you need to add an escaped (since you are using <code>re.VERBOSE</code> flag) space between <code>ON</code> and <code>ANY</code> as <code>\b</code> word boundary <em>being a <strong>zero-width assertion</em></strong> does not consume any text, just asserts a position between sp...
0
2016-10-05T14:04:01Z
[ "python", "regex", "word-boundary" ]
Sending audio data from JS to Python
39,875,668
<p>I'm trying to send a .wav audio file (blob) från JS to Python using Flask. I simply want to save the file on the Python end and be able to play it on my computer. Here is my try:</p> <p><strong>JS:</strong> </p> <pre><code>fetch(serverUrl, { method: "post", body: blob }); </code></pre> <p>Where blob is of th...
0
2016-10-05T13:43:56Z
39,879,185
<p>Have you tried using FormData?</p> <pre><code>var form = new FormData(); form.append('file', BLOBDATA, FILENAME); $.ajax({ type: 'POST', url: 'ServerURL', data: form, // Our pretty new form cache: false, processData: false, // tell jQuery not to process the data contentType: false // tell jQuery not to...
0
2016-10-05T16:22:28Z
[ "javascript", "python", "audio", "flask", "blob" ]
Sending audio data from JS to Python
39,875,668
<p>I'm trying to send a .wav audio file (blob) från JS to Python using Flask. I simply want to save the file on the Python end and be able to play it on my computer. Here is my try:</p> <p><strong>JS:</strong> </p> <pre><code>fetch(serverUrl, { method: "post", body: blob }); </code></pre> <p>Where blob is of th...
0
2016-10-05T13:43:56Z
39,897,411
<p>You are passing an array of event objects to the Blob constructor not the audio data.<br> The data is <code>e.data</code>, so your code should be</p> <pre><code>mediaRecorder.ondataavailable = e =&gt; { chunks.push(e.data); } </code></pre>
2
2016-10-06T13:30:22Z
[ "javascript", "python", "audio", "flask", "blob" ]
Is there a built-in function in Tensorflow for shuffling or permutating tensors?
39,875,674
<p>What's the best way to permutate a tensor along both axis (first rows and then columns or vice versa)? Should I define a <code>py_func</code> and do it using numpy or use one of tensor transformation functions like <code>tf.slice</code> - I don't know if that's possible.</p> <p>To achieve this using numpy, I usuall...
1
2016-10-05T13:44:17Z
39,875,757
<p>What about <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/constant_op.html#random_shuffle" rel="nofollow"><code>tf.random_shuffle()</code></a> combined with <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/array_ops.html#transpose" rel="nofollow">tensor transposition</a> (<code>...
0
2016-10-05T13:47:15Z
[ "python", "numpy", "tensorflow" ]
convert decimal to string python
39,875,794
<p>I imported tab delimited file to create a dataframe (<code>df</code>) which has the following <code>label</code>:</p> <pre><code>label 1 2 3 1 </code></pre> <p>This is stored as pandas.core.series.Series and I want to convert it to string format so that I can get rid of the decimals when I write this out to a te...
1
2016-10-05T13:48:55Z
39,875,899
<p>You can use the <code>float_format</code> keyword argument of the <code>to_string()</code> method:</p> <pre><code>df.to_string(columns=['label'], index=False, float_format=lambda x: '{:d}'.format(x)) </code></pre>
1
2016-10-05T13:53:11Z
[ "python", "pandas", "decimal", "tostring" ]
convert decimal to string python
39,875,794
<p>I imported tab delimited file to create a dataframe (<code>df</code>) which has the following <code>label</code>:</p> <pre><code>label 1 2 3 1 </code></pre> <p>This is stored as pandas.core.series.Series and I want to convert it to string format so that I can get rid of the decimals when I write this out to a te...
1
2016-10-05T13:48:55Z
39,876,067
<p>Using <code>astype(int)</code> will change a <code>float</code> to an <code>int</code> and will drop your <code>.0</code> as desired.</p> <pre><code>import pandas as pd df = pd.DataFrame({'label': [1.0, 2.0, 4.0, 1.0]}) print(df) label 0 1.0 1 2.0 2 4.0 3 1.0 df.label = df.label.astype(int) print(df) ...
1
2016-10-05T14:00:35Z
[ "python", "pandas", "decimal", "tostring" ]
convert decimal to string python
39,875,794
<p>I imported tab delimited file to create a dataframe (<code>df</code>) which has the following <code>label</code>:</p> <pre><code>label 1 2 3 1 </code></pre> <p>This is stored as pandas.core.series.Series and I want to convert it to string format so that I can get rid of the decimals when I write this out to a te...
1
2016-10-05T13:48:55Z
39,876,132
<p>I think you have some <code>NaN</code> values, so <code>int</code> are converted to <code>float</code> because <a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html#na-type-promotions" rel="nofollow">na type promotions</a>.</p> <p>So you can read data in column <code>label</code> as <code>str</code> and...
1
2016-10-05T14:04:11Z
[ "python", "pandas", "decimal", "tostring" ]
Django 1.10 Using a dropdown menu to filter queries
39,875,830
<p>I have a database with a bunch of pictures and the countries they were taken in. This is for a photo album on this site I'm making. Currently, I have all the pictures on one page. I like this. I want to now be able to search for all the pictures from a certain country, or city. My design calls for two buttons on top...
0
2016-10-05T13:50:39Z
39,876,366
<p>You'll need Ajax to do that.</p> <p>Follow <a href="https://realpython.com/blog/python/django-and-ajax-form-submissions/" rel="nofollow">this</a> tutorial to help you.</p> <p>you need to download a <a href="https://raw.githubusercontent.com/realpython/django-form-fun/master/part1/main.js" rel="nofollow">script</a>...
1
2016-10-05T14:14:07Z
[ "jquery", "python", "django", "django-models", "django-templates" ]
Sorting object attributes in different orders
39,875,855
<p>I'm writing a soccer league program and I want to sort the table before printing it out. Each team is a member of a class with certain attributes and so far I've been able to sort the integer attributes correctly.</p> <pre><code>for team in sorted(teams, key=attrgetter("points", "goalDiff", "scored", "name"), rever...
0
2016-10-05T13:51:27Z
39,875,911
<p>If all attributes (except the name) are numeric, negate those numbers to get a reverse sort for those:</p> <pre><code>sorted(teams, key=lambda t: (-t.points, -t.goalDiff, -t.scored, t.name)) </code></pre> <p>Negating numbers gives you a way to reverse their sort order without actually having to reverse the sort.</...
6
2016-10-05T13:53:58Z
[ "python", "python-3.x", "sorting" ]
Python: PySerial disconnecting from device randomly
39,875,897
<p>I have a process that runs data acquisition using PySerial. It's working fine now, but there's a weird thing I had to do to make it work continuously, and I'm not sure this is normal, so I'm asking this question.</p> <p><strong>What happens:</strong> It looks like that the connection drops now and then! Around once...
0
2016-10-05T13:53:01Z
40,110,426
<p>The problem reduced a lot after not calling <code>inWaiting()</code> very frequently. Anyway, I kept the reconnect part to ensure that my program never fails. Thanks for "Kobi K" for suggesting the possible cause of the problem.</p>
0
2016-10-18T14:05:01Z
[ "python", "pyserial", "stability" ]
Phone menu - Python 3
39,876,060
<p>I'm trying to make some project of phone Menu, with viewing, adding and removing contacts. Which way would be better, to add contact to dictionary or by making new file and write/read from it?</p> <p>I tried first method - I had added new contact to empty dictionary and then I tried to view it by using viewing opti...
1
2016-10-05T14:00:13Z
39,876,413
<p>In both options you are overwriting the dictionary on every iteration. You should initilize it only once outside the loop. For the first option it will look like:</p> <pre><code>phone_contacts = {} # this line moved from inside the loop while condition == True: print("Menu") print("contacts") ...
0
2016-10-05T14:16:10Z
[ "python", "python-3.x", "dictionary" ]
Phone menu - Python 3
39,876,060
<p>I'm trying to make some project of phone Menu, with viewing, adding and removing contacts. Which way would be better, to add contact to dictionary or by making new file and write/read from it?</p> <p>I tried first method - I had added new contact to empty dictionary and then I tried to view it by using viewing opti...
1
2016-10-05T14:00:13Z
39,876,663
<p>You should define all functions before and outside the main while(True). You should turn the ifs block into a function that receives the input. You should make it explicit which key is which option.</p> <pre><code>list1=['a','b','c'] def operateList(number): if number == '3': try: list1.remove(input('...
0
2016-10-05T14:26:07Z
[ "python", "python-3.x", "dictionary" ]
Phone menu - Python 3
39,876,060
<p>I'm trying to make some project of phone Menu, with viewing, adding and removing contacts. Which way would be better, to add contact to dictionary or by making new file and write/read from it?</p> <p>I tried first method - I had added new contact to empty dictionary and then I tried to view it by using viewing opti...
1
2016-10-05T14:00:13Z
39,880,951
<p>First thing, you have to declare phone_contacts and the functions outside of the loop.</p> <p>Second there are redundancies in the conditions.</p> <p>The idea of creating a file to store contacts is great. I would save it as a <code>.json</code> file as it is very simple to handle.</p> <p>Here is the code, which ...
0
2016-10-05T18:09:51Z
[ "python", "python-3.x", "dictionary" ]