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 |
|---|---|---|---|---|---|---|---|---|---|
infinite while loop in python when integer compared with range | 39,315,460 | <p>my while code:</p>
<pre><code>i=0
a = range(100)
while i < range(100):
print i
i += 9
</code></pre>
<p>this goes into an infinite loop...may i know why?</p>
<p>is it because an integer is compared to the list?
but what happens when i becomes greater than 99?</p>
<p>shouldnt it come out... | 0 | 2016-09-04T09:26:44Z | 39,315,493 | <p><code>range(100)</code> is a list of integers from 1 to 100 over which you are supposed to iterate. So, <code>len(range(100)</code> = 100. In python 2.x, a list is always greater than an integer. A very simple way to fix this problem is:</p>
<pre><code>i=0
while i < 100: # instead of range(100)
print i
i... | 0 | 2016-09-04T09:29:53Z | [
"python",
"python-2.7",
"while-loop"
] |
Issue when trying to install ipython through terminal | 39,315,558 | <p>I want to install <code>ipython</code> through the macOS terminal (I have tried both <code>easy_install</code> and <code>pip</code>), but a specific problem always occurs, which is described in the last line:</p>
<pre><code>Searching for ipython
Reading https://pypi.python.org/simple/ipython/
Best match: ipython 5.... | 1 | 2016-09-04T09:40:33Z | 39,317,018 | <p>Well, assuming that <code>sudo easy_install ipython</code> is used to install <code>ipython</code>, this is what worked for me, in order to get the latest version of <code>six</code>.</p>
<p><code>sudo pip install --ignore-installed six</code>, which is described more analytically <a href="http://stackoverflow.com/... | 1 | 2016-09-04T12:40:59Z | [
"python",
"osx",
"terminal",
"ipython"
] |
Can't get lFilter to work (rpi2b) | 39,315,576 | <p>Some information: I am using a rpi2b with a cirrus logic audio card and have worked out the kernel changes to get the sound card going, I can output without problems, I can record from line in without problems (I am using pyAudio). </p>
<p>Now I only want to filter the signal and have found a lot of functions in th... | 1 | 2016-09-04T09:43:34Z | 39,320,138 | <p>For one thing, you need to keep the final conditions from one chunk and feed it as initial conditions to the next chunk. Otherwise the filter assumes rest at the start of each chunk, which will result in glitches at each chunk.</p>
<pre><code>global zi
audio_data, zi = signal.lfilter(b, a, full_data, zi=zi)`
</cod... | 0 | 2016-09-04T18:23:11Z | [
"python",
"numpy",
"scipy",
"raspberry-pi2"
] |
Tkinter ListBox and dictionaries | 39,315,584 | <p>Displaying list items in a tkinter listbox looks like this:</p>
<pre><code>from tkinter import *
root = Tk()
lst = ["one", "two", "three"]
lstbox = Listbox(root)
lstbox.pack()
for item in lst:
lstbox.insert(END, item)
root.mainloop()
</code></pre>
<p>How can I display a dictionary with both its keys and va... | 0 | 2016-09-04T09:44:28Z | 39,315,685 | <p>Iterate over the keys of the dictionary and insert a string comprising the key and its value. You can use <code>str.format()</code> to create the string. Here's an example:</p>
<pre><code>d = {"one": 1, "two": 2, "three": 3}
for key in d:
lstbox.insert(END, '{}: {}'.format(key, d[key]))
</code></pre>
<hr>
<p... | 1 | 2016-09-04T09:55:33Z | [
"python",
"dictionary",
"tkinter",
"listbox"
] |
Invalid literal for int() with base 10: ' ', reading off text file | 39,315,773 | <p>Im trying to make a text game/rpg in python. Im getting an</p>
<blockquote>
<p>line 89, in
surv = int(statload.readline(3))</p>
<p>ValueError: invalid literal for int() with base 10: ''</p>
</blockquote>
<p>error code, when trying to read off a file. the other ones around it read fine.</p>
<p>Readin... | -3 | 2016-09-04T10:05:54Z | 39,315,840 | <p>You are using raedline incorrectly. The argument in readline() should be number of bytes to read from the file, not the line number to read.</p>
<p>What you want to be doing is something like this:</p>
<pre><code>with open("Statsheet.txt", "r") as file:
stats = file.readlines()
luck = int(stats[0])
surv = int... | -1 | 2016-09-04T10:14:17Z | [
"python",
"sys"
] |
Invalid literal for int() with base 10: ' ', reading off text file | 39,315,773 | <p>Im trying to make a text game/rpg in python. Im getting an</p>
<blockquote>
<p>line 89, in
surv = int(statload.readline(3))</p>
<p>ValueError: invalid literal for int() with base 10: ''</p>
</blockquote>
<p>error code, when trying to read off a file. the other ones around it read fine.</p>
<p>Readin... | -3 | 2016-09-04T10:05:54Z | 39,315,855 | <p>The argument to <code>readline()</code> is unnecessary in your case. Just drop it and the code will work:</p>
<pre><code>luck = int(statload.readline())
surv = int(statload.readline())
</code></pre>
<p>If you're curious, <code>statload.readline(2)</code> reads the first two characters (<code>45</code>) and leaves ... | 1 | 2016-09-04T10:15:51Z | [
"python",
"sys"
] |
Invalid literal for int() with base 10: ' ', reading off text file | 39,315,773 | <p>Im trying to make a text game/rpg in python. Im getting an</p>
<blockquote>
<p>line 89, in
surv = int(statload.readline(3))</p>
<p>ValueError: invalid literal for int() with base 10: ''</p>
</blockquote>
<p>error code, when trying to read off a file. the other ones around it read fine.</p>
<p>Readin... | -3 | 2016-09-04T10:05:54Z | 39,315,856 | <p>It looks like once you execute luck = int(statload.readline(2)), the file pointer moves to the end of the file, and there's nothing more to read. Try this:</p>
<pre><code>statload = open("Statsheet.txt","r").read().split('\n')
luck = int(statload[0])
surv = int(statload[1])
</code></pre>
| 0 | 2016-09-04T10:16:06Z | [
"python",
"sys"
] |
Match number between '<<' (regex) | 39,315,811 | <p>I have the following string</p>
<blockquote>
<p>All files | 100 <<222>></p>
</blockquote>
<p>And would like to match the number between <code><< >></code></p>
<p>How can I do that? </p>
<p>So far I tried this expression <code>(?<<)(.*?)(?>>)</code></p>
| 0 | 2016-09-04T10:11:21Z | 39,315,846 | <p>The problem is, that <code><</code> is a special character, which needs to be escaped. Also, the <code>?</code> in the first and third group are invalid:</p>
<pre><code>(\<\<)(?P<number>\d*?)(\>\>)
</code></pre>
<p>Additionally, I named the group with the number and used <code>\d</code> to mat... | 2 | 2016-09-04T10:15:00Z | [
"python",
"regex"
] |
Match number between '<<' (regex) | 39,315,811 | <p>I have the following string</p>
<blockquote>
<p>All files | 100 <<222>></p>
</blockquote>
<p>And would like to match the number between <code><< >></code></p>
<p>How can I do that? </p>
<p>So far I tried this expression <code>(?<<)(.*?)(?>>)</code></p>
| 0 | 2016-09-04T10:11:21Z | 39,315,864 | <p>Try this,</p>
<pre><code>In [1]: match = re.compile(r'<<(\d+)>>')
In [2]: match.findall('100 <<222>>')
Out[2]: ['222']
</code></pre>
<p>Regex model</p>
<pre><code><<(\d+)>>
</code></pre>
<p><img src="https://www.debuggex.com/i/igWnc7UKlm_2GgcB.png" alt="Regular expression visu... | 1 | 2016-09-04T10:17:18Z | [
"python",
"regex"
] |
Use .ckpt and .meta -files to make predictions with Inception in TensorFlow | 39,315,920 | <p>I used the Inception-library <em>(Tensorflow/models/Inception-tutorial on github)</em>,
feeding selfmade TFRecord-files to imagenet_train.py, and ended up with a 7Gb directory containing .ckpt and .meta files.</p>
<p>How do i use them to make actual predictions?(also evaluating, testing, <strong>testing with actua... | 1 | 2016-09-04T10:24:28Z | 39,333,832 | <p><a href="https://www.tensorflow.org/versions/r0.10/how_tos/variables/index.html#restoring-variables" rel="nofollow">https://www.tensorflow.org/versions/r0.10/how_tos/variables/index.html#restoring-variables</a> provides pretty much everything you should need.</p>
<p>The code there is:</p>
<pre><code># Add ops to s... | 0 | 2016-09-05T15:34:54Z | [
"python",
"machine-learning",
"tensorflow"
] |
Pandas merge 5 csv files with only 1 different column name | 39,315,923 | <p>I have 5 csv files which I'm trying to merge using Python Pandas, also I'm running 64-bit Python cause of Memory issue.</p>
<p>All 5 csv files have identical column names:
<code>['A', 'B', 'C', ... 'Start_time', 'end_time', 'Unique_column']</code></p>
<p>Here <strong>Unique_column</strong> is the different column ... | 1 | 2016-09-04T10:24:33Z | 39,316,011 | <p>IIUC, use <code>pd.concat</code> after having set the index on each to be all common columns.</p>
<p>Imagine you have all files imported into the list <code>dfs</code></p>
<pre><code>dfs = [df1, df2, df3, df4, df5]
</code></pre>
<p>Then concat like</p>
<pre><code>common_cols = ['A', 'B', 'C', 'Start_time', 'end_... | 1 | 2016-09-04T10:35:20Z | [
"python",
"csv",
"pandas",
"merge"
] |
Pandas merge 5 csv files with only 1 different column name | 39,315,923 | <p>I have 5 csv files which I'm trying to merge using Python Pandas, also I'm running 64-bit Python cause of Memory issue.</p>
<p>All 5 csv files have identical column names:
<code>['A', 'B', 'C', ... 'Start_time', 'end_time', 'Unique_column']</code></p>
<p>Here <strong>Unique_column</strong> is the different column ... | 1 | 2016-09-04T10:24:33Z | 39,316,040 | <p>you can do</p>
<pre><code>df_master['unique1'] = df_reference1['unique1']
</code></pre>
<p>this will create the new row 'unique1'. Watch your indexing!</p>
| 0 | 2016-09-04T10:38:48Z | [
"python",
"csv",
"pandas",
"merge"
] |
When I try to do errbot after errbot --init, I get the following error? | 39,316,009 | <p>I can get errbot terminal as >>>. I am using python 3.5 and virtual enviroment is activated. </p>
<p>I am building a chatops bot for telegram. I was working on other device where errbot was fine but I can't even install it here. Can any one help me here ?</p>
<pre><code>16:05:42 ERROR errbot.cli ... | 0 | 2016-09-04T10:35:07Z | 39,316,545 | <p>This is caused by <a href="https://github.com/errbotio/errbot/issues/841" rel="nofollow">a bug in errbot</a> itself which affects the <code>Text</code> backend. What you can do to work around this until this is fixed upstream is to simply install <a href="https://pypi.python.org/pypi/pytest/" rel="nofollow">pytest</... | 0 | 2016-09-04T11:43:02Z | [
"python",
"python-3.x",
"errbot"
] |
email with optional headers error | 39,316,013 | <p>I'm attempting to send a sample email, but get the following error:</p>
<pre><code>>>> import smtplib
>>> from email.mime.text import MIMEText
>>> def send_email(subj, msg, from_addr, *to, host="localhost", port=1025, **headers):
... email = MIMEText(msg)
... email['Subject'] = subj
.... | 0 | 2016-09-04T10:35:34Z | 39,316,056 | <p>You are misunderstanding how <code>*args</code> and <code>**kwargs</code> work. They capture additional positional and keyword arguments, while you are passing in an extra tuple and an extra dictionary as <code>(...)</code> and <code>headers=headers</code>, respectively.</p>
<p>That means that <code>to</code> is no... | 1 | 2016-09-04T10:40:28Z | [
"python",
"python-3.x",
"smtplib"
] |
Splitting arithmetric expressions in python with regexps | 39,316,072 | <p>i have a following snippet, generally i want to split arithmetic expression (with negative numbers) to tokens.</p>
<pre><code>import re
import collections
NUM = r'(?P<NUM>-?\d+)'
PLUS = r'(?P<PLUS>\+)'
MINUS = r'(?P<MINUS>-)'
TIMES = r'(?P<TIMES>\*)'
DIVIDE = r'(?P<DIVIDE>... | 0 | 2016-09-04T10:43:04Z | 39,316,811 | <p>I think the easiest way is just to create expressions by seperating each part with space.</p>
<p>ex.</p>
<pre><code>expr= '2 - -2'
Token(type='NUM', value='2')
Token(type='MINUS', value='-')
Token(type='NUM', value='-2')
</code></pre>
<p>The problem is that the computer dosen't know wheter you've forgot to add a... | 0 | 2016-09-04T12:14:58Z | [
"python",
"regex",
"parsing"
] |
How to read a audio file in Python similar to Matlab audioread? | 39,316,087 | <p>I'm using <code>wavefile.read()</code> in Python to import a audio file to Python. What I want is read a audio file where every sample is in double and normalized to -1.0 to +1.0 similar to Matlab <code>audioread()</code> function. How can I do it ?</p>
| 1 | 2016-09-04T10:45:25Z | 39,319,960 | <p>Use <a href="http://pysoundfile.readthedocs.io/en/latest/#soundfile.read" rel="nofollow">read</a> function of the <a href="https://pypi.python.org/pypi/PySoundFile/" rel="nofollow">PySoundFile</a> package. By default it will return exactly what you request: a numpy array containing the sound file samples in double-... | 1 | 2016-09-04T18:06:01Z | [
"python",
"matlab",
"audio"
] |
Deploy webapp on GAE then do changes online from GAE console | 39,316,090 | <p>I deployed a webapp2 python application on GAE. Is there any way with which i can explore the source code or make changes in the project files from GAE console. Is it possible that if i only want to update a single .py file on already deployed app rather than again deploying the whole project?</p>
| 0 | 2016-09-04T10:45:39Z | 39,319,187 | <p>I think you're looking for this :</p>
<p><a href="https://console.cloud.google.com/code/develop" rel="nofollow">https://console.cloud.google.com/code/develop</a></p>
<p>I pushed my code on Google Cloud Platform with git, and I'm able to change text files directly online.</p>
<p>The doc is here :
<a href="https://... | 1 | 2016-09-04T16:40:12Z | [
"python",
"google-app-engine"
] |
python : Bootstrapping by random sampling | 39,316,142 | <p>I have an array like this,</p>
<pre><code>[[ 5.80084178e-05 1.20779787e-02 -2.65970238e-02]
[ -1.36810406e-02 6.85722519e-02 -2.60280724e-01]
[ 4.21996519e-01 -1.43644036e-01 2.12904690e-01]
[ 3.03098198e-02 1.50170659e-02 -1.09683402e-01]
[ -1.50776089e-03 7.22369575e-03 -3.71181228e-02]
[ -... | -1 | 2016-09-04T10:53:29Z | 39,316,373 | <p>If the above initial 11x3 array is 'A' ,</p>
<pre><code>import random
arr=np.zeros(shape=(1000,5))
for k in range(0,1000) :
B=[]
for i in range(0,3):
B.append(random.choice(A.transpose()[i]))
arr[k]=B
</code></pre>
<p>simply, 'arr' will give me what I am looking for. But isn't there a better, existing ... | 0 | 2016-09-04T11:23:04Z | [
"python"
] |
Python: write at the specific position in a file | 39,316,183 | <p>I have two files one having let suppose list of keys while other file have keys and value pair written like below.</p>
<blockquote>
<p>keys```values</p>
</blockquote>
<p>Now, assuming I have to search for each keys in the later file having key value pair and on matching the keys, have to write some value for spe... | 1 | 2016-09-04T10:59:01Z | 39,317,027 | <p>There's no possible way to write in a specific place in a text file</p>
<p>A good alternative is:</p>
<ul>
<li>Read the file <code>everything = letmethink.read()</code></li>
<li>Insert new data <code>everything = everything[:pos] + new_data + everything[pos + 1:]</code></li>
<li>Delete the file <code>letmethink.tr... | 1 | 2016-09-04T12:41:33Z | [
"python",
"file-handling"
] |
Issue calling method outside class python | 39,316,211 | <p>I'm working on a python assingment involving creating and using a class with several methods. I won't post the whole thing as it'll be simpler to point out my issue if I instead show an example of what I'm trying to do.</p>
<pre><code>class Fruit(self,color,name):
def __init__(self, color, name):
self.c... | 0 | 2016-09-04T11:02:36Z | 39,316,333 | <p>Basically you are calling an instance method without an instance that's why you are getting this error</p>
<pre><code> TypeError: unbound method return_list() must be called with Fruit instance as first argument (got int instance instead)
</code></pre>
<p>The corrected code</p>
<pre><code> fruit_1.return_li... | 1 | 2016-09-04T11:18:05Z | [
"python",
"list",
"python-2.7",
"class",
"methods"
] |
Issue calling method outside class python | 39,316,211 | <p>I'm working on a python assingment involving creating and using a class with several methods. I won't post the whole thing as it'll be simpler to point out my issue if I instead show an example of what I'm trying to do.</p>
<pre><code>class Fruit(self,color,name):
def __init__(self, color, name):
self.c... | 0 | 2016-09-04T11:02:36Z | 39,316,352 | <p>You seem to have a misunderstanding of Classes and class instances.</p>
<p>The <code>return_list</code> function you have defined is part of the <code>Fruit</code> class, i.e. each instance of the <code>Fruit</code> class contains this method. But the use of this function, which is to return a specific fruit from f... | 0 | 2016-09-04T11:19:54Z | [
"python",
"list",
"python-2.7",
"class",
"methods"
] |
Issue calling method outside class python | 39,316,211 | <p>I'm working on a python assingment involving creating and using a class with several methods. I won't post the whole thing as it'll be simpler to point out my issue if I instead show an example of what I'm trying to do.</p>
<pre><code>class Fruit(self,color,name):
def __init__(self, color, name):
self.c... | 0 | 2016-09-04T11:02:36Z | 39,316,370 | <p>Here's a possible solution to your problem:</p>
<pre><code>class Fruit():
def __init__(self, color, name):
self.color = color
self.name = name
def __str__(self):
return "Color: {0} Name: {1}".format(self.color, self.name)
class FruitBasket():
def __init__(self):
self... | 0 | 2016-09-04T11:22:45Z | [
"python",
"list",
"python-2.7",
"class",
"methods"
] |
Python 3: How to convert array to list of dictionary? | 39,316,241 | <pre><code>def get_list(name, ids):
single_database = {}
database = []
for id in ids:
single_database['id'] = id
single_database['name'] = name
database.append(single_database.copy())
return database
input = [{'name': 'David', 'id': ['d1','d2']},
{'name':'John',... | 0 | 2016-09-04T11:07:32Z | 39,316,282 | <p>This should work</p>
<pre><code>list_of_dicts = [
{'id': id, 'name': d['name']}
for d in input
for id in d['id']
]
</code></pre>
<p>or in a more verbose form:</p>
<pre><code>def get_list(input):
list_of_dicts = []
for d in input:
for id in d['id']:
list_of_dicts.append({
... | 8 | 2016-09-04T11:11:43Z | [
"python",
"arrays",
"dictionary"
] |
Python 3: How to convert array to list of dictionary? | 39,316,241 | <pre><code>def get_list(name, ids):
single_database = {}
database = []
for id in ids:
single_database['id'] = id
single_database['name'] = name
database.append(single_database.copy())
return database
input = [{'name': 'David', 'id': ['d1','d2']},
{'name':'John',... | 0 | 2016-09-04T11:07:32Z | 39,316,287 | <p>You can build this in single line of code, Beauty of python</p>
<pre><code>result = [{'id':j,'name':i['name']} for i in input_dict for j in i['id']]
</code></pre>
<p><strong>Result</strong> </p>
<pre><code>[{'id': 'd1', 'name': 'David'},
{'id': 'd2', 'name': 'David'},
{'id': 'j1', 'name': 'John'},
{'id': 'j2'... | 2 | 2016-09-04T11:12:28Z | [
"python",
"arrays",
"dictionary"
] |
Change to recognized encoding when reading a text file? | 39,316,250 | <p>When a text file is open for reading using (say) UTF-8 encoding, is it possible to change encoding during the reading?</p>
<p><strong>Motivation:</strong> It hapens that you need to read a text file that was written using non-default encoding. The text format may contain the information about the used encoding. Let... | 0 | 2016-09-04T11:09:18Z | 39,316,713 | <p>Classic usage is:</p>
<ul>
<li>Open the file in binary format (bytes string)</li>
<li>read a chunk and guess the encoding (For instance with a simple scanning or using RegEx)</li>
</ul>
<p>Then:</p>
<ul>
<li>close the file and re-open it in text mode with the found encoding
Or</li>
<li>move to the beginning: seek... | 1 | 2016-09-04T12:05:10Z | [
"python",
"file",
"python-3.x",
"encoding"
] |
Sending data from html to database | 39,316,259 | <p>The following partial code is a mix of HTML and python. Where a products' values (<code>item_name, description, item_price</code>) of the table <code>products</code> from my database are laid out on HTML and has a "add to cart" input button next to each item.</p>
<pre><code>{% for product in products %}
<li&... | 0 | 2016-09-04T11:10:35Z | 39,317,213 | <p>Yes you can, you just need to create a view to do it.</p>
<p>Your view will have a parameter that will take <code>product.product_id</code>, like so:</p>
<pre><code>def addToCart(request, product_id):
p = Product.objects.filter(product_id = product_id)
#put the product in your member's cart table,
</code><... | 0 | 2016-09-04T13:05:29Z | [
"python",
"django",
"django-forms"
] |
How to make sure output is same length? | 39,316,275 | <p>I want to know is there a way in python to make sure that the output is the same length , by adding white space or something like that.</p>
<pre><code>78364721 apple 3 3 9
35619833 orange 4 2 8
46389121 chicken 1 10 10
total price of order £ 27
</code></pre>
<p>I want :</p>
<pre><code>78364721 apple 3 3 9
3... | 0 | 2016-09-04T11:11:19Z | 39,316,464 | <p>Here's a simple example using <a href="https://docs.python.org/3/library/string.html#format-string-syntax" rel="nofollow">format string syntax</a>:</p>
<pre><code># -*- coding: utf-8 -*-
dataframe = [
[78364721, "apple", 3, 3, 9],
[35619833, "orange", 4, 2, 8],
[46389121, "chicken", 1, 10, 10]
]
for ro... | 0 | 2016-09-04T11:33:15Z | [
"python",
"python-3.x"
] |
Error while stemming arabic text in file using ISRIStemmer | 39,316,345 | <p>I am trying to stem the contents of a text file (text.txt) in Arabic Language using nltk.stem.isri .
The text.txt file contains the following Arabic text:</p>
<p>تتÙÙØ¹ اÙÙ
شاعر Ø§ÙØªÙ ÙØ´Ø¹Ø± Ø¨ÙØ§ Ø§ÙØ¥ÙØ³Ø§Ù Ø®ÙØ§Ù ØÙØ§ØªÙØ ÙØªÙÙÙ ÙØ°Ù اÙÙ
شاعر تبعا٠ÙÙ
ÙØ§Ù٠أ٠أش... | 0 | 2016-09-04T11:19:20Z | 39,316,537 | <p>Try decoding the lines from the file to <em>unicode</em> before passing it to the stemmer. I am assuming that your input file is encoded as UTF8 (seems likely looking at the error), however, you can change the encoding as suits:</p>
<pre><code>for line in f:
line = line.decode('utf8') # use the correct encod... | 1 | 2016-09-04T11:41:53Z | [
"python",
"nltk",
"arabic"
] |
Get continuous dataframe in pandas by filling the missing month with 0 | 39,316,392 | <p>I have a pandas dataframe as shown below where I have Month-Year, need to get the continuous dataframe which should include count as 0 if no rows are found for that month. Excepcted output is shown below. </p>
<h2>Input dataframe</h2>
<pre><code>Month | Count
--------------
Jan-15 | 10
Feb-15 | 100
Mar-15 | 2... | -5 | 2016-09-04T11:25:02Z | 39,316,502 | <p>You can set the Month column as the index. It looks like Excel input, if so, it will be parsed at 01.01.2015 so you can resample it as follows:</p>
<pre><code>df.set_index('Month').resample('MS').asfreq().fillna(0)
Out:
Count
Month
2015-01-01 10.0
2015-02-01 100.0
2015-03-01 20.0
2015-... | 1 | 2016-09-04T11:37:45Z | [
"python",
"pandas",
"resampling"
] |
Multidimensionnal array class and line object in Python | 39,316,443 | <p>I have a question that spawned from writing my own class to manage a two-dimension table.</p>
<p>I started by creating a simple class as follows, creating an empty_line object that was copied as much as needed to create the number of lines:</p>
<pre><code>class Table(object):
"""Table class, allows the creation of... | 1 | 2016-09-04T11:30:50Z | 39,316,572 | <p>In your code:</p>
<pre><code>self.empty_line = [defaultcontent for i in range(self.columns)]
self.table = [self.empty_line for j in range(self.lines)]
</code></pre>
<p>The empty_line is copied in every line of the table using swallow copy. You copied only references, not the default content.</p>
<p>To fix that:</... | 1 | 2016-09-04T11:45:14Z | [
"python",
"object",
"multidimensional-array"
] |
OpenCV giving wrong color to colored images on loading | 39,316,447 | <p>I'm loading in a color image in Python OpenCV and plotting the same. However, the image I get has it's colors all mixed up. </p>
<p>Here is the code:</p>
<pre><code>import cv2
import numpy as np
from numpy import array, arange, uint8
from matplotlib import pyplot as plt
img = cv2.imread('lena_caption.png', cv2.... | 0 | 2016-09-04T11:31:18Z | 39,316,695 | <p>OpenCV uses BGR as its default colour order for images, matplotlib uses RGB. When you display an image loaded with OpenCv in matplotlib the channels will be back to front. </p>
<p>The easiest way of fixing this is to use OpenCV to explicitly convert it back to RGB, much like you do when creating the greyscale image... | 2 | 2016-09-04T12:01:29Z | [
"python",
"image",
"opencv",
"colors"
] |
Should functions take extra arguments for the sake of testing? | 39,316,449 | <p>I am writing tests for a program I intend to write that checks for certain lines in configuration files.</p>
<p>For example, the program might check that the line: AllowConnections-
is contained in the file SomeFile.conf.</p>
<p>My function stub does not take any arguments because I know the file that I am going ... | 0 | 2016-09-04T11:31:28Z | 39,316,506 | <p>It would be quite possible to define the function as</p>
<pre><code>def checkline_in_file(filename="SomeFile.conf"):
</code></pre>
<p>Using a default value for the filename. In testing it can be overridden. In production you don't need to give it an argument.</p>
<p>Later on, when phb decides that all file extens... | 0 | 2016-09-04T11:38:03Z | [
"python",
"testing"
] |
Should functions take extra arguments for the sake of testing? | 39,316,449 | <p>I am writing tests for a program I intend to write that checks for certain lines in configuration files.</p>
<p>For example, the program might check that the line: AllowConnections-
is contained in the file SomeFile.conf.</p>
<p>My function stub does not take any arguments because I know the file that I am going ... | 0 | 2016-09-04T11:31:28Z | 39,316,539 | <p>The code you test, and the code you run should be same.</p>
<p>I do not recommend using a filename, because now you are dealing with (in one function) opening the file - and the errors associated with that part, and then confirming the file format (the actual purpose of the function).</p>
<p>It sounds to me that y... | 1 | 2016-09-04T11:42:11Z | [
"python",
"testing"
] |
App Engine module import issue | 39,316,511 | <p>I am writing unit tests for a Flask based application running on App Engine. </p>
<p>As per the <a href="https://cloud.google.com/appengine/docs/python/tools/localunittesting" rel="nofollow">documentation</a>, I have included the following lines</p>
<pre><code>import sys
sys.path.insert(1, '/Users/vinay/tools/goo... | 0 | 2016-09-04T11:38:37Z | 39,319,017 | <p>Looks like you don't have the <code>google_appengine</code> package where you think you do. You will not see an error if you try to add a nonexistent path to your sys path. Add this between lines 5 and 7 to check your path:</p>
<pre><code>from pprint import pprint
pprint(sys.path)
</code></pre>
<p>Check for mor... | 0 | 2016-09-04T16:21:45Z | [
"python",
"python-2.7",
"google-app-engine"
] |
Python pandas conditional column dealing with None | 39,316,521 | <p>If I have pandas data like this:</p>
<pre><code>s1 s2 s3
1 None 1
1 2 1
2 2 2
1 2 None
</code></pre>
<p>I want to add a new column 's' whose value will be None if the values of s1, s2 and s3 don't match. If they match (I want to ignore None in this comparision) the value shoul... | 1 | 2016-09-04T11:39:26Z | 39,316,584 | <p>Assuming your columns are numeric and None's are treated as NaN's, you can do:</p>
<pre><code>df['s'] = np.where(df.std(axis=1)==0, df.mean(axis=1), np.nan)
df
Out:
s1 s2 s3 s
0 1 NaN 1.0 1.0
1 1 2.0 1.0 NaN
2 2 2.0 2.0 2.0
3 1 2.0 NaN NaN
</code></pre>
<p>This is based on the fact ... | 1 | 2016-09-04T11:46:46Z | [
"python",
"pandas"
] |
How to do sum in Loop | 39,316,646 | <p>I have a exercise ,Input data will contain the total count of pairs to process in the first line.
The following lines will contain pairs themselves - one pair at each line.
Answer should contain the results separated by spaces.
My code:</p>
<pre><code> n = int(raw_input())
sum = 0
for i in range(n):
... | -2 | 2016-09-04T11:54:52Z | 39,316,746 | <p>Uh oh, it looks like you're reusing the same variable <code>i</code> in the inner loop as the outer loop -- this is bad practice and can lead to bugs down the road. </p>
<p>What you're doing currently is adding both elements in each pair to sum and then printing that at the end, you can fix this in two different wa... | 0 | 2016-09-04T12:08:16Z | [
"python",
"loops",
"sum"
] |
How to do sum in Loop | 39,316,646 | <p>I have a exercise ,Input data will contain the total count of pairs to process in the first line.
The following lines will contain pairs themselves - one pair at each line.
Answer should contain the results separated by spaces.
My code:</p>
<pre><code> n = int(raw_input())
sum = 0
for i in range(n):
... | -2 | 2016-09-04T11:54:52Z | 39,317,164 | <p>with your current code what you get is the total sum of all the given numbers, to get the sum per line you need to initialize your counter in the outer loop, and then print it, and as you want to print all it in the same line there are several ways to do it, like save it in a list or telling <a href="https://docs.py... | 0 | 2016-09-04T13:00:08Z | [
"python",
"loops",
"sum"
] |
How to import from Qt:: namespase (Qt5, Python3.x)? | 39,316,693 | <p>For my application I need to set some widget parameters like alignment (<code>Qt::AlignBottom</code>) and others. But I can't import them (other PyQt5 staff imports withot any issues).</p>
<p>Using this code</p>
<pre><code>from PyQt5 import Qt
progressBar = QProgressBar(splash)
progressBar.setAlignment(Qt.AlignBo... | 1 | 2016-09-04T12:01:12Z | 39,317,267 | <p>You can do this</p>
<pre><code>>>> from PyQt5.QtCore import Qt
>>> Qt.AlignBottom
64
>>>
</code></pre>
<p>You can't import <code>AlignBottom</code> only because QtCore is not a package itself, it's just a module on it's own (a single file). it's important to know that <strong>all package... | 1 | 2016-09-04T13:11:39Z | [
"python",
"qt",
"python-3.x",
"pyqt5"
] |
How to import from Qt:: namespase (Qt5, Python3.x)? | 39,316,693 | <p>For my application I need to set some widget parameters like alignment (<code>Qt::AlignBottom</code>) and others. But I can't import them (other PyQt5 staff imports withot any issues).</p>
<p>Using this code</p>
<pre><code>from PyQt5 import Qt
progressBar = QProgressBar(splash)
progressBar.setAlignment(Qt.AlignBo... | 1 | 2016-09-04T12:01:12Z | 39,349,139 | <p>I think the confusion here is that PyQt has a special virtual module called <code>Qt</code>, which imports <em>everything</em> into a single namespace. This is a quite useful feature, but it's a real shame that the name clash with <code>QtCore.Qt</code> wasn't avoided.</p>
<p>In the first example, the error can be ... | 2 | 2016-09-06T12:33:36Z | [
"python",
"qt",
"python-3.x",
"pyqt5"
] |
How should I multiply 1d-array in 3d-array by 2d-matrix with numpy | 39,316,715 | <p>I want bellow calculation.Values used in this example are variable in real case.</p>
<pre><code> A = [[1,1,1],[2,1,1]]
B =[[[1,2,3],[2,2,2]],[[1,1,2],[1,1,1]]]
result = apply_some_function(A,B)
>> result = [[[6,7],[6,8]],
[[4,5],[3,4]]]
</code></pre>
<p>Is their any efficient way satisfy abov... | 0 | 2016-09-04T12:05:13Z | 39,316,801 | <p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.tensordot.html" rel="nofollow"><code>np.tensordot</code></a> or <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a>. </p>
<pre><code>In [19]: np.tensordot(B, A, (-1,... | 3 | 2016-09-04T12:13:53Z | [
"python",
"arrays",
"numpy"
] |
Python - Minimum of list of tuples using min(list, key=func) how to improve efficiency | 39,316,823 | <p>Given a list <code>templates</code> of tuples <code>(region, calc_3d_harmonics(region))</code> where <code>calc_3d_harmonics</code> is some function that returns a signature for each region, I need to find the region with the minimal score (the actual score doesn't matter).</p>
<p>The score of a region is given by ... | 1 | 2016-09-04T12:17:23Z | 39,317,001 | <p>When in doubt, do not guess, <a href="https://docs.python.org/3/library/profile.html" rel="nofollow">profile it</a>.</p>
<p>Putting all of your code behind, we may refer to cPython implementation. We can see, that <code>min</code> function uses <a href="https://github.com/python/cpython/blob/master/Python/bltinmodu... | 0 | 2016-09-04T12:38:36Z | [
"python",
"list",
"numpy",
"tuples",
"min"
] |
Python - Minimum of list of tuples using min(list, key=func) how to improve efficiency | 39,316,823 | <p>Given a list <code>templates</code> of tuples <code>(region, calc_3d_harmonics(region))</code> where <code>calc_3d_harmonics</code> is some function that returns a signature for each region, I need to find the region with the minimal score (the actual score doesn't matter).</p>
<p>The score of a region is given by ... | 1 | 2016-09-04T12:17:23Z | 39,317,089 | <p><code>min(lst, key=func)</code> calls <code>func</code> once on each item of <code>lst</code> (and that also applies to the key function of <code>max</code>, <code>list.sort</code> and <code>sorted</code>). So if <code>lst</code> contains duplicated items then the key function does unnecessary work, unless you use a... | 1 | 2016-09-04T12:50:55Z | [
"python",
"list",
"numpy",
"tuples",
"min"
] |
Python Pandas: Best strategy to import heterogenious csv file | 39,316,831 | <p>I have a inhomogenious csv-File I want to read into pandas. The file looks like that:</p>
<pre><code>2016-01-01; 1.00; 2.00
2016-01-02; 1,10; 2.05
2016-01-03; 0.95; 1.90
Some other text in here
2016-01-04; 1.01; 2.04
Some more text there
2016-01-05; 1.06; 2.07
</code></pre>
<p>I only need the text lines so I can s... | 2 | 2016-09-04T12:18:10Z | 39,317,017 | <p>If you'd like to discard lines starting with a single special <em>character</em>, you can use the <code>comment</code> parameter of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>, as noted by @cel in the comment above. </p>
<p>Otherwise,... | 2 | 2016-09-04T12:40:58Z | [
"python",
"pandas"
] |
Determine how many decimal digits of a float are precise | 39,316,849 | <p>In my real-life problem, I multiply the size of a widget, with a <code>size_hint</code> which can be anything from <code>0.</code> to <code>1.</code>. Assuming the minimum size of a widget is <code>0</code> and the max size is <code>10,000</code>, on which digit should I expect the error to occur, when I multiply <c... | 0 | 2016-09-04T12:21:01Z | 39,317,030 | <p>I'd recommend you take a read to <a href="https://docs.python.org/3/whatsnew/3.5.html#pep-485-a-function-for-testing-approximate-equality" rel="nofollow">pep485</a></p>
<p>Using <code>==</code> operator to compare floating-point values is not the right way to go, instead consider using <a href="https://docs.python.... | 0 | 2016-09-04T12:42:02Z | [
"python",
"floating-point",
"precision",
"significant-digits"
] |
Determine how many decimal digits of a float are precise | 39,316,849 | <p>In my real-life problem, I multiply the size of a widget, with a <code>size_hint</code> which can be anything from <code>0.</code> to <code>1.</code>. Assuming the minimum size of a widget is <code>0</code> and the max size is <code>10,000</code>, on which digit should I expect the error to occur, when I multiply <c... | 0 | 2016-09-04T12:21:01Z | 39,317,152 | <p>If we assume that the size of the widget is stored exactly, then there are 2 sources of error: the conversion of <code>size_hint</code> from decimal -> binary, and the multiplication. In Python, these should both be correctly rounded to nearest, so each should have relative error of half an ulp (<a href="https://en.... | 2 | 2016-09-04T12:58:52Z | [
"python",
"floating-point",
"precision",
"significant-digits"
] |
Determine how many decimal digits of a float are precise | 39,316,849 | <p>In my real-life problem, I multiply the size of a widget, with a <code>size_hint</code> which can be anything from <code>0.</code> to <code>1.</code>. Assuming the minimum size of a widget is <code>0</code> and the max size is <code>10,000</code>, on which digit should I expect the error to occur, when I multiply <c... | 0 | 2016-09-04T12:21:01Z | 39,323,523 | <p>To answer the decimal to double-precision floating-point conversion part of your question...</p>
<p>The conversion of decimal fractions between 0.0 and 0.1 will be good to <a href="http://www.exploringbinary.com/decimal-precision-of-binary-floating-point-numbers/" rel="nofollow">15-16 decimal digits</a> (Note: you ... | 1 | 2016-09-05T03:26:14Z | [
"python",
"floating-point",
"precision",
"significant-digits"
] |
TypeError: hash must be unicode or bytes, not None | 39,316,867 | <p>I am working on Flask project works with mongoengine. Register code hashed to password with <strong>passlib.hash</strong> when user registered. When I try to read password in login authentication I've got this error.</p>
<p><strong>TypeError: hash must be unicode or bytes, not None</strong></p>
<p><a href="http:/... | 1 | 2016-09-04T12:23:18Z | 39,317,257 | <p>I guess the problem is here:</p>
<pre><code>user = User.objects(email=form.email.data, password=str(passW)).first()
</code></pre>
<p>If your database can't find any match user, user will be none. So you'd better use if else to tell if the user exist first.</p>
<h3>EDIT</h3>
<p>From the doc in Passlib, </p>
<pr... | 1 | 2016-09-04T13:10:05Z | [
"python",
"unicode",
"hash",
"flask",
"typeerror"
] |
TypeError: hash must be unicode or bytes, not None | 39,316,867 | <p>I am working on Flask project works with mongoengine. Register code hashed to password with <strong>passlib.hash</strong> when user registered. When I try to read password in login authentication I've got this error.</p>
<p><strong>TypeError: hash must be unicode or bytes, not None</strong></p>
<p><a href="http:/... | 1 | 2016-09-04T12:23:18Z | 39,320,293 | <p>Just as @aison said above I had to change objects variable with the objects field variable as user.password </p>
<pre><code>if sha256_crypt.verify(passW, user.password):
</code></pre>
<p>Also needed to change model queryset itself. I removed the password field in the query, beacuse the password already verifying ... | 0 | 2016-09-04T18:40:59Z | [
"python",
"unicode",
"hash",
"flask",
"typeerror"
] |
Unable to parse data from weather website | 39,316,881 | <p>Hey i want to parse weather data from the following website: <a href="http://www.indiaweather.gov.in" rel="nofollow">http://www.indiaweather.gov.in</a></p>
<p>If you observe you have a search bar which lets you enter any indian city's name and when you hit go you end up on a page with the weather data for that city... | -2 | 2016-09-04T12:24:31Z | 39,318,224 | <p>You could use Beautiful Soup! to get your desired data between specific html tags. If you want to do it yourself you could post your data by calling the site's api. first install requests. <code>pip install requests</code> then</p>
<pre><code>import re
import requests
# the data is between align="left"><fon... | -1 | 2016-09-04T14:56:06Z | [
"python",
"html",
"parsing",
"beautifulsoup",
"weather"
] |
Cannot get unique IDs for a string python2.7 | 39,316,897 | <p>I am trying to make unique ID from a list of words. I want these numbers to be globally unique. For example, if another list appears, I want the unique ID to be the same e.g. for "density", the ID might be <code>151111911</code>, and this will be the same if "density" occurs in a different list.</p>
<p>As you can s... | 0 | 2016-09-04T12:26:18Z | 39,317,081 | <p>You could directly use the <code>hash()</code> function in Python. Hash function will return a unique hash which can be used as an ID for any given string as is your case but it may differ on different platforms (32 bit/64 bit, OS, python version)</p>
<pre><code>hash("answer")
-8597262460139880008
</code></pre>
<p... | -1 | 2016-09-04T12:48:55Z | [
"python",
"string",
"python-2.7",
"hash",
"unique"
] |
Cannot get unique IDs for a string python2.7 | 39,316,897 | <p>I am trying to make unique ID from a list of words. I want these numbers to be globally unique. For example, if another list appears, I want the unique ID to be the same e.g. for "density", the ID might be <code>151111911</code>, and this will be the same if "density" occurs in a different list.</p>
<p>As you can s... | 0 | 2016-09-04T12:26:18Z | 39,317,092 | <p>You could use the words themselves, a hash of the words, or can even convert the string into a number.</p>
| 1 | 2016-09-04T12:51:19Z | [
"python",
"string",
"python-2.7",
"hash",
"unique"
] |
Cannot get unique IDs for a string python2.7 | 39,316,897 | <p>I am trying to make unique ID from a list of words. I want these numbers to be globally unique. For example, if another list appears, I want the unique ID to be the same e.g. for "density", the ID might be <code>151111911</code>, and this will be the same if "density" occurs in a different list.</p>
<p>As you can s... | 0 | 2016-09-04T12:26:18Z | 39,317,181 | <p>From the <a href="https://docs.python.org/2.7/library/functions.html#intern]" rel="nofollow">docs</a></p>
<blockquote>
<p>Interned strings are not immortal (like they used to be in Python 2.2 and before); you must keep a reference to the return value of intern() around to benefit from it.</p>
</blockquote>
<p>At... | 2 | 2016-09-04T13:02:46Z | [
"python",
"string",
"python-2.7",
"hash",
"unique"
] |
Cannot get unique IDs for a string python2.7 | 39,316,897 | <p>I am trying to make unique ID from a list of words. I want these numbers to be globally unique. For example, if another list appears, I want the unique ID to be the same e.g. for "density", the ID might be <code>151111911</code>, and this will be the same if "density" occurs in a different list.</p>
<p>As you can s... | 0 | 2016-09-04T12:26:18Z | 39,317,379 | <p>Perhaps the easiest way is to use a <code>defaultdict</code> with a <code>itertools.count</code> with a <code>float</code> as its starting position, eg:</p>
<pre><code>from collections import defaultdict
from itertools import count
# Start from 1.0 and increment by one - can change to start from any value or even ... | 1 | 2016-09-04T13:23:40Z | [
"python",
"string",
"python-2.7",
"hash",
"unique"
] |
TypeError when indexing numpy array using numba | 39,316,939 | <p>I need to sum up elements in a 1D <code>numpy</code> array (below: <code>data</code>) based on another array with information on class memberships (<code>labels</code>). I use <code>numba</code>in the code below to speed it up. However, If I dot not explicitly cast with <code>int()</code> in the line <code>ret[int(f... | 1 | 2016-09-04T12:30:32Z | 39,317,766 | <p>The problem is that <code>find</code> can either return an <code>int</code> or <code>None</code> if it doesn't find anything, thus I think the <code>?int64</code> error. To avoid casting, you need to provide an <code>int</code> return value when <code>find</code> exits without finding the desired value and then hand... | 1 | 2016-09-04T14:07:48Z | [
"python",
"numba"
] |
issue using Singleton pattern with tkinter Photoimage/Tk in python | 39,316,971 | <p>Wrote the following code to display a chessboard using Tkinter in Python:</p>
<pre><code>import tkinter as tk
class Gui(tk.Tk):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls, *args, **kwargs)
cls._instance.__in... | 0 | 2016-09-04T12:34:34Z | 39,317,359 | <p>The answer to your questions boils down to two factors:</p>
<ol>
<li>The root window must exist before you can create an image</li>
<li>You must keep a reference to the image or tkinter will destroy
the image data when it does garbage collection.</li>
</ol>
<p>The proper way to use this code would be to first cre... | 1 | 2016-09-04T13:21:54Z | [
"python",
"tkinter",
"singleton"
] |
Regex to match swedish words but not numbers | 39,317,008 | <p>So I have made a regex (in Python) that currently matches all words but ignores special characters.</p>
<pre><code>/([\wåäöÃ
ÃÃ]+)/g
</code></pre>
<p>However, it also matches numbers. How can I make it so that it does not match numbers?</p>
| 0 | 2016-09-04T12:39:38Z | 39,317,050 | <p>The <code>\w</code> character class is equivalent to <code>[A-Za-z0-9_]</code>.</p>
<p>So maybe:</p>
<pre><code>[åäöÃ
ÃÃA-Za-z_]+
</code></pre>
<p>will be better choice </p>
| 3 | 2016-09-04T12:44:00Z | [
"python",
"regex"
] |
Pass current value(instance) in the udpate form | 39,317,156 | <p>I have an api for updating the object. But update form shows empty field. How can i show form filled with current value? If i want to show current value filled in just django, i would do formname(instance=object). How can i do similar in DRF when using RetrieveAPIView. </p>
<pre><code>class RestaurantUpdateAPI(Retr... | 0 | 2016-09-04T12:59:24Z | 39,317,858 | <p>You api url is ../edit/..., so I think you wanna use this api to edit your restaurant.(btw, REST API should not use "edit" in it, you just use http method to handle this). In your case, if you want use get method and post method at the same time.You should use <a href="http://www.django-rest-framework.org/api-guide/... | 0 | 2016-09-04T14:16:08Z | [
"python",
"django",
"python-3.x",
"django-rest-framework"
] |
Name duplicates previous WSGI daemon definition | 39,317,200 | <p>I'm changing the domain name of a site. For a period I want the old domain name and the new domain name to point to the site. I'm running a Python Django site.</p>
<p>My original Apache2 conf works fine and the basis is:</p>
<pre><code><VirtualHost *:80>
ServerAdmin [email protected]
ServerNam... | 0 | 2016-09-04T13:04:11Z | 39,317,370 | <p>change <code>originalsite</code> name </p>
<p>not in the directory address just the name like </p>
<pre><code>WSGIDaemonProcess somethingelse python-path=/var/www/originalsite:/var/www/originalsite/env/ââlib/python2.7/site-pââackages
</code></pre>
<p>and </p>
<pre><code>WSGIProcessGroup somethingelse
</c... | 0 | 2016-09-04T13:22:28Z | [
"python",
"django",
"apache",
"mod-wsgi"
] |
Name duplicates previous WSGI daemon definition | 39,317,200 | <p>I'm changing the domain name of a site. For a period I want the old domain name and the new domain name to point to the site. I'm running a Python Django site.</p>
<p>My original Apache2 conf works fine and the basis is:</p>
<pre><code><VirtualHost *:80>
ServerAdmin [email protected]
ServerNam... | 0 | 2016-09-04T13:04:11Z | 39,322,401 | <p>The reason for the error is because the name of a mod_wsgi daemon process group must be unique across the whole Apache installation. It is not possible to use the same daemon process group name in different <code>VirtualHost</code> definitions. This is necessary to avoid conflicts when working out what daemon proces... | 0 | 2016-09-04T23:39:48Z | [
"python",
"django",
"apache",
"mod-wsgi"
] |
Advice on how I should structure program | 39,317,241 | <p>For the program I am trying to design, I am checking that certain conditions exist in configuration files. For example, that the line: <strong>ThisExists</strong> is in the program, or that <strong>ThisIsFirst</strong> exists in the file followed by <strong>ThisAlsoExists</strong> somewhere later down in the file.</... | 0 | 2016-09-04T13:08:44Z | 39,318,134 | <p>If available libraries (configparser etc.) aren't enough I would probably use regular expressions.</p>
<pre><code>import re
check_a = re.compile('^SomeCondition$', flags=re.MULTILINE)
check_b = re.compile('^Start(?:.|\n)*?End$', flags=re.MULTILINE)
def main(file_name):
with open(file_name, 'r') as file_object... | 0 | 2016-09-04T14:47:13Z | [
"python",
"parsing"
] |
Advice on how I should structure program | 39,317,241 | <p>For the program I am trying to design, I am checking that certain conditions exist in configuration files. For example, that the line: <strong>ThisExists</strong> is in the program, or that <strong>ThisIsFirst</strong> exists in the file followed by <strong>ThisAlsoExists</strong> somewhere later down in the file.</... | 0 | 2016-09-04T13:08:44Z | 39,318,379 | <p>For a software engineering perspective, your current approach has the some nice advantages. The logic of the functions are fully decoupled from one another and can be separately debugged and tested. The complexity of each individual function is low. And this approach allows you to easily incorporate various check... | 1 | 2016-09-04T15:12:22Z | [
"python",
"parsing"
] |
How to use a global variable for all class methods in Python? | 39,317,260 | <ul>
<li><p>I have a <code>Person</code> class, which holds an <code>age</code> property, now I need to make it accessible in all method inside <code>Person</code> class, so that all methods work properly</p></li>
<li><p>My code is as following:</p></li>
</ul>
<pre class="lang-py prettyprint-override"><code>class Pers... | -1 | 2016-09-04T13:10:45Z | 39,317,452 | <p>You need <code>age</code> to be an instance attribute of the Person class. To do that, you use the <code>self.age</code> syntax, like this:</p>
<pre><code>class Person:
def __init__(self, initialAge):
# Add some more code to run some checks on initialAge
if initialAge < 0:
print("... | 1 | 2016-09-04T13:31:09Z | [
"python",
"class",
"object",
"methods",
"instance"
] |
Python: Polygon does not close (shapely | 39,317,261 | <p>When creating a polygon using the Shapely, I push 4 vertices in the the polygon function. The output should be a tuple with 5 elements (the first vertex is doubled, and described as the last one too).</p>
<p>It seems, however, that the order of the input vertices I pass to the function has impact the result: somet... | 1 | 2016-09-04T13:10:50Z | 39,347,117 | <p>I think it is related with the third coordinate. In the documentation (<a href="http://toblerity.org/shapely/manual.html" rel="nofollow">shapely doc</a>), it tells: </p>
<blockquote>
<p>A third z coordinate value may be used when constructing instances,
but has no effect on geometric analysis. All operations ar... | 1 | 2016-09-06T10:45:55Z | [
"python",
"shapely"
] |
How to test that a function only accepts a certain type? | 39,317,275 | <p>I want to ensure that <code>twist_data</code> only gets a list of integers as an argument, and add a unit test.</p>
<pre><code> def twist_data(n):
n=list(n)
a=[]
b=[]
for i in n:
if i<=0:
a.append(i)
if i>0:
b.append(i)
n=[len(a),sum(b)]
... | -1 | 2016-09-04T13:12:30Z | 39,321,774 | <pre><code>def all_ints(numbers):
return all(isinstance(number, int) for number in numbers)
def validate_list(numbers):
return all((isinstance(numbers, list), all_ints(numbers))
def twist_data(numbers):
if not validate_list(numbers):
raise TypeError('"numbers" must be of type "list", where all e... | 0 | 2016-09-04T21:47:18Z | [
"python",
"unit-testing"
] |
Retrieve data from a collection(mongo),modify the returned object and insert it into another mongo collection | 39,317,353 | <pre><code>{
"name" : "XYZ",
"phone" : 12345,
"emp_id" : 9999,
"sal" : 5000
}
</code></pre>
<p>I want to add data on this record and store it into another database. I have tried this:</p>
<pre><code>db=connection.testing
results=db.test.find({"name":"XYZ"})
for i in results:
i.a... | 0 | 2016-09-04T13:21:03Z | 39,318,979 | <p>since <code>i</code> in your example seems to be a dictionary, you most likely need something like <code>i.update({'dept': 'Marketing'})</code> or <code>i['dept']='Marketing'</code> in order to introduce new key/value pair </p>
| 1 | 2016-09-04T16:17:39Z | [
"python",
"mongodb",
"pymongo"
] |
' | ' operator between python set objects | 39,317,373 | <p>Recently while making changes to a python module someone else wrote which does some processing on Pandas dataframe I came across a line of code which looks like this :</p>
<p><code>
indices_invalid_entries = \
list(set(indices_invalid_entries) | set(list(df[pd.isnull(df[i])].index)))
</code></p>
<p>where indices_i... | 1 | 2016-09-04T13:23:05Z | 39,317,454 | <p>You can always try it out:</p>
<pre><code>>>> x = set([1,2,3])
>>> y = set([2,3,4])
>>> x | y
set([1, 2, 3, 4])
>>>
</code></pre>
| 4 | 2016-09-04T13:31:34Z | [
"python",
"pandas",
"numpy"
] |
' | ' operator between python set objects | 39,317,373 | <p>Recently while making changes to a python module someone else wrote which does some processing on Pandas dataframe I came across a line of code which looks like this :</p>
<p><code>
indices_invalid_entries = \
list(set(indices_invalid_entries) | set(list(df[pd.isnull(df[i])].index)))
</code></p>
<p>where indices_i... | 1 | 2016-09-04T13:23:05Z | 39,317,479 | <p>As explained in the <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">documentation</a>, the | operator is the <strong>union operator</strong>.</p>
<p>So as you mentioned in you answer, </p>
<pre><code>indices_invalid_entries <-- union(indices_invalid_entries,df[pd.isnull(df[i])].index)
</cod... | 3 | 2016-09-04T13:34:28Z | [
"python",
"pandas",
"numpy"
] |
Hosting static website with Django | 39,317,434 | <p>I have Django app running live on AWS at, <code>www.domain.com/admin</code>. It doesn't posses any html pages, we only make use of Django-Admin.</p>
<p>Now I have to host a website at <code>www.domain.com</code>.
I have my website package in this form,</p>
<pre><code>site
|-sass
|-js
|-img
|-fonts
|-css
|-in... | 0 | 2016-09-04T13:29:50Z | 39,317,948 | <p>This answer is a reply to <a href="http://stackoverflow.com/questions/39317434/hosting-static-website-with-django?noredirect=1#comment65967301_39317434">this comment</a>, not an answer to the original question.</p>
<ol>
<li><p>In your Apache config, change: <code>WSGIScriptAlias /</code> to <code>WSGIScriptAlias /a... | 1 | 2016-09-04T14:25:23Z | [
"python",
"django",
"django-templates",
"django-admin"
] |
Is this an efficient way to compute a moving average? | 39,317,436 | <p>I've some <code>{open|high|low|close}</code> market data. I want to compute a Simple Moving Average from the <code>close</code> value of each row.</p>
<p>I've had a look around and couldn't find a simple way to do this. I've computed it via the below method. I want to know if there is a better way:</p>
<pre><code>... | 1 | 2016-09-04T13:29:54Z | 39,317,607 | <pre><code>data['SMA10'] = pd.rolling_mean(data['<CLOSE>'][:], 10)
</code></pre>
<p>Was my original found solution, however you get a warning saying it's deprecated</p>
<p>Therefore:</p>
<pre><code>data['SMA10'] = data['<CLOSE>'][:].rolling(window=10, center=False).mean()
</code></pre>
| 1 | 2016-09-04T13:50:31Z | [
"python",
"pandas",
"dataframe",
"moving-average"
] |
Is this an efficient way to compute a moving average? | 39,317,436 | <p>I've some <code>{open|high|low|close}</code> market data. I want to compute a Simple Moving Average from the <code>close</code> value of each row.</p>
<p>I've had a look around and couldn't find a simple way to do this. I've computed it via the below method. I want to know if there is a better way:</p>
<pre><code>... | 1 | 2016-09-04T13:29:54Z | 39,317,656 | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html" rel="nofollow"><code>np.convolve</code></a> as suggested in this <a href="http://stackoverflow.com/a/22621523/6614295">answer</a>. So something like this should work:</p>
<pre><code>data.loc[ma-1:, "SMA10"] = np.convolve(d... | 0 | 2016-09-04T13:56:32Z | [
"python",
"pandas",
"dataframe",
"moving-average"
] |
Is this an efficient way to compute a moving average? | 39,317,436 | <p>I've some <code>{open|high|low|close}</code> market data. I want to compute a Simple Moving Average from the <code>close</code> value of each row.</p>
<p>I've had a look around and couldn't find a simple way to do this. I've computed it via the below method. I want to know if there is a better way:</p>
<pre><code>... | 1 | 2016-09-04T13:29:54Z | 39,317,753 | <p>Pandas provides all the tools you'll need for this kind of thing.
Assuming you have your data indexed by time:</p>
<pre><code>data['SMA10'] = data['<close>'].rolling(window=10).mean()
</code></pre>
<p>Voila. </p>
<p>Edit:
I suppose just note the newer api usage. Quoting from the <a href="http://pandas.pyda... | 3 | 2016-09-04T14:06:27Z | [
"python",
"pandas",
"dataframe",
"moving-average"
] |
Shifting x labels in Matplotlib, Ipython | 39,317,551 | <p>I'm trying to make three charts in one output with matplotlib in an ipython notebook. When I output the chart is correct for the fisrt one, but on the second and third the x labels are messed up, and there are more cells in the second and third chart. I want them all to be uniform. </p>
<pre><code>fig, axs = plt.su... | 0 | 2016-09-04T13:43:18Z | 39,319,365 | <p>You should almost never use <code>set_xticklabels</code> because it is (under the hood) just using a <code>FixedFormatter</code> to tick labels. If you do not also set the locator to be <code>FixedLocator</code>, then the tick labels are applied, in sequence, to the ticks.</p>
<p>As of mpl 1.5, there is a <code>ti... | 0 | 2016-09-04T16:58:40Z | [
"python",
"pandas",
"matplotlib",
"ipython"
] |
Converting GET request parameter to int ... if it is numeric | 39,317,681 | <p>lets say i'm showing some data to user , i want user to be able to perform some sort of filtering on a numeric field in the database using a <code>GET</code> form so i have something like this </p>
<pre><code>code = request.GET.get('code')
condition = {}
if( code is not None and int(code) > 0 ):
condition['... | -1 | 2016-09-04T13:59:06Z | 39,317,745 | <p>The reason you are getting this error because int() expects the value in number it can be in the form string but it should be a number like "22","33" etc are valid .</p>
<p>But in your case you are passing empty that's why its raising an error. You can achieve your desired output using type(), it helps you in check... | 0 | 2016-09-04T14:05:54Z | [
"python",
"django",
"python-3.x",
"django-1.9"
] |
Converting GET request parameter to int ... if it is numeric | 39,317,681 | <p>lets say i'm showing some data to user , i want user to be able to perform some sort of filtering on a numeric field in the database using a <code>GET</code> form so i have something like this </p>
<pre><code>code = request.GET.get('code')
condition = {}
if( code is not None and int(code) > 0 ):
condition['... | -1 | 2016-09-04T13:59:06Z | 39,317,846 | <p><code>isnumeric</code> could check if <code>code</code> can be <em>casted</em> to <code>int</code> and also check that <code>code</code> is positive (when converted to integer) thus replacing <code>int(code) > 0</code>:</p>
<pre><code>if code is not None and code.isnumeric():
condition['code'] = int(code)
</... | 1 | 2016-09-04T14:15:08Z | [
"python",
"django",
"python-3.x",
"django-1.9"
] |
Converting GET request parameter to int ... if it is numeric | 39,317,681 | <p>lets say i'm showing some data to user , i want user to be able to perform some sort of filtering on a numeric field in the database using a <code>GET</code> form so i have something like this </p>
<pre><code>code = request.GET.get('code')
condition = {}
if( code is not None and int(code) > 0 ):
condition['... | -1 | 2016-09-04T13:59:06Z | 39,317,989 | <p>You should use a Django form with one or more IntegerFields; they do this conversion for you, then you can get the result from <code>cleaned_data</code>.</p>
| 1 | 2016-09-04T14:30:27Z | [
"python",
"django",
"python-3.x",
"django-1.9"
] |
Pandas Mean for Certain Column | 39,317,702 | <p>I have a pandas dataframe like that:</p>
<p><a href="http://i.stack.imgur.com/KOZan.png" rel="nofollow"><img src="http://i.stack.imgur.com/KOZan.png" alt="enter image description here"></a></p>
<p>How can I able to calculate mean (min/max, median) for specific column if Cluster==1 or CLuster==2?</p>
<p>Thanks!</p... | 0 | 2016-09-04T14:00:55Z | 39,317,744 | <p>You can create new df with only the relevant rows, using:</p>
<pre><code>newdf = df[df['cluster'].isin([1,2)]
newdf.mean(axis=1)
</code></pre>
<p>In order to calc mean of a specfic column you can:</p>
<pre><code>newdf["page"].mean(axis=1)
</code></pre>
| 1 | 2016-09-04T14:05:23Z | [
"python",
"pandas",
"numpy"
] |
Pandas Mean for Certain Column | 39,317,702 | <p>I have a pandas dataframe like that:</p>
<p><a href="http://i.stack.imgur.com/KOZan.png" rel="nofollow"><img src="http://i.stack.imgur.com/KOZan.png" alt="enter image description here"></a></p>
<p>How can I able to calculate mean (min/max, median) for specific column if Cluster==1 or CLuster==2?</p>
<p>Thanks!</p... | 0 | 2016-09-04T14:00:55Z | 39,317,806 | <h2>Simple intuitive answer</h2>
<p>First pick the rows of interest, then average then pick the columns of interest.</p>
<pre><code>clusters_of_interest = [1, 2]
columns_of_interest = ['page']
# rows of interest
newdf = df[ df.CLUSTER.isin(clusters_of_interest) ]
# average and pick columns of interest
newdf.mean(axi... | 0 | 2016-09-04T14:11:27Z | [
"python",
"pandas",
"numpy"
] |
Pandas Mean for Certain Column | 39,317,702 | <p>I have a pandas dataframe like that:</p>
<p><a href="http://i.stack.imgur.com/KOZan.png" rel="nofollow"><img src="http://i.stack.imgur.com/KOZan.png" alt="enter image description here"></a></p>
<p>How can I able to calculate mean (min/max, median) for specific column if Cluster==1 or CLuster==2?</p>
<p>Thanks!</p... | 0 | 2016-09-04T14:00:55Z | 39,317,833 | <p>You can do it in one line, using <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">boolean indexing</a>. For example you can do something like:</p>
<pre><code>import numpy as np
import pandas as pd
# This will just produce an example DataFrame
df = pd.DataFrame({'a... | 0 | 2016-09-04T14:14:00Z | [
"python",
"pandas",
"numpy"
] |
Pandas Mean for Certain Column | 39,317,702 | <p>I have a pandas dataframe like that:</p>
<p><a href="http://i.stack.imgur.com/KOZan.png" rel="nofollow"><img src="http://i.stack.imgur.com/KOZan.png" alt="enter image description here"></a></p>
<p>How can I able to calculate mean (min/max, median) for specific column if Cluster==1 or CLuster==2?</p>
<p>Thanks!</p... | 0 | 2016-09-04T14:00:55Z | 39,317,855 | <p>If you meant take the mean only where Cluster is 1 or 2, then the other answers here address your issue. If you meant take a separate mean for each value of Cluster, you can use pandas' aggregation functions, including <code>groupyby</code> and <code>agg</code>:</p>
<pre><code>df.groupby("Cluster").mean()
</code><... | 1 | 2016-09-04T14:16:00Z | [
"python",
"pandas",
"numpy"
] |
Domain error with square roots | 39,317,746 | <p>I am trying to copy a code from the book I am learning from. The program is supposed to find the square roots of a quadratic function but once I run the module in IDLE I get an error.</p>
<pre><code>#This is a program to find the square roots of a quadratic function.
import math
def main():
print ("this is... | 0 | 2016-09-04T14:05:58Z | 39,317,875 | <p>Everytime <code>b * b - 4 * a * c</code> is a negative number, <code>math.sqrt(b * b - 4 * a * c)</code> will raise a <code>ValueError</code>.</p>
<p>Either check that before, or use <code>sqrt</code> from the <a href="https://docs.python.org/3.4/library/cmath.html" rel="nofollow"><code>cmath</code></a> module to a... | 1 | 2016-09-04T14:18:45Z | [
"python",
"python-3.x"
] |
Domain error with square roots | 39,317,746 | <p>I am trying to copy a code from the book I am learning from. The program is supposed to find the square roots of a quadratic function but once I run the module in IDLE I get an error.</p>
<pre><code>#This is a program to find the square roots of a quadratic function.
import math
def main():
print ("this is... | 0 | 2016-09-04T14:05:58Z | 39,317,907 | <p>I'm guessing you're taking the square root of a negative number which is not in the domain of the <code>math.sqrt</code> function. It will raise a <code>ValueError</code>. You can get rid of this just by checking the discriminant. The discriminant is the bit inside the root. If it is negative, there are no solutions... | 0 | 2016-09-04T14:21:55Z | [
"python",
"python-3.x"
] |
Matplotlib figure size in Jupyter reset by inlining in Jupyter | 39,317,796 | <p>This question is more of a curiosity.</p>
<p>To change the default fig size to a custom one in matplotlib, one does</p>
<pre><code>from matplotlib import rcParams
from matplotlib import pyplot as plt
rcParams['figure.figsize'] = 15, 9
</code></pre>
<p>after that, figure appears with chosen size. </p>
<p>Now, I'm... | 0 | 2016-09-04T14:10:25Z | 39,327,020 | <p>IPython's inline backend <a href="https://github.com/ipython/ipykernel/blob/4.5.0/ipykernel/pylab/config.py#L45" rel="nofollow">sets some rcParams</a> when it is initialized. This is configurable, and you can override it with your own configuration:</p>
<pre><code># in ~/.ipython/ipython_config.py
c.InlineBackend.r... | 1 | 2016-09-05T08:56:57Z | [
"python",
"matplotlib",
"plot",
"jupyter"
] |
Detecting if an arc has been clicked in pygame | 39,317,909 | <p>I am currently trying to digitalize an boardgame I invented (repo: <a href="https://github.com/zutn/King_of_the_Hill" rel="nofollow">https://github.com/zutn/King_of_the_Hill</a>). To make it work I need to check if one of the tiles (the arcs) on this <a href="http://i.stack.imgur.com/DTXzF.jpg" rel="nofollow">board<... | 0 | 2016-09-04T14:22:04Z | 39,350,866 | <p>This is a simple arc class that will detect if a point is contained in the arc, but it will only work with circular arcs.</p>
<pre><code>import pygame
from pygame.locals import *
import sys
from math import atan2, pi
class CircularArc:
def __init__(self, color, center, radius, start_angle, stop_angle, width=1... | 1 | 2016-09-06T13:56:19Z | [
"python",
"pygame",
"collision-detection"
] |
dataframe math in pandas | 39,317,959 | <p><strong>TOTALLY RE WROTE ORIGINAL QUESTION</strong></p>
<p>I read raw data from a csv file "CloseWeight4.csv"</p>
<pre><code>df=pd.read_csv('CloseWeights4.csv')
Date Symbol ClosingPrice Weight
3/1/2010 OGDC 116.51 0.1820219
3/2/2010 OGDC 117.32 0.1820219
3/3/2010 OGDC 1... | 1 | 2016-09-04T14:26:31Z | 39,318,180 | <pre><code>import numpy as np
import pandas as pd
</code></pre>
<h2>define the variables</h2>
<pre><code>data = np.mat(''' 85.0700 116.51 98.159650 78.70;
85.1077 117.32 98.159650 79.68;
85.0490 116.40 98.176422 80.87;
84.9339 116.58 98.177066 80.21;
84.8000 117.61 98.160936 81.50''')
cols = ['FX', '... | 0 | 2016-09-04T14:51:46Z | [
"python",
"pandas",
"dataframe"
] |
dataframe math in pandas | 39,317,959 | <p><strong>TOTALLY RE WROTE ORIGINAL QUESTION</strong></p>
<p>I read raw data from a csv file "CloseWeight4.csv"</p>
<pre><code>df=pd.read_csv('CloseWeights4.csv')
Date Symbol ClosingPrice Weight
3/1/2010 OGDC 116.51 0.1820219
3/2/2010 OGDC 117.32 0.1820219
3/3/2010 OGDC 1... | 1 | 2016-09-04T14:26:31Z | 39,320,059 | <p>IIUC you can do it this way:</p>
<pre><code>In [267]: port_ret = ret.dot(df3)
In [268]: port_ret
Out[268]:
Weight
Date
2010-03-01 NaN
2010-03-02 0.007938
2010-03-03 0.006431
2010-03-04 -0.004278
2010-03-05 0.009902
In [269]: decay = 0.5
In [270]: decay_df = pd.DataFrame({'decFac':decay**np... | 1 | 2016-09-04T18:15:39Z | [
"python",
"pandas",
"dataframe"
] |
Problems installing python module pybfd | 39,318,053 | <p>I've been trying to install the <code>pybfd</code> module but nothing works so far.</p>
<p>Tried the following:</p>
<p><code>pip install pybfd</code> returns <code>error: option --single-version-externally-managed not recognized</code>. After a quick search I found the <code>--egg</code> option for <code>pip</code... | 0 | 2016-09-04T14:36:59Z | 39,318,468 | <p>After some trial and error I discovered that <code>binutils-dev</code> and <code>python-dev</code> packages were missing and causing the header path errors. After installing those the setup script worked.</p>
| 0 | 2016-09-04T15:21:09Z | [
"python",
"pip",
"easy-install"
] |
Loading variable from txt | 39,318,065 | <p>I'm having problems with the following code:</p>
<pre><code>f=open('config.txt')
lines=f.readlines()
print(lines[1])
print(lines[3])
print(lines[5])
print(lines[7])
print(lines[9])
print(lines[11])
#Import and define
import serial
import time
time.sleep(5)
#Settings
Port = lines[1]
TargetMaxVoltage = float(lines[... | 2 | 2016-09-04T14:38:32Z | 39,319,317 | <p>Checkout the Error log
there is written can't open <code>COM11\n</code> so you have to remove the newline (<code>\n</code>).</p>
<p>Example: <code>Port.strip()</code></p>
| 0 | 2016-09-04T16:53:19Z | [
"python",
"database",
"error-handling",
"serial-port"
] |
Why can generator expressions be iterated over only once? | 39,318,106 | <p>This program:</p>
<pre><code>def pp(seq):
print(''.join(str(x) for x in seq))
print(''.join(str(x) for x in seq))
print('---')
pp([0,1,2,3])
pp(range(4)) # range in Python3, xrange in Python2
pp(x for x in [0,1,2,3])
</code></pre>
<p>prints this:</p>
<pre><code>0123
0123
---
0123
0123
---
0123
---
... | 0 | 2016-09-04T14:43:58Z | 39,318,144 | <blockquote>
<p>My question is why it was decided to implement generator expressions not similar to other objects that seem to be equivalent or at least very similar?</p>
</blockquote>
<p>Because that's exactly what a generator is, if you make it similar to other iterables you have to preserve all the items in memor... | 1 | 2016-09-04T14:47:38Z | [
"python"
] |
Why can generator expressions be iterated over only once? | 39,318,106 | <p>This program:</p>
<pre><code>def pp(seq):
print(''.join(str(x) for x in seq))
print(''.join(str(x) for x in seq))
print('---')
pp([0,1,2,3])
pp(range(4)) # range in Python3, xrange in Python2
pp(x for x in [0,1,2,3])
</code></pre>
<p>prints this:</p>
<pre><code>0123
0123
---
0123
0123
---
0123
---
... | 0 | 2016-09-04T14:43:58Z | 39,318,171 | <p>A generator <em>runs arbitrary code</em>, and returns a lazy sequence with the items yielded by that code.</p>
<ul>
<li>That code could be providing an infinite sequence.</li>
<li>That code could be reading contents off a network connection.</li>
<li>That code could be modifying external variables every time it ite... | 3 | 2016-09-04T14:51:03Z | [
"python"
] |
np.cast in numpy results in incorrect result | 39,318,232 | <p>This use of np.cast: </p>
<pre><code>np.cast['f'](np.pi)
</code></pre>
<p>results in an incorrect value for pi:</p>
<pre><code>array(3.1415927410125732, dtype=float32)
</code></pre>
<p>why did this happen?</p>
| 0 | 2016-09-04T14:57:12Z | 39,318,332 | <p>Real pi value up to a few digits more than <code>float32</code> precision (from <a href="http://www.geom.uiuc.edu/~huberty/math5337/groupe/digits.html" rel="nofollow">here</a>)</p>
<pre><code>`3.14159265358979323846264338327950288...`
</code></pre>
<p><code>float32</code> precision has an accuracy from 6 to 9 dec... | 3 | 2016-09-04T15:07:41Z | [
"python",
"numpy"
] |
Serialize two nested schema with marshmallow | 39,318,251 | <p>I am fairly new to python. I have two SQLAlchemy models as follows:</p>
<pre><code>class listing(db.Model):
id = db.Integer(primary_key=True)
title = db.String()
location_id = db.Column(db.Integer, db.ForeignKey('location.id'))
location = db.relationship('Location', lazy='joined')
class location(db.Model):
id... | 1 | 2016-09-04T14:59:27Z | 39,758,980 | <p>The right is to use the class that you created NestedSchema and not nested_schema, do this:</p>
<pre><code>result,errors = NestedSchema().dump({'listing':listing,'location':location})
</code></pre>
<p>And the result wiil be:</p>
<pre><code>dict: {
u'listing': {u'id': 8, u'title': u'foo'},
u'location... | 2 | 2016-09-28T23:08:01Z | [
"python",
"flask-sqlalchemy",
"marshmallow"
] |
lua cjson cannot decode specific unicode char? | 39,318,257 | <p>I'm getting the following error from lua cjson when trying to decode a specific unicode char,</p>
<pre><code>root@9dc8433e6d83:~/torch-rnn# th train.lua -input_h5 data/aud.h5 -input_json data/aud.json -batch_size 50 -seq_length 100 -rnn_size 256 -max_epochs 50
Running with CUDA on GPU 0
/root/torch/install/bin/lu... | 1 | 2016-09-04T15:00:03Z | 39,320,587 | <p>It seems the problem was unicode surrogates, understanding that means I can filter/switch them for different values. In this use case, thats not such a big problem.</p>
| 0 | 2016-09-04T19:17:01Z | [
"python",
"unicode",
"utf-8",
"lua",
"torch"
] |
Find index of first occurrence in sorted list | 39,318,277 | <p>I have a sorted list that looks like this:</p>
<pre><code>sortedlist = ['0','0','0','1','1,'1,'2',2','3']
</code></pre>
<p>I also have a count variable:</p>
<pre><code>count = '1'
</code></pre>
<p>*note: sometimes count can be an integar greater that the max value in the list. For example <code>count = '4'</code... | 0 | 2016-09-04T15:01:37Z | 39,318,395 | <p>As your list is already sorted, so the maximum value will be the last element of your list i.e <code>maxval = sortedlist[-1]</code> . secondly there is an error in your for loop. <code>for i in sortedlist:</code> This gives you each element in the list . To get index do a for loop on range <code>len(sortedlist)</cod... | 0 | 2016-09-04T15:13:58Z | [
"python",
"list",
"for-loop"
] |
Find index of first occurrence in sorted list | 39,318,277 | <p>I have a sorted list that looks like this:</p>
<pre><code>sortedlist = ['0','0','0','1','1,'1,'2',2','3']
</code></pre>
<p>I also have a count variable:</p>
<pre><code>count = '1'
</code></pre>
<p>*note: sometimes count can be an integar greater that the max value in the list. For example <code>count = '4'</code... | 0 | 2016-09-04T15:01:37Z | 39,318,397 | <p>You could use a function (using <a href="https://docs.python.org/3/glossary.html#term-eafp" rel="nofollow">EAFP</a> principle) to find the first occurrence that is equal to or greater than the count:</p>
<pre><code>In [239]: l = ['0','0','0','1','1','1','2','2','3']
In [240]: def get_index(count, sorted_list):
... | 1 | 2016-09-04T15:14:04Z | [
"python",
"list",
"for-loop"
] |
Find index of first occurrence in sorted list | 39,318,277 | <p>I have a sorted list that looks like this:</p>
<pre><code>sortedlist = ['0','0','0','1','1,'1,'2',2','3']
</code></pre>
<p>I also have a count variable:</p>
<pre><code>count = '1'
</code></pre>
<p>*note: sometimes count can be an integar greater that the max value in the list. For example <code>count = '4'</code... | 0 | 2016-09-04T15:01:37Z | 39,318,462 | <p>Your logic is wrong, you have a so called <em>sorted list</em> of strings which unless you compared as integer would not be sorted correctly, you should use <em>integers</em> from the get-go and <a href="https://docs.python.org/2/library/bisect.html#bisect.bisect_left" rel="nofollow">bisect_left</a> to find index:</... | 2 | 2016-09-04T15:20:45Z | [
"python",
"list",
"for-loop"
] |
Find index of first occurrence in sorted list | 39,318,277 | <p>I have a sorted list that looks like this:</p>
<pre><code>sortedlist = ['0','0','0','1','1,'1,'2',2','3']
</code></pre>
<p>I also have a count variable:</p>
<pre><code>count = '1'
</code></pre>
<p>*note: sometimes count can be an integar greater that the max value in the list. For example <code>count = '4'</code... | 0 | 2016-09-04T15:01:37Z | 39,318,522 | <p>Using <code>itertools.dropwhile()</code>:</p>
<pre class="lang-py prettyprint-override"><code>from itertools import dropwhile
sortedlist = [0, 0, 0, 1, 1, 1, 2, 2, 3]
def getindex(count):
index = len(sortedlist) - len(list(dropwhile(lambda x: x < count, sortedlist)))
return "some_string" if index >=... | 0 | 2016-09-04T15:27:18Z | [
"python",
"list",
"for-loop"
] |
Find index of first occurrence in sorted list | 39,318,277 | <p>I have a sorted list that looks like this:</p>
<pre><code>sortedlist = ['0','0','0','1','1,'1,'2',2','3']
</code></pre>
<p>I also have a count variable:</p>
<pre><code>count = '1'
</code></pre>
<p>*note: sometimes count can be an integar greater that the max value in the list. For example <code>count = '4'</code... | 0 | 2016-09-04T15:01:37Z | 39,318,704 | <p>As there are some over-complicated solutions here it's worth posting how straightforwardly this can be done:</p>
<pre><code>def get_index(a, L):
for i, b in enumerate(L):
if b >= a:
return i
return "over"
get_index('1', ['0','0','2','2','3'])
>>> 2
get_index('1', ['0','0','0... | 2 | 2016-09-04T15:46:30Z | [
"python",
"list",
"for-loop"
] |
Find index of first occurrence in sorted list | 39,318,277 | <p>I have a sorted list that looks like this:</p>
<pre><code>sortedlist = ['0','0','0','1','1,'1,'2',2','3']
</code></pre>
<p>I also have a count variable:</p>
<pre><code>count = '1'
</code></pre>
<p>*note: sometimes count can be an integar greater that the max value in the list. For example <code>count = '4'</code... | 0 | 2016-09-04T15:01:37Z | 39,319,025 | <p>First of all:</p>
<pre><code>for i in range(1, 100):
if i >= 3:
break
destroyTheInterwebz()
print i
</code></pre>
<p>Will <em>never</em> execute that last function. It will onmy peint <code>1</code> and <code>2</code>. Because <code>break</code> <em>immediately</em> leaves the loop; it does <em>not<... | 0 | 2016-09-04T16:22:35Z | [
"python",
"list",
"for-loop"
] |
Django archive via crontab in production | 39,318,363 | <p>I'm having trouble getting crontab to execute a site backup, using django-archive.</p>
<p>crontab file:</p>
<pre><code>0 5 * * * python ~/SBGBook/gbsite/manage.py archive
</code></pre>
<p>Error:</p>
<pre><code> Traceback (most recent call last):
File "/home/jgates/SBGBook/gbsite/manage.py", line 17, in <... | 0 | 2016-09-04T15:10:27Z | 39,318,639 | <p>Try to use the python interpreter from your virtualenv :</p>
<pre><code>0 5 * * * /path/to/virtualenv/bin/python ~/SBGBook/gbsite/manage.py archive
</code></pre>
| 1 | 2016-09-04T15:39:14Z | [
"python",
"django",
"crontab",
"dev-to-production"
] |
converting a flat list to a nested dictionary based on items from the list | 39,318,366 | <p>For example, I have a flat list like this:</p>
<pre><code>[' a',
' aa1',
' aaa1',
' aaa2',
' aaa3',
' aaa4',
' aaa5',
' aa2',
' aaa6',
' aaa7',
' aaa8',
' aaa9',
' aaa10',
' b',
' bb1',
' bbb1',
' bbb2',
' bbb3',
' bb2',
' bbb4',
' bbb5',
' bbb6',
' bb3',
' bbb7',
' bbb8',
'... | 2 | 2016-09-04T15:10:41Z | 39,318,871 | <p>I think the spaces only make the list awkward, you don't necessarily need them to achieve what you want.</p>
<p>First, <code>strip</code> all the spaces from the list items, then build the dictionary starting off from <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow... | 2 | 2016-09-04T16:04:19Z | [
"python",
"list",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.