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
pip install jupyter: "Unable to locate finder for 'pip._vendor.distlib'"
39,552,710
<p>I'm trying to install <code>jupyter</code> to use the IPython Notebook under Windows. However, if I run <code>pip install jupyter</code> I'm getting</p> <pre><code> Using cached pyzmq-15.4.0.zip Requirement already satisfied (use --upgrade to upgrade): wcwidth in c:\users\stefan\appdata\local\programs\python\pytho...
0
2016-09-17T23:34:45Z
39,908,861
<p>Try uninstalling pip and installing get-pip.py. It appears to be a bug in the 3.6 version for Windows. <a href="https://github.com/pypa/pip/issues/3964" rel="nofollow">https://github.com/pypa/pip/issues/3964</a></p>
1
2016-10-07T03:22:56Z
[ "python", "pip", "jupyter" ]
pip install jupyter: "Unable to locate finder for 'pip._vendor.distlib'"
39,552,710
<p>I'm trying to install <code>jupyter</code> to use the IPython Notebook under Windows. However, if I run <code>pip install jupyter</code> I'm getting</p> <pre><code> Using cached pyzmq-15.4.0.zip Requirement already satisfied (use --upgrade to upgrade): wcwidth in c:\users\stefan\appdata\local\programs\python\pytho...
0
2016-09-17T23:34:45Z
40,142,402
<p>uninstall current pip by typing:</p> <pre><code>python -m pip uninstall pip setuptools </code></pre> <p>download get-pip.py from <a href="https://bootstrap.pypa.io/get-pip.py" rel="nofollow">https://bootstrap.pypa.io/get-pip.py</a> and run it:</p> <pre><code>python get-pip.py </code></pre>
1
2016-10-19T22:15:41Z
[ "python", "pip", "jupyter" ]
How to take input as operation
39,552,718
<p>I'm trying to make a calculator but little bit different. I'm thinking if a get input as operation like:</p> <pre><code>first_number = input('Type first number: ') first_operation = input('Type your operation (+, -, *, /): ') second_number = input('Type second number: ') first_answer = input('Do you wanna stop here...
-1
2016-09-17T23:36:04Z
39,552,865
<p>Grab the operations from the <a href="https://docs.python.org/3/library/operator.html" rel="nofollow"><code>operator</code></a> module and create a dictionary of the available operators:</p> <pre><code>&gt;&gt;&gt; from operator import add, sub, mul, truediv &gt;&gt;&gt; ops = {'+': add, '-': sub, '*': mul, '/': tr...
0
2016-09-18T00:02:15Z
[ "python", "python-3.x" ]
How to edit many objects at the same time in django?
39,552,720
<p>Well, usually, when I like edit one object I using instance and get_object_or_404, something like this:</p> <pre><code>question = get_object_or_404(Question, id = id) form = FormQuestion(request.POST, instance=question) if request.method == 'POST': if form.is_valid(): form.save() return redirec...
0
2016-09-17T23:36:41Z
39,712,293
<p>First place, is much better you develop in CBV(Class Based Views), where you will do the view more easily.</p> <p>I had a problem around your problem, follow how do it: <a href="http://stackoverflow.com/questions/39534543/django-inlineformset-factory-how-to-edit">Django - inlineformset-factory (How to Edit)</a> And...
0
2016-09-26T20:59:51Z
[ "python", "django", "edit" ]
How to use python to interpret a url
39,552,767
<p>I'm writing code that is attempting to extract the text from the <a href="https://libraryofbabel.info" rel="nofollow">Library of Babel</a>.</p> <p>They basically use a system of Hexes, Walls, Shelfs, Volumes and Pages to split up their library of randomly generated text files. Here is an example (<a href="https://l...
0
2016-09-17T23:44:55Z
39,552,868
<p>Put on you glasses :<br> You are requesting <code>browse.cgi</code> instead of <code>book.cgi</code><br><br> <a href="https://libraryofbabel.info/browse.cgi?2-w2-s1-v10:72" rel="nofollow">https://libraryofbabel.info/browse.cgi?2-w2-s1-v10:72</a><br> instead of<br> <a href="https://libraryofbabel.info/book.cgi?2-w2-s...
3
2016-09-18T00:04:17Z
[ "python", "beautifulsoup" ]
Apply Numpy function over entire Dataframe
39,552,773
<p>I am applying this function over a dataframe <code>df1</code> such as the following:</p> <pre><code> AA AB AC AD 2005-01-02 23:55:00 "EQUITY" "EQUITY" "EQUITY" "EQUITY" 2005-01-03 00:00:00 32.32 19.5299 32.32 31.04...
0
2016-09-17T23:45:46Z
39,552,922
<p>You need to do it the following way :</p> <pre><code>def func(row): return row/np.sum(row) df2 = pd.concat([df[:1], df[1:].apply(func, axis=1)], axis=0) </code></pre> <p>It has 2 steps :</p> <ol> <li><code>df[:1]</code> extracts the first row, which contains strings, while <code>df[1:]</code> represents the r...
2
2016-09-18T00:14:38Z
[ "python", "pandas", "numpy", "dataframe" ]
Override settings from another Django app
39,552,784
<p>How can I in my project settings.py override a setting from an apps settings.py?</p> <p>I tried importing it like this:</p> <pre><code>import app.settings EXTENSIONS = { 'Folder': [''], 'Image': ['.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff', '.svg'], } </code></pre> <p><strong>But I get an error:</str...
1
2016-09-17T23:47:14Z
39,553,591
<p>I think what you're looking for is:</p> <pre><code>from app.settings import * </code></pre> <p>The goal is to import the settings into the module namespace.</p>
-1
2016-09-18T02:52:56Z
[ "python", "django" ]
Override settings from another Django app
39,552,784
<p>How can I in my project settings.py override a setting from an apps settings.py?</p> <p>I tried importing it like this:</p> <pre><code>import app.settings EXTENSIONS = { 'Folder': [''], 'Image': ['.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff', '.svg'], } </code></pre> <p><strong>But I get an error:</str...
1
2016-09-17T23:47:14Z
39,560,722
<p>Your SECRET_KEY is empty or missing in settings.py file.</p> <p>Add random generated SECRET_KEY to settings file.</p> <p>For example:</p> <pre><code># SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '=6x$7smkllimrwa@j+d7(tr%i=3cax!bz+0vyje%$!gj+*dvd4' </code></pre>
0
2016-09-18T17:38:55Z
[ "python", "django" ]
SQLAlchemy load_only on parent model
39,552,809
<p>When eager loading a child relationship, how can I only load few columns of the parent model:</p> <p>This works if I only need <code>title</code> column of the <code>chapters</code> model:</p> <pre><code>session.query(Book)\ .options(joinedload('chapters').load_only('title')) </code></pre> <p>But this throws ...
1
2016-09-17T23:52:30Z
39,553,869
<p>The error message says you're only selecting <code>Book.author</code>, instead of instances of <code>Book</code>. Where is <code>chapters</code> going to go if all it's returning is a list of strings (for <code>author</code>).</p> <p>You can either do:</p> <pre><code>session.query(Book.author, Chapter.title).selec...
2
2016-09-18T03:45:41Z
[ "python", "sql", "orm", "sqlalchemy" ]
How to read a python tuple using PyYAML?
39,553,008
<p>I have the following YAML file named <code>input.yaml</code>:</p> <pre class="lang-yaml prettyprint-override"><code>cities: 1: [0,0] 2: [4,0] 3: [0,4] 4: [4,4] 5: [2,2] 6: [6,2] highways: - [1,2] - [1,3] - [1,5] - [2,4] - [3,4] - [5,4] start: 1 end: 4 </code></pre> <p>I'm loading it using P...
1
2016-09-18T00:32:36Z
39,553,138
<p>I wouldn't call what you've done hacky for what you are trying to do. Your alternative approach from my understanding is to make use of python-specific tags in your YAML file so it is represented appropriately when loading the yaml file. However, this requires you modifying your yaml file which, if huge, is probably...
2
2016-09-18T01:05:26Z
[ "python", "yaml", "pyyaml" ]
How to read a python tuple using PyYAML?
39,553,008
<p>I have the following YAML file named <code>input.yaml</code>:</p> <pre class="lang-yaml prettyprint-override"><code>cities: 1: [0,0] 2: [4,0] 3: [0,4] 4: [4,4] 5: [2,2] 6: [6,2] highways: - [1,2] - [1,3] - [1,5] - [2,4] - [3,4] - [5,4] start: 1 end: 4 </code></pre> <p>I'm loading it using P...
1
2016-09-18T00:32:36Z
39,554,610
<p>Depending on where your YAML input comes from your "hack" is a good solution, especially if you would use <code>yaml.safe_load()</code> instead of the unsafe <code>yaml.load()</code>. If only the "leaf" sequences in your YAML file need to be tuples you can do ¹:</p> <pre><code>import pprint import ruamel.yaml from...
1
2016-09-18T05:57:44Z
[ "python", "yaml", "pyyaml" ]
giving index to QLineEdit
39,553,013
<p>i want to give index for QLineEdit's.</p> <p>i have this code.</p> <pre><code> from PyQt4 import QtGui, QtCore import sys class Main(QtGui.QMainWindow): def __init__(self, parent = None): super(Main, self).__init__(parent) # main button self.addButton = QtGui.QPushButton('button to...
0
2016-09-18T00:34:00Z
39,556,238
<p>You can set a list in Main class, like this ['aaa', 'bbb', 'ccc'], and set a var = 0.</p> <pre><code>class Main(QtGui.QMainWindow): def __init__(self, parent = None): super(Main, self).__init__(parent) # self.lineText = ['aaa', 'bbb', 'ccc'] self.var = 0 ... def add...
0
2016-09-18T09:42:29Z
[ "python", "qt", "pyqt", "pyqt4" ]
why two points can't show in the figure (matplotlib)?
39,553,030
<p>Figure1 show data points<a href="http://i.stack.imgur.com/j7b9r.png" rel="nofollow">1</a></p> <p><a href="http://i.stack.imgur.com/j7b9r.png" rel="nofollow">1</a>:<a href="http://i.stack.imgur.com/j7b9r.png" rel="nofollow"><img src="http://i.stack.imgur.com/j7b9r.png" alt="enter image description here"></a></p> <p...
2
2016-09-18T00:38:40Z
39,554,821
<p>With the help of Andras Deak, I use <code>plt.ylim([0, max(r)+1])</code>to solve this problem.Thanks.</p>
0
2016-09-18T06:28:45Z
[ "python", "matplotlib" ]
I can load multiple stock tickers from yahoo finance, but I am having trouble adding new columns before it is saved to a csv
39,553,271
<p>The code below starts by uploading data from yahoo finance in pnls. It does this successufly. Then I have code where I want to add columns to the loaded data in pnls. This part is unsuccessful. Finally I want to save pnls to a csv file which it does successfully if the column changes are not in the code.</p> <p>The...
1
2016-09-18T01:34:11Z
39,561,996
<p>The line</p> <pre><code>pnls = {i:dreader.DataReader(i,'yahoo','1985-01-01',datetime.today()) for i in symbols} </code></pre> <p>builds a python <code>dict</code> (using <a href="http://stackoverflow.com/questions/14507591/python-dictionary-comprehension">dictionary comprehension</a>). To check this, you can run t...
1
2016-09-18T19:50:28Z
[ "python", "csv", "pandas", "dataframe" ]
Representing time sequence input/output in tensorflow
39,553,292
<p>I've been working through the TensorFlow documentation (still learning), and I can't figure out how to represent input/output sequence data. My inputs are a sequences of 20 8-entry vectors, making a 8x20xN matrix, where N is the number of instances. I'd like to eventually pass these through an LSTM for sequence to...
0
2016-09-18T01:39:54Z
39,556,093
<p>As described in the excellent blog post by <a href="http://www.wildml.com/2016/08/rnns-in-tensorflow-a-practical-guide-and-undocumented-features/" rel="nofollow">WildML</a>, the proper way is to save your example in a TFRecord using the formate <code>tf.SequenceExample()</code>. Using TFRecords for this provides the...
1
2016-09-18T09:27:28Z
[ "python", "tensorflow" ]
sorting list of a sentence and number
39,553,334
<p>I have checked several of the answers on how to sort lists in python, but I can't figure this one out.</p> <p>Let's say I have a list like this: ['Today is a good day,1', 'yesterday was a strange day,2', 'feeling hopeful,3']</p> <p>Is there a way to sort by the number after each sentence? </p> <p>I am trying to l...
0
2016-09-18T01:52:13Z
39,553,358
<p>This worked for me:</p> <pre><code>sorted(myList, key=lambda x: x[-1]) </code></pre> <p>If you need to go into double digits:</p> <pre><code>sorted(myList, key=lambda x: int(x.split(',')[1])) </code></pre>
0
2016-09-18T01:58:36Z
[ "python", "python-3.x" ]
sorting list of a sentence and number
39,553,334
<p>I have checked several of the answers on how to sort lists in python, but I can't figure this one out.</p> <p>Let's say I have a list like this: ['Today is a good day,1', 'yesterday was a strange day,2', 'feeling hopeful,3']</p> <p>Is there a way to sort by the number after each sentence? </p> <p>I am trying to l...
0
2016-09-18T01:52:13Z
39,553,370
<p>You can do this</p> <pre><code>&gt;&gt;&gt; sorted(l, key=lambda x : int(x.split(',')[-1])) ['Today is a good day,1', 'yesterday was a strange day,2', 'feeling hopeful,3'] &gt;&gt;&gt; </code></pre> <p>This would also work if you happen to have numbers in your string that have more than one digit</p> <pre><code>...
2
2016-09-18T02:01:07Z
[ "python", "python-3.x" ]
sorting list of a sentence and number
39,553,334
<p>I have checked several of the answers on how to sort lists in python, but I can't figure this one out.</p> <p>Let's say I have a list like this: ['Today is a good day,1', 'yesterday was a strange day,2', 'feeling hopeful,3']</p> <p>Is there a way to sort by the number after each sentence? </p> <p>I am trying to l...
0
2016-09-18T01:52:13Z
39,553,511
<p>Since no one has commented on your coding attempts so far:</p> <pre><code>def sortMyList(string): return len(string)-1 sortedList = sorted(MyList, key=sortMyList()) </code></pre> <p>You are on your way, but there are a few issues. First, the <code>key</code> argument expects a function. That function should b...
3
2016-09-18T02:34:48Z
[ "python", "python-3.x" ]
How to update drawing area in GTK
39,553,371
<p>I'm trying to make a clock using GTK in python 2. The version I have at this point is just a basic one, it will be much more complicated, however I need to make it refresh first. In the end it will be a screensaver, hopefully.</p> <p>I have tried to understand how queue_draw() works, but I can't figure it out. I'm ...
2
2016-09-18T02:01:15Z
39,554,199
<p>You can use <code>glib.timeout_add_seconds(...)</code> to setup a timer to call <code>queue_draw()</code> every second:</p> <pre><code>import glib </code></pre> <p>Add a function to refresh the clock:</p> <pre><code>def refresh_clock(self): self.drawing_area.queue_draw() return True </code></pre> <p>Upda...
3
2016-09-18T04:44:38Z
[ "python", "python-2.7", "gtk" ]
text to columns with comma delimiter using python
39,553,392
<p>how to divide a column in to two columns in an excel using a delimiter ', 'and name the header's using python</p> <p>here is my code</p> <pre><code>import openpyxl w=openpyxl.load_workbook('DDdata.xlsx') active=w.active a=active.columns[1] for cellobj in a: s=cellobj.value fila=s.split(',') print...
0
2016-09-18T02:06:10Z
39,561,076
<p>This looks to be a duplicate of <a href="http://stackoverflow.com/questions/14745022/pandas-dataframe-how-do-i-split-a-column-into-two">this post</a>, but here's a solution for you to consider:</p> <pre><code>import pandas as pd df = pd.read_excel('input.xlsx') df['First Name'], df['Last Name'] = df['Applicant Na...
0
2016-09-18T18:17:50Z
[ "python", "python-3.x", "pandas", "openpyxl" ]
Python to exe win32crypt CryptProtectData error
39,553,474
<p>I wrote code which is using win32crypt. When I'm running in Python IDLE there is no problem. I get all data that I need. But when i'm converted to .exe and executed it I didn't get any result. I get this error</p> <blockquote> <p>Traceback (most recent call last): File "chromeHack.py", line 22, in pywintype...
-1
2016-09-18T02:26:41Z
39,934,506
<p>You have to run in system command(windows?cmd:shell) to test the code before changing the code to exe.</p> <p>The result told you that you have a wrong returned value after using the win32crypt.CryptUnprotectData.</p> <p>the correct usage: <a href="http://timgolden.me.uk/pywin32-docs/win32crypt__CryptUnprotectData...
0
2016-10-08T16:08:21Z
[ "python", "winapi" ]
Dynamically update label text in kivy program (Python)
39,553,559
<p>New to the kivy library and having some trouble dynamically updating a property. The label here is just a place-holder. Ultimately I want the displayed image to change sequentially based on which quadrant the user clicks/touches.</p> <p>The program runs fine with no errors, hover the label (label2) does not updat...
0
2016-09-18T02:46:29Z
39,555,298
<p>Use a numeric property, so kivy can track its changes.</p> <pre><code>from kivy.properties import NumericProperty ... class TouchInput(Widget): incr = NumericProperty(5) ... </code></pre>
1
2016-09-18T07:47:26Z
[ "python", "dynamic", "kivy" ]
Python - object has no attribute Error
39,553,578
<p><strong>I re-wrote the entire class from scratch in a separate file and everything magically worked, conditionals and all. So, I simply imported that class and a couple functions from the new file into the master file. I still have no idea what went wrong the first time around.</strong></p> <p><strong>Note the issu...
-1
2016-09-18T02:50:39Z
39,553,785
<p>Your code does:</p> <ol> <li>Set the value of <code>.name =</code> inside <code>__init__()</code></li> <li>That goes through the setter, and sets <code>.__name =</code></li> <li>When you read it by <code>.name</code> that reads through the getter, and reads <code>.__name</code></li> </ol> <p>And your description o...
2
2016-09-18T03:30:27Z
[ "python", "object", "attributes", "field" ]
Python - object has no attribute Error
39,553,578
<p><strong>I re-wrote the entire class from scratch in a separate file and everything magically worked, conditionals and all. So, I simply imported that class and a couple functions from the new file into the master file. I still have no idea what went wrong the first time around.</strong></p> <p><strong>Note the issu...
-1
2016-09-18T02:50:39Z
39,553,854
<p>The exception <em>can</em> be caused if your class does not define an attribute <code>__health</code> in its <code>__init__()</code> method. Trying to read its value will trigger the problem. The attribute will be created by calling the setter method (indirectly through attribute assignment), and after that the attr...
0
2016-09-18T03:42:46Z
[ "python", "object", "attributes", "field" ]
How can I avoid JSON percent-encoding and \u-escaping?
39,553,703
<p>When I parse the file</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;meta charset="UTF-8"&gt;&lt;/head&gt; &lt;body&gt;&lt;a href="Düsseldorf.html"&gt;Düsseldorf&lt;/a&gt;&lt;/body&gt; &lt;/html&gt; </code></pre> <p>using</p> <pre><code>item = SimpleItem() item['name'] = response.xpath('//a/text()')[0].ext...
0
2016-09-18T03:15:09Z
39,554,214
<pre><code>&gt;&gt;&gt; a = [{ "name": "D\u00fcsseldorf", "url": "D\u00fcsseldorf.html" }] &gt;&gt;&gt; a [{'url': 'Düsseldorf.html', 'name': 'Düsseldorf'}] &gt;&gt;&gt; json.dumps(a, ensure_ascii=False) '[{"url": "Düsseldorf.html", "name": "Düsseldorf"}]' </code></pre>
2
2016-09-18T04:46:24Z
[ "python", "json", "unicode", "scrapy" ]
How can I avoid JSON percent-encoding and \u-escaping?
39,553,703
<p>When I parse the file</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;meta charset="UTF-8"&gt;&lt;/head&gt; &lt;body&gt;&lt;a href="Düsseldorf.html"&gt;Düsseldorf&lt;/a&gt;&lt;/body&gt; &lt;/html&gt; </code></pre> <p>using</p> <pre><code>item = SimpleItem() item['name'] = response.xpath('//a/text()')[0].ext...
0
2016-09-18T03:15:09Z
39,570,495
<p>this seems to work for me</p> <pre><code># -*- coding: utf-8 -*- import scrapy import urllib class SimpleItem(scrapy.Item): name = scrapy.Field() url = scrapy.Field() class CitiesSpider(scrapy.Spider): name = "cities" allowed_domains = ["sitercity.info"] start_urls = ( 'http://en.siste...
1
2016-09-19T10:07:10Z
[ "python", "json", "unicode", "scrapy" ]
How do you specifiy a Neumann (fixed flux normal to face) boundary condition in Fipy?
39,553,706
<p>How do I explicitly set the flux normal to a boundary face in a fipy mesh to be a specific value, without constraining components of flux within the face?</p> <p>A Neumann boundary condition can be specified as: (1) fixed component of flux normal to a boundary face, or (2) as a complete specification of flux at the...
1
2016-09-18T03:15:23Z
39,575,670
<p>Please see the discussion on <a href="http://www.ctcms.nist.gov/fipy/documentation/USAGE.html#applying-fixed-flux-boundary-conditions" rel="nofollow">fixed flux boundary conditions</a>. Basically, you add a source containing the the divergence of the desired boundary flux to FiPy's default no-flux condition.</p>
2
2016-09-19T14:29:30Z
[ "python", "mesh", "pde", "fipy" ]
How do you specifiy a Neumann (fixed flux normal to face) boundary condition in Fipy?
39,553,706
<p>How do I explicitly set the flux normal to a boundary face in a fipy mesh to be a specific value, without constraining components of flux within the face?</p> <p>A Neumann boundary condition can be specified as: (1) fixed component of flux normal to a boundary face, or (2) as a complete specification of flux at the...
1
2016-09-18T03:15:23Z
39,578,205
<p>In terms of just specifying the flux normal to a boundary for a variable independent of solving an equation, there does not appear to be any way to do that. The syntax might be <code>phi.faceGrad[0].constrain(...)</code> for example, but that currently doesn't work in FiPy. It might also be difficult to implement fo...
2
2016-09-19T16:49:12Z
[ "python", "mesh", "pde", "fipy" ]
How do you specifiy a Neumann (fixed flux normal to face) boundary condition in Fipy?
39,553,706
<p>How do I explicitly set the flux normal to a boundary face in a fipy mesh to be a specific value, without constraining components of flux within the face?</p> <p>A Neumann boundary condition can be specified as: (1) fixed component of flux normal to a boundary face, or (2) as a complete specification of flux at the...
1
2016-09-18T03:15:23Z
39,713,838
<p>The discussion on fixed flux boundary conditions does answer my question, but I had not understood the documentation, which is very brief. Below is a worked example that illustrates how to apply this in a simple 2D case, similar to the mesh20x20 example.</p> <pre><code>import matplotlib.pyplot as plt from fipy impo...
0
2016-09-26T23:24:40Z
[ "python", "mesh", "pde", "fipy" ]
how to simplify a try, if except code in python for repetitive input?
39,553,737
<p>I used multiple if elif, also there are repetitive try, if, except command to eliminate negative, non-integer, non-number input, can I have a command that eliminate those ones altogether? Thanks! The code is as the following:</p> <pre><code>print("Welcome to Supermarket") print("1. Potatoes($0.75 per potato)") prin...
1
2016-09-18T03:20:22Z
39,553,803
<p>Extract the common validation code into it's own function:</p> <pre><code>def validate_input(input_message): """Validate that input is a positive integer""" amount = int(input(input_message)) if amount &lt; 0: raise ValueError("positive number required") return amount </code></pre> <p>Then ...
0
2016-09-18T03:32:54Z
[ "python", "python-3.x" ]
how to simplify a try, if except code in python for repetitive input?
39,553,737
<p>I used multiple if elif, also there are repetitive try, if, except command to eliminate negative, non-integer, non-number input, can I have a command that eliminate those ones altogether? Thanks! The code is as the following:</p> <pre><code>print("Welcome to Supermarket") print("1. Potatoes($0.75 per potato)") prin...
1
2016-09-18T03:20:22Z
39,553,845
<p>I would suggest to do a function that validates that the input is an integer and greater than zero. Something like :</p> <pre><code>def validateInt(value): value = int(value) #try to cast the value as an integer if value &lt; 0: raise ValueError </code></pre> <p>In your code you can now use it a...
0
2016-09-18T03:41:19Z
[ "python", "python-3.x" ]
How to access property cross class and cross file in Python?
39,553,792
<p>Now I need a property which in another class to do something in one class.</p> <p>just like:</p> <pre><code>a.py class A: def __init__(self, io_loop): # the same io_loop instance self.access = None self.w_id = None self.io_loop = io_loop @gen.coroutine def setup(self)...
1
2016-09-18T03:31:01Z
39,554,355
<p>You can't access that variable until you create an instance that initializes. Otherwise, <code>w_id</code> doesn't exist in <code>A</code>.</p> <p>If you want to give <code>w_id</code> an arbitrary value for access from other classes, put it as a class variable, means you write directly <code>w_id = 'some value'</c...
0
2016-09-18T05:15:00Z
[ "python", "tornado" ]
Vim double-indents python files
39,553,825
<p>I get the following behavior. Given this <code>settings.py</code> snippet, hitting 'o' from line 33</p> <pre><code>31# Application definition 32 33 INSTALLED_APPS = [ 34 'rest_framework', </code></pre> <p>I get this</p> <pre><code>31# Application definition 32 33 INSTALLED_APPS = [ 34 |&lt;-cursor i...
2
2016-09-18T03:37:28Z
39,554,322
<p>This happens because of default vim indentation plugin for Python. It inserts 2 <code>shiftwidth</code> on the first line below <code>[</code>.</p> <p>You can see code which causes this behaviour here: <a href="https://github.com/vim/vim/blob/0b9e4d1224522791c0dbbd45742cbd688be823f3/runtime/indent/python.vim#L74" r...
3
2016-09-18T05:07:04Z
[ "python", "vim" ]
inserting values into numpy array
39,553,837
<p>I am new to python and numpy, coming from a java background.</p> <p>I want to insert int values into a an array. However my current way of doing it is not resulting in the proper values. I create an array 'a' of size 5, and would like to insert int values into 'a'. </p> <pre><code>data = ocr['data'] test_data = ...
1
2016-09-18T03:39:59Z
39,553,939
<p>When you initialize a numpy array by <code>np.empty()</code>, it allocates enough space for you, but the values inside these supposedly empty cells will be random rubbish. E.g.</p> <pre><code>&gt;&gt;&gt; a = np.empty(5,dtype = int) &gt;&gt;&gt; a array([-2305843009213693952, -2305843009213693952, 4336320...
3
2016-09-18T03:57:14Z
[ "python", "arrays", "numpy" ]
Use apply() with Pandas Series
39,553,866
<p>I have the code below:</p> <pre><code>import pandas as pd frame = pd.DataFrame(np.random.randn(4,3), columns=list('bde'),index=['Utah','Ohio','Texas','Oregon']) frame b d e Utah 0.479210 0.161892 -1.315375 Ohio -0.572543 0.080203 -0.446178 Texas 0.052954 0.043417 0.365056 Oregon 1.46...
2
2016-09-18T03:45:21Z
39,553,927
<p>The problem is <code>.apply</code> on a Series works <em>elementwise</em>, in a <code>DataFrame</code> it works <em>by series</em> or <em>by row</em>. If you really want to use <code>.apply</code> this way, you can subset like this:</p> <pre><code>In [9]: frame.loc[:,['d']] Out[9]: d Utah 2.25948...
1
2016-09-18T03:54:58Z
[ "python", "pandas", "lambda" ]
syntax error near unexpected token while use subprocess
39,553,923
<p>This design makes me cry,code below,please help</p> <pre><code>def runbatch(CMD,HOST): print CMD print HOST for host in HOST: env.host_string=host print CMD print env.host_string print "Execute command : \"%s\" at Host : %s" %(CMD,host) print "--------------------...
0
2016-09-18T03:54:30Z
39,558,590
<p><code>subprocess.Popen()</code> runs a bash command on your <strong>local machine</strong>. What <code>fabric</code> has to offer is a way to enter a command on <em>local machine</em> which got sent to and run on a <em>remote machine</em>. To this end, you need a <code>fabfile.py</code> (for now, you need to name it...
0
2016-09-18T14:15:36Z
[ "python", "subprocess", "fabric" ]
Python module returning True
39,554,009
<p>I'm writing Python for a kind of computer, and the login module always returns true, even if it's not in the <code>users</code> dictionary:</p> <pre><code>cur_user = "null" users = { "Splavacado100": "20310" } def login(): good_login = 0 user_name = raw_input("Enter your username: ") for user in us...
0
2016-09-18T04:10:52Z
39,554,045
<p>There is something wrong with your second method. I took it out and the first part works. I then took out the last else in the first method and seems to work. Try <a href="https://repl.it/DcBH" rel="nofollow">this</a></p> <pre><code>cur_user = "null" users = { "Splavacado100": "20310" } def login(): good_lo...
0
2016-09-18T04:18:35Z
[ "python", "python-2.7" ]
Python module returning True
39,554,009
<p>I'm writing Python for a kind of computer, and the login module always returns true, even if it's not in the <code>users</code> dictionary:</p> <pre><code>cur_user = "null" users = { "Splavacado100": "20310" } def login(): good_login = 0 user_name = raw_input("Enter your username: ") for user in us...
0
2016-09-18T04:10:52Z
39,554,051
<p>Instead of returning "None", return None (as "None" is always true as it is a non-zero value).</p>
3
2016-09-18T04:19:13Z
[ "python", "python-2.7" ]
Python module returning True
39,554,009
<p>I'm writing Python for a kind of computer, and the login module always returns true, even if it's not in the <code>users</code> dictionary:</p> <pre><code>cur_user = "null" users = { "Splavacado100": "20310" } def login(): good_login = 0 user_name = raw_input("Enter your username: ") for user in us...
0
2016-09-18T04:10:52Z
39,554,094
<p>I think your login function should look more like;</p> <pre><code>def login(): raw_user = raw_input("Enter your username: ") password = users.get(raw_user) if not password: return False raw_password = raw_input("Enter your password: ") if password == raw_password: return True ...
0
2016-09-18T04:27:02Z
[ "python", "python-2.7" ]
Django: Trouble with named URLs instead of ids
39,554,208
<p>So I'm making a study app that involves flash cards. A user can make subjects and put decks containing cards in them. So for example, in the Biology subject, there would be a Deck called "unit one" and in that deck would be full of cards. The URL for a deck would ideally look like</p> <pre><code>localhost:8000/subj...
1
2016-09-18T04:45:49Z
39,554,276
<p>Have you tried setting <a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.slug_url_kwarg" rel="nofollow"><code>SubjectView.slug_url_kwarg</code></a>?</p>
0
2016-09-18T04:59:11Z
[ "python", "django" ]
Django: Trouble with named URLs instead of ids
39,554,208
<p>So I'm making a study app that involves flash cards. A user can make subjects and put decks containing cards in them. So for example, in the Biology subject, there would be a Deck called "unit one" and in that deck would be full of cards. The URL for a deck would ideally look like</p> <pre><code>localhost:8000/subj...
1
2016-09-18T04:45:49Z
39,554,784
<p>Just an assumption. Try by change <code>Char</code> to <code>Slug</code></p> <pre><code>class Subject(models.Model): subject_name = models.SlugField(max_length=100) description = models.TextField() </code></pre> <p>Also </p> <pre><code>slug_field = "subject_name" </code></pre>
1
2016-09-18T06:24:11Z
[ "python", "django" ]
Python3 change string to byte
39,554,250
<p>I'm using Python3.5 and I want to change <code>\xe1BA\x06\xbe\x084</code> into <code>b'\xe1BA\x06\xbe\x084'</code></p> <p>But using <code>'\xe1BA\x06\xbe\x084'.encode('ascii')</code> or <code>'\xe1BA\x06\xbe\x084'.encode('utf-8')</code>doesn't work.</p> <p>In <code>.encode('utf-8')</code>, it will become<br> <code...
2
2016-09-18T04:53:56Z
39,554,398
<p>Use the <code>latin1</code> codec.</p> <pre><code>&gt;&gt;&gt; '\xe1BA\x06\xbe\x084'.encode('latin1') b'\xe1BA\x06\xbe\x084' </code></pre> <p>The reason why this works (and is the way it is) because originally those bytes sequences were defined to be those characters by the <a href="https://en.wikipedia.org/wiki/I...
4
2016-09-18T05:23:59Z
[ "python", "unicode", "utf-8" ]
Python3 change string to byte
39,554,250
<p>I'm using Python3.5 and I want to change <code>\xe1BA\x06\xbe\x084</code> into <code>b'\xe1BA\x06\xbe\x084'</code></p> <p>But using <code>'\xe1BA\x06\xbe\x084'.encode('ascii')</code> or <code>'\xe1BA\x06\xbe\x084'.encode('utf-8')</code>doesn't work.</p> <p>In <code>.encode('utf-8')</code>, it will become<br> <code...
2
2016-09-18T04:53:56Z
39,554,513
<p>You can try all kind of encodings to see if it match what you want.</p> <pre><code>s = '\xe1BA\x06\xbe\x084' code_list = ["ascii", "big5", "big5hkscs", "cp037", "cp424", "cp437", "cp500", "cp720", "cp737", "cp775", "cp850", "cp852", "cp855", "cp856", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863", "cp864",...
1
2016-09-18T05:42:14Z
[ "python", "unicode", "utf-8" ]
python 2.7 string reverse
39,554,258
<p>If I need to implement string reverse by myself in Python 2.7 other than using system library, wondering if any more efficient solutions? I tried my code runs slow for a very long string (e.g. a few thousand characters). Thanks.</p> <p>For string reverse I mean, for example, given s = "hello", return "olleh". </p> ...
0
2016-09-18T04:55:20Z
39,554,273
<p>Try recursion</p> <pre><code>def reverse(str): if str == "": return str else: return reverse(str[1:]) + str[0] </code></pre>
3
2016-09-18T04:58:10Z
[ "python", "python-2.7" ]
python 2.7 string reverse
39,554,258
<p>If I need to implement string reverse by myself in Python 2.7 other than using system library, wondering if any more efficient solutions? I tried my code runs slow for a very long string (e.g. a few thousand characters). Thanks.</p> <p>For string reverse I mean, for example, given s = "hello", return "olleh". </p> ...
0
2016-09-18T04:55:20Z
39,554,275
<p>Try this:</p> <pre><code>def reverseString(self, s): return s[::-1] </code></pre>
6
2016-09-18T04:59:09Z
[ "python", "python-2.7" ]
python 2.7 string reverse
39,554,258
<p>If I need to implement string reverse by myself in Python 2.7 other than using system library, wondering if any more efficient solutions? I tried my code runs slow for a very long string (e.g. a few thousand characters). Thanks.</p> <p>For string reverse I mean, for example, given s = "hello", return "olleh". </p> ...
0
2016-09-18T04:55:20Z
39,554,304
<h2>EDIT: Actually, I was mistaken</h2> <p>I did a rough-and-dirty test comparing the two functions and the complexity looks to be the same: linear</p> <p><a href="http://i.stack.imgur.com/sZttR.png" rel="nofollow"><img src="http://i.stack.imgur.com/sZttR.png" alt="enter image description here"></a></p> <p>It seems ...
2
2016-09-18T05:02:55Z
[ "python", "python-2.7" ]
why it is saying at i have declare kernel
39,554,292
<pre><code> import numpy as np from numpy.fft import fft2, ifft2 import cv2 from PIL import Image def wiener_filter(img,kernel,K = 10): kernel=([3,1],[2,1]) dummy = np.copy(img) kernel = np.pad(kernel, [(0, dummy.shape[0] - kernel.shape[0]), (0, dummy.shape[1] - kernel.shape[1...
1
2016-09-18T05:01:05Z
39,554,311
<p>There : </p> <pre><code>def wiener_filter(img,kernel,K = 10): kernel=([3,1],[2,1]) </code></pre> <p>You define a function that takes <code>kernel</code> as a parameter and you overwrite it directly.</p> <p>Then you try to use <code>kernel.shape</code> which obviously doesn't exist in <code>([3,1],[2,1])</code...
2
2016-09-18T05:04:13Z
[ "python", "numpy" ]
Laser Detection Sensor
39,554,399
<p><br /> I have been trying to work on a project that requires me to know when a laser is being hit into a sensor. Unfortunately, I am not able to find such a product that gives an output current when it is hit by a laser to be used with a Raspberry Pi/Arduino. I heard of Laser Break Beam Sensors, but I do not want to...
-1
2016-09-18T05:24:01Z
39,554,494
<p>Look into a standard LED. They can produce a current when hit with a laser. Or a small solar panel might work better. You can then interpret this using a python script and GPIO from the Raspberry Pi. The laser can also be wired from a GPIO and controlled from software.</p>
2
2016-09-18T05:39:35Z
[ "python", "arduino", "raspberry-pi", "raspberry-pi2", "electronics" ]
How can I find the position in a list where an item differs from the previous item?
39,554,417
<pre><code>l1 = [1,2,2,2] </code></pre> <p>In the list above, I know that the element differs in l1[0]. Is there any way to find the position in python?</p>
0
2016-09-18T05:26:53Z
39,554,492
<p>Try this: </p> <pre><code>l1.index(min(set(l1), key=l1.count)) </code></pre> <p>EDIT:</p> <p>The lambda expression <code>min(set(l1), key=l1.count)</code> tells us what is the element that occurs the fewest number of times in the list. Then we use <code>l1.index</code> to figure out the position of that element i...
2
2016-09-18T05:39:11Z
[ "python" ]
How can I find the position in a list where an item differs from the previous item?
39,554,417
<pre><code>l1 = [1,2,2,2] </code></pre> <p>In the list above, I know that the element differs in l1[0]. Is there any way to find the position in python?</p>
0
2016-09-18T05:26:53Z
39,554,525
<p>Try this:</p> <pre><code>l1 = [1,2,2,2] for pos, i in enumerate(l1): if l1.count(i)==1: print pos </code></pre>
0
2016-09-18T05:44:32Z
[ "python" ]
How can I find the position in a list where an item differs from the previous item?
39,554,417
<pre><code>l1 = [1,2,2,2] </code></pre> <p>In the list above, I know that the element differs in l1[0]. Is there any way to find the position in python?</p>
0
2016-09-18T05:26:53Z
39,554,548
<pre><code>import numpy as np UniqueList, indices = np.unique(l1, return_inverse=True) print(UniqueList) #Unique elements in List l1 </code></pre> <p>array([1, 2])</p> <pre><code>print(indices) #indices of element in l1 mapped to UniqueList </code></pre> <p>array([0, 1, 1, 1])</p>
1
2016-09-18T05:48:08Z
[ "python" ]
How can I find the position in a list where an item differs from the previous item?
39,554,417
<pre><code>l1 = [1,2,2,2] </code></pre> <p>In the list above, I know that the element differs in l1[0]. Is there any way to find the position in python?</p>
0
2016-09-18T05:26:53Z
39,554,710
<p>Assuming you need to show indexes of <strong><em>all</em></strong> occurrences where items change:</p> <pre><code>l = [1 ,2, 2, 3, 3, 1, 1] changes = [i for i, n in list(enumerate(l))[1:] if l[i] != l[i-1]] print(changes) &gt; [1, 3, 5] </code></pre> <p>This simply compares each item from the list with the previ...
0
2016-09-18T06:12:26Z
[ "python" ]
How can I find the position in a list where an item differs from the previous item?
39,554,417
<pre><code>l1 = [1,2,2,2] </code></pre> <p>In the list above, I know that the element differs in l1[0]. Is there any way to find the position in python?</p>
0
2016-09-18T05:26:53Z
39,555,376
<p>Using a modification of <code>itertools</code> recipe <code>unique_everseen</code> for a solution that keeps track of new entries in a list.</p> <pre><code>from itertools import ifilterfalse def unique_everseen(iterable, key=None, per_index=False): "List unique elements, preserving order. Remember all elements ...
0
2016-09-18T07:56:05Z
[ "python" ]
Odoo v9 - Set a dynamic domain when EDITING a form (not creating)
39,554,587
<p>Lets say you are setting a field called "Animal Type", and there is a field dependent upon this called "Favorite toy". If the "Animal Type" is a dog, I'd want to set the domain of "Favorite toy" to something like ('isdogtoy','=',True). If its a cat, then maybe we set it to False or some other condition.</p> <p>Nor...
1
2016-09-18T05:54:21Z
39,587,047
<p>This is the best that I could come up with, using a computed field. Here is an example solution from my code</p> <p>In my XML,</p> <pre><code> &lt;field name="uom_id" position="replace"&gt; &lt;!-- The category_id.name is really only used to filter when islocaluom=True. The result is that if a uom_class is u...
0
2016-09-20T06:22:48Z
[ "python", "openerp", "views" ]
If statement with input check with incorrect outputs
39,554,637
<p>Backstory: I have been trying to actually learn python instead of just snipping from others. I have created a simple script that uses <code>webbrowser</code>. It may be a dirty script and I would love input like "you should do <em>this</em>", "<em>this</em> can be simplified". The thing i cant figure out is using <c...
1
2016-09-18T06:02:19Z
39,554,715
<p>There's a different way to check if the value is one of the given values. You should make your if condition be like this:</p> <pre><code>if a in ('y', 'yes', 'Y', 'Yes', 'YES'): </code></pre> <p>It is fast and understandable. </p> <p>Here's a reason why your condition does not work.<br> Let's say we entered <cod...
1
2016-09-18T06:13:35Z
[ "python", "if-statement", "python-3.4" ]
If statement with input check with incorrect outputs
39,554,637
<p>Backstory: I have been trying to actually learn python instead of just snipping from others. I have created a simple script that uses <code>webbrowser</code>. It may be a dirty script and I would love input like "you should do <em>this</em>", "<em>this</em> can be simplified". The thing i cant figure out is using <c...
1
2016-09-18T06:02:19Z
39,554,860
<p>The following code should work:</p> <pre><code>import webbrowser a = 'y' while a != 'n': a = input ('Do you want to search?(y or n)') a = a[0].lower() if a in "y": b = input ('What do you want to search?') ab = ('https://www.google.com//search?q='+b) urlab = ab webbrowse...
1
2016-09-18T06:35:53Z
[ "python", "if-statement", "python-3.4" ]
np arrays being immutable - "assignment destination is read-only"
39,554,660
<p>FD** - I am a Python newb as well as a stack overflow newb as you can tell. I have edited the question based on comments.</p> <p>My goal is to read a set of PNG files, create Image(s) with Image.open('filename') and convert them to simple 2D arrays with only 1s and 0s. The PNG is of the format RGBA with mostly only...
2
2016-09-18T06:05:54Z
39,554,807
<p>Check if the array is writable with</p> <pre><code>&gt;&gt;&gt; img.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : False ALIGNED : True UPDATEIFCOPY : False </code></pre> <p>If <code>WRITEABLE</code>is false, change it with</p> <pre><code>img.setflags(write=1) </code></pre>
2
2016-09-18T06:26:50Z
[ "python", "arrays", "numpy" ]
geeksforgeeks practice: how to take inputs?
39,554,767
<p>I am trying to code in geeksforgeeks practice in this link: <a href="http://www.practice.geeksforgeeks.org/problem-page.php?pid=282" rel="nofollow">http://www.practice.geeksforgeeks.org/problem-page.php?pid=282</a></p> <p>I use Python. The default code does not have anything. How should I take my inputs and return ...
-2
2016-09-18T06:22:22Z
39,554,816
<p>Cool! I hope you've had fun so far!</p> <p>Python makes these operations quite easy. Both of the functions you'll want to start with are builtins, so you don't even need to <code>import</code> anything!</p> <p>For inputs, this is probably best handled with <a href="https://docs.python.org/3/library/functions.html#...
3
2016-09-18T06:28:25Z
[ "python" ]
geeksforgeeks practice: how to take inputs?
39,554,767
<p>I am trying to code in geeksforgeeks practice in this link: <a href="http://www.practice.geeksforgeeks.org/problem-page.php?pid=282" rel="nofollow">http://www.practice.geeksforgeeks.org/problem-page.php?pid=282</a></p> <p>I use Python. The default code does not have anything. How should I take my inputs and return ...
-2
2016-09-18T06:22:22Z
39,554,854
<p>To take user input, use the <code>input()</code> function. For displaying output to user, use the <code>print()</code> function</p> <pre><code>originalString = input('Enter The String : ') # Perform manipulations here print('Modified String is : ', modifiedString) </code></pre>
3
2016-09-18T06:34:46Z
[ "python" ]
geeksforgeeks practice: how to take inputs?
39,554,767
<p>I am trying to code in geeksforgeeks practice in this link: <a href="http://www.practice.geeksforgeeks.org/problem-page.php?pid=282" rel="nofollow">http://www.practice.geeksforgeeks.org/problem-page.php?pid=282</a></p> <p>I use Python. The default code does not have anything. How should I take my inputs and return ...
-2
2016-09-18T06:22:22Z
39,555,423
<p>hope it work for you :</p> <pre><code>T = int(raw_input()) if T &lt; 0 or T &gt; 10 : print '0&lt;=T&lt;=10 !' exit(0) for x in xrange(T): print '.'.join(str(raw_input()).split('.')[::-1]) </code></pre>
0
2016-09-18T08:02:57Z
[ "python" ]
Bind acl file generate from CSV ip list using bash
39,554,782
<p>I would like to generate geoiplist.acl file from a csv file. acl file format:</p> <pre><code>acl "A1" { 31.14.133.39/32; 37.221.172.0/23; acl "A2" { 5.145.149.142/32; 57.72.6.0/24; ...... </code></pre> <p>the csv file: <a href="http://download.db-ip.com/free/dbip-country-2016-09.csv.gz" rel="nofoll...
-1
2016-09-18T06:24:04Z
39,563,512
<p>The issue here is that DB-IP provide the begin and end value of each range in human readable IP address format. Why they have done this, I'm not sure, because the more universal (easier to process) format is to simply present these values in integer form.</p> <p>In any case, I have modified the Python script on <a ...
0
2016-09-18T23:14:08Z
[ "python", "bash", "csv", "bind9" ]
Aggregate function to data frame in pandas
39,554,806
<p>I want to create a dataframe from an aggregate function. I thought that it would create by default a dataframe as this solution states, but it creates a series and I don't know why (<a href="http://stackoverflow.com/questions/10373660/converting-a-pandas-groupby-object-to-dataframe">Converting a Pandas GroupBy objec...
0
2016-09-18T06:26:34Z
39,554,857
<p>Breaking down your code:</p> <pre><code>df2 = df.groupby(['JobTitle'])['TotalPay'].mean() </code></pre> <p>The <code>groupby</code> is fine. It's the <code>['TotalPay']</code> that is the misstep. That is telling the <code>groupby</code> to only execute the the <code>mean</code> function on the <code>pd.Series</...
1
2016-09-18T06:35:31Z
[ "python", "pandas", "dataframe", "aggregate-functions", "series" ]
Retrieving specific data from a .json file more efficiently?
39,554,826
<p>I have the following <code>.json</code> file, which have some lists like values in some elements:</p> <pre><code>{ "paciente": [ { "id": 1234, "nombre": "Pablo", "sesion": [ { "id": 12345, "juego": [ { "nombre": "bonzo", "ni...
0
2016-09-18T06:29:12Z
39,555,610
<p>Depending on what else your program is doing, it may or may not matter if you speed the code up. You should use the <code>profile</code> or <code>cProfile</code> module to find out where your script is spending its time and work on those.</p> <p>Regardless, you could save some processing time by removing all the re...
1
2016-09-18T08:27:40Z
[ "python", "arrays", "json" ]
Retrieving specific data from a .json file more efficiently?
39,554,826
<p>I have the following <code>.json</code> file, which have some lists like values in some elements:</p> <pre><code>{ "paciente": [ { "id": 1234, "nombre": "Pablo", "sesion": [ { "id": 12345, "juego": [ { "nombre": "bonzo", "ni...
0
2016-09-18T06:29:12Z
39,556,022
<p>Note that you are omitting the second patient record in your data (Bernardo), and that you assume there are always exactly two iterations. This might not always be true.</p> <p>When you look for speed, your code is close to the best you can get, but for the above reasons, you would probably do good to add some test...
1
2016-09-18T09:19:14Z
[ "python", "arrays", "json" ]
Django: Use post() in UpdateView to populate form's fields with instance's existing field values
39,554,829
<p>I have trouble getting the current instance's fields on my UpdateView. How do I get the specific instance based on its id?</p> <p><strong>views.py</strong></p> <pre><code>class ShowUpdate(UpdateView): model = Show fields = ['description', 'season', 'episode'] def post(self, request, **kwargs): request...
0
2016-09-18T06:29:47Z
40,088,457
<p>Look to the <a href="http://ccbv.co.uk/projects/Django/1.10/django.views.generic.edit/UpdateView/" rel="nofollow">UpdateView</a> docs</p> <p>This View has method <code>get_object(self, queryset=None)</code></p> <p>In you case just need to call it in <code>POST</code> method something like this:</p> <pre><code>cla...
0
2016-10-17T14:00:54Z
[ "python", "django" ]
CSjark: NameError name 'Platform' is not defined
39,554,877
<p>I'm usually not working with Python (but have ability to read the code). I'm trying to use <a href="http://csjark.readthedocs.io/" rel="nofollow">csjark</a>. All the dependencies were installed correctly. When executing <code>csjark.py</code> I'm receiving following error: </p> <pre><code>NameError name 'Platform' ...
-1
2016-09-18T06:38:41Z
39,554,927
<p>Maybe your program is importing the wrong platform.py, for example this one: <a href="https://docs.python.org/2/library/platform.html" rel="nofollow">https://docs.python.org/2/library/platform.html</a> which doesn't seem to have a Platform class. Try renaming the platform.py to something else and importing from that...
1
2016-09-18T06:46:42Z
[ "python", "csjark" ]
Want to choose multiple random numbers from a given list of numbers in python
39,554,926
<p>In Python how can I choose two or more random numbers from a given list,such that the numbers are chosen in the same sequence they are arranged in the list they are chosen from?It seems random.choice selects only one number from the list per iteration and as stated earlier random.sample does not give satisfactory an...
-3
2016-09-18T06:46:30Z
39,554,959
<h3>Answer for original version of question:</h3> <p>To get two samples randomly, use <a href="https://docs.python.org/3/library/random.html" rel="nofollow"><code>random.sample</code></a>. First, lets define a list:</p> <pre><code>&gt;&gt;&gt; lst = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] </code></pre> <p>Now, let...
0
2016-09-18T06:50:58Z
[ "python", "python-2.7", "random" ]
Want to choose multiple random numbers from a given list of numbers in python
39,554,926
<p>In Python how can I choose two or more random numbers from a given list,such that the numbers are chosen in the same sequence they are arranged in the list they are chosen from?It seems random.choice selects only one number from the list per iteration and as stated earlier random.sample does not give satisfactory an...
-3
2016-09-18T06:46:30Z
40,028,712
<p>Looks like you want four <em>consecutive</em> values starting at a random offset, not four values from anywhere in the sequence. So don't use <code>sample</code>, just select a random start point (early enough to ensure the slice doesn't run off the end of the <code>list</code> and end up shorter than desired), then...
0
2016-10-13T18:48:01Z
[ "python", "python-2.7", "random" ]
Python - BeautifulSoup: find td width
39,554,944
<p>I have many tables and each has table data tag something like this:</p> <pre><code>&lt;td width="563" valign="top" bgcolor="#FFFF99" class="text"&gt; ... &lt;td width="12" bgcolor="#FFFF99" class="lettnav"&gt; &lt;td bgcolor="#FFFF99" class="lettnav"&gt; </code></pre> <p>The goal is to locate which <code>&lt;td&gt...
2
2016-09-18T06:49:02Z
39,555,125
<p>In BeautifulSoup attributes are accessed in dict notation (see <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#attributes" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/bs4/doc/#attributes</a> for more information).</p> <p>Using <code>width=aCell["width"]</code> your code works:</p> ...
0
2016-09-18T07:19:27Z
[ "python", "html", "beautifulsoup" ]
Python - BeautifulSoup: find td width
39,554,944
<p>I have many tables and each has table data tag something like this:</p> <pre><code>&lt;td width="563" valign="top" bgcolor="#FFFF99" class="text"&gt; ... &lt;td width="12" bgcolor="#FFFF99" class="lettnav"&gt; &lt;td bgcolor="#FFFF99" class="lettnav"&gt; </code></pre> <p>The goal is to locate which <code>&lt;td&gt...
2
2016-09-18T06:49:02Z
39,556,845
<p>To find the <em>td</em> with the largest width you can use <em>max</em> on the list of <em>td's</em> returned from the <em>find_all</em> call, setting the key to <code>key=lambda t: int(t["width"])</code>:</p> <pre><code>soup = BeautifulSoup(page, 'html.parser') cells = soup.find_all("td", width=True) mx_td = max(...
1
2016-09-18T10:51:31Z
[ "python", "html", "beautifulsoup" ]
How to reuse a custom @contextlib.contextmanager?
39,554,981
<p>I'm trying to create a wrapper to make context objects optional. When the condition is true, the thing should behave like the wrapped context object, otherwise it should behave like a no-op context object. This example works for using the wrapped object once, but fails it it is reused.</p> <p>Example:</p> <pre><co...
1
2016-09-18T06:55:11Z
39,555,073
<p>You can't do that with <code>contextlib.contextmanager</code>. As mentioned in passing in <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" rel="nofollow">the docs</a>, context managers created by contextmanager are one-shot.</p> <p>You will have to write your own class with <co...
4
2016-09-18T07:10:36Z
[ "python", "python-3.x", "contextmanager" ]
Pymongo: How to insert an array of multiple fields in a document?
39,555,057
<p>I am working on <code>MongoDB</code> in <code>python</code> <code>[pymongo]</code>. I want to insert an array of multiple fields in a document. For example: In the below structure of a collection, I want to insert array of <code>Places Visited</code> in all documents. I do not know what it is called in the world of ...
-1
2016-09-18T07:08:22Z
39,555,281
<p>This should give you the idea how to do it </p> <pre><code>import pymongo client = pymongo.MongoClient('yourHost', 30000) # adjust to your needs db = client.so coll = db.yourcollection # show initial data for doc in coll.find(): print(doc) # update data places_visited = [ "Palace of Dob", "Palace of...
1
2016-09-18T07:45:18Z
[ "python", "mongodb", "pymongo" ]
Can I safely do inference from another thread when using tf.train.Optimizer(use_locking=True)?
39,555,060
<p>I have several threads that run operation on the same TensorFlow graph. The operations are either inference or optimization of a neural network. I can use the <code>use_locking</code> parameter for the optimizer to prevent concurrent updates of the variables.</p> <p>However, does this safe me from reading partially...
0
2016-09-18T07:09:02Z
39,577,466
<p>Do your inference calls need to be on an up-to-date version of the graph? If you don't mind some delay, you could make a copy of the graph by calling sess.graph.as_graph_def on the training thread, and then create a new session on the inference thread using that graph_def periodically.</p>
0
2016-09-19T16:05:22Z
[ "python", "multithreading", "thread-safety", "locking", "tensorflow" ]
Python deduplicate records - dedupe
39,555,127
<p>I want to use <a href="https://github.com/datamade/dedupe" rel="nofollow">https://github.com/datamade/dedupe</a> to deduplicate some records in python. Looking at their examples </p> <pre><code>data_d = {} for row in data: clean_row = [(k, preProcess(v)) for (k, v) in row.items()] row_id = int(row['id']) ...
0
2016-09-18T07:19:44Z
39,555,215
<p>It appears that <code>df.to_dict(orient='index')</code> will produce the representation you are looking for:</p> <p>import pandas</p> <pre><code>data = [[1, 2, 3], [4, 5, 6]] columns = ['a', 'b', 'c'] df = pandas.DataFrame(data, columns=columns) df.to_dict(orient='index') </code></pre> <p>results in </p> <pre>...
2
2016-09-18T07:35:38Z
[ "python", "pandas", "dictionary", "duplicates", "dedupeplugin" ]
Python deduplicate records - dedupe
39,555,127
<p>I want to use <a href="https://github.com/datamade/dedupe" rel="nofollow">https://github.com/datamade/dedupe</a> to deduplicate some records in python. Looking at their examples </p> <pre><code>data_d = {} for row in data: clean_row = [(k, preProcess(v)) for (k, v) in row.items()] row_id = int(row['id']) ...
0
2016-09-18T07:19:44Z
39,555,259
<p>You can try something like this:</p> <pre><code>df = pd.DataFrame({'A': [1,2,3,4,5], 'B': [6,7,8,9,10]}) A B 0 1 6 1 2 7 2 3 8 3 4 9 4 5 10 print(df.T.to_dict()) {0: {'A': 1, 'B': 6}, 1: {'A': 2, 'B': 7}, 2: {'A': 3, 'B': 8}, 3: {'A': 4, 'B': 9}, 4: {'A': 5, 'B': 10}} </code></pre> <p><em>This is ...
0
2016-09-18T07:42:09Z
[ "python", "pandas", "dictionary", "duplicates", "dedupeplugin" ]
Python deduplicate records - dedupe
39,555,127
<p>I want to use <a href="https://github.com/datamade/dedupe" rel="nofollow">https://github.com/datamade/dedupe</a> to deduplicate some records in python. Looking at their examples </p> <pre><code>data_d = {} for row in data: clean_row = [(k, preProcess(v)) for (k, v) in row.items()] row_id = int(row['id']) ...
0
2016-09-18T07:19:44Z
39,558,156
<p>A python dictionary is not required, you just need an object that allows indexing by column name. i.e. <code>row['col_name']</code></p> <p>So, assuming <code>data</code> is a pandas dataframe should just be able to do something like:</p> <pre><code>data_d = {} for row_id, row in data.iterrows(): data_d[row_id]...
0
2016-09-18T13:30:07Z
[ "python", "pandas", "dictionary", "duplicates", "dedupeplugin" ]
In django how can I make the result of the background program as a record and then insert it to mysql
39,555,160
<p>In django, I want to make the result of the program in server as a record and then insert it to the mysql, how can I do this?</p>
0
2016-09-18T07:26:26Z
39,559,057
<p>If your program is part of django, you can just follow <a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/#creating-objects" rel="nofollow">Creating objects</a>, if not, you can do something in your program settings:</p> <pre><code>import django os.environ['DJANGO_SETTINGS_MODULE'] = 'your_django_pro...
0
2016-09-18T15:00:16Z
[ "python", "django" ]
AttributeError: instance has no attribute
39,555,189
<p>This seems to be a common error in Python, and I've found many instances of people asking about similar but spent the last (long amount of time) trying those solutions where they seemed applicable and have had no luck, so resorting to asking to find out what I'm missing. </p> <p>I'm receiving <strong>AttributeErro...
1
2016-09-18T07:31:11Z
39,555,209
<p>This that you have:</p> <pre><code>def ___init___(self): </code></pre> <p>Is not the same as this that gets called when an object is instantiated:</p> <pre><code>def __init__(self): </code></pre> <p>The difference is that you have <em>three</em> underscores on either side of <code>init</code>, while two are requ...
2
2016-09-18T07:34:30Z
[ "python", "python-2.7", "oop", "attributeerror" ]
AttributeError: instance has no attribute
39,555,189
<p>This seems to be a common error in Python, and I've found many instances of people asking about similar but spent the last (long amount of time) trying those solutions where they seemed applicable and have had no luck, so resorting to asking to find out what I'm missing. </p> <p>I'm receiving <strong>AttributeErro...
1
2016-09-18T07:31:11Z
39,555,211
<p>Your init function has three underscores:</p> <pre><code>def ___init___(self): </code></pre> <p>It <a href="https://docs.python.org/2/reference/datamodel.html#basic-customization" rel="nofollow">should have only two</a>:</p> <pre><code>def __init__(self): </code></pre> <p>As it is written now, it is not being ca...
2
2016-09-18T07:34:42Z
[ "python", "python-2.7", "oop", "attributeerror" ]
How to add space between two widgets placed in grid in tkinter ~ python?
39,555,194
<p>a. Have placed a widget in the row 0 in the grid as shown below.</p> <pre><code>self.a_button = Button(root, text="A Button") self.a_button.grid(row=0, column=1) </code></pre> <p>b. And tried placing another widget in row 2 inside the grid.</p> <pre><code>self.b_button = Button(root, text="B Button") self.b_butto...
-2
2016-09-18T07:31:54Z
39,555,320
<p>When you pack the widget you can use</p> <pre><code>self.a_button = Button(root, text="A Button") self.a_button.grid(row=0, column=1, padx=10, pady=10) </code></pre> <p>Using padx and pady you can add padding to the outer side of the button and alternatively if you want to increase the size of the button you can ...
1
2016-09-18T07:48:43Z
[ "python", "python-2.7", "tkinter" ]
MySQL Error in Python
39,555,227
<blockquote> <p>I need to insert a record into the table MemberDetails but I end up with the error stating " _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'I' at line 1") "</p> </blockqu...
-3
2016-09-18T07:37:59Z
39,555,414
<p>You need to add spacing as well as the columns in the table each variable will be inserted into, your query should be like this:</p> <pre><code>"INSERT INTO MemberDetails (datetime, phone, code, address, stuid, birthdate, num, name, pass, dept, year, sec) VALUES (" + "'2016-2020','" + PhoneNum + "','VEC','" + Addre...
-1
2016-09-18T08:00:40Z
[ "python", "mysql" ]
Calling a C++ CUDA device function from a Python kernel
39,555,235
<p>I'm working on a project that involves creating CUDA kernels in Python. Numba works quite well (what these guys have accomplished is quite incredible), and so does PyCUDA.</p> <p>My problem is that I want to call a C device function from my Python generated kernel. I couldn't find a way to accomplish this. Numba ca...
1
2016-09-18T07:38:37Z
39,557,406
<p>As far as I am aware, this isn't possible in either language. Neither exposes the necessary toolchain controls for separate compilation or APIs to do runtime linking of device code.</p>
2
2016-09-18T11:57:14Z
[ "python", "cuda", "cython", "numba", "pycuda" ]
What are the advantages and disadvantages of creating class and instance in this way in Python?
39,555,299
<pre><code>class CIFAR10Record(object): pass result = CIFAR10Record() result.height = 32 result.width = 32 result.depth = 3 </code></pre> <p>This snippet of code creates a class and its instance.</p> <p>What are the advantages and disadvantages of this pattern?</p>
2
2016-09-18T07:47:28Z
39,555,354
<p>This code uses a class in order to "bunch together" a number of related fields.</p> <p>The pros are that it's very flexible. The class is defined without any members. Any function can decide which fields to add. Different invocations can create objects of this class, and populate them in different ways (so, simulta...
4
2016-09-18T07:53:34Z
[ "python", "class" ]
Force vertical display with pprint
39,555,387
<p>I'm using <code>pprint</code> to display the <code>diff</code> between two dictionaries. Sometimes the values in the dictionary are long strings, which I want to see as single lines, so I set the <code>width</code> to some large value. Unfortunately, sometimes these dictionary are shallow (i.e., while in the gener...
2
2016-09-18T07:57:10Z
39,556,354
<h2>Option: Use <code>json</code></h2> <p>I found converting the dictionary to JSON more predictable than <code>pprint</code>. In addition, there you have an option to sort the keys, which should help your comparison</p> <pre><code> &gt;&gt;&gt; import json &gt;&gt;&gt; d1 = {'a': 'a', 'b': 'b', 'c':'c'} ...
1
2016-09-18T09:56:06Z
[ "python", "dictionary", "pretty-print" ]
TKinter - How to stop a loop with a stop button?
39,555,463
<p>I have this program which beeps every second until it's stopped. The problem is that after I press "Start" and the beeps starts, I cannot click the "Stop" button because the window freezes. Any help is welcome.</p> <pre><code>#!/usr/bin/python import Tkinter, tkMessageBox, time, winsound, msvcrt running = True Fr...
1
2016-09-18T08:08:55Z
39,556,017
<p>There are several things wrong with your code. First of all you shouldn't use <code>time.sleep()</code> in a Tkinter program because it interferes with the <code>mainloop()</code>. Instead one typically uses the universal widget method <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html" rel="n...
2
2016-09-18T09:18:31Z
[ "python", "tkinter" ]
TKinter - How to stop a loop with a stop button?
39,555,463
<p>I have this program which beeps every second until it's stopped. The problem is that after I press "Start" and the beeps starts, I cannot click the "Stop" button because the window freezes. Any help is welcome.</p> <pre><code>#!/usr/bin/python import Tkinter, tkMessageBox, time, winsound, msvcrt running = True Fr...
1
2016-09-18T08:08:55Z
39,556,024
<p>The problem is that the while loop in <code>start()</code> blocks the GUI handler <code>mainloop()</code>. Try using <code>Tk.after()</code> in <code>start()</code>:</p> <pre><code>def start(force=True): global running if force: running = True if running: winsound.Beep(Freq, Dur) ...
0
2016-09-18T09:19:43Z
[ "python", "tkinter" ]
TKinter - How to stop a loop with a stop button?
39,555,463
<p>I have this program which beeps every second until it's stopped. The problem is that after I press "Start" and the beeps starts, I cannot click the "Stop" button because the window freezes. Any help is welcome.</p> <pre><code>#!/usr/bin/python import Tkinter, tkMessageBox, time, winsound, msvcrt running = True Fr...
1
2016-09-18T08:08:55Z
39,556,099
<p>You code have <code>top.mainloop()</code> which has a <code>while</code> loop running inside it and on top of that you also have a while loop inside <code>def start():</code>. So it is like loop inside loop. </p> <p>You can create a function that does what you want for the body of the loop. It should do exactly on...
3
2016-09-18T09:27:49Z
[ "python", "tkinter" ]
TKinter - How to stop a loop with a stop button?
39,555,463
<p>I have this program which beeps every second until it's stopped. The problem is that after I press "Start" and the beeps starts, I cannot click the "Stop" button because the window freezes. Any help is welcome.</p> <pre><code>#!/usr/bin/python import Tkinter, tkMessageBox, time, winsound, msvcrt running = True Fr...
1
2016-09-18T08:08:55Z
39,556,213
<p>Beaten to the punch again but here goes nothing. As above use the <code>after</code> function to prevent the <code>mainloop</code> blocking.<br> See: <a href="http://stackoverflow.com/questions/25753632/tkinter-how-to-use-after-method#25753719">tkinter: how to use after method</a></p> <pre><code>#!/usr/bin/python i...
0
2016-09-18T09:40:09Z
[ "python", "tkinter" ]
re.findall() returning the wrong values when using optionals
39,555,527
<p>I'm following along in a tutorial and I seem to be stuck on what seems to be an easy thing to do:</p> <pre><code>numRegex = re.compile(r'\d+(\s+\w+)?') spam = numRegex.findall("my address is 999 Street Ave City CA 95014 x") print(len(spam)) print(spam) </code></pre> <p>this returns <code>[' Street', ' x']</code>...
0
2016-09-18T08:16:03Z
39,555,543
<p>You are capturing the group wrongly. Try:</p> <pre><code>numRegex = re.compile(r'(\d+(?:\s+\w+)?)') </code></pre> <p>Or, </p> <pre><code>numRegex = re.compile(r'\d+(?:\s+\w+)?') </code></pre> <p><code>\d+(\s+\w+)?</code> seeks for the whole pattern, but only matches <code>(\s+\w+)</code> part because, this is th...
0
2016-09-18T08:18:04Z
[ "python", "regex" ]
Plot quadratic function / model with matplotlib
39,555,569
<p>I'm playing around with python and want to plot a quadratic linear regression with matplotlib. The problem is, that my plot ends up being a lot of connected lines/dots instead of just the one function:</p> <p><a href="http://i.stack.imgur.com/EljBs.png" rel="nofollow">Plot</a></p> <p><a href="http://i.stack.imgur....
0
2016-09-18T08:22:18Z
39,555,778
<p>From what I can see, the x values on your plots are not sorted in ascending order. The plot does what it should and connects the dots, but they are in such an order that the line jumps "back" and "forward" on the x-axis. Now - you can't see that on the linear plot as everything is on a single line, but starts to bec...
0
2016-09-18T08:48:51Z
[ "python", "matplotlib" ]
Plot quadratic function / model with matplotlib
39,555,569
<p>I'm playing around with python and want to plot a quadratic linear regression with matplotlib. The problem is, that my plot ends up being a lot of connected lines/dots instead of just the one function:</p> <p><a href="http://i.stack.imgur.com/EljBs.png" rel="nofollow">Plot</a></p> <p><a href="http://i.stack.imgur....
0
2016-09-18T08:22:18Z
39,555,794
<p>You need to sort your values. You can take any approach. Personally, I would just use <code>pandas</code> but there are more lightweight solutions for sure.</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'x':lin_train.reshape((lin_train.shape[0],)), 'y':quad_model.predict(quad_train)}) &gt;&gt;&gt; df.sort_values(b...
0
2016-09-18T08:51:28Z
[ "python", "matplotlib" ]
How to keep one single column as a dataframe
39,555,592
<p>I have dataframe with 20 columns and one index.</p> <p>Its shape is something like (100, 20).</p> <p>I want to slice the 3rd column from this dataframe, but want to keep the result as a dataframe of (100,1). </p> <ol> <li>If I do a <code>v = df['col3']</code>, I get a Series (which I do not want)</li> <li>If I do...
2
2016-09-18T08:25:42Z
39,555,643
<blockquote> <p>If I do a <code>v = df['col3']</code>, I get a Series (which I do not want)</p> </blockquote> <p>If you use <code>df[cols]</code>, where <code>cols</code> is a list, you'll get a DataFrame (not a Series). This includes the case where it is a list consisting of a single item. So, you can use <code>df[...
3
2016-09-18T08:32:00Z
[ "python", "pandas", "sklearn-pandas" ]
How to keep one single column as a dataframe
39,555,592
<p>I have dataframe with 20 columns and one index.</p> <p>Its shape is something like (100, 20).</p> <p>I want to slice the 3rd column from this dataframe, but want to keep the result as a dataframe of (100,1). </p> <ol> <li>If I do a <code>v = df['col3']</code>, I get a Series (which I do not want)</li> <li>If I do...
2
2016-09-18T08:25:42Z
39,555,884
<p>Another handy trick is <code>to_frame()</code></p> <pre><code>df['col3'].to_frame() </code></pre>
2
2016-09-18T09:03:01Z
[ "python", "pandas", "sklearn-pandas" ]
setting up nginx with django
39,555,611
<p>I have created a django project called "yo" in my /home/ubuntu/test directory.</p> <p>These are my nginx files:</p> <p>nginx/sites-available/yo</p> <pre><code> server { listen 80; server_name 52.89.220.11; location = /favicon.ico { access_log off; log_not_found off; } location ...
1
2016-09-18T08:27:42Z
39,557,230
<ul> <li>you have unmatched parens in your <code>nginx/sites-enabled/yo_nginx.conf</code></li> <li><code>nginx/sites-available/yo</code> is not read by nginx - only files ending in <code>.conf</code> and located in <code>nginx/sites-enabled/</code> are read in default nginx configuration.</li> <li>since your command li...
1
2016-09-18T11:36:42Z
[ "python", "django", "nginx" ]
setting up nginx with django
39,555,611
<p>I have created a django project called "yo" in my /home/ubuntu/test directory.</p> <p>These are my nginx files:</p> <p>nginx/sites-available/yo</p> <pre><code> server { listen 80; server_name 52.89.220.11; location = /favicon.ico { access_log off; log_not_found off; } location ...
1
2016-09-18T08:27:42Z
39,558,941
<p>First install required applications. sudo apt-get install nginx uwsgi uwsgi-plugin-python python-virtualenv Versions of packages that will be used:</p> <pre><code>Nginx Uwsgi Virtualenv Django Virtualenv. </code></pre> <p>I store my project in ~/projects. Now I'm creating python virtual environment for my projec...
1
2016-09-18T14:48:42Z
[ "python", "django", "nginx" ]
How to translate Python console program (including while true loop) to PyQt?
39,555,653
<p>I have a Python console program that I want to transfer to a GUI. I thought of using PyQt 5, but I'm open to alternatives.</p> <p>The simplified console code looks like this:</p> <pre><code>while True: data = obtain_data_from_device(source) print(datatotext(data)) </code></pre> <p>Now from what I understand...
0
2016-09-18T08:33:52Z
39,556,908
<p>You could try something like this:</p> <pre><code>import sys import random import time import string from PyQt5 import QtWidgets, QtCore def obtain_data_from_device(source): time.sleep(0.001) data = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(len(source...
0
2016-09-18T10:59:27Z
[ "python", "qt", "pyqt" ]
How to translate Python console program (including while true loop) to PyQt?
39,555,653
<p>I have a Python console program that I want to transfer to a GUI. I thought of using PyQt 5, but I'm open to alternatives.</p> <p>The simplified console code looks like this:</p> <pre><code>while True: data = obtain_data_from_device(source) print(datatotext(data)) </code></pre> <p>Now from what I understand...
0
2016-09-18T08:33:52Z
39,558,057
<p>One option, since you already have a working program that writes to STDOUT, is to let the GUI program run the console program as a child process using <code>QProcess</code>.</p> <p>The child will run asynchronously under control of the GUI program and the GUI program will receive the child's output via signals, i.e...
1
2016-09-18T13:18:16Z
[ "python", "qt", "pyqt" ]
How to define a weighted loss function in TensorFlow?
39,555,745
<p>I have a training dataset of train_data and train_labels which is train_data_node and train_labels_node in the graph of tensorflow. As you know, I can use the loss function of tensorflow as bellows:</p> <pre><code>logits = model(train_data_node) loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits( ...
1
2016-09-18T08:45:29Z
39,564,270
<p>I have finally solved the problem by myself using the function tf.boolen_mask() of tensorflow. The defined custom weighted loss function is as bellows:</p> <pre><code>def calLoss(logits, labels, augs): augSum = tf.reduce_sum(augs) pred = tf.less(augSum, BATCH_SIZE) def noaug(logits, labels, augs): augs =...
0
2016-09-19T01:43:59Z
[ "python", "tensorflow" ]
Flask context missing in 404 errorhandler
39,555,768
<p>I have the following structure for my flask application. When an invalid url comes in a 404 error is called, but my 404.html requires data from the context_processor but in the abort 404 the blueprint is None so context_processor is never called and 404.html is missing data.</p> <p>How can I approach this different...
0
2016-09-18T08:47:40Z
39,555,787
<p>When a route is not found, no blueprint is set yet (because setting a blueprint requires a route to be determined first). As such a 404 error handler can't count on a blueprint to have been determined.</p> <p>You'd have to execute the <code>get_data()</code> call manually. Test if a specific global has been set, th...
1
2016-09-18T08:50:25Z
[ "python", "flask" ]
Jinja2 include & extends not working as expected
39,555,769
<p>I used <code>include</code> and <code>extends</code> in the <code>base.html</code> file and expect them to be included in order. But the <code>extends</code> template is appended to the end of the file.</p> <p>I expect my template to give me the output of:</p> <pre class="lang-html prettyprint-override"><code>&lt;...
2
2016-09-18T08:47:49Z
39,555,899
<p>I think that you want to use <code>include</code> instead of <code>extends</code> in </p> <pre><code>{% extends "content.html" %} </code></pre>
0
2016-09-18T09:05:49Z
[ "python", "flask", "jinja2" ]