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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Fast Fourier Transform Javascript | 38,316,538 | <p>I need a FFT function like the FFT in <code>numpy</code> (python) that takes only ONE list( length doesnt necessarily need to be power of 2).</p>
<p>I used <code>dsp.js</code> but it needs the Buffer size and buffer size <strong>must</strong> be power of 2 but my data length is 500.</p>
<p>is there any library tha... | 1 | 2016-07-11T21:30:25Z | 38,449,845 | <p>In addition to the options presented in the blog post suggested by SleuthEye, there is another <a href="http://www.akiti.ca/FourierTransform.html" rel="nofollow">Discrete Fourier Transform</a>, which happens to be written in JavaScript. The output format may be different than what you'd get from other programs (e.g.... | 0 | 2016-07-19T04:56:09Z | [
"javascript",
"python",
"fft"
] |
Need proper directory structure for python packages and guidelines on good API design | 38,316,546 | <p>I am in the midst of releasing a python package, and am confused about every aspect of packaging.</p>
<p>To start, my directory structure is as follows:</p>
<pre><code>SamplePackage/
- setup.py
- README.rst
- LICENSE.rst
- sampledir/
-__init__.py
-sample.py
-utils.py
</code></pre>
<p>currently <co... | 0 | 2016-07-11T21:31:13Z | 38,328,652 | <p>First of all, I thing you've misunderstood what is difference between package and project. You directory structure should be something like this</p>
<pre><code>arbitrary_name_of_project/
- setup.py
- README.rst
- LICENSE.rst
- package_name/
-__init__.py
-sample.py
-utils.py
</code></pre>
<p>Python ... | 0 | 2016-07-12T12:15:59Z | [
"python",
"import",
"pip",
"pypi",
"module-packaging"
] |
'float' object is not subscriptable to add to array | 38,316,688 | <p>I'm coding for a project at school (GCSEs) and we have been tasked that the user will enter the value of a population and we have to code a program where python displays a model to show the population after a set number of generations.
Once the user has entered their desired values I need to display it in a table-l... | -3 | 2016-07-11T21:42:28Z | 38,316,791 | <p>I'm guessing <code>adult_pop</code> and the other population variables are not something that is subscriptable (i.e lists, tuples, dicts, etc) and are either ints or floats instead. That means you are trying to enter a type that does not allow that kind of examination, hence you are getting the error.</p>
<p>I thin... | 0 | 2016-07-11T21:51:39Z | [
"python"
] |
How can better format the output that I'm attempting to save from several regressions? | 38,316,727 | <p>I'd like to loop through several specifications of a linear regression and save the results for each model in a python dictionary. The code below is somewhat successful but additional text (e.g. datatype information) is included in the dictionary making it unreadable. Moreover, regarding the confidence interval, I'... | 1 | 2016-07-11T21:46:00Z | 38,320,615 | <p>This is how I'd summarize what you were showing. Hopefully it helps give you some ideas.</p>
<pre><code>import pandas as pd
import statsmodels.formula.api as smf
data = pd.DataFrame(np.random.randn(30, 5), columns=list('YABCD'))
results = {}
for c in data.columns[1:]:
f = 'Y ~ {}'.format(c)
r = smf.ols(f... | 1 | 2016-07-12T05:24:09Z | [
"python",
"pandas",
"dictionary",
"formatting"
] |
Rearranging 3D numpy arrays in a specific manner | 38,316,752 | <p>I'm working with 3D matrices in numpy. I'm actually passing these matrices to C using ctypes to carry out some calculation and then getting back a result. Now the thing is, my result is correct (I did the math on paper to verify), but it's just not in a form I want it to be. </p>
<p>Here's an example. I have a 3D a... | 0 | 2016-07-11T21:48:27Z | 38,316,809 | <p>Your desired output is your initial array with the order of the axes reversed. That's how NumPy generalizes transposes to arbitrary-dimensional arrays, so you can use the <code>T</code> attribute for this:</p>
<pre><code>In [3]: x
Out[3]:
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[... | 2 | 2016-07-11T21:53:40Z | [
"python",
"numpy",
"matrix"
] |
Converting a txt file to xls file | 38,316,779 | <p>I need some help with specifying format of values in xls. I am converting a txt file into xls.</p>
<p>Below is my current code. As I read the txt file, i need to put the values as Int/Float or str. Int is ok, as well str, but I can't solve a problem with floats.</p>
<p><code>366351.77</code> or <code>-6000.00</cod... | 1 | 2016-07-11T21:51:01Z | 38,316,852 | <p>Use the <code>set_explicit_value</code> method of the <code>cell</code> object.</p>
<pre><code>cell.set_explicit_value(value=your_float, data_type='f')
</code></pre>
<p>Docs:
<a href="https://openpyxl.readthedocs.io/en/default/api/openpyxl.cell.cell.html#openpyxl.cell.cell.Cell.set_explicit_value" rel="nofollow">h... | 1 | 2016-07-11T21:58:06Z | [
"python",
"excel",
"type-conversion"
] |
Converting a txt file to xls file | 38,316,779 | <p>I need some help with specifying format of values in xls. I am converting a txt file into xls.</p>
<p>Below is my current code. As I read the txt file, i need to put the values as Int/Float or str. Int is ok, as well str, but I can't solve a problem with floats.</p>
<p><code>366351.77</code> or <code>-6000.00</cod... | 1 | 2016-07-11T21:51:01Z | 38,331,963 | <p>First of all tks so much Nicarus, your help solved my problem.</p>
<p>Here is my final code, now The values as Number(Values, Accounts, Index..) are being correctly added as a number in the Worksheet, and the others value as (Date, Description...) are being added as String</p>
<p><a href="http://i.stack.imgur.com/... | 0 | 2016-07-12T14:38:52Z | [
"python",
"excel",
"type-conversion"
] |
How do I get python to search text for one word in a list rather than all the words in a list? | 38,316,816 | <p>I want to create a list of synonym words, and have python search for co-locations, but I don't need every single word in the list to show up. I just need one of the words from each list to be present. </p>
<p>I have conversations threads from an online forum in a csv file. I have been looking for words that co-l... | 0 | 2016-07-11T21:54:01Z | 38,316,886 | <p>So you would like to provide one or more words and return all posts which contain either the word(s), or synonyms of the word(s), you provided.</p>
<p>It appears finding synonyms of a word is tricky. Some <a href="http://stackoverflow.com/questions/19348973/all-synonyms-for-word-in-python">have suggested</a> using... | 1 | 2016-07-11T22:00:41Z | [
"python"
] |
Ignoring Multiple Whitespace Characters in a MongoDB Query | 38,316,869 | <p>I have a MongoDB query that searches for addresses. The problem is that if a user accidentally adds an extra whitespace, the query will not find the address. For example, if the user types <code>123 Fakeville St</code> instead of <code>123 Fakeville St</code>, the query will not return any results.</p>
<p>Is the... | 0 | 2016-07-11T21:59:16Z | 38,316,966 | <p>Clean up the query before sending it off:</p>
<pre><code>>> import re
>>> re.sub(r'\s+', ' ', '123 abc')
'123 abc'
>>> re.sub(r'\s+', ' ', '123 abc def ghi')
'123 abc def ghi'
</code></pre>
<p>You'll probably want to make sure that the data in your database is similarly normalised. Al... | 1 | 2016-07-11T22:05:52Z | [
"python",
"regex",
"mongodb"
] |
Ignoring Multiple Whitespace Characters in a MongoDB Query | 38,316,869 | <p>I have a MongoDB query that searches for addresses. The problem is that if a user accidentally adds an extra whitespace, the query will not find the address. For example, if the user types <code>123 Fakeville St</code> instead of <code>123 Fakeville St</code>, the query will not return any results.</p>
<p>Is the... | 0 | 2016-07-11T21:59:16Z | 38,321,765 | <p>An alternative approach without using regex you could try is to utilise <a href="https://docs.mongodb.com/manual/core/index-text/#text-indexes" rel="nofollow">MongoDB text indexes</a>. By adding a text index on the field you can perform text searches using <a href="https://docs.mongodb.com/manual/reference/operator/... | 0 | 2016-07-12T06:46:42Z | [
"python",
"regex",
"mongodb"
] |
Confused about encoding issue when read from mysql via python code | 38,316,906 | <p>There is one row in Mysql table as following:</p>
<pre><code>1000, Intel® Rapid Storage Technology
</code></pre>
<p>The table's charset='utf8' when was created.
When I used python code to read it, it become the following:</p>
<pre><code>Intelî Management Engine Firmware
</code></pre>
<p>My python code as fol... | 2 | 2016-07-11T22:01:54Z | 38,317,083 | <p>Have you tried leaving off the charset in the connect string and then setting afterwards?</p>
<pre><code>db = MySQLdb.connect(db,user,passwd,dbName,port)
db.set_character_set('utf8')
</code></pre>
| 0 | 2016-07-11T22:17:25Z | [
"python",
"mysql",
"encoding",
"character-encoding"
] |
Confused about encoding issue when read from mysql via python code | 38,316,906 | <p>There is one row in Mysql table as following:</p>
<pre><code>1000, Intel® Rapid Storage Technology
</code></pre>
<p>The table's charset='utf8' when was created.
When I used python code to read it, it become the following:</p>
<pre><code>Intelî Management Engine Firmware
</code></pre>
<p>My python code as fol... | 2 | 2016-07-11T22:01:54Z | 38,318,857 | <p>When trying to use utf8/utf8mb4, if you see <strong>Mojibake</strong>, check the following.
This discussion also applies to <strong>Double Encoding</strong>, which is not necessarily visible.</p>
<ul>
<li>The bytes to be stored need to be utf8-encoded.</li>
<li>The connection when <code>INSERTing</code> and <code>S... | 0 | 2016-07-12T01:59:21Z | [
"python",
"mysql",
"encoding",
"character-encoding"
] |
Python Selenium - What are possible keys in FireFox webdriver profile preferences | 38,316,910 | <p>I couldn't really find this information anywhere, I am looking for a list of possible keys that can be used in the <code>profile.set_preference()</code> API.</p>
<p>Here is some context:</p>
<pre><code>from selenium import webdriver
from pyvirtualdisplay import Display
display = Display(visible=0, size=(1024, 768)... | 0 | 2016-07-11T22:01:58Z | 38,316,989 | <p>I usually just open <code>about:config</code> and search the list of preferences there. There is also <a href="http://kb.mozillazine.org/About:config_entries" rel="nofollow">this helpful resource</a> which documents part of the preferences.</p>
| 0 | 2016-07-11T22:08:00Z | [
"python",
"selenium",
"selenium-firefoxdriver",
"webautomation"
] |
Python Selenium - What are possible keys in FireFox webdriver profile preferences | 38,316,910 | <p>I couldn't really find this information anywhere, I am looking for a list of possible keys that can be used in the <code>profile.set_preference()</code> API.</p>
<p>Here is some context:</p>
<pre><code>from selenium import webdriver
from pyvirtualdisplay import Display
display = Display(visible=0, size=(1024, 768)... | 0 | 2016-07-11T22:01:58Z | 38,317,164 | <p>You can look at <code>profile.DEFAULT_PREFERENCES</code> which is the <code>json</code> at <code>python2.7/site-packages/selenium/webdriver/firefox/webdriver_prefs.json</code></p>
<pre><code>{u'frozen': {u'app.update.auto': False,
u'app.update.enabled': False,
u'browser.EULA.3.accepted': True,
u'browser.EULA.... | 2 | 2016-07-11T22:25:38Z | [
"python",
"selenium",
"selenium-firefoxdriver",
"webautomation"
] |
Pandas - select rows with best values | 38,317,041 | <p>I have this dataframe</p>
<pre><code> col1 col2 col3
0 2 A 1
1 1 A 100
2 3 B 12
3 4 B 2
</code></pre>
<p>I want to select the highest col1 value from all with A, then the one from all with B, etc, i.e. this is the desired output</p>
<pre><code> col1 col2 col3
0 2 A 1
3 ... | 3 | 2016-07-11T22:13:33Z | 38,317,089 | <p>is that what you want?</p>
<pre><code>In [16]: df.groupby('col2').max().reset_index()
Out[16]:
col2 col1
0 A 2
1 B 4
</code></pre>
| 3 | 2016-07-11T22:18:04Z | [
"python",
"pandas",
"dataframe"
] |
Pandas - select rows with best values | 38,317,041 | <p>I have this dataframe</p>
<pre><code> col1 col2 col3
0 2 A 1
1 1 A 100
2 3 B 12
3 4 B 2
</code></pre>
<p>I want to select the highest col1 value from all with A, then the one from all with B, etc, i.e. this is the desired output</p>
<pre><code> col1 col2 col3
0 2 A 1
3 ... | 3 | 2016-07-11T22:13:33Z | 38,320,725 | <p>use <code>groupby('col2')</code> then use <code>idxmax</code> to get the index of the max values within each group. Finally, use these index values to slice the original dataframe.</p>
<pre><code>df.loc[df.groupby('col2').col1.idxmax()]
</code></pre>
<p><a href="http://i.stack.imgur.com/hP9Ow.png" rel="nofollow">... | 2 | 2016-07-12T05:33:53Z | [
"python",
"pandas",
"dataframe"
] |
Faster way to parse .pcap | 38,317,092 | <p>I am trying to parse huge .pcap files (~1-2GB each). I have tried to use scapy but so far it is much to slow. I have benchmarked timings using the following code with different values for count</p>
<pre><code>from scapy.all import *
from scapy.layers.dns import DNSRR, DNS, DNSQR
import time
t0 = time.time()
pcap ... | 1 | 2016-07-11T22:18:13Z | 39,276,127 | <p>To really give you solid feedback I'd need you to post a larger chunk of your code. But from what I can see: </p>
<p>My first thought would be to use threading (if possible: I'm not sure what the rest of your code looks like)</p>
<p>My second thought would be to check the return type of your rdpcap() function and ... | 0 | 2016-09-01T15:59:23Z | [
"python",
"packet",
"scapy",
"tcpdump",
"dpkt"
] |
Inserting layout into QDialog when signal is emitted from combobox | 38,317,141 | <p>I have a ui created in qtdesigner that looks like this:</p>
<p><a href="http://i.stack.imgur.com/sfdnT.png" rel="nofollow"><img src="http://i.stack.imgur.com/sfdnT.png" alt="enter image description here"></a></p>
<p>and I want to insert another layout containing a couple of widgets between the groupbox titled "Equ... | 1 | 2016-07-11T22:23:24Z | 38,317,356 | <p>The layout that contains all the others will be the dialog's layout, so you can try something like this:</p>
<pre><code> def enableInitialValueEntry(self):
...
if vartype == "Stock":
...
main_layout = self.layout()
main_layout.insertLayout(2, hbox)
</code></pre... | 1 | 2016-07-11T22:44:59Z | [
"python",
"qt",
"pyqt",
"qdialog",
"qlayout"
] |
Can you use "first class" concept on Python methods/attributes? | 38,317,314 | <p>Can the "first-class" concept be applied to Python methods/attributes like it can functions? </p>
<pre><code>>>>a=sum
>>>a([1,2,3])
6
</code></pre>
<p>I would like to do something like:</p>
<pre><code>>>>case='lower'
>>>'UPPERCASE'.case()
</code></pre>
<p>To produce the string... | 0 | 2016-07-11T22:40:07Z | 38,317,369 | <p>You can do it this way:</p>
<pre><code>case = str.lower # Take the lower() method of the str class.
case('UPPERCASE') # pass your string as the first argument, which is self.
</code></pre>
<p>In this case, Python being explicit about <code>self</code> being the first argument to methods makes this a lot clearer to... | 0 | 2016-07-11T22:46:14Z | [
"python"
] |
python extract word from multiple lines into 1 list | 38,317,354 | <p>I am trying to extract unique words out of the following text into 1 list. </p>
<pre><code>But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
</code></pre>
<p>But I keep getting a list within the lis... | 2 | 2016-07-11T22:44:55Z | 38,317,401 | <p>When you do <code>line.lower.split()</code> you get a List of words. You're appending a list of words to your list, lst. Use extend instead of append. Extend would add each element of the list returned by the split() function. Also the second for loop <code>for word in line:</code> is unnecessary.
Additionally, if ... | 2 | 2016-07-11T22:49:53Z | [
"python",
"list",
"split",
"strip"
] |
python extract word from multiple lines into 1 list | 38,317,354 | <p>I am trying to extract unique words out of the following text into 1 list. </p>
<pre><code>But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
</code></pre>
<p>But I keep getting a list within the lis... | 2 | 2016-07-11T22:44:55Z | 38,317,406 | <p>Use this:<br></p>
<pre><code>list += word
</code></pre>
<p>Instead of:</p>
<pre><code>lst.append(word)
</code></pre>
| 2 | 2016-07-11T22:50:13Z | [
"python",
"list",
"split",
"strip"
] |
python extract word from multiple lines into 1 list | 38,317,354 | <p>I am trying to extract unique words out of the following text into 1 list. </p>
<pre><code>But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
</code></pre>
<p>But I keep getting a list within the lis... | 2 | 2016-07-11T22:44:55Z | 38,317,419 | <p>A list comprehension does the same like you've done. </p>
<p>Then use <a href="https://docs.python.org/3.5/library/itertools.html#itertools.chain.from_iterable" rel="nofollow"><code>chain.from_iterable</code></a> to <em>chain</em> all the sublists into one list:</p>
<pre><code>from itertools import chain
lst = li... | 0 | 2016-07-11T22:51:05Z | [
"python",
"list",
"split",
"strip"
] |
python extract word from multiple lines into 1 list | 38,317,354 | <p>I am trying to extract unique words out of the following text into 1 list. </p>
<pre><code>But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
</code></pre>
<p>But I keep getting a list within the lis... | 2 | 2016-07-11T22:44:55Z | 38,317,431 | <p>If the order is not important, you can use set instead of list:</p>
<pre><code>fname = input("Enter file name: ")
fh = open(fname)
uniq_words = set()
for line in fh:
line = line.strip()
uniq_words_in_line = line.split(' ')
uniq_words.update(uniq_words_in_line)
print(uniq_words)
</code></pre>
| 0 | 2016-07-11T22:52:25Z | [
"python",
"list",
"split",
"strip"
] |
python extract word from multiple lines into 1 list | 38,317,354 | <p>I am trying to extract unique words out of the following text into 1 list. </p>
<pre><code>But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
</code></pre>
<p>But I keep getting a list within the lis... | 2 | 2016-07-11T22:44:55Z | 38,317,539 | <p>As @Shalan and @BladeMight suggested, the issue is that <code>word = line.lower().split()</code> produces a list, and <code>append</code> appends the list rather than adding to it. I think a syntactically simple way to write this would be:</p>
<pre><code>fname = input("Enter file name: ")
fh = open(fname)
lst = lis... | 0 | 2016-07-11T23:03:42Z | [
"python",
"list",
"split",
"strip"
] |
Should I use Threads or multiple processess? | 38,317,462 | <p>I wanted to get some help with an application... Currently I have a script that saves certain information to a database table, well call this table "x". I have another script that gets and saves other info to a different database table, well call this one "y". I also have a script that runs formulas on the informati... | 0 | 2016-07-11T22:55:58Z | 38,317,881 | <p>Based on Harp's second comment to his original post <em>(which was posted <strong>after</strong> your answer),</em> I suspect that you would now agree with me that <em>processes</em> are probably called-for here, based on this newly-supplied information.</p>
<p>However, I find myself questioning just how much "trul... | 0 | 2016-07-11T23:44:12Z | [
"python",
"multithreading",
"multiprocessing"
] |
Finding separators/delimiters in lists of strings | 38,317,525 | <p>I am trying to find separators in a file that may or may not have separators, and what those separators are - if any - is also not known.</p>
<p>So far I have written the following code in an attempt to "solve" this:</p>
<pre><code>strings = [
'cabhb2k4ack_sfdfd~ffrref_lk',
'iodja_24ed~092oi3jelk_fcjcad',
... | 0 | 2016-07-11T23:02:24Z | 38,318,218 | <p>I'd use a <code>Counter</code> instead of <code>.count</code>, take skrrgwasme's suggestion to use a list, and use <code>itertools.combinations</code> to help iterate over the subsets of possible separators:</p>
<pre><code>from collections import Counter
from itertools import combinations
def subsets(elems):
f... | 1 | 2016-07-12T00:31:39Z | [
"python"
] |
Finding separators/delimiters in lists of strings | 38,317,525 | <p>I am trying to find separators in a file that may or may not have separators, and what those separators are - if any - is also not known.</p>
<p>So far I have written the following code in an attempt to "solve" this:</p>
<pre><code>strings = [
'cabhb2k4ack_sfdfd~ffrref_lk',
'iodja_24ed~092oi3jelk_fcjcad',
... | 0 | 2016-07-11T23:02:24Z | 38,319,625 | <p>Given the rule 1, each separator has a number of occurences / line that is steady from the first line to the last one of the list. </p>
<p>I don't find the rule 3 very well expressed. I think it must be understood as: "every character used as separator can't be found among others characters considered non-separator... | 1 | 2016-07-12T03:36:51Z | [
"python"
] |
Average based on a Criteria/ Condition Numpy Python | 38,317,528 | <p>So I want to take the average of all values in column b when column a is a particular and plot it using Matplotlib.</p>
<p><a href="http://i.stack.imgur.com/bVAUw.png" rel="nofollow"><img src="http://i.stack.imgur.com/bVAUw.png" alt="enter image description here"></a></p>
<p>So in the table above I want to average... | 0 | 2016-07-11T23:02:44Z | 38,318,052 | <p>With NumPy only, you could use <code>np.unique(..., return_indx=True)</code> to find the indices which demarcate the chunks with constant <code>A</code> value:</p>
<pre><code>data_temp.sort(order=['A'])
uniqs, idx = np.unique(data_temp['A'], return_index=True)
idx = np.r_[idx, len(data_temp)]
# >>> idx
# a... | 2 | 2016-07-12T00:07:14Z | [
"python",
"numpy",
"matplotlib",
"average"
] |
Python Error: ValueError: Non-integer arg 1 for randrange() | 38,317,543 | <p>I'm getting the above error in my code. It's just a simple text-based game.</p>
<p>Here's the code:</p>
<pre><code>import os
import sys
import random
class Player:
def __init__(self, name):
self.name = name
self.maxhealth = 100
self.health = self.maxhealth
self.attack = 10
... | 0 | 2016-07-11T23:04:02Z | 38,317,563 | <p>Use <code>EnemyAttack = random.randint(math.floor(enemy.attack / 2), enemy.attack)</code>, or use <code>math.ceil()</code> to round the result of <code>enemy.attack / 2</code>. </p>
<p><code>randrange()</code> expects whole integers. The error is occurring because the result of <code>enemy.attack / 2</code> isn't a... | 0 | 2016-07-11T23:06:23Z | [
"python",
"random"
] |
How to convert strings to numbers, when taking data from .csv to .xlsx, using openpyxl | 38,317,584 | <p>I wrote this code to take info I have stored inside a .csv file and put it into a .xlsx file. When it is in the excel doc all of the information are strings. I can't figure out a way to change them into numbers so I can then use openpyxl in order to create a line graph. Here is the code </p>
<pre><code>import openp... | 0 | 2016-07-11T23:08:43Z | 38,317,652 | <p>The CSV reader reads the file into a 2D list, where each row represents a line. The data is read in and stored as strings. So you'd need to explicitely cast the values to the desired type, something like this:</p>
<pre><code>ws.cell(row=i, column=h).value = float(exampleData[a][b])
</code></pre>
<p>Look here for f... | 0 | 2016-07-11T23:16:00Z | [
"python",
"excel",
"csv",
"openpyxl"
] |
Moving from localhost to real URL in Flask? | 38,317,593 | <p>I'm developing a site with Python and Flask and want to move from localhost in my browser to my team's development server and development site but I'm having problems. I've already looked at the Flask documentation, which recommends using <code>host='0.0.0.0'</code> or specifying <code>SERVER_NAME</code>. Thusfar, n... | 1 | 2016-07-11T23:09:19Z | 38,317,895 | <p>If you run with <code>host='0.0.0.0'</code> from the server, you should be able to navigate to <code>example.org:4343</code> and see your app.</p>
<p>Additionally, <code>SERVER_NAME</code> requires the port, per the <a href="http://flask.pocoo.org/docs/0.11/config/" rel="nofollow">documentation</a>:</p>
<blockquot... | 2 | 2016-07-11T23:45:10Z | [
"python",
"flask"
] |
Installing beautifulsoup | 38,317,730 | <p>I have installed beautifulsoup for Python, but it gives me this error when I import the library:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "D:/Playroom/WebScraper_01.py", line 2, in <module>
from bs4 import BeautifulSoup
File "C:\Python\lib\site-pack... | 0 | 2016-07-11T23:24:49Z | 38,317,858 | <p>Probably incorrect install, use pip to install correctly.</p>
| 0 | 2016-07-11T23:41:19Z | [
"python"
] |
Installing beautifulsoup | 38,317,730 | <p>I have installed beautifulsoup for Python, but it gives me this error when I import the library:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "D:/Playroom/WebScraper_01.py", line 2, in <module>
from bs4 import BeautifulSoup
File "C:\Python\lib\site-pack... | 0 | 2016-07-11T23:24:49Z | 38,317,874 | <ul>
<li><p>If you get the ImportError âNo module named HTMLParserâ, your problem is that youâre running the Python 2 version of the code under Python 3.</p></li>
<li><p>If you get the ImportError âNo module named html.parserâ, your problem is that youâre running the Python 3 version of the code under Pytho... | 1 | 2016-07-11T23:43:22Z | [
"python"
] |
Fitting exponential decay | 38,317,828 | <p>I'm trying to solve the following linearized equation:</p>
<p><strong>lnâ¡{1ây/y}=lnâ¡(c)âb(x)</strong></p>
<p>Using python scipy curvefit or another similar method, could your please let me know how to do this?</p>
<p>Sample data:</p>
<pre><code>x = [15, 16, 17, 18, 19, 20]
y = [0.78, 0.67, 0.56, 0.41, 0... | 1 | 2016-07-11T23:37:33Z | 38,319,431 | <p>I will not understand well your problem.</p>
<p>In this moment I will think on many ways. (Certainly I don't know if they are the best)</p>
<p>1.- I will take the function that you have.</p>
<p><strong>lnâ¡{1ây/y}=lnâ¡(c)âb(x)</strong></p>
<p>Anb if this the equation that you want solve (find the intersect... | 0 | 2016-07-12T03:11:45Z | [
"python",
"scipy"
] |
Fitting exponential decay | 38,317,828 | <p>I'm trying to solve the following linearized equation:</p>
<p><strong>lnâ¡{1ây/y}=lnâ¡(c)âb(x)</strong></p>
<p>Using python scipy curvefit or another similar method, could your please let me know how to do this?</p>
<p>Sample data:</p>
<pre><code>x = [15, 16, 17, 18, 19, 20]
y = [0.78, 0.67, 0.56, 0.41, 0... | 1 | 2016-07-11T23:37:33Z | 38,328,475 | <p>I suspect the problem in your code is the c parameter, since curve_fit tries using negatives values resulting in error. Unfortunately, I didn't find any reference in the docs as to how to 'bound' the output parameters (someone can improve this answer by pointing out how to do this). Try replacing c by log_c, which c... | 0 | 2016-07-12T12:07:17Z | [
"python",
"scipy"
] |
Mark date by column contents in pandas (vectorized) | 38,318,001 | <p>I have data of the following form:</p>
<pre><code> JournalInformation Month
Dec. American Journal of Science
Molecular Methods. Aug DOI: 10101
Science Journal Jun.
Dec. Cognitive Science weekly
</code></pre>
<p>Goal:</p>
<pre><code> JournalInformation Month
Dec. A... | 3 | 2016-07-11T23:58:27Z | 38,318,054 | <p>Use <code>str.extract</code> and <code>map</code></p>
<pre><code>regex = r'({})'.format('|'.join(months_of_year.keys()))
df.JournalInformation.str.extract(regex, expand=False).map(months_of_year)
</code></pre>
<h3>Explanation</h3>
<pre><code>print regex
(Feb|Aug|Jan|Dec|Sept|Oct|Mar|May|Jun|Jul|Apr|Nov)
</code><... | 4 | 2016-07-12T00:07:21Z | [
"python",
"pandas",
"dataframe",
"vectorization"
] |
Circular contour detection in an image python opencv | 38,318,011 | <p>I am trying to have the circle detected in the following image.</p>
<p><a href="http://i.stack.imgur.com/3xGG4.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/3xGG4.jpg" alt="enter image description here"></a></p>
<p>So I did color thresholding and finally got this result.</p>
<p><a href="http://i.stack.im... | 0 | 2016-07-11T23:59:58Z | 38,327,369 | <p>I guess there was problem with the thresholds for color segmentation, So the idea here was to generate a binary mask. By inspection your region of interest seems to be brighter than the other regions of input image, so thresholding can simply be done on a grayScale image to simplify the context. <em>Note: You may ch... | 0 | 2016-07-12T11:18:17Z | [
"python",
"opencv",
"matplotlib",
"computer-vision",
"edge-detection"
] |
Circular contour detection in an image python opencv | 38,318,011 | <p>I am trying to have the circle detected in the following image.</p>
<p><a href="http://i.stack.imgur.com/3xGG4.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/3xGG4.jpg" alt="enter image description here"></a></p>
<p>So I did color thresholding and finally got this result.</p>
<p><a href="http://i.stack.im... | 0 | 2016-07-11T23:59:58Z | 38,351,568 | <p>The task is much easier when performed with the red plane only.</p>
<p><a href="http://i.stack.imgur.com/XErQ9.png" rel="nofollow"><img src="http://i.stack.imgur.com/XErQ9.png" alt="enter image description here"></a></p>
| 1 | 2016-07-13T12:19:50Z | [
"python",
"opencv",
"matplotlib",
"computer-vision",
"edge-detection"
] |
Numpy Arrays: Extracting preferentially ordered values from array with Nans without padding? | 38,318,041 | <p>Suppose I have an array (M,N) where the values in each "column", N, represent data recordings of N different machines. Let's also imagine each "row", M, represents a unique "timestamp" where data was recorded for all of the N machines.</p>
<p>The array (M,N) is structured in a way so that at M = 0, this would corre... | 2 | 2016-07-12T00:05:36Z | 38,318,148 | <p>This is the kind of question that can generate many interesting answers. Someone will probably come up with a better way than this, but to get things started, here's one possibility:</p>
<pre><code>In [99]: AX
Out[99]:
array([[ 0.53826804, -0.9450442 , nan, 0.47251871, nan],
[ nan, ... | 3 | 2016-07-12T00:21:24Z | [
"python",
"arrays",
"numpy",
null
] |
How do I iterate through a dict while also removing newline characters? | 38,318,129 | <p>I'm trying to iterate through a dictionary and remove newline characters, and having difficult with parsing the items.</p>
<p>Say we have </p>
<pre><code>line_contents = {"user_id": "6GrH6gp09pqYykGv86D6Dg", "text": "Decent selection of more than just bar food. \n\nJumbo fish sandwich is aptly named. \n\nSeem to b... | 0 | 2016-07-12T00:18:31Z | 38,318,210 | <p>Actually, you aren't using a dictionary comprehension. That is a function call with a single argument: a generator expression. A dictionary comprehension would be more like this:</p>
<pre><code>line_contents = {key: value.replace("\n", "") for key, value in line_contents.items()}
</code></pre>
<p><strong>Edit</s... | 4 | 2016-07-12T00:30:20Z | [
"python",
"dictionary"
] |
How do I iterate through a dict while also removing newline characters? | 38,318,129 | <p>I'm trying to iterate through a dictionary and remove newline characters, and having difficult with parsing the items.</p>
<p>Say we have </p>
<pre><code>line_contents = {"user_id": "6GrH6gp09pqYykGv86D6Dg", "text": "Decent selection of more than just bar food. \n\nJumbo fish sandwich is aptly named. \n\nSeem to b... | 0 | 2016-07-12T00:18:31Z | 38,318,231 | <p>You can use dict comprehension but since some of your values are not strings you have to take that into account:</p>
<pre><code>line_contents = {k: v.replace('\n', '') if isinstance(v, str) else v for k, v in line_contents.items()}
</code></pre>
<p>In case both keys and values contain newline you can use <code>dic... | 3 | 2016-07-12T00:33:26Z | [
"python",
"dictionary"
] |
Convert log data into time series frequency in spark using python | 38,318,146 | <blockquote>
<p>update</p>
<p>Technically, I want to convert log data into time series frequency in spark. I've searched a lot, but didn't find a good way to deal with big data.</p>
<p>I know pd.dataframe can get count for some feature, but my dataset is too big to use a dataframe.</p>
<p>which means I... | 0 | 2016-07-12T00:20:51Z | 38,318,830 | <p>If you can have the output data be a list of <code>((month, day, hour), count)</code> values, the following should work:</p>
<pre><code>from pyspark import SparkConf, SparkContext
import datetime
conf = SparkConf().setMaster("local[*]").setAppName("WriteDates")
sc = SparkContext(conf = conf)
RDD_to_fill = sc.para... | 0 | 2016-07-12T01:55:37Z | [
"python",
"apache-spark",
"mapreduce",
"pyspark"
] |
Jupyter Notebook: Output image in previous line | 38,318,166 | <p>I want to plot some image side by side in my jupyter notebook. So it can save some space for display. For example</p>
<p><a href="http://i.stack.imgur.com/C2QpD.png" rel="nofollow"><img src="http://i.stack.imgur.com/C2QpD.png" alt="enter image description here"></a></p>
<p>This is done through</p>
<pre><code>fig ... | 0 | 2016-07-12T00:24:35Z | 38,319,304 | <p>first let me recommend you use a colormap other than the jet colormap for the reasons detailed in <a href="https://www.youtube.com/watch?v=xAoljeRJ3lU" rel="nofollow">A better colormap for matplotlib</a>. </p>
<p>As to what you want to do you can achieve this with a modified code from: <a href="http://stackoverflow... | 0 | 2016-07-12T02:56:42Z | [
"python",
"matplotlib",
"ipython",
"jupyter-notebook"
] |
Jupyter Notebook: Output image in previous line | 38,318,166 | <p>I want to plot some image side by side in my jupyter notebook. So it can save some space for display. For example</p>
<p><a href="http://i.stack.imgur.com/C2QpD.png" rel="nofollow"><img src="http://i.stack.imgur.com/C2QpD.png" alt="enter image description here"></a></p>
<p>This is done through</p>
<pre><code>fig ... | 0 | 2016-07-12T00:24:35Z | 38,320,547 | <p>use the following <code>align_figures()</code>:</p>
<pre><code>def align_figures():
import matplotlib
from matplotlib._pylab_helpers import Gcf
from IPython.display import display_html
import base64
from ipykernel.pylab.backend_inline import show
images = []
for figure_manager in Gcf.ge... | 1 | 2016-07-12T05:17:54Z | [
"python",
"matplotlib",
"ipython",
"jupyter-notebook"
] |
I have a generator in my Python function; how can I return a modified list? | 38,318,280 | <p>A little background: I've been trying to code a "Sieve of Eratosthenes" algorithm. At the request of some fine (and very patient) programmers on the StackOverflow Python chatroom, I did some reading on the <code>enumerate()</code> function and found a way to incorporate it into my code (yes, I'm very much a novice h... | 0 | 2016-07-12T00:39:47Z | 38,318,437 | <p>This has nothing to do with <code>enumerate</code> you are trying to return something in a generator which before python 3.3 is illegal, and <a href="http://stackoverflow.com/questions/16780002/return-in-generator-together-with-yield-in-python-3-3">from 3.3+ it means something entirely different.</a></p>
<p>I'd rec... | 1 | 2016-07-12T01:00:55Z | [
"python",
"algorithm",
"function",
"generator",
"enumerate"
] |
Anaconda import mpi4py but not mpi | 38,318,303 | <p>I installed anaconda on 32 bit windows system. Then installed the mpi4py package with conda install. </p>
<pre><code>conda search mpi4py
Fetching package metadata .......
mpi4py 2.0.0 py27_0 defaults
* 2.0.0 py27_msmpi_0 mpi4py
... | 0 | 2016-07-12T00:42:22Z | 38,332,136 | <p>It looks like you don't have Microsoft MPI installed on your system. Did you get the following message when you did <code>conda install mpi4py</code>?</p>
<blockquote>
<p>mpi4py requires that Microsoft MPI 6 be installed on the host
system. That is a systemwide installation that is currently
not available thr... | 1 | 2016-07-12T14:45:57Z | [
"python",
"anaconda",
"mpi4py"
] |
Django DB with foreign keys and 3nf | 38,318,319 | <p>I have a simple DB structure:</p>
<pre><code>Category
+ id (pk)
+ name (String)
+ description (String)
Software
+ id (pk)
+ name (String)
+ description (String)
+ (removed for brevity)
SoftwareCategory
+ sid (FK to Software)
+ cid (FK to Category)
</code></pre>
<p>My conundrum... | 0 | 2016-07-12T00:44:32Z | 38,336,631 | <p>I figured it out. The documentation for <a href="https://docs.djangoproject.com/en/1.9/topics/db/models/#intermediary-manytomany" rel="nofollow">manytomanyfields</a> was a bit opaque to me and after working through it and another example I was able to figure out what I needed to do with the <a href="https://docs.dj... | 0 | 2016-07-12T18:43:34Z | [
"python",
"django"
] |
Implementing only part of a Python class in C | 38,318,332 | <p>I have a python class that has a couple performance-sensitive methods that justify being implemented in C. But it also has some methods that don't need to be fast and that would be a giant pain to write in C.</p>
<p>Is there a standard way to have the best of both worlds, where a few core methods are defined in C b... | 1 | 2016-07-12T00:46:13Z | 38,318,406 | <p>If the C code doesn't need to interact with the object itself, possibly you could use the <a href="https://docs.python.org/3/library/ctypes.html#module-ctypes" rel="nofollow"><code>ctypes</code></a> module to call C functions from your python code.</p>
<p>Put your C code in into a shared library or DLL and then cal... | 1 | 2016-07-12T00:57:25Z | [
"python",
"c"
] |
Implementing only part of a Python class in C | 38,318,332 | <p>I have a python class that has a couple performance-sensitive methods that justify being implemented in C. But it also has some methods that don't need to be fast and that would be a giant pain to write in C.</p>
<p>Is there a standard way to have the best of both worlds, where a few core methods are defined in C b... | 1 | 2016-07-12T00:46:13Z | 38,318,506 | <p>Try <a href="http://docs.cython.org/src/tutorial/cython_tutorial.html" rel="nofollow">Cython</a>. It really does a fantastic job blending the best features of both languages. No longer do you have to decide between control and performance, and efficiency and ease of development.</p>
| 1 | 2016-07-12T01:11:14Z | [
"python",
"c"
] |
How can I make a python3 program not crash if it tries to add a string and a number together | 38,318,340 | <p>Source code</p>
<hr>
<pre><code>import sys
hi = input("Input a number ")
yo = input("Input a second number ")
total = int(hi) + int(yo)
def convertStr(s):
try:
ret = int(s)
print(int(total))
except ValueError:
ret = str(total)
print("There was an... | -2 | 2016-07-12T00:47:57Z | 38,318,426 | <p>You can use your function <code>convertStr(s)</code> on input <code>hi</code> and <code>yo</code>. If input is not a number then ask again for input.</p>
| 0 | 2016-07-12T00:59:21Z | [
"python",
"python-3.x"
] |
Is there any way to call a class from inside subparser? | 38,318,351 | <p>Inside of</p>
<pre><code>def parse_args():
</code></pre>
<p>I have a few subparsers, I typically call functions directly </p>
<pre><code>.set_defaults(func=SOMEFUNCTION)
</code></pre>
<p>but I do have a </p>
<pre><code>class Something(object):
</code></pre>
<p>How can I access the class and then call the fun... | 0 | 2016-07-12T00:49:24Z | 38,318,543 | <p>I'm guessing a lot about your needs</p>
<p>But you are doing something like:</p>
<pre><code>subparser.set_defaults(func=SOMEFUNCTION)
</code></pre>
<p>and later</p>
<pre><code>args = parser.parse_args()
args.func(args) # call the function
</code></pre>
<p>to run <code>SOMEFUNCTION</code> on the rest of t... | 0 | 2016-07-12T01:16:37Z | [
"python",
"argparse"
] |
2d convolution in python with missing data | 38,318,362 | <p>I know there is scipy.signal.convolve2d function to handle 2 dimension convolution for 2d numpy array, and there is numpy.ma module to handle missing data, but these two methods don't seem to compatible with each other (which means even if you mask a 2d array in numpy, the process in convolve2d won't be affected). I... | 0 | 2016-07-12T00:51:16Z | 38,333,445 | <p>I found this link "<a href="http://stackoverflow.com/questions/16495298/how-to-apply-a-mask-from-one-array-to-another-array">enter link description here</a>" which is basically the same question. Thanks all.</p>
| 0 | 2016-07-12T15:42:33Z | [
"python",
"numpy",
"scipy",
"convolution"
] |
What are list comprehension scoping rules within a Python class? | 38,318,370 | <p>In the following code, the <code>mc</code> assigment works fine in Python 2 and 3. </p>
<p>The <code>cc</code> assignment, which uses the same list comprehension within a class, works in Python 2 but fails with Python 3.</p>
<p>What explains this behavior?</p>
<pre><code>ml1 = "a b c".split()
ml2 = "1 2 3".split(... | 9 | 2016-07-12T00:52:26Z | 38,318,470 | <p>In Python 3, list comprehensions have their own scope, which follows the same rules as a function scope. You know how the methods of a class don't automatically look inside the class scope for variable lookup?</p>
<pre><code>class Example:
var = 1
def this_fails(self):
print(var)
Example().this_fail... | 2 | 2016-07-12T01:06:27Z | [
"python",
"python-2.7",
"python-3.x",
"python-3.5"
] |
Python script to continuously check the quality of wlan connection and output to GPIO | 38,318,413 | <p>I'm trying to use this iwlist scan parsing script to turn on a GPIO (with attached LED), indicating a wireless connection:</p>
<pre><code>#!/usr/bin/env python
import sys
import subprocess
import RPi.GPIO as GPIO
import time
interface = "wlan0"
ledPin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(ledPin, GPIO.OUT)
def... | 1 | 2016-07-12T00:58:10Z | 38,318,483 | <p>It looks like you are not calling main().</p>
<pre><code>if __name__ == '__main__':
main()
</code></pre>
| 0 | 2016-07-12T01:08:04Z | [
"python",
"wifi",
"gpio"
] |
How can I modify my graph so it displays the proper information for the axes? | 38,318,416 | <p>I have written a program to solve the Heat Equation (<code>u_t = k * u_xx</code>) numerically by method of Finite Differences.</p>
<p>For my problem, <code>u</code> is function of <code>x</code> and <code>t</code>, where <code>0 < x < L</code> and <code>t > 0</code>. I have specified <code>L = 1</code> (t... | 0 | 2016-07-12T00:58:32Z | 38,319,576 | <p>You have some issues with your code as your u turns out to be 40x1601 and not 40x1600. However, I think the plot you may be after (after correcting u) is</p>
<pre><code>corrected_u = u[:,:-1:]
plt.pcolor(t, x, corrected_u)
</code></pre>
<p><a href="http://i.stack.imgur.com/wkx85.png" rel="nofollow"><img src="http:... | 1 | 2016-07-12T03:29:00Z | [
"python",
"matplotlib",
"plot"
] |
How to add elements to a sorted redis set in python | 38,318,573 | <p>I have a Django app where users upload photos for the general public to see and comment on. One requirement is that the uploaded photo must not be something the website has already seen recently. To accomplish this, I calculate the <a href="https://www.safaribooksonline.com/blog/2013/11/26/image-hashing-with-python/... | 2 | 2016-07-12T01:20:09Z | 38,319,260 | <p>Yes, <a href="https://redis-py.readthedocs.io/en/latest/#redis.Redis.zadd" rel="nofollow">zadd</a> is a bit tricky.</p>
<blockquote>
<p>NOTE: The order of arguments differs from that of the official ZADD
command. For backwards compatability, this method accepts arguments in
the form of name1, score1, name2, s... | 1 | 2016-07-12T02:49:33Z | [
"python",
"django",
"redis"
] |
Perfomance improvement - Looping with Get Method | 38,318,574 | <p>I've built a program to fill up a databank and, by the time, it's working. Basically, the program makes a request to the app I'm using (via REST API) returns the data I want and then manipulate to a acceptable form for the databank.</p>
<p>The problem is: the GET method makes the algorithm too slow, because I'm ace... | 2 | 2016-07-12T01:20:11Z | 38,319,318 | <p>if the bottleneck is in your network request, there isn't much you can do except to perhaps use gzip or deflate but with <a href="http://docs.python-requests.org/en/v0.10.7/user/quickstart/" rel="nofollow">requests</a> ..</p>
<blockquote>
<p>The gzip and deflate transfer-encodings are automatically decoded for
... | 1 | 2016-07-12T02:57:54Z | [
"python",
"django",
"performance",
"rest"
] |
Python how to bubble up exception with full stack information | 38,318,576 | <p>See the following code</p>
<pre><code>def ex_string(ex):
return "Error:{} Traceback:{}".format(ex, traceback.format_exc())
def map_values(listing):
...
obj = listing['value']
...
def process_listing(listing):
try:
listing = map_values(listing)
except Exception as ex:
do_som... | 0 | 2016-07-12T01:20:23Z | 38,318,611 | <p>Use <code>raise</code> with no argument inside an <code>except</code> clause to reraise the exception you're handling with its original traceback:</p>
<pre><code>def process_listing(listing):
try:
listing = map_values(listing)
except Exception as ex:
do_some_handling(listing)
print e... | 4 | 2016-07-12T01:23:21Z | [
"python"
] |
404 error in Flask tutorial | 38,318,645 | <p>I just started using the Flask tutorial : </p>
<pre><code>from flask import Flask
app = Flask(__name__)
@app.route('/user/<username>')
def show_user_profile(username):
return 'User %s' % (username)
</code></pre>
<p>and I am getting the following error:</p>
<pre><code>The requested URL was not found on... | -2 | 2016-07-12T01:28:21Z | 38,322,036 | <p>You need to activate your virtual environment.</p>
<pre><code>source venv/bin/activate
</code></pre>
<p><strong>UPDATED</strong><br>
Try this on your python shell:</p>
<pre><code>>>> from flask import Flask, url_for
>>> app = Flask(__name__)
>>> @app.route('/')
... def index(): pass
.... | 0 | 2016-07-12T07:01:02Z | [
"python",
"flask",
"http-status-code-404"
] |
404 error in Flask tutorial | 38,318,645 | <p>I just started using the Flask tutorial : </p>
<pre><code>from flask import Flask
app = Flask(__name__)
@app.route('/user/<username>')
def show_user_profile(username):
return 'User %s' % (username)
</code></pre>
<p>and I am getting the following error:</p>
<pre><code>The requested URL was not found on... | -2 | 2016-07-12T01:28:21Z | 38,337,850 | <p>As @MattHealy pointed out you've only got one route, <code>/user/<username></code>. <code><username></code> is part of a "dynamic url". It's explained right in the tutorial: <a href="http://flask.pocoo.org/docs/0.11/quickstart/#variable-rules" rel="nofollow">http://flask.pocoo.org/docs/0.11/quickstart/#v... | 0 | 2016-07-12T19:58:21Z | [
"python",
"flask",
"http-status-code-404"
] |
How do I call A np.zeros of integers? | 38,318,648 | <pre><code>Musica = np.zeros((row*120,3))
for k in range(21, 90):
for i in range(row):
for j in range(Max[k], Min[k]):
Musica[i*120 + j,:] = 0,i,j
if np.all(data[i*col + j,:]==(255.000,0.000,0.000,i,j)):
Music[i*120 + j,:] = 1,i,j
</code></pre>
<p><code>Max[k]</code... | 0 | 2016-07-12T01:28:47Z | 38,318,808 | <p>You could try <code>np.zeros(shape).astype(int)</code>.</p>
<p>EDIT:
Actually, zeros accepts the dtype argument. So even better is <code>np.zeros(shape, dtype=int)</code></p>
| 1 | 2016-07-12T01:52:35Z | [
"python"
] |
Need explanation some terms in python code | 38,318,705 | <p>this is my code</p>
<pre><code>'''Nimal,30,60
Saman,80,45
Upali,100,80
above text is in input.txt
'''
f1 = open('input.txt','r')
f2 = open('output.txt','w')
line = f1.readline()
while(line):
data = (line.strip()).split(',')
total = float(data[1])+float(data[2])
f2.write('{},{},{},{}\n'.forma... | 0 | 2016-07-12T01:36:35Z | 38,318,779 | <p>In your example, line is a string. In python, a string will be evaluated as False if it's an empty string, say <code>''</code>. Otherwise, it will be evaluated as True.</p>
<p>What <code>f2.write('{},{},{},{}\n'.format(data[0],data[1],data[2],total))</code> does is to fill the four <code>{}</code> with the correspo... | 1 | 2016-07-12T01:48:16Z | [
"python",
"string"
] |
Python best way to assume a value from dictionary? | 38,318,771 | <p>I am reading a dictionary from external source, let's say </p>
<pre><code>data = {'name': 'James', 'gender': 'male'}
</code></pre>
<p>And sometimes</p>
<pre><code>data = {'name': 'James', 'gender': 'male', 'article': {'title':'abc'}}
</code></pre>
<p>And sometimes</p>
<pre><code>data = {'name': 'James', 'gender... | 2 | 2016-07-12T01:47:42Z | 38,318,834 | <p>By default <code>.get()</code> will return <code>None</code> if the key doesn't exist. In your case you are returning an empty dictionary.</p>
<p>Now, I don't know what error is being raised, but I am sure its from <code>get_stuff(article)</code> rather than your list comprehension.</p>
<p>You have a few ways to s... | 2 | 2016-07-12T01:56:22Z | [
"python",
"dictionary"
] |
Python best way to assume a value from dictionary? | 38,318,771 | <p>I am reading a dictionary from external source, let's say </p>
<pre><code>data = {'name': 'James', 'gender': 'male'}
</code></pre>
<p>And sometimes</p>
<pre><code>data = {'name': 'James', 'gender': 'male', 'article': {'title':'abc'}}
</code></pre>
<p>And sometimes</p>
<pre><code>data = {'name': 'James', 'gender... | 2 | 2016-07-12T01:47:42Z | 38,318,898 | <p>how about this</p>
<pre><code>>>> data = {1:(42,23)}
>>> [x for x in data.get(1) or []]
[42, 23]
>>> [x for x in data.get(32) or []]
[]
</code></pre>
<p>use <code>or</code> to change to your default value in case you get <code>None</code> or something that eval to false </p>
<p><strong>... | 0 | 2016-07-12T02:04:41Z | [
"python",
"dictionary"
] |
Python best way to assume a value from dictionary? | 38,318,771 | <p>I am reading a dictionary from external source, let's say </p>
<pre><code>data = {'name': 'James', 'gender': 'male'}
</code></pre>
<p>And sometimes</p>
<pre><code>data = {'name': 'James', 'gender': 'male', 'article': {'title':'abc'}}
</code></pre>
<p>And sometimes</p>
<pre><code>data = {'name': 'James', 'gender... | 2 | 2016-07-12T01:47:42Z | 38,320,268 | <p>First off you seem to think that using an <a href="https://docs.python.org/2/library/stdtypes.html#boolean-operations-and-or-not" rel="nofollow"><code>or</code></a> expression to discard <a href="https://docs.python.org/2/library/stdtypes.html#truth-value-testing" rel="nofollow">false-y results</a> from <code>data.g... | 1 | 2016-07-12T04:52:49Z | [
"python",
"dictionary"
] |
Python best way to assume a value from dictionary? | 38,318,771 | <p>I am reading a dictionary from external source, let's say </p>
<pre><code>data = {'name': 'James', 'gender': 'male'}
</code></pre>
<p>And sometimes</p>
<pre><code>data = {'name': 'James', 'gender': 'male', 'article': {'title':'abc'}}
</code></pre>
<p>And sometimes</p>
<pre><code>data = {'name': 'James', 'gender... | 2 | 2016-07-12T01:47:42Z | 38,320,751 | <p>There's nothing wrong with using exceptions to break out early in this case. I'm assuming you want the title value, or None, no matter what the data is. The following function will work (for Python 3).</p>
<pre><code>def get_title(d):
try:
return data.get("article").get("title")
except AttributeErro... | 2 | 2016-07-12T05:35:48Z | [
"python",
"dictionary"
] |
Python best way to assume a value from dictionary? | 38,318,771 | <p>I am reading a dictionary from external source, let's say </p>
<pre><code>data = {'name': 'James', 'gender': 'male'}
</code></pre>
<p>And sometimes</p>
<pre><code>data = {'name': 'James', 'gender': 'male', 'article': {'title':'abc'}}
</code></pre>
<p>And sometimes</p>
<pre><code>data = {'name': 'James', 'gender... | 2 | 2016-07-12T01:47:42Z | 38,322,419 | <p>Since you're loading this data from an external source, one option is a preprocessing step <em>as soon as</em> you load it:</p>
<pre><code>from collections import Mapping
def remove_none(d):
for k, v in d.items():
if v is None:
del d[k]
if isinstance(v, Mapping):
remove_... | 0 | 2016-07-12T07:22:53Z | [
"python",
"dictionary"
] |
iter over a list nested with dict and list to change value in dict | 38,318,819 | <p>I got a really big data like below, the structure may not be fixed, but I want to find each key name is 'used', multi the value of the 'used' by 10. How can I do it? The difficult part is the list structure for some time for some reason will be changed, and the 'used': inf should be kept unchanged.</p>
<pre><code>[... | 0 | 2016-07-12T01:54:16Z | 38,318,918 | <p>As I see it, the answer is:</p>
<pre><code>for item in list:
for usage in item['block_data']:
for used in usage['usage']:
new_used = used['used'] * 10
</code></pre>
<p>At least, that code worked for me.</p>
| 0 | 2016-07-12T02:07:30Z | [
"python",
"list",
"dictionary",
"data-structures"
] |
iter over a list nested with dict and list to change value in dict | 38,318,819 | <p>I got a really big data like below, the structure may not be fixed, but I want to find each key name is 'used', multi the value of the 'used' by 10. How can I do it? The difficult part is the list structure for some time for some reason will be changed, and the 'used': inf should be kept unchanged.</p>
<pre><code>[... | 0 | 2016-07-12T01:54:16Z | 38,319,034 | <p>Using list comprehension:</p>
<pre><code>[k['used']*10 if isinstance(k['used'], (int, long)) else k['used'] for i in a for j in i['block_data'] for k in j['usage']]
Out[29]:
[500,
500,
131900,
582823000,
2300,
12500,
12400,
24500,
22272200,
1500,
6900,
'inf',
'inf',
2700,
1100,
300,
1300,
3900,
3... | 0 | 2016-07-12T02:21:58Z | [
"python",
"list",
"dictionary",
"data-structures"
] |
Parsing function arguments based on pattern | 38,318,902 | <p>I'm completely stumped as to how to do this. I've been trying for a while, but can't find a suitable way.</p>
<p>So, let's say that I have a pattern representing a function with two arguments: <code>function_name(arg0, arg1)</code>.</p>
<p>How can I get the values of <code>arg0</code> and <code>arg1</code>?</p>
<... | 0 | 2016-07-12T02:04:56Z | 38,319,018 | <p>you can use module <code>re</code> for regex pattern matching:</p>
<pre><code>In [27]: import re
...: s='function_name(10, 20)'
...: m=re.search(r'\((.*),(.*)\)', s)
...: m.groups()
Out[27]: ('10', ' 20')
In [28]: arg1, arg2 = m.groups()
...: print arg1, arg2
...:
10 20
</code></pre>
| 1 | 2016-07-12T02:20:20Z | [
"python"
] |
Given 2 points, return a 3rd point between them that is closer to the first point given | 38,318,913 | <p>Given 2 points <code>A(x1,y1,z1)</code> and <code>B(x2,y2,z2)</code>, return <code>C(x3,y3,z3)</code> that is on the line AB but is closer to A.</p>
<pre><code>A ----C----------------B
</code></pre>
<p>In 3D space.</p>
<p>Using Python.</p>
| 0 | 2016-07-12T02:06:58Z | 38,318,982 | <p>This returns a point that lies one third of the way between A and B.</p>
<pre><code>def thirdPoint(x1,y1,z1,x2,y2,z2):
x3 = (x2-x1)/3.0 + x1
y3 = (y2-y1)/3.0 + y1
z3 = (z2-z1)/3.0 + z1
return x3, y3, z3
</code></pre>
| 1 | 2016-07-12T02:16:12Z | [
"python",
"math",
"geometry"
] |
Finding first tag in HTML file with BeautifulSoup | 38,318,926 | <p>I have a set of HTML files which I want to pull the first tag in each file. As the files donât have a specific tag which will always be the first in the file, Iâm not sure how to do this.</p>
<p>As an example, for the following snippet, the first tag would be <code><html></code>.</p>
<pre><code><html&... | 1 | 2016-07-12T02:08:18Z | 38,319,199 | <p>You can use <code>BeautifulSoup</code> in this case, just issue <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find" rel="nofollow"><code>find()</code></a> on a <code>BeautifulSoup</code> object - it would find the first element in the tree. <a href="https://www.crummy.com/software/BeautifulSoup/bs4... | 1 | 2016-07-12T02:42:17Z | [
"python",
"beautifulsoup",
"bs4"
] |
Python - Blackjack game not getting anymore than 1 player | 38,318,958 | <p>I am working through a python programming book and one of the chapters has a blackjack game. I am running through this exercise to find errors in the program and handle it. One of the errors is that I am asking for a number of players in a range between 1 and 7. So in theory, I should be able to have up to 7 players... | 0 | 2016-07-12T02:12:50Z | 38,318,997 | <p>As I see it, there's a problem in this line of code:</p>
<pre><code>while response not in (low, high) #It checks if variable response equals only 1 or 8.
</code></pre>
<p>Try changing it to:</p>
<pre><code>while response not in range(low, high) #This checks if variable response equals any number between 1 and 8
<... | 1 | 2016-07-12T02:18:16Z | [
"python",
"python-3.5"
] |
Python - Blackjack game not getting anymore than 1 player | 38,318,958 | <p>I am working through a python programming book and one of the chapters has a blackjack game. I am running through this exercise to find errors in the program and handle it. One of the errors is that I am asking for a number of players in a range between 1 and 7. So in theory, I should be able to have up to 7 players... | 0 | 2016-07-12T02:12:50Z | 38,319,143 | <p>There is a logical error in the loop in your main due to improper indentation.</p>
<p>You have</p>
<pre><code>def main():
print("\t\tWelcome to Blackjack!")
names = []
number = games.ask_number("How many players? (1 - 7): ", low=1, high=8)
for i in range(number):
name = input("Enter player ... | 3 | 2016-07-12T02:36:04Z | [
"python",
"python-3.5"
] |
Accessing python dictionary whose keys are tuples with a wildcard | 38,319,000 | <p>I have a dictionary with tuples as keys:</p>
<pre><code>d = {
('John', 'Blue', 1): 100,
('Bill', 'Green', 5): 200,
('Paul', 'Blue', 4): 300,
('Bill', 'Green', 7): 400
}
</code></pre>
<p>Is it possible to pull out the values of those keys which match, say <code>('Bill', 'Green', _)</code>, such that... | 1 | 2016-07-12T02:18:37Z | 38,319,074 | <p>Don't expect it to be very fast, but:</p>
<pre><code>search_key = ("Paul", "Blue")
values = [value for key, value in d.items() if search_key == key[:len(search_key)]]
</code></pre>
<p>Will return all matching values.</p>
<p>EDIT: by replacing <code>key[:2]</code> with <code>key[:len(search_key)]</code> this solut... | 3 | 2016-07-12T02:27:14Z | [
"python",
"dictionary"
] |
Accessing python dictionary whose keys are tuples with a wildcard | 38,319,000 | <p>I have a dictionary with tuples as keys:</p>
<pre><code>d = {
('John', 'Blue', 1): 100,
('Bill', 'Green', 5): 200,
('Paul', 'Blue', 4): 300,
('Bill', 'Green', 7): 400
}
</code></pre>
<p>Is it possible to pull out the values of those keys which match, say <code>('Bill', 'Green', _)</code>, such that... | 1 | 2016-07-12T02:18:37Z | 38,319,076 | <p>Using list comprehension:</p>
<pre><code>[d[k] for k in d.keys() if k[0]=='Bill' and k[1]=='Green']
Out[37]: [400, 200]
</code></pre>
| 1 | 2016-07-12T02:27:16Z | [
"python",
"dictionary"
] |
Accessing python dictionary whose keys are tuples with a wildcard | 38,319,000 | <p>I have a dictionary with tuples as keys:</p>
<pre><code>d = {
('John', 'Blue', 1): 100,
('Bill', 'Green', 5): 200,
('Paul', 'Blue', 4): 300,
('Bill', 'Green', 7): 400
}
</code></pre>
<p>Is it possible to pull out the values of those keys which match, say <code>('Bill', 'Green', _)</code>, such that... | 1 | 2016-07-12T02:18:37Z | 38,319,218 | <p>A python dictionary is implemented as a <a href="https://en.wikipedia.org/wiki/Hash_table" rel="nofollow">hash table</a> so there is no efficient way to find similar keys, only exact matches. You can of course loop over the items and check each key to see if it matches your pattern.</p>
<p>Python does have a <code>... | 0 | 2016-07-12T02:43:50Z | [
"python",
"dictionary"
] |
Accessing python dictionary whose keys are tuples with a wildcard | 38,319,000 | <p>I have a dictionary with tuples as keys:</p>
<pre><code>d = {
('John', 'Blue', 1): 100,
('Bill', 'Green', 5): 200,
('Paul', 'Blue', 4): 300,
('Bill', 'Green', 7): 400
}
</code></pre>
<p>Is it possible to pull out the values of those keys which match, say <code>('Bill', 'Green', _)</code>, such that... | 1 | 2016-07-12T02:18:37Z | 38,319,398 | <p>a variant of the path followed by MaThMaX</p>
<pre><code>[d[(a,b,c)] for a, b, c in d.keys() if a == 'Bill' and b == 'Green']
</code></pre>
| 0 | 2016-07-12T03:08:17Z | [
"python",
"dictionary"
] |
Python while loop not updating | 38,319,033 | <p>I'm very new to Python.</p>
<p>I'm trying to display the current temperature from a sensor, which I get from a bash script. I use <code>sed</code> to replace the string in the python script (<code>temp.py</code>), which prints that string to an LCD Display. </p>
<p>Unfortunately, when I run <code>temp.py</code>, i... | 0 | 2016-07-12T02:21:55Z | 38,319,085 | <p>Changing the .py file on disk won't change the running program. The .py file is only read once, when the program starts. After that, the .py file isn't used again until the program is run again.</p>
| 5 | 2016-07-12T02:28:56Z | [
"python",
"bash"
] |
Python while loop not updating | 38,319,033 | <p>I'm very new to Python.</p>
<p>I'm trying to display the current temperature from a sensor, which I get from a bash script. I use <code>sed</code> to replace the string in the python script (<code>temp.py</code>), which prints that string to an LCD Display. </p>
<p>Unfortunately, when I run <code>temp.py</code>, i... | 0 | 2016-07-12T02:21:55Z | 38,319,090 | <p>have your sed script constantly update a file called <code>"label.txt"</code> (you probably dont even need <code>sed</code> ... as an aside, why arent you just interfacing the sensor from python?)</p>
<p>then in your temp.py script</p>
<pre><code>while True:
lcd_string(open("label.txt").read(),LCD_LINE_1,1)
... | 2 | 2016-07-12T02:29:15Z | [
"python",
"bash"
] |
Python while loop not updating | 38,319,033 | <p>I'm very new to Python.</p>
<p>I'm trying to display the current temperature from a sensor, which I get from a bash script. I use <code>sed</code> to replace the string in the python script (<code>temp.py</code>), which prints that string to an LCD Display. </p>
<p>Unfortunately, when I run <code>temp.py</code>, i... | 0 | 2016-07-12T02:21:55Z | 38,319,121 | <p>The <em>.py</em> file generates a bytecode to run. See the <em>.pyc</em> file beside your <em>temp.py</em>. So, once the script is running it won't load your change (the one made with <em>sed</em> command) in <em>temp.py</em> until you run it again.</p>
<p>I really suggest you another approach where you don't use a... | 1 | 2016-07-12T02:33:46Z | [
"python",
"bash"
] |
Python while loop not updating | 38,319,033 | <p>I'm very new to Python.</p>
<p>I'm trying to display the current temperature from a sensor, which I get from a bash script. I use <code>sed</code> to replace the string in the python script (<code>temp.py</code>), which prints that string to an LCD Display. </p>
<p>Unfortunately, when I run <code>temp.py</code>, i... | 0 | 2016-07-12T02:21:55Z | 38,319,156 | <p>A bad idea is to reload lcd.py every iteration, the newly value updated by sed will works after saving(the lcd.py file). The code as follows,</p>
<pre><code>while True:
reload(lcd) # <--------
lcd_string("Temp: 25.123 *C",LCD_LINE_1,1)
time.sleep(1)
</code></pre>
<p>Note it is not recommended in p... | 0 | 2016-07-12T02:36:58Z | [
"python",
"bash"
] |
How to write real value of -2.12683575e-04 in a file (Python) | 38,319,104 | <p>I am currently working with really tiny values and when I try to write a value like <strong>-0.000212683575</strong> in a file, it write me <strong>-2.12683575e-04</strong>.
The problem is that I would like to have this value <strong>-0.000212683575</strong> written in the file or a least this one <strong>-0.0002126... | 1 | 2016-07-12T02:31:39Z | 38,319,232 | <p>While writing a number in a file, you can write it as a string and it'll be all you need. ex:</p>
<pre><code>>>> num = -0.000212683575
>>> f = open("a.txt","w")
>>> f.write(str(num))
>>> f.close()
>>> open("a.txt","r").read()
'-0.000212683575'
>>>
</code></pre>... | 0 | 2016-07-12T02:45:12Z | [
"python"
] |
How to write real value of -2.12683575e-04 in a file (Python) | 38,319,104 | <p>I am currently working with really tiny values and when I try to write a value like <strong>-0.000212683575</strong> in a file, it write me <strong>-2.12683575e-04</strong>.
The problem is that I would like to have this value <strong>-0.000212683575</strong> written in the file or a least this one <strong>-0.0002126... | 1 | 2016-07-12T02:31:39Z | 38,319,343 | <p>Python allows you to choose formats. For example, this gives the scientific notation that you don't want:</p>
<pre><code>>>> x = -0.00021268357
>>> '{:.2e}'.format(x)
'-2.13e-04'
</code></pre>
<p>But, this format gives the decimal notation that you prefer:</p>
<pre><code>>>> '{:.9f}'.... | 2 | 2016-07-12T03:01:21Z | [
"python"
] |
Change python object functions | 38,319,137 | <p>I've seen somewhere that there was a way to change some object functions in python</p>
<pre><code>def decorable(cls):
cls.__lshift__ = lambda objet, fonction: fonction(objet)
return cls
</code></pre>
<p>I wondered if you could do things like in ruby, with the :</p>
<pre><code>number.times
</code></pre>
<... | -2 | 2016-07-12T02:35:18Z | 38,335,133 | <p>Ordinarily not -
as a rule, Python types defined in native code -in CPython can't be monkey patched to have new methods. Although there are means to do that with direct memory access and changing the C object structures, using CPython - that is not considered "clever", "beautiful", much less usable. (check <a href=... | 0 | 2016-07-12T17:09:23Z | [
"python",
"function",
"class",
"object"
] |
Using Nested Keys as Values in Python Dictionary | 38,319,182 | <p>I am trying to map English descriptions to the nested elements that I will need to access from a dictionary so I can present the data in an English readable format. For example I will print something like:</p>
<pre><code>for k,v in A_FIELDS.iteritems()
print k + "= " resultsDict[v]
</code></pre>
<p>For every ... | -4 | 2016-07-12T02:40:33Z | 38,319,401 | <p>Store each key in a <code>list</code>.</p>
<pre><code>resultsDict = {'requests':{'all':0, 'cached':1, 'uncached':2},
'bandwidth':{'all':0, 'cached':1, 'uncached':2},
'pageviews':{'all':0, 'cached':1, 'uncached':2},
'uniques':{'all':0, 'cached':1, 'uncached':2}}
A_FIELDS = {
'Total Requests' : ['reques... | 1 | 2016-07-12T03:08:33Z | [
"python",
"dictionary",
"nested"
] |
Issue with identifying and cropping text from image with OpenCV and Python | 38,319,205 | <p>I am working with code that was taken from this answer: <a href="http://stackoverflow.com/questions/24385714/detect-text-region-in-image-using-opencv/35078614">Detect text region in image using Opencv</a></p>
<p>The code I am working with is:</p>
<pre><code>import cv2
def captch_ex(file_name ):
img = cv2.imre... | 0 | 2016-07-12T02:42:38Z | 38,320,634 | <p>The issue is with the <code>cv2.findContours()</code> method, actually it has different return arguments for Opencv 2 and Opencv 3, You must check for the documentation of the Opencv version you are using, In general terms:</p>
<p>For <a href="http://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_s... | 1 | 2016-07-12T05:25:22Z | [
"python",
"opencv"
] |
Splitting duplicates into separate table - Pandas | 38,319,249 | <p>In Pandas, I can drop duplicate rows inside a database based on a single column using the</p>
<pre><code>data.drop_duplicates('foo')
</code></pre>
<p>command. I'm wondering if there is a way to catch this data in another table for independent review.</p>
| 2 | 2016-07-12T02:47:49Z | 38,319,278 | <p>You can call the <code>duplicated</code> method on the <code>foo</code> column and then subset your original data frame based on it, something like this:</p>
<pre><code>data.loc[data['foo'].duplicated(), :]
</code></pre>
<p>As an example:</p>
<pre><code>data = pd.DataFrame({'foo': [1,1,1,2,2,2], 'bar': [1,1,2,2,3... | 3 | 2016-07-12T02:52:28Z | [
"python",
"pandas",
"duplicates"
] |
Splitting duplicates into separate table - Pandas | 38,319,249 | <p>In Pandas, I can drop duplicate rows inside a database based on a single column using the</p>
<pre><code>data.drop_duplicates('foo')
</code></pre>
<p>command. I'm wondering if there is a way to catch this data in another table for independent review.</p>
| 2 | 2016-07-12T02:47:49Z | 38,319,819 | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow"><code>drop_duplicates</code></a> has a companion method <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html" rel="nofollow"><code>duplicated</code></a>. Th... | 3 | 2016-07-12T04:00:29Z | [
"python",
"pandas",
"duplicates"
] |
find best approach to recognize list of sequence word in sentence | 38,319,344 | <p>I have two list of words that I would like to find in a sentence based on a sequence. I would like to check is it possible to use "regular expression" or I should use check the sentence by if condition?</p>
<pre><code>n_ali = set(['ali','aliasghar'])
n_leyla = set(['leyla','lili',leila])
positive_adj = set(['good',... | -1 | 2016-07-12T03:01:25Z | 38,319,693 | <p>You should consider removing stopwords.</p>
<pre><code>import nltk
from nltk.corpus import stopwords
>>> words = [word for word in nltk.word_tokenize(sentence) if word not in stopwords.words('english')]
>>> words
['aliasghar', 'nice', 'man', '.', 'ali', 'handsome', 'man', 'life', '.', 'lili', 'man... | 1 | 2016-07-12T03:44:23Z | [
"python",
"python-3.x",
"nltk"
] |
Python Inheritance from immutable class int, why arguments' order matters when copying? | 38,319,351 | <p>I am trying to implement a class inherited from int, and adding some members to it, but I find the instance from the derived class cannot be copied correctly(even deep copy) if the order of arguments change, see the example below, trying create a positive int class:</p>
<pre><code># Example 1
import copy as cp
clas... | 0 | 2016-07-12T03:02:18Z | 38,319,403 | <p><code>m = cp.copy(n)</code> ends up calling <code>m = PositiveInt(n)</code> which in turn is calling <code>m=PositiveInt(3)</code></p>
<p>you could subclass <code>__copy__</code></p>
<pre><code>def __copy__(self):
return PositiveInt(self.arg0,self,self.arg1)
</code></pre>
<p>or you could check the first argu... | 0 | 2016-07-12T03:08:47Z | [
"python",
"inheritance",
"int",
"copy",
"immutability"
] |
Passing Data from post() to get_context_data() | 38,319,384 | <p>I am generating an object from a submitted form. I want to pass along the generated <code>AutoField</code> to the next form as a hidden form element. However, I cannot figure out how to pass a variable from <code>post()</code> to <code>get_context_data()</code>. I know that <code>post()</code> is called first, follo... | 0 | 2016-07-12T03:06:12Z | 38,321,700 | <p>By defining <code>post</code> yourself, you've overridden the default behaviour of the view. You can see that there is no call to get_context_data, or any of the other class methods, so naturally they won't be called.</p>
<p>Generally you should not be overriding the specific get or post methods. You haven't shown ... | 2 | 2016-07-12T06:42:02Z | [
"python",
"django"
] |
Passing Data from post() to get_context_data() | 38,319,384 | <p>I am generating an object from a submitted form. I want to pass along the generated <code>AutoField</code> to the next form as a hidden form element. However, I cannot figure out how to pass a variable from <code>post()</code> to <code>get_context_data()</code>. I know that <code>post()</code> is called first, follo... | 0 | 2016-07-12T03:06:12Z | 38,323,049 | <p>You have to find a way to pass the object ID to the next page. The options that come to mind are to put it into the URL or as solarissmoke has suggested save it in the session. If you are doing it in the url you can also put the page sequence there (meaning 1 for the forst form, 2 for the second...). </p>
<p>The ni... | 1 | 2016-07-12T07:56:38Z | [
"python",
"django"
] |
ValueError: invalid literal for int() with base 10: 'Height (mm)' | 38,319,409 | <pre><code>import csv
from decimal import *
def mean(data_set):
return Decimal(sum(data_set)) / len(data_set)
def variance(data_set):
mean_res = mean(data_set)
differences = []
squared_res = []
for elem in data_set:
differences.append(elem - mean_res)
for elem in differences:
s... | 0 | 2016-07-12T03:09:19Z | 38,319,446 | <p>use <code>height_data[:-11]</code> or <code>height_data[:-12]</code> (if you have a <code>space</code> between you number and <code>Height (mm)</code></p>
<pre><code>if __name__ == "__main__":
with open("dog_data.csv", "r") as csv_file:
csv_reader = csv.reader(csv_file)
height_data = []
... | 0 | 2016-07-12T03:12:55Z | [
"python"
] |
ValueError: invalid literal for int() with base 10: 'Height (mm)' | 38,319,409 | <pre><code>import csv
from decimal import *
def mean(data_set):
return Decimal(sum(data_set)) / len(data_set)
def variance(data_set):
mean_res = mean(data_set)
differences = []
squared_res = []
for elem in data_set:
differences.append(elem - mean_res)
for elem in differences:
s... | 0 | 2016-07-12T03:09:19Z | 38,319,498 | <p>I think your problem is that you read the header (first line) which contain words, and you try to parse it as int. </p>
<p>Try to add </p>
<pre><code>next(csv_reader, None)
</code></pre>
<p>Before your loop to skip first row. </p>
<p>As to "How do I tackle that error", for next time simply use print:</p>
<pre><... | 1 | 2016-07-12T03:19:08Z | [
"python"
] |
Check mock called with runtime object create | 38,319,505 | <p>I have code for cassandra cluster like</p>
<pre><code>cluster = Cluster(
config.CASS_CLUSTER,
load_balancing_policy=policies.DCAwareRoundRobinPolicy(
config.CASS_D_CENTER))
</code></pre>
<p>When I write UT for this and try to check <code>Cluster</code> call with my parameter.</p>
<pre>... | 2 | 2016-07-12T03:20:08Z | 38,319,588 | <pre><code>mock_cluster.assert_called_with(
config.CASS_CLUSTER,
load_balancing_policy=mock.ANY)
</code></pre>
| 1 | 2016-07-12T03:30:52Z | [
"python",
"mocking",
"pymock"
] |
Could not convert string to float error. ideas/suggestions? | 38,319,531 | <pre><code>def displaymsg(avg):
DL=str("deans list")
AP=str("academic probation")
message=("no message")
if (avg>3.5):#if input for avg is > 3.5 message will is = DL
message=DL
else:
if (avg<2.0):#if avg is < 2.0 message is =AP
message=AP
return str(messag... | 0 | 2016-07-12T03:23:46Z | 38,319,731 | <p>I see two issues with your code:</p>
<ol>
<li><p>You initialize firstData to a tuple. So the line</p>
<p>if firstData==0:</p></li>
</ol>
<p>will never be true.</p>
<ol start="2">
<li><p>You should surround this statement within a try/except clause:</p>
<p>gpa.append (float(data))</p></li>
</ol>
<p>The reason w... | 1 | 2016-07-12T03:49:01Z | [
"python"
] |
passing a function for decorator | 38,319,598 | <p>Need a help on this.</p>
<p>Have a file with_class.py that holds implementation of decorator on classes. The function is being called from another file use_class.py.</p>
<p>with_class.py</p>
<pre><code>def __init__(self,f):
self.f = f
def __call__(self,x):
self.f(x)
@decorate
def foo(x):
print ... | 0 | 2016-07-12T03:32:22Z | 38,320,445 | <p>The argument to foo must be a function. This code</p>
<pre><code>with_class.foo(with_class.decorate.disp())
</code></pre>
<p>is the exact equivalent of</p>
<pre><code>x = with_class.decorate.disp()
with_class.foo(x)
</code></pre>
<p>The error occurs in the first line when you call <code>with_class.decorate.disp... | 1 | 2016-07-12T05:09:16Z | [
"python"
] |
How to get millisecond and microsecond-resolution timestamps in Python | 38,319,606 | <p>I finally figured this out and would like to share the knowledge and save someone a bunch of time, so see my answer below. <s>However, I still need answers for Linux, so please answer if you know, as my code in my answer is for Windows only.</s></p>
<p>UPDATE: I've figured it out for Linux too, including for pre-Py... | 2 | 2016-07-12T03:34:24Z | 38,319,607 | <p><s>For Windows:</s> Here's a fully-functional module for both Linux (works with pre-Python 3.3 too) and Windows:</p>
<p>Functions and code samples.<br>
Functions include: </p>
<ul>
<li>micros() </li>
<li>millis() </li>
<li>delay() </li>
<li>delayMicroseconds()</li>
</ul>
<p>Python code module:</p>
<pre><code>""... | 1 | 2016-07-12T03:34:24Z | [
"python",
"timestamp",
"delay",
"timing",
"milliseconds"
] |
How to get millisecond and microsecond-resolution timestamps in Python | 38,319,606 | <p>I finally figured this out and would like to share the knowledge and save someone a bunch of time, so see my answer below. <s>However, I still need answers for Linux, so please answer if you know, as my code in my answer is for Windows only.</s></p>
<p>UPDATE: I've figured it out for Linux too, including for pre-Py... | 2 | 2016-07-12T03:34:24Z | 38,936,014 | <pre><code>import time
def delayMicroseconds(n):
time.sleep(n / 1000000.)
def delayMillisecond(n):
time.sleep(n / 1000.)
</code></pre>
<p>See also: <a href="https://stackoverflow.com/questions/510348/how-can-i-make-a-time-delay-in-python">How can I make a time delay in Python?</a></p>
| 0 | 2016-08-13T19:00:49Z | [
"python",
"timestamp",
"delay",
"timing",
"milliseconds"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.