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 |
|---|---|---|---|---|---|---|---|---|---|
Why is using the Python mmap module much slower than calling POSIX mmap from C++? | 38,682,501 | <p>C++ code:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <string>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/time.h>
using namespace std;
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
int main() {
timeval tv1, tv2, tv3, t... | 0 | 2016-07-31T09:18:00Z | 38,682,857 | <p>To elaborate on what @Daniel said â any Python operation has more overhead (in some cases <em>way</em> more, like orders of magnitude) than the comparable amount of code implementing a solution in C++.</p>
<p>The loop filling the buffer is indeed the culprit â but also the <code>mmap</code> module itself has a ... | 1 | 2016-07-31T10:04:48Z | [
"python",
"c++",
"performance",
"posix",
"mmap"
] |
Weird characters printed during json key-value printing | 38,682,556 | <p>I have made a python program to get the movie/tv show information using the OMDb API <a href="http://www.omdbapi.com/" rel="nofollow">http://www.omdbapi.com/</a> </p>
<p>I am getting an error while printing the running years of the tv show. Here's a part of the code where this is happening:</p>
<pre><code>keys = [... | -2 | 2016-07-31T09:24:54Z | 38,682,630 | <p>You are encoding Unicode text to UTF-8 before printing:</p>
<pre><code>print key.encode('utf-8') + ' : ' + value.encode('utf-8')
</code></pre>
<p>Your console or terminal is not configured to interpret UTF-8 however. It is being sent bytes and it is then displaying characters based on a <em>different</em> codec al... | 2 | 2016-07-31T09:33:49Z | [
"python",
"json",
"python-2.7",
"utf-8",
"character-encoding"
] |
jira-python create_issue jiraerror http 400 with a url of local address | 38,682,713 | <p>I'm new to jira-python. I am trying to automate a bit on jira management, blocked on creating issue for a long time, going along with the jira-python official documents.
I'm confused with the createmeta of create_issue() method. After trial and error, I'm blocked with a strange http 400 error followed by a url with ... | 1 | 2016-07-31T09:46:37Z | 38,698,327 | <p>The error detail message is:</p>
<pre><code>Field 'description' cannot be set. It is not on the appropriate screen, or unknown.
</code></pre>
<p>If you go to the <em>Project Settings</em> of your project in JIRA and click on <em>Screens</em> then you can check the <em>Screen Scheme</em> that is associated with you... | 0 | 2016-08-01T11:59:41Z | [
"python",
"jira",
"jira-rest-api"
] |
NLP - extract categories/tags from text | 38,682,784 | <p>Does anyone have any idea or can give me directions about how I can extract categories from an article?</p>
<p>What I have is a corpus of few thousands of articles (about sports, news, buisness etc.) I can work with.</p>
<p>For example, if theres an article about sports I would like my program to know if its socce... | 0 | 2016-07-31T09:55:43Z | 38,682,870 | <p>I guess that you can use some machine learning approaches to achieve this. What comes to my mind is using <a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf" rel="nofollow">tf-idf</a> statistic. </p>
<p>There is an online course on Coursera called "<a href="https://www.coursera.org/specializations/machine-learni... | 0 | 2016-07-31T10:07:19Z | [
"python",
"nltk",
"gensim"
] |
NLP - extract categories/tags from text | 38,682,784 | <p>Does anyone have any idea or can give me directions about how I can extract categories from an article?</p>
<p>What I have is a corpus of few thousands of articles (about sports, news, buisness etc.) I can work with.</p>
<p>For example, if theres an article about sports I would like my program to know if its socce... | 0 | 2016-07-31T09:55:43Z | 38,683,983 | <p>As you don't have gold data for training, first you will need to create some.</p>
<p>For that, you will need to <strong>define your classes</strong> and define some <strong>rules</strong> which are obvious selection for each class,</p>
<pre><code>article_text.contains("soccer")
article_text.contains("Ronaldo")
<... | 0 | 2016-07-31T12:29:54Z | [
"python",
"nltk",
"gensim"
] |
How do I cast a 2D list to a void pointer and back | 38,682,817 | <p>I'm trying to write two Cython functions to wrap external functions. The functions are the inverse of each another; one accepts a string, and returns a struct with two fields: a void pointer to a 2D array (the second dimension is always two elements: <code>[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], ⦠]</code>), and the ... | 3 | 2016-07-31T10:00:27Z | 38,683,207 | <p>I think the issue is that you're trying to use 2D arrays and 1D memoryviews</p>
<p>In the encoding function </p>
<pre><code> # the coords are a 2D, C contiguous array
cdef double[:,::1] ncoords = np.array(coords, dtype=np.float64)
# ...
coords_ffi.data = <void*>&ncoords[0,0] # take the 0,0... | 3 | 2016-07-31T10:52:24Z | [
"python",
"numpy",
"cython"
] |
Can't import module in folders aside from home | 38,682,909 | <p>I was trying to install the module, tweepy, through the python3 shell on Ubuntu in a folder called dtrump in my home directory (donald trump response twitter bot), except it keeps saying "ImportError: No module named 'tweepy'". While you may think I simply did not install tweepy, I have, I even uninstalled to reinst... | 0 | 2016-07-31T10:11:42Z | 38,683,825 | <p>Run the following command from a terminal:</p>
<pre><code>sudo apt-get install python3-pip
</code></pre>
<p>This should help</p>
| 0 | 2016-07-31T12:11:00Z | [
"python",
"python-3.x",
"ubuntu",
"module",
"pip"
] |
Cube root of negative real numbers | 38,682,936 | <p>I'm trying to plot a quite complex function, i.e. <code>log(x/(x-2))**Rational(1,3)</code>. I'm working only with real numbers. If I try to plot it, <code>sympy</code> only plots the <strong>x>2 part</strong> of it.</p>
<p>I found that actually complex numbers come into play and, for example,<code>root(-8,3).n()</... | 2 | 2016-07-31T10:15:59Z | 38,707,315 | <p>It seems SymPy's plot has a bug, so for now, you'll have to use <code>lambdify</code> and <code>matplotlib</code> to plot it manually:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
f = lambdify(x, (real_root((log(x/(x-2))), 3)), 'numpy')
vals = np.linspace(2, 10, 1000)
plt.plot(vals, f(vals))
<... | 2 | 2016-08-01T20:12:11Z | [
"python",
"sympy",
"python-3.5"
] |
Sqlite3 & Python creating tables | 38,683,021 | <p>I'm trying to use the scrapy pipeline to store its data in a sqlite3 database here is the little part that trows a OperationalError: near "Transaction": syntax error</p>
<pre><code>def createResidentialTable(self):
self.cur.execute("""CREATE TABLE IF NOT EXISTS Residential
(Id INT PRIMARY KEY NOT NULL, ... | 0 | 2016-07-31T10:28:21Z | 38,683,056 | <p><code>Transaction</code> is a <a href="https://www.sqlite.org/lang_keywords.html" rel="nofollow">reserved keyword</a> which you are not allowed to use as an identifier. Just use something other than <code>Transaction</code> as an identifier.</p>
| 1 | 2016-07-31T10:31:34Z | [
"python",
"sqlite",
"sqlite3"
] |
No module named pymongo - Jython | 38,683,037 | <p>I have a python script and i am executing the same through java process using Jython.</p>
<p>Database - <strong>mongodb</strong></p>
<p><strong>Pom.xml</strong></p>
<pre><code><dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<versio... | 0 | 2016-07-31T10:30:19Z | 38,683,492 | <p>I solved by importing the module like below :-</p>
<pre><code> PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState());
PySystemState sys = interpreter.getSystemState();
sys.path.append(new PyString("\\python_modules\\pymongo-3.3.0-cp26-none-win_amd64.whl"));
</code></pre>
<p>I hav... | 0 | 2016-07-31T11:29:08Z | [
"java",
"python",
"mongodb",
"jython-2.7"
] |
404 on media files - Django | 38,683,105 | <p>Last night I uploaded my project to pythonanywhere.com where I wanted to test my <strong>production</strong> settings. In one of my models I allow <strong>users to upload</strong> JPG's (Logo of a team). The uploading process works good, the file lands in my MEDIA_ROOT. The issue is that when I try to access it in m... | 2 | 2016-07-31T10:37:48Z | 38,683,329 | <p>You need to set a media files mapping in PythonAnywhere's dashboard. From their <a href="https://help.pythonanywhere.com/pages/DjangoStaticFiles/">documentation</a>:</p>
<ul>
<li>Go to the <strong>Web</strong> tab on the PythonAnywhere dashboard</li>
<li>Go to the <strong>Static Files</strong> section</li>
<li>Ente... | 5 | 2016-07-31T11:08:21Z | [
"python",
"django",
"django-settings"
] |
Validating id recieved with regular expression | 38,683,217 | <p>I'm trying to get ID from URL (in django):</p>
<pre><code>url(r'^preset/(P<pk>\d+)$', views.route_preset_api.as_view()),
</code></pre>
<p>This works well as long as the input is a number. But if it isn't a number the page will return a 500 error.</p>
<p>How can I do a special case, that will take care of al... | 0 | 2016-07-31T10:54:17Z | 38,683,374 | <p>First of all your pattern is missing a required <code>?</code> which specifies a named group. It should be:</p>
<pre><code>r'^preset/(?P<pk>\d+)$'
</code></pre>
<p>which will associate the matched substring with the group name <code>pk</code>, i.e. a named group. Without the <code>?</code> the regex will lit... | 0 | 2016-07-31T11:14:23Z | [
"python",
"regex",
"django"
] |
Tkinter app using sockets hangs on start | 38,683,324 | <p>I am having problems with a socket/tkinter login app. The server is on a Raspberry Pi but even with the server not on I see no reason that this should hang on startup. I have imported a module I have made which I will include.</p>
<p>Why does it hang?</p>
<p>Here is my client code - the one that hangs:</p>
<pre><... | -1 | 2016-07-31T11:07:42Z | 38,683,667 | <p>The reason it hangs is because you are mixing both <code>pack</code> and <code>grid</code> in the same parent widget. Consider the following code:</p>
<pre><code>class LoginFrame(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.pack()
self.l = loginutility.Logi... | 0 | 2016-07-31T11:48:54Z | [
"python",
"sockets",
"tkinter"
] |
Python regex group search returns only the first match | 38,683,380 | <p>I need to extract the contents of the numbered list. Please check the following url: <a href="https://regex101.com/r/oS0yT5/1" rel="nofollow">https://regex101.com/r/oS0yT5/1</a></p>
<pre><code>string = @BarsAndMelody #3thingsthatmakeyousmile #1) @livingleondre #2) Leondre and Charlie #3) chocolate âºï¸ í ½í¹
p... | 1 | 2016-07-31T11:14:47Z | 38,683,444 | <p>You need <code>re.findall</code> to find <em>all</em> the matches, not only the first:</p>
<pre><code>string = "@BarsAndMelody #3thingsthatmakeyousmile #1) @livingleondre #2) Leondre and Charlie #3) chocolate âºï¸ í ½í¹
please notice me í ½í¸ it's my birthdayí ½í±"
p = re.findall("(?<=[#\s][\d][\)\.\:][\s... | 3 | 2016-07-31T11:23:12Z | [
"python",
"regex"
] |
Scrapy - 301 redirect in shell | 38,683,382 | <p>I can not find a solution to the following problem. I am using Scrapy (latest version) and am trying to debug a spider.
Using <code>scrapy shell https://jigsaw.w3.org/HTTP/300/301.html</code> -> it does not follow the redirect ( it is using a default spider to get the data). If I am running my spider it follows the ... | 1 | 2016-07-31T11:14:58Z | 38,683,410 | <p>Scrapy uses Redirect Middleware for redirects, however it's not enabled in shell. Quick fix for this:</p>
<pre><code>scrapy shell "https://jigsaw.w3.org/HTTP/300/301.html"
fetch(response.headers['Location'])
</code></pre>
<p>Also to debug your spider you probably want to inspect the response your spider is receivi... | 2 | 2016-07-31T11:18:36Z | [
"python",
"web-scraping",
"scrapy",
"scrapy-shell"
] |
Python - return date and time value and use it later | 38,683,386 | <p>I have the following code, but I'm not quite sure how it's going to work.</p>
<p>I'll execute the following:</p>
<pre><code>date = strftime("%Y-%m-%d %H:%M:%S")
</code></pre>
<p>and it will return exact date and time of the moment I call this. I want to use the exact output of this date and time in another functi... | 0 | 2016-07-31T11:15:22Z | 38,683,417 | <p>Does anything stop you from passing <code>date</code> as a parameter to your other function ? </p>
<p><a href="http://www.tutorialspoint.com/python/python_functions.htm" rel="nofollow">http://www.tutorialspoint.com/python/python_functions.htm</a></p>
<p>If you can't pass it as a parameter, and both functions are w... | 1 | 2016-07-31T11:19:34Z | [
"python",
"python-2.7"
] |
How to decode base64 in python3 | 38,683,439 | <p>I have a base64 encrypt code, and I can't decode in python3.5</p>
<pre><code>import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA" # Unencrypt is 202cb962ac59075b964b07152d234b70
base64.b64decode(code)
</code></pre>
<p>Result:</p>
<pre><code>binascii.Error: Incorrect padding
</code></pre>
<p... | 2 | 2016-07-31T11:23:01Z | 38,683,518 | <p>According to this <a href="http://stackoverflow.com/a/2942039/6495334">answer</a>, you can just add the required padding.</p>
<pre><code>code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA"
b64_string = code
b64_string += "=" * ((4 - len(b64_string) % 4) % 4)
base64.b64decode(b64_string) #'admin:202cb962ac5... | 0 | 2016-07-31T11:31:24Z | [
"python",
"base64"
] |
How to decode base64 in python3 | 38,683,439 | <p>I have a base64 encrypt code, and I can't decode in python3.5</p>
<pre><code>import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA" # Unencrypt is 202cb962ac59075b964b07152d234b70
base64.b64decode(code)
</code></pre>
<p>Result:</p>
<pre><code>binascii.Error: Incorrect padding
</code></pre>
<p... | 2 | 2016-07-31T11:23:01Z | 38,683,522 | <p>It actually seems to just be that <code>code</code> is incorrectly <a href="https://en.wikipedia.org/wiki/Base64#Padding" rel="nofollow">padded</a> (<code>code</code> is incomplete)</p>
<pre><code>import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA"
base64.b64decode(code+"=")
</code></pre>
<p... | 0 | 2016-07-31T11:31:47Z | [
"python",
"base64"
] |
How to decode base64 in python3 | 38,683,439 | <p>I have a base64 encrypt code, and I can't decode in python3.5</p>
<pre><code>import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA" # Unencrypt is 202cb962ac59075b964b07152d234b70
base64.b64decode(code)
</code></pre>
<p>Result:</p>
<pre><code>binascii.Error: Incorrect padding
</code></pre>
<p... | 2 | 2016-07-31T11:23:01Z | 38,683,523 | <p>Base64 needs a string with length multiple of 4. If the string is short, it is padded with 1 to 3 <code>=</code>.</p>
<pre><code>import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA="
base64.b64decode(code)
# b'admin:202cb962ac59075b964b07152d234b70'
</code></pre>
| 2 | 2016-07-31T11:31:47Z | [
"python",
"base64"
] |
How to decode base64 in python3 | 38,683,439 | <p>I have a base64 encrypt code, and I can't decode in python3.5</p>
<pre><code>import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA" # Unencrypt is 202cb962ac59075b964b07152d234b70
base64.b64decode(code)
</code></pre>
<p>Result:</p>
<pre><code>binascii.Error: Incorrect padding
</code></pre>
<p... | 2 | 2016-07-31T11:23:01Z | 38,683,654 | <p>I tried the other way around. If you know what the unencrypted value is:</p>
<pre><code>>>> import base64
>>> unencoded = b'202cb962ac59075b964b07152d234b70'
>>> encoded = base64.b64encode(unencoded)
>>> print(encoded)
b'MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA='
>>> ... | 0 | 2016-07-31T11:47:21Z | [
"python",
"base64"
] |
How to apply my own function along each rows and columns with NumPy | 38,683,562 | <p>I'm using NumPy to store data into matrices.
I'm struggling to make the below Python code perform better.
<code>RESULT</code> is the data store I want to put the data into.</p>
<pre><code>TMP = np.array([[1,1,0],[0,0,1],[1,0,0],[0,1,1]])
n_row, n_col = TMP.shape[0], TMP.shape[0]
RESULT = np.zeros((n_row, n_col))
d... | 2 | 2016-07-31T11:36:44Z | 38,684,188 | <p><strong>Approach #1</strong></p>
<p>You could do something like this as a vectorized solution -</p>
<pre><code># Store number of rows in TMP as a paramter
N = TMP.shape[0]
# Get the indices that would be used as row indices to select rows off TMP and
# also as row,column indices for setting output array. These... | 1 | 2016-07-31T12:55:33Z | [
"python",
"python-3.x",
"numpy"
] |
Embedding Matplotlib and Slider in Tk window | 38,683,656 | <p>I am trying to embed a matplotlib window inside a tkinter GUI, but I am having trouble getting the "slider" widget to show up. In fact, the code below does show an embedded image, but the image itself is behaving like a slider, if you click on it!</p>
<p>I have tried using the ideas from this question </p>
<p><a h... | 0 | 2016-07-31T11:47:41Z | 38,692,794 | <p>I don't know what your code does. I tried to change it as little as I can:</p>
<pre><code>import matplotlib
matplotlib.use('TkAgg')
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import Tkinter as Tk
import matplotlib.pyplot as plt
class Emb... | 0 | 2016-08-01T07:04:54Z | [
"python",
"python-2.7",
"matplotlib",
"tkinter"
] |
Print Arabic words from Python to ESC/POS printer? | 38,683,686 | <p>I have an Odoo implementation, and I need to print Arabic words to an ESC/POS printer.</p>
<p>The Odoo community has already developed a Python module that translates UTF-8 text to ESC/POS Code Page. The problem is that when I print Arabic text I'm getting reversed text and disconnected letters.</p>
<p>How do I pr... | 2 | 2016-07-31T11:50:42Z | 39,425,875 | <p>As noted in the comments, it is not a trivial task display UTF-8 Arabic text correctly on an embedded device. You need to handle text direction, joining and character encoding.</p>
<p>I've had an attempt at this in the past for a <a href="https://github.com/mike42/escpos-php" rel="nofollow">PHP ESC/POS driver</a> t... | 0 | 2016-09-10T12:02:03Z | [
"python",
"escpos"
] |
Python Pandas: How to set Dataframe Column value as X-axis labels | 38,683,709 | <p>Say I have data in following format:</p>
<pre><code>Region Men Women
City1 10 5
City2 50 89
</code></pre>
<p>When I load it in Dataframe and plot graph, it shows index as X-axis labels instead of <code>Region</code> name. How do I get names on X-axis?</p>
<p>So far I tried:</p>
<pre><code>import pa... | 3 | 2016-07-31T11:54:14Z | 38,683,832 | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.bar.html" rel="nofollow">plot.bar()</a> method inherits its arguments from <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="nofollow">plot()</a>, which has <code>rot</code> argument:</p... | 2 | 2016-07-31T12:11:36Z | [
"python",
"pandas",
"matplotlib",
"dataframe"
] |
Python Pandas: How to set Dataframe Column value as X-axis labels | 38,683,709 | <p>Say I have data in following format:</p>
<pre><code>Region Men Women
City1 10 5
City2 50 89
</code></pre>
<p>When I load it in Dataframe and plot graph, it shows index as X-axis labels instead of <code>Region</code> name. How do I get names on X-axis?</p>
<p>So far I tried:</p>
<pre><code>import pa... | 3 | 2016-07-31T11:54:14Z | 38,683,877 | <p>Since you're using pandas, it looks like you can pass the tick labels right to the DataFrame's <code>plot()</code> method. <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="nofollow">(docs)</a>. (e.g. <code>df.plot(..., xticks=<your labels>)</code>)</p>
<p>Addit... | 2 | 2016-07-31T12:16:01Z | [
"python",
"pandas",
"matplotlib",
"dataframe"
] |
Django's Model.save() modifies undesired columns | 38,683,838 | <p>Recently I've found that Django ORM's <code>Model.save()</code> executes an SQL to update 'ALL' columns by default, even if nothing has been modified.
This really concerns me, because any changes I made has a chance to be set back to the original value by some other <code>Model.save()</code> process.</p>
<p>For ex... | 2 | 2016-07-31T12:12:09Z | 38,684,417 | <p>As other folks said in comments, you have classic type of <a href="http://stackoverflow.com/questions/34510/what-is-a-race-condition">race condition</a>. There are some ways of dealing this in Django. You've already mention some of this, but they can't be considered safety in my experience. I highly suggest you to w... | 0 | 2016-07-31T13:24:14Z | [
"python",
"sql",
"django"
] |
Django's Model.save() modifies undesired columns | 38,683,838 | <p>Recently I've found that Django ORM's <code>Model.save()</code> executes an SQL to update 'ALL' columns by default, even if nothing has been modified.
This really concerns me, because any changes I made has a chance to be set back to the original value by some other <code>Model.save()</code> process.</p>
<p>For ex... | 2 | 2016-07-31T12:12:09Z | 38,759,882 | <p>You only need one column for a similar race condition to happen:</p>
<pre><code># Process 1
account = Account.objects.get(pk=1)
account.balance += 1000
# Process 2
account = Account.objects.get(pk=1)
account.balance -= 10
account.save()
# Process 1
account.save()
</code></pre>
<p>Now the balance deduction from p... | 0 | 2016-08-04T06:23:59Z | [
"python",
"sql",
"django"
] |
How to define (string+int+...) URL Pattern RegEx Django | 38,683,848 | <p>my url :
<code>http://127.0.0.1:8000/avatar/Z0FBQUFBQlhuZWI3ejVzTU10TUwyY0twMFJqZHM5MU1LajdEVnJfSzVWN3RXcUFya00wZjdLOUZmbjBzUG5ZSldibkNXeEtMQ1dsZnE4WXlRd0lNLXllRXhNbS1CUWdFSnc9PQ==</code> </p>
<p>url pattern : <code>url(r'^avatar/(?P<avaID>\w+)$', ReportsController.UserImage),</code></p>
<p>"w+" this means ... | 0 | 2016-07-31T12:13:10Z | 38,683,888 | <p>Then match every character using <code>.</code>:</p>
<pre><code> url(r'^avatar/(?P<avaID>.+)$', ReportsController.UserImage)
</code></pre>
| 1 | 2016-07-31T12:17:22Z | [
"python",
"django",
"python-2.7"
] |
PyInstaller exe only works when run from cmd | 38,683,881 | <p>I'm trying to pack a python tool I wrote into an exe file for use on Windows 10. As far as I know, the exe is built correctly. It loads and everything works if I run it from the command line. </p>
<p>However, if I try to run the tool from Explorer (double-clicking the icon), I get a "Failed to execute script" error... | 0 | 2016-07-31T12:16:43Z | 38,684,586 | <p>I figured it out! </p>
<p>I had to convert the gui.ui file into a package.</p>
<ol>
<li>I created the package "gui," containing an empty __init__.py</li>
<li>I ran <code>pyuic4 gui.ui -o gui.py</code>to convert the gui.ui code into Python</li>
<li>I moved both gui.ui and gui.py files into the gui directory</li>
<l... | 0 | 2016-07-31T13:45:37Z | [
"python",
"windows",
"pyinstaller"
] |
find the negative couple in matrix using pandas | 38,684,026 | <p>I have got a covariance matrix using <code>dataframe.cov()</code> in pandas, now i want to find all the most negative couple(eg. <code>v1</code> and <code>v3</code> is the most negative couple in the matrix because matrix[<code>v1</code>, <code>v3</code>] is minimum, and then <code>v1</code> and <code>v3</code> is e... | 2 | 2016-07-31T12:35:48Z | 38,684,337 | <pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame({'V1': [471.18954309999998, 404.05969449999998, -59.847098750000001, 415.21412069999997, -571.67208340000002], 'V2': [404.05969449999998, 4768.2518380000001, 3740.3315439999997, 557.05004150000002, 1750.5427280000001], 'V3': [-59.847098750000001, 3740.... | 2 | 2016-07-31T13:12:45Z | [
"python",
"pandas",
"dataframe",
"covariance"
] |
find the negative couple in matrix using pandas | 38,684,026 | <p>I have got a covariance matrix using <code>dataframe.cov()</code> in pandas, now i want to find all the most negative couple(eg. <code>v1</code> and <code>v3</code> is the most negative couple in the matrix because matrix[<code>v1</code>, <code>v3</code>] is minimum, and then <code>v1</code> and <code>v3</code> is e... | 2 | 2016-07-31T12:35:48Z | 38,684,983 | <p>consider the dataframe <code>df</code></p>
<pre><code>import numpy as np
import pandas as pd
rows = pd.Index(['V1', 'V2', 'V3', 'V4', 'V5'], name='rows')
cols = pd.Index(['V1', 'V2', 'V3', 'V4', 'V5'], name='cols')
df = pd.DataFrame(
[[ 471.189543, 404.059694, -59.847099, 415.214121, -571.672083,],
... | 1 | 2016-07-31T14:28:29Z | [
"python",
"pandas",
"dataframe",
"covariance"
] |
Django: Umlaut problems in admin page | 38,684,050 | <p>I went through the django tutorial <a href="https://docs.djangoproject.com/en/1.9/intro/tutorial01/" rel="nofollow">https://docs.djangoproject.com/en/1.9/intro/tutorial01/</a>, created a couple of models. Some of the models have German labels with umlauts:</p>
<p><a href="http://i.stack.imgur.com/2PCc6.png" rel="no... | 0 | 2016-07-31T12:39:02Z | 38,684,224 | <p>Let's say you have a simple model with title attribute. You have to encode that title to <code>utf-8</code>, something like this should work.</p>
<pre><code>class MyModel(models.Model):
title = models.CharField(max_length=255)
def __str__(self):
return self.title.encode('UTF-8')
def __repr__(s... | 1 | 2016-07-31T12:59:30Z | [
"python",
"django"
] |
Saving Auto-Incrementing line number in Inline field Django | 38,684,096 | <p>I have the following model as an inline field in another model:</p>
<pre><code>class route_ordering(models.Model):
route_id = models.ForeignKey(route, on_delete=models.CASCADE)
activity_id = models.ForeignKey(activity, on_delete=models.CASCADE)
day = models.IntegerField()
order = models.IntegerField()
... | 0 | 2016-07-31T12:45:23Z | 38,684,167 | <p>I can't guarantee this will work, and I'm not able to test out right now, but I think you can pass in a generator to your default value arg.</p>
<pre><code>define increment():
return range(1, 1000)
</code></pre>
<p>And wherever your passing in a default just call <code>next(increment())</code></p>
<p>Sorry I ... | 0 | 2016-07-31T12:52:55Z | [
"python",
"django",
"postgresql",
"django-models"
] |
Python - using list() and manipulating lists | 38,684,165 | <p>I seem to have a problem with my list generating script. I'm trying to convert a string into a list of string-lists, in order to use it in a specific fonction. </p>
<p>For exemple I want to convert the string
<code>'abc'</code> to a : <code>[['a'],['b'],['c']]</code>.
so the script i wrote was:</p>
<pre><code>s... | 2 | 2016-07-31T12:52:50Z | 38,684,193 | <p>This is a classic mistake: <code>[[0]]*n</code> creates a list of <code>n</code> references to a unique object <code>[0]</code>. Use this instead to create a list of <code>n</code> different objects all equal to <code>[0]</code>: <code>[[0] for i in range(n)]</code>. This way, you can then change the value of each o... | 3 | 2016-07-31T12:56:08Z | [
"python",
"list"
] |
Python - using list() and manipulating lists | 38,684,165 | <p>I seem to have a problem with my list generating script. I'm trying to convert a string into a list of string-lists, in order to use it in a specific fonction. </p>
<p>For exemple I want to convert the string
<code>'abc'</code> to a : <code>[['a'],['b'],['c']]</code>.
so the script i wrote was:</p>
<pre><code>s... | 2 | 2016-07-31T12:52:50Z | 38,684,195 | <p><code>[[0]] * len(s)</code> doesn't do what you think it does, see this example: <a class='doc-link' href="http://stackoverflow.com/documentation/python/3553/common-pitfalls/12259/list-multiplication-and-common-references#t=201607311255286287854">List multiplication and common references</a></p>
<p>Also consider th... | 5 | 2016-07-31T12:56:20Z | [
"python",
"list"
] |
Getting strings in a entry widget and printing some response through a label | 38,684,271 | <p>So i saw many videos and questions and stuff but i'm still stuck on how i can respond to strings in an entry widget.so far all the tuts and videos seem to show how to handle numbers and not string,To be more specific i want to make a Tkinter Gui box that has an entry widget and when i type 'hey',it should respond/an... | 0 | 2016-07-31T13:06:05Z | 38,684,331 | <p>You can use a <code>StringVar</code> to get/set the string value of an Entry widget:</p>
<pre><code>import tkinter as tk
master = tk.Tk()
val = tk.StringVar()
entry = tk.Entry(master, textvariable=val)
entry.pack()
val.set("some value")
the_string = val.get()
print(the_string)
# some value
</code></pre>
| 1 | 2016-07-31T13:12:15Z | [
"python",
"user-interface",
"tkinter",
"python-3.4"
] |
What's the purpose of a password in symmetric cryptography? | 38,684,333 | <p>I found the Python package to encrypt some data and see <a href="https://cryptography.io/en/latest/fernet/#using-passwords-with-fernet" rel="nofollow">this</a> in python Cryptography:</p>
<blockquote>
<p>It is possible to use passwords with Fernet(symmetric key). To do this, you need to run the password through a... | 0 | 2016-07-31T13:12:25Z | 38,684,378 | <p>A password is something that can be remembered by a person whereas a key is usually not remembered, because it is long (at least 128 bit or Hex-encoded in 32 characters) and is supposed to be really random (indistinguishable from random noise). If you want to encrypt something with a key, but this key cannot be tran... | 6 | 2016-07-31T13:19:50Z | [
"python",
"security",
"cryptography",
"passwords",
"symmetric-key"
] |
BeautifulSoup won't remove i element | 38,684,392 | <p>I am learning how to parse and manipulate <code>html</code> using <code>beautiful soup</code> like so:</p>
<pre><code>from lxml.html import parse
import urllib2
from urllib2 import urlopen
from BeautifulSoup import BeautifulSoup
url = 'some-url-here'
req = urllib2.Request(url, headers={'User-Agent' : "Magic Browse... | 1 | 2016-07-31T13:21:23Z | 38,684,510 | <p>The issue is actually the fact you are using the deprecated <em>Beautifulsoup3</em>, install <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow"><em>bs4</em></a> and everything will work fine:</p>
<pre><code>In [10]: import urllib2
In [11]: from bs4 import BeautifulSoup # bs4
In [12]:... | 1 | 2016-07-31T13:36:29Z | [
"python",
"beautifulsoup",
"web-crawler"
] |
Autocompletion with Jedi-vim gives Error | 38,684,578 | <pre><code>-- Omni completion (^O^N^P) Pattern not found
</code></pre>
<p>This is the error that I am getting when I look into the :messages in Vim.</p>
<pre><code>Please install Jedi if you want to use jedi-vim.
The error was: dlopen(/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python... | 0 | 2016-07-31T13:45:04Z | 38,684,786 | <p>I installed jedi-vim with pathogen, and it now works.</p>
<pre><code>pip install --user jedi
cd ~/.vim/bundle/
git clone https://github.com/davidhalter/jedi-vim.git
</code></pre>
<p>You can also run <strong>this</strong>:</p>
<pre><code>sudo apt-get install vim-python-jedi
</code></pre>
<p>This should help</p>
| 1 | 2016-07-31T14:06:34Z | [
"python",
"vim",
"vim-plugin",
"jedi-vim"
] |
Autocompletion with Jedi-vim gives Error | 38,684,578 | <pre><code>-- Omni completion (^O^N^P) Pattern not found
</code></pre>
<p>This is the error that I am getting when I look into the :messages in Vim.</p>
<pre><code>Please install Jedi if you want to use jedi-vim.
The error was: dlopen(/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python... | 0 | 2016-07-31T13:45:04Z | 38,686,061 | <p>This has happened because of the 2 versions python installed on the Mac.
One that came by default resided in /usr/bin directory and was 2.7.10 version. One that I installed using brew was in the /usr/local/bin directory and was 2.7.12 version. </p>
<p>Vim was using the 2.7.10 version but looking for packages in the... | 1 | 2016-07-31T16:25:22Z | [
"python",
"vim",
"vim-plugin",
"jedi-vim"
] |
Autocompletion with Jedi-vim gives Error | 38,684,578 | <pre><code>-- Omni completion (^O^N^P) Pattern not found
</code></pre>
<p>This is the error that I am getting when I look into the :messages in Vim.</p>
<pre><code>Please install Jedi if you want to use jedi-vim.
The error was: dlopen(/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python... | 0 | 2016-07-31T13:45:04Z | 39,723,279 | <p>uninstall was not a solution in my case, vim complained at the very beginning, that is not finding python support
I did the following:</p>
<pre><code>cd /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/
mv _io.so _io.so.orig
cp /usr/lib/python2.7/lib-dynload/_io.so... | 0 | 2016-09-27T11:17:52Z | [
"python",
"vim",
"vim-plugin",
"jedi-vim"
] |
Bring all values in an array closer together | 38,684,614 | <p>I need to do is "crush" the values in l1 by some percentage so they are closer together such that perhaps if an array l1 were ...</p>
<pre><code>l1 =[10,20,30,40,50,60,70,80,90,100]
</code></pre>
<p>Then l2 <em>could be...</em> </p>
<pre><code>l2 = [12.5, 25.0, 37.5, 50.0, 62.5, 45.0, 52.5, 60.0, 67.5, 75.0]
</co... | -3 | 2016-07-31T13:48:47Z | 38,684,860 | <p>Why not find the lowest number in your list and divide the whole list by that number? Or even any number that you want. </p>
<pre><code>num = percentage/100 # gets you a decimal
l2 = [x*num for x in l1]
</code></pre>
<p>Use <code>min()</code> to find the lowest number of the list if you want to go that way.</p>
| 0 | 2016-07-31T14:12:50Z | [
"python",
"arrays",
"algorithm",
"sorting"
] |
Bring all values in an array closer together | 38,684,614 | <p>I need to do is "crush" the values in l1 by some percentage so they are closer together such that perhaps if an array l1 were ...</p>
<pre><code>l1 =[10,20,30,40,50,60,70,80,90,100]
</code></pre>
<p>Then l2 <em>could be...</em> </p>
<pre><code>l2 = [12.5, 25.0, 37.5, 50.0, 62.5, 45.0, 52.5, 60.0, 67.5, 75.0]
</co... | -3 | 2016-07-31T13:48:47Z | 38,685,211 | <p>Just scale towards the median?</p>
<pre><code>>>> l1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> import statistics
>>> median = statistics.median(l1)
>>> [(x - median) / 10 + median for x in l1]
[50.5, 51.5, 52.5, 53.5, 54.5, 55.5, 56.5, 57.5, 58.5, 59.5]
</code></pre>
| 2 | 2016-07-31T14:55:49Z | [
"python",
"arrays",
"algorithm",
"sorting"
] |
How to change the arrow head style in matplotlib annotate? | 38,684,619 | <p>I want to change the head of an arrow in an annotation (<code>matplotlib</code>), but it doesn't work when used together with other properties, like <code>shrink</code>. It seems to change the type of object created, by looking at the parameters set.</p>
<hr>
<p><strong>Example</strong></p>
<p>The following code ... | 3 | 2016-07-31T13:49:19Z | 38,684,804 | <p>From the <a href="http://matplotlib.org/api/text_api.html#matplotlib.text.Annotation" rel="nofollow">matplotlib documentation</a>, "if the dictionary has a key arrowstyle, a FancyArrowPatch instance is created with the given dictionary and is drawn. Otherwise, a YAArrow patch instance is created and drawn."</p>
<p>... | 1 | 2016-07-31T14:08:04Z | [
"python",
"numpy",
"matplotlib"
] |
Porting python hash digest to node js | 38,684,647 | <p>I'm trying to port a Python script to Node and I've become stuck on SHA1 hashes.</p>
<p>The following Python code:</p>
<pre><code>import hashlib
user = 'test'
ret = hashlib.sha1(user.encode('utf-8')).digest()
print(ret);
</code></pre>
<p>Prints out:</p>
<pre><code>b'\xa9J\x8f\xe5\xcc\xb1\x9b\xa6\x1cL\x08s\xd3\... | 1 | 2016-07-31T13:52:39Z | 38,684,790 | <p>Both results are the same already. The string representation of bytes (the stuff you see on the console) differs in JavaScript and Python though. To prove that they're identical, convert both to an integer list:</p>
<pre><code>> var crypto = require('crypto');
> var generator = crypto.createHash('sha1');
>... | 2 | 2016-07-31T14:06:44Z | [
"python",
"node.js",
"sha1"
] |
Customize Keras' loss function in a way that the y_true will depend on y_pred | 38,684,768 | <p>I'm working on a multi-label classifier. I have many output labels [1, 0, 0, 1...] where 1 indicates that the input belongs to that label and 0 means otherwise. </p>
<p>In my case the loss function that I use is based on MSE. I want to change the loss function in a way that when the output label is -1 than it will ... | 3 | 2016-07-31T14:05:04Z | 38,738,401 | <p>I believe this is what you looking for.</p>
<pre><code>import theano
from keras import backend as K
from keras.layers import Dense
from keras.models import Sequential
def customized_loss(y_true, y_pred):
loss = K.switch(K.equal(y_true, -1), 0, K.square(y_true-y_pred))
return K.sum(loss)
if __name__ == '__... | 1 | 2016-08-03T08:31:41Z | [
"python",
"classification",
"theano",
"keras"
] |
Redirect Embedded Python IO to a console created with AllocConsole Win32 application | 38,684,857 | <p>i know that there is similar question but my efforts to resolve this problem were not successful. I want to redirect Python interpreter I/O, but i have only succeeded to redirect stdout. I have still problem with stdin and stderr. Based on <a href="http://stackoverflow.com/questions/1698439/redirect-embedded-python-... | 0 | 2016-07-31T14:12:22Z | 38,783,629 | <p>i have found solution by changing few things and using Python 3.x instead of 2.x. Now everything works fine if we modify script a bit in accordance to Python 3.x standard. </p>
<pre><code>PyObject* sys = PyImport_ImportModule("sys");
if (sys == NULL)
{
/*show error*/
}
PyObject* io = PyImport_ImportModule("io")... | 0 | 2016-08-05T07:33:00Z | [
"python",
"redirect",
"python-c-api",
"python-c-extension"
] |
What is Python replacement for PHP's error_get_last() function? | 38,684,921 | <p>I need to implement an <code>atexit</code> Python function that would get the last error object and check for it's type. If the type of python error corresponds to PHP's <code>E_ERROR</code> I should save the error's output to a file. </p>
<p>The PHP code I'm porting looks like so:</p>
<pre><code>register_shutdown... | 3 | 2016-07-31T14:19:16Z | 38,684,978 | <p>I would use <a href="https://docs.python.org/3/library/sys.html#sys.last_value" rel="nofollow"><code>sys.last_value</code></a> for this:</p>
<pre><code>import atexit
import sys
def fatal_handler():
try:
e = sys.last_value
except AttributeError: # no exception prior to execution of fatal_handler
... | 2 | 2016-07-31T14:27:41Z | [
"php",
"python",
"exception-handling",
"port"
] |
What is Python replacement for PHP's error_get_last() function? | 38,684,921 | <p>I need to implement an <code>atexit</code> Python function that would get the last error object and check for it's type. If the type of python error corresponds to PHP's <code>E_ERROR</code> I should save the error's output to a file. </p>
<p>The PHP code I'm porting looks like so:</p>
<pre><code>register_shutdown... | 3 | 2016-07-31T14:19:16Z | 38,685,146 | <p>When an exception is raised and uncaught, the interpreter calls <a href="https://docs.python.org/3/library/sys.html#sys.excepthook" rel="nofollow">sys.excepthook</a> with info about the exception. The default function prints out a given traceback and exception to sys.stderr. You can replace this function with a func... | 1 | 2016-07-31T14:48:39Z | [
"php",
"python",
"exception-handling",
"port"
] |
How does django static exactly work | 38,684,976 | <p>I have always used PHP and finally decided to get out of that cave and explore other scripting languages like django.</p>
<p>I am still wrapping my head around project structure in django and can't seem to figure out how to include css, js, and other so called static files.</p>
<p>I have read up on the django wiki... | 1 | 2016-07-31T14:27:26Z | 38,685,037 | <p>When you use the <code>static</code> tag in your template:</p>
<pre><code><link rel="stylesheet" type="text/css" href="{% static '/static/menu.css' %}"/>
</code></pre>
<p>It will just be expanded by replacing the <code>{% static</code> part, with the <code>STATIC_URL</code> value. So that tag becomes:</p>
<... | 1 | 2016-07-31T14:34:30Z | [
"python",
"django",
"static"
] |
How metaclass ( __call__) working in this case? | 38,685,013 | <pre><code>import inspect
class meta(type):
def __new__(cls, t_name, bases, argdict):
print "inside meta __new__"
return super(meta, cls).__new__(cls, t_name, bases, argdict)
def __init__(self, t_name, bases, argdict):
print "inside __init__ of meta"
def __call__(cls, *args, **kwargs):
... | 0 | 2016-07-31T14:31:38Z | 38,685,383 | <p>The first argument of a method is the instance. An instance of a metaclass is a class, which is why we name the argument <code>cls</code>.</p>
<p><code>super()</code> needs the instance so that it can follow MRO properly. Its methods are already bound to an appropriate instance and so don't need the instance to be ... | 0 | 2016-07-31T15:14:09Z | [
"python",
"call",
"super",
"metaclass"
] |
How can I re-run my program in python | 38,685,021 | <p>I would like to know how can I re-run this program. After succeful process I want to offer an opportunity to use this program again without closing and re-opeing.
How can I do it?
After run this code it just open window of python and instantly close it.</p>
<pre><code>def sifra():
retezec = input("Zadejte slovo: "... | -1 | 2016-07-31T14:32:35Z | 38,685,419 | <p>Perhaps all you need is for your program window to stay open until you can inspect the result. But your question is about continuing to run the program after it reaches the end, so here is the answer to that:</p>
<ol>
<li><p>Open a Windows command window ("CMD prompt").</p></li>
<li><p>Run your program by explicitl... | 0 | 2016-07-31T15:18:54Z | [
"python",
"caesar-cipher"
] |
How can I re-run my program in python | 38,685,021 | <p>I would like to know how can I re-run this program. After succeful process I want to offer an opportunity to use this program again without closing and re-opeing.
How can I do it?
After run this code it just open window of python and instantly close it.</p>
<pre><code>def sifra():
retezec = input("Zadejte slovo: "... | -1 | 2016-07-31T14:32:35Z | 38,687,833 | <p>Problem was in type of variable zprava..it should be zprava = "" not zprava = 0
and in missing quotation marks in if (i > ord(z)): --> if (i > ord("z")):</p>
<p>But one thing that is still not working is ending program..Why sys.exit() does not work?</p>
| 0 | 2016-07-31T19:49:34Z | [
"python",
"caesar-cipher"
] |
Search JSON returned from API by value in Python | 38,685,098 | <p>I'm accessing an API using Python 2.7.12 which gives a JSON response. The JSON looks something like this:</p>
<pre><code>{
"Header": {
"GeneratedAt": "2016-07-31T13:42:33",
"PeriodA": {
"startDate": "20160718",
"type": "WEEKLY",
"endDate": "20160724"
... | 1 | 2016-07-31T14:43:07Z | 38,685,133 | <p><code>json.loads</code> gives you a regular Python nested dictionary, so something like this should work (assuming the Data entry you want is always the first one):</p>
<pre><code>for metric in data['Data'][0]['Metrics']:
if metric['name'] == "Sales":
totalSales = metric['values']['A']
</code></pre>
<p... | 2 | 2016-07-31T14:47:31Z | [
"python",
"json"
] |
Search JSON returned from API by value in Python | 38,685,098 | <p>I'm accessing an API using Python 2.7.12 which gives a JSON response. The JSON looks something like this:</p>
<pre><code>{
"Header": {
"GeneratedAt": "2016-07-31T13:42:33",
"PeriodA": {
"startDate": "20160718",
"type": "WEEKLY",
"endDate": "20160724"
... | 1 | 2016-07-31T14:43:07Z | 38,685,147 | <p>Presuming the order is always the same you just access by key, you also don't need to use json.loads as requests can handle that for you:</p>
<pre><code>js = requests.get(url).json()
total_sales = js["Data"][0]['Metrics'][0]["values"]["A"]
print(total_sales)
</code></pre>
<p>If the order can be different, just i... | 3 | 2016-07-31T14:48:42Z | [
"python",
"json"
] |
Python Input Validation for both alphabets and numeric in one input | 38,685,121 | <p>How do i do an input validation for NRIC numbers where there are both numbers and alphabets?
Example of NRIC number: S9738275G, S8937231H, S7402343B
ic=input('Enter NRIC Number: ')</p>
| 2 | 2016-07-31T14:45:37Z | 38,685,139 | <p>This can be done in a lot of different ways. Depending on the scale of your application, you might want something simpler or more complex.</p>
<p>If you want something rock solid, you can use a library such as <a href="https://github.com/kolypto/py-good" rel="nofollow">Pygood</a> for that.</p>
<p>If you're looking... | 0 | 2016-07-31T14:48:05Z | [
"python"
] |
Python Input Validation for both alphabets and numeric in one input | 38,685,121 | <p>How do i do an input validation for NRIC numbers where there are both numbers and alphabets?
Example of NRIC number: S9738275G, S8937231H, S7402343B
ic=input('Enter NRIC Number: ')</p>
| 2 | 2016-07-31T14:45:37Z | 38,685,297 | <p>Try this</p>
<pre class="lang-py prettyprint-override"><code>string = 'S9738275G';
if string.isalnum():
print('It\'s alphanumeric string')
else:
print('It\'s not an alphanumeric string')
</code></pre>
| 0 | 2016-07-31T15:04:52Z | [
"python"
] |
Python Input Validation for both alphabets and numeric in one input | 38,685,121 | <p>How do i do an input validation for NRIC numbers where there are both numbers and alphabets?
Example of NRIC number: S9738275G, S8937231H, S7402343B
ic=input('Enter NRIC Number: ')</p>
| 2 | 2016-07-31T14:45:37Z | 38,685,509 | <p>For your use case this should be enough:</p>
<pre><code>>>> a = 'A12345678B'
>>> if a[0].isalpha() and a[-1].isalpha() and a[1:-1].isdigit(): print True
...
True
>>> a = 'A12345678'
>>> if a[0].isalpha() and a[-1].isalpha() and a[1:-1].isdigit(): print True
...
>>>
</... | 1 | 2016-07-31T15:27:54Z | [
"python"
] |
How to use index in a while loop which finds the next occurrence each time | 38,685,432 | <p>I want to find the index of a letter in one string and then replace the letter in the same index but in another string, both strings are members of the dictionary. </p>
<p>however if there is more than one occurrence of the charStr (the single character) in the string it will only give the index of the first occurr... | 2 | 2016-07-31T15:20:00Z | 38,685,447 | <p>The <code>index()</code> method takes a second argument that specifies the position at which you start searching.</p>
<pre><code>'abcbd'.index('b') # 1
'abcbd'.index('b', 1) # 1
'abcbd'.index('b', 2) # 3
'abcbd'.index('b', 3) # 3
</code></pre>
<p>So at each iteration, you can use <code>pos = x('secWord').index(cha... | 4 | 2016-07-31T15:21:17Z | [
"python",
"string",
"python-3.x",
"indexing"
] |
How to correctly capture generator output in a list comprehension? | 38,685,441 | <p>I'm having some confusion with regards to a generator that I am using to create a sum of squares in python. Essentially I am iterating over vectors stored in a dictionary and finding the SS with another target vector.</p>
<p>I'm trying to code more pythonically by using list comprehension and generators but am stru... | 1 | 2016-07-31T15:20:43Z | 38,685,454 | <p>You want to use <code>list(operation(v, l))</code>. Generators are yielded as a generator object and so you have to explicitly convert them to a list using <code>list()</code>.</p>
<p>Explained with examples <a href="http://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html#returning-iterable-objects-inste... | 2 | 2016-07-31T15:21:50Z | [
"python",
"generator"
] |
How to correctly capture generator output in a list comprehension? | 38,685,441 | <p>I'm having some confusion with regards to a generator that I am using to create a sum of squares in python. Essentially I am iterating over vectors stored in a dictionary and finding the SS with another target vector.</p>
<p>I'm trying to code more pythonically by using list comprehension and generators but am stru... | 1 | 2016-07-31T15:20:43Z | 38,685,553 | <p>You're using generators wrong way. That <code>yield</code> will anyways only be executed once (provided you convert the return value to a list). And it's result in not even used in a generator expression.</p>
<p>You can change that code to something like this:</p>
<pre><code>def operation(orig, nbr):
for orig,... | 3 | 2016-07-31T15:33:01Z | [
"python",
"generator"
] |
How to correctly capture generator output in a list comprehension? | 38,685,441 | <p>I'm having some confusion with regards to a generator that I am using to create a sum of squares in python. Essentially I am iterating over vectors stored in a dictionary and finding the SS with another target vector.</p>
<p>I'm trying to code more pythonically by using list comprehension and generators but am stru... | 1 | 2016-07-31T15:20:43Z | 38,685,556 | <p>You don't need <code>yield</code> as you are returning a list. The below <code>sum</code> function in <code>operation</code> is actually a <a href="https://www.python.org/dev/peps/pep-0289/" rel="nofollow">generator expression</a> than accomplishes the same thing.</p>
<p>Thus, <code>sum([x ** 0.5 for x in some_lis... | 2 | 2016-07-31T15:33:22Z | [
"python",
"generator"
] |
Properly creating a mouse event with Kivy | 38,685,626 | <p>I am trying to create a program that will control the mouse on on my Kivy application. What is the proper way to create a provider and send it the locations I want to move and click at?</p>
| 1 | 2016-07-31T15:40:56Z | 38,687,691 | <p>Take a look at the recorder module, it can both record events and also replay them</p>
<p>Here is a small example: (change RECORD to False to watch the replay after recording ... )</p>
<pre><code>import kivy
from kivy.uix.button import Button
from kivy.app import App
from kivy.input.recorder import Recorder
rec =... | 1 | 2016-07-31T19:31:50Z | [
"python",
"mouseevent",
"kivy",
"modeling"
] |
insert timestamp to json response in python | 38,685,654 | <p>I am trying to insert timestamp to the json curl get request and publish to pubnub and failing to serialize to right format</p>
<pre><code>#!/usr/bin/python
import requests
import json
import sys
import datetime
from pubnub import Pubnub
now = datetime.datetime.now()
pubnub = Pubnub(
publish_key = "key",
subscri... | 0 | 2016-07-31T15:44:43Z | 38,685,752 | <p>You get this result because you are sending a tuple containing a dictionary and the timestamp, so obviously it will return the tuple as the response. Try to inserting the timestamp in the message you will send. </p>
<p>See if the below works:</p>
<pre><code>message = json.loads(requests.get("http://localhost:8080/... | 0 | 2016-07-31T15:53:28Z | [
"python",
"json",
"pubnub"
] |
quicksort code in Python | 38,685,665 | <p>I am trying to code quicksort in Python but wasn't able to correct the errors? How do I fix all these errors? Is there anything wrong with the logic?</p>
<pre><code>Traceback (most recent call last):
line 35, in module
line 5, in quicksort
line 3, in quicksort
line 30, in partition
IndexError: lis... | 0 | 2016-07-31T15:45:53Z | 38,686,686 | <pre><code> elif a[pivot] > a[right] :
temp = a[right]
a[right] = a[pivot]
a[pivot] = a[temp]
pivot = right
</code></pre>
<p>Notice you set <code>a[pivot]</code> to <code>a[temp]</code>. You need to set it to <code>temp</code>.</p>
<p>and here:</p>
<pre><code> elif a[pivot] <... | 0 | 2016-07-31T17:34:05Z | [
"python",
"quicksort"
] |
A surprise with 1**math.nan and 0j**math.nan | 38,685,737 | <p>I'm surprised that </p>
<pre><code>>>> import math
>>> 1**math.nan
1.0
</code></pre>
<p>And while we are at it, also that</p>
<pre><code>>>> 0j**math.nan
0j
</code></pre>
<p>I didn't find any other examples. Is there a reason or some logic I've missed that makes this the right choice? ... | 12 | 2016-07-31T15:52:36Z | 38,687,984 | <p>Quoting this <a href="http://stackoverflow.com/questions/17863619/why-does-nan0-1">question</a> which in turns quotes IEEE 754 (see <a href="https://en.wikipedia.org/wiki/NaN#Function_definition" rel="nofollow">Wikipedia</a>),</p>
<blockquote>
<p>The 2008 version of the IEEE 754 standard says that pow(1,qNaN) and... | 6 | 2016-07-31T20:08:33Z | [
"python",
"floating-point",
null,
"ieee-754"
] |
Print dataframe after grouping H2o python | 38,685,750 | <p><strong>Data:</strong> "<a href="https://github.com/estimate/pandas-exercises/blob/master/baby-names2.csv" rel="nofollow">https://github.com/estimate/pandas-exercises/blob/master/baby-names2.csv</a>"<br>
In pandas:<br></p>
<pre><code>df=pd.read_csv("baby-names2.csv")
df_group=df.groupby("year")
print df_group.head(... | 0 | 2016-07-31T15:53:27Z | 38,689,601 | <p>To get an h2o frame after you've used <code>groupby()</code>, use <code>.get_frame()</code> which returns the result of the group-by. For example, if you wanted to get the count for each year you could do:</p>
<pre><code>df=h2o.import_file("baby-names2.csv")
df_group=df.group_by("year").count()
df_group.get_frame()... | 0 | 2016-08-01T00:37:42Z | [
"python",
"pandas",
"h2o"
] |
import logging.handlers breaks my program. Why? | 38,685,895 | <p>While debugging a problem I have simplified the program in question to just few lines, but I still do not understand what's wrong. Could you please help?</p>
<pre><code>import logging
def setup():
logging.warning("start")
import logging.handlers
setup()
</code></pre>
<p>The code above produces an excepti... | 0 | 2016-07-31T16:06:49Z | 38,685,946 | <p>The <code>logging.warning</code> function will try to reference the variable from local scope first in <code>setup()</code> function, which is from <code>import logging.handlers</code>, and it finds it to be declared after the line you're using it.</p>
<p>Try changing it to:</p>
<pre><code>import logging
def setu... | 2 | 2016-07-31T16:11:30Z | [
"python",
"python-import"
] |
import logging.handlers breaks my program. Why? | 38,685,895 | <p>While debugging a problem I have simplified the program in question to just few lines, but I still do not understand what's wrong. Could you please help?</p>
<pre><code>import logging
def setup():
logging.warning("start")
import logging.handlers
setup()
</code></pre>
<p>The code above produces an excepti... | 0 | 2016-07-31T16:06:49Z | 38,686,010 | <p>You can see the problem if you disassemble the bytecode for that function:</p>
<pre>
>>> dis.dis(setup)
2 0 LOAD_FAST 0 (logging)
3 LOAD_ATTR 0 (warning)
6 LOAD_CONST 1 ('start')
9 CALL_FUNCTION 1 (1 positio... | 2 | 2016-07-31T16:19:11Z | [
"python",
"python-import"
] |
How to create a non-blocking function? | 38,686,084 | <p>I am new to tornado.</p>
<p>It's exciting about the part of Coroutines.</p>
<p>So i try to convert a blocking function into a non-blocking at first.</p>
<pre><code>@tornado.concurrent.return_future
def calculate(callback):
start_time = time.time()
res = urllib2.urlopen("https://www.google.com/")
print... | 1 | 2016-07-31T16:27:29Z | 38,687,632 | <p><code>return_future</code> doesn't make a function non-blocking; it takes a non-blocking function that uses callbacks and makes it coroutine-friendly. </p>
<p>The only way to make a blocking function non-blocking without making deep changes to it is to run it in another thread or process, as with a <code>ThreadPool... | 2 | 2016-07-31T19:24:08Z | [
"python",
"tornado"
] |
Trouble clicking web element with python, selenium, and pyvirtualdisplay | 38,686,182 | <p>I have a simple web crawler that logs into Twitter, goes the the following page, then grabs information from all my followers (if they are muted, etc) by clicking on the gear icon. The problem is that click functionality has stopped working on my new computer.</p>
<p>Also, I am using the Firefox() web driver.</p>
... | 2 | 2016-07-31T16:39:02Z | 38,686,717 | <p>It could be due to a window too small where the targeted element ends up hidden under another one. Try to set the original size:</p>
<pre><code>driver.set_window_size(1920, 1200)
</code></pre>
<p>You could also try to change the scroll behaviour if your element ends up hidden under the top banner:</p>
<pre><code>... | 2 | 2016-07-31T17:36:57Z | [
"python",
"python-2.7",
"selenium",
"firefox",
"pyvirtualdisplay"
] |
Search for an Xpath returning results outside an element with a specified attribute in scrapy | 38,686,206 | <p>I'm using the scrapy shell to grab all of the links in the subcategories section of this site: <a href="https://www.dmoz.org/Computers/Programming/Languages/Python/" rel="nofollow">https://www.dmoz.org/Computers/Programming/Languages/Python/</a>. </p>
<p>There's probably a more efficient Xpath, but the one I came u... | 0 | 2016-07-31T16:41:13Z | 38,686,352 | <p>I cant seem to find any id with the name doc in the page You are trying to scrape, You might haven't set a starting response.xpath. do you get the same result if You should to change, so like: </p>
<pre><code>response.xpath('//*div[@id="subcategories-div"]/section/div/div/a/@href').extract()
</code></pre>
| 0 | 2016-07-31T16:56:00Z | [
"python",
"html",
"xpath",
"scrapy"
] |
How to calculate how many different ways I can order a list in python | 38,686,269 | <p>I'm a little confused on how to do this, and I know it probably requires a bit of probability knowledge too (which I'm lacking).</p>
<p>How can I calculate how many ways, and also get all the possibilities, of how many ways I can order a list?</p>
<p>For example if I have <code>lst = ["a", "a", "a", "a", "b", "b",... | 3 | 2016-07-31T16:47:28Z | 38,686,314 | <p>You can use <code>permutations()</code> to get the all permutations, and <code>set()</code> in order to remove the duplicate items:</p>
<pre><code>>>> from itertools import permutations
>>> set(permutations(lst))
{('b', 'a', 'b', 'a', 'a', 'a', 'b'), ('b', 'a', 'a', 'b', 'a', 'a', 'b'), ('b', 'a',... | 6 | 2016-07-31T16:51:58Z | [
"python",
"probability"
] |
How to calculate how many different ways I can order a list in python | 38,686,269 | <p>I'm a little confused on how to do this, and I know it probably requires a bit of probability knowledge too (which I'm lacking).</p>
<p>How can I calculate how many ways, and also get all the possibilities, of how many ways I can order a list?</p>
<p>For example if I have <code>lst = ["a", "a", "a", "a", "b", "b",... | 3 | 2016-07-31T16:47:28Z | 38,693,715 | <p>As Kasramvd mentions, using <code>itertools.permutations</code> is <em>not</em> an efficient way to generate permutations of a list that contains repeated elements. Your sample data has 7 elements, so <code>itertools.permutations</code> generates 7! = 5040 permutations, but there are only 35 = <a href="https://en.wi... | 5 | 2016-08-01T08:00:46Z | [
"python",
"probability"
] |
How to calculate how many different ways I can order a list in python | 38,686,269 | <p>I'm a little confused on how to do this, and I know it probably requires a bit of probability knowledge too (which I'm lacking).</p>
<p>How can I calculate how many ways, and also get all the possibilities, of how many ways I can order a list?</p>
<p>For example if I have <code>lst = ["a", "a", "a", "a", "b", "b",... | 3 | 2016-07-31T16:47:28Z | 38,731,083 | <p>It sounds like you are simply trying to calculate the number of distinguishable permutations, not generate them.</p>
<p>If you have n<sub>1</sub> indistinguishable elements of one kind, n<sub>2</sub> indistinguishable elements of another kind, up to n<sub>k</sub> elements of the last kind, then the formula for numb... | 0 | 2016-08-02T21:50:43Z | [
"python",
"probability"
] |
How to define a callable function whenever the value of any element in the list gets changed? | 38,686,344 | <p>I know this question is kind of simple and silly but I got stymied of searching the internet. Consider we have a 2-dimensional list in Python which represents a game board of hex and its elements would be changed by some function (like playing stone at some cell in the game board).</p>
<p>What I am looking for is a... | 1 | 2016-07-31T16:55:20Z | 38,686,541 | <p>Your requirements:</p>
<ul>
<li><p>2-dimensinal list in python which represents a game board of hex </p></li>
<li><p>and its elements would be changed by some function (like playing stone at some cell in the game board). </p></li>
<li><p>a function to be called whenever the value of any element in the array gets ch... | 1 | 2016-07-31T17:18:40Z | [
"python",
"list",
"numpy"
] |
How to set a variable's subproperty? | 38,686,377 | <p>I am a newbie to Python. I got some Python sample code from a software vendor who extended their software API with boost.python so we can call them in Python. I am confused with some of the segments, such as:</p>
<pre class="lang-py prettyprint-override"><code>settings = zoo.AddAnimalSettings(carni_bird_list)
setti... | 1 | 2016-07-31T16:58:34Z | 38,686,564 | <p>I don't really see what's the issue. Consider an <code>Enum</code> defined in python:</p>
<pre><code>import enum
class Type(enum.Enum):
Bird = 0
Cat = 1
</code></pre>
<p>The <code>Type.Bird</code> and <code>Type.Cat</code> are <strong>instances</strong> of the <code>Type</code> class:</p>
<pre><code>>... | 2 | 2016-07-31T17:20:59Z | [
"python"
] |
Smooth line with spline and datetime objects doesn't work | 38,686,415 | <p>I have been trying to make a plot smoother, like it is done <a href="http://stackoverflow.com/questions/5283649/plot-smooth-line-with-pyplot">here</a>, but my Xs are datetime objects that are not compatible with linspace..</p>
<p>I convert the Xs to matplotlib dates:</p>
<pre><code>Xnew = matplotlib.dates.date2num... | 0 | 2016-07-31T17:04:56Z | 38,687,139 | <p>Your <code>X</code> values are reversed, <code>scipy.interpolate.spline</code> requires the independent variable to be monotonically increasing, and this method is deprecated - use <code>interp1d</code> instead (see below).</p>
<pre><code>>>> from scipy.interpolate import spline
>>> import numpy a... | 1 | 2016-07-31T18:27:37Z | [
"python",
"datetime",
"matplotlib",
"scipy",
"interpolation"
] |
Having both a method and a function which do the same thing? | 38,686,437 | <p>Is there a convention on how to have both a method and a function that do the same thing (or whether to do this at all)?</p>
<p>Consider, for example,</p>
<pre><code>from random import choice
from collections import Counter
class MyDie:
def __init__(self, smallest, largest, how_many_rolls):
self.min =... | 0 | 2016-07-31T17:07:11Z | 38,686,864 | <p>Here is an alternative that still allows you to encapsulate the logic in <code>MyDie</code>. Create a class method in <code>MyDie</code> </p>
<pre><code>@staticmethod
def count_specified_values(random_func, number_of_values):
return Counter([randoms_func() for n in range(number_of_values)])
</code></pre>
<p>You... | 0 | 2016-07-31T17:54:50Z | [
"python",
"function",
"methods"
] |
Cant understand why i am getting a keyerror in my django python app | 38,686,475 | <p>I know that a key error is raised when a dict() object is requested (using the format a = adict[key]) and the key is not in the dictionary. But my key is there. It's telling me that the 'embed' key is the problem</p>
<p>heres my code</p>
<pre><code> def scrape_and_store_vlad():
url_two = 'http://www.exa... | -1 | 2016-07-31T17:12:10Z | 38,686,601 | <p>The key is clearly not there, otherwise you would not get a <code>KeyError</code>.</p>
<p>You do not set the key in your <code>scrape_and_store_vlad</code> method.</p>
<pre><code>def scrape_and_store_vlad():
...
entries = [{'href': url_two + div.a.get('href'),
'src': url_two + div.a.img.get... | 1 | 2016-07-31T17:24:00Z | [
"python",
"django",
"dictionary",
"keyerror"
] |
Where is python folder? Python install problems | 38,686,493 | <p>I have installed Python 3.5.2 on my windows 8 computer, I tried in cmd <code>python --version</code> and it gave me that stupid error: </p>
<p>"python is not recognized as an internal or external command..."</p>
<p>I also have no files named python on my computer anywhere. I used the search feature on file explore... | 0 | 2016-07-31T17:14:33Z | 38,686,576 | <p>You may try to use <code>which python</code> to find out the location of python in your computer. If it doesn't work and you cannot find where is the your installed directory, you may need to reinstall and make sure you remember the installation directory and add it as a environment variable in windows system.</p>
| 0 | 2016-07-31T17:21:23Z | [
"python",
"install"
] |
Where is python folder? Python install problems | 38,686,493 | <p>I have installed Python 3.5.2 on my windows 8 computer, I tried in cmd <code>python --version</code> and it gave me that stupid error: </p>
<p>"python is not recognized as an internal or external command..."</p>
<p>I also have no files named python on my computer anywhere. I used the search feature on file explore... | 0 | 2016-07-31T17:14:33Z | 38,686,608 | <p>In Windows 8 for Python 3.* I believe it is:
C:\Users\<em>yourusername</em>\AppData\Local\Programs\Python\</p>
<p>To use that from the Windows command line you will need to add it to your path. </p>
<p>Control Panel -> Advanced System Settings -> Environment Variables -> System Variables -> Path</p>
<p>Add in th... | 1 | 2016-07-31T17:24:24Z | [
"python",
"install"
] |
Where is python folder? Python install problems | 38,686,493 | <p>I have installed Python 3.5.2 on my windows 8 computer, I tried in cmd <code>python --version</code> and it gave me that stupid error: </p>
<p>"python is not recognized as an internal or external command..."</p>
<p>I also have no files named python on my computer anywhere. I used the search feature on file explore... | 0 | 2016-07-31T17:14:33Z | 38,687,374 | <p>I was probably same problem with python launcher.</p>
<p>In registry by <strong>regedit</strong> change
<code>HKEY_CLASSES_ROOT\Python.File\shell\open\command</code> from <code>"C:\some\path\to\python" "%1" %*</code> to <code>"C:\Windows\py.exe" "%1" %*</code>.</p>
<p>And first line of script shoud be:</p>
<pre><... | 0 | 2016-07-31T18:54:45Z | [
"python",
"install"
] |
How to properly display image in Python? | 38,686,610 | <p>I found this code:</p>
<pre><code>from PIL import Image, ImageTk
import tkinter as tk
root = tk.Tk()
img = Image.open(r"Sample.jpg")
canvas = tk.Canvas(root, width=500, height=500)
canvas.pack()
tk_img = ImageTk.PhotoImage(img)
canvas.create_image(250, 250, image=tk_img)
root.mainloop()
</code></pre>
<p>It disp... | 1 | 2016-07-31T17:24:32Z | 38,728,999 | <p>Well, no, your first example still cuts off by a few pixels. All top level windows will have padding around their absolute borders to prevent other elements from 'bleeding' into the borders and looking unprofessional.</p>
<p>You are still being given a canvas of 604 pixels by 604 pixels, but the root window itself ... | 0 | 2016-08-02T19:31:28Z | [
"python",
"python-3.x",
"tkinter",
"python-imaging-library"
] |
Combining files into multiIndex dataframe in python and finally export to txt | 38,686,713 | <p>I have a couple of files that all have the same first column (<code>X</code>), and the same column names (<code>X</code>, <code>B</code>, <code>C</code>), but the second and third column are different values.</p>
<pre><code>X | B | C
-----------
a 0 2
b 4 9
...
z 3 0
</code></pre>
<p>I want to comb... | 0 | 2016-07-31T17:36:42Z | 38,687,408 | <p>Edit - Adding a one-liner, credits to @ptrj.</p>
<pre><code>df = pd.concat([df1.set_index('X'),df2.set_index('X')],axis=1,keys = ['F1','F2'])
In []: df
Out[]:
F1 F2
B C B C
X
a 0 2 0 4
b 4 9 8 18
z 3 0 6 0
</code></pre>
<hr>
<p>Alternative Solution : </p>
<p>You can define a Multi... | 0 | 2016-07-31T18:58:44Z | [
"python",
"pandas",
"multi-index"
] |
Frequency diagram with matplotlib | 38,686,716 | <p>I am trying to automate a frequency diagram with matplotlib in Python in order to count occurences, instead of having to manually plot in Excel. However, I am not able to make an similar as possible diagram as I have done in Excel. Is this possible with Matplotlib?</p>
<p>In Excel:</p>
<p><a href="http://i.stack.i... | 0 | 2016-07-31T17:36:50Z | 38,686,854 | <p>Matplotlib does support styling. You may prefer the ggplot style:</p>
<pre><code>plt.style.use('ggplot')
</code></pre>
<p>There are many other premade styles, or you can create your own:
<a href="http://matplotlib.org/users/style_sheets.html" rel="nofollow">http://matplotlib.org/users/style_sheets.html</a></p>
| 0 | 2016-07-31T17:52:49Z | [
"python",
"excel",
"matplotlib"
] |
Frequency diagram with matplotlib | 38,686,716 | <p>I am trying to automate a frequency diagram with matplotlib in Python in order to count occurences, instead of having to manually plot in Excel. However, I am not able to make an similar as possible diagram as I have done in Excel. Is this possible with Matplotlib?</p>
<p>In Excel:</p>
<p><a href="http://i.stack.i... | 0 | 2016-07-31T17:36:50Z | 38,687,017 | <pre><code>import numpy as np
import matplotlib.pyplot as plt
def make_hist(ax, x, bins=None, binlabels=None, width=0.85, extra_x=1, extra_y=4,
text_offset=0.3, title=r"Frequency diagram",
xlabel="Values", ylabel="Frequency"):
if bins is None:
xmax = max(x)+extra_x
bin... | 2 | 2016-07-31T18:13:19Z | [
"python",
"excel",
"matplotlib"
] |
Extending Python: process numpy arrays | 38,686,765 | <p>I wrote an extension for Python 3 in C++</p>
<p>My module is capable of handling arrays like <code>[1.0, 0.0, 0.0]</code>.
I want to add support for numpy arrays as well.</p>
<p>I process arrays with the following code:</p>
<pre><code>PyObject * MyFunction(PyObject * self, PyObject * args) {
PyObject * list;
... | 2 | 2016-07-31T17:42:23Z | 39,477,955 | <p>First of all there is no <code>numpy</code> equivalent for:</p>
<ul>
<li>PyList_Type</li>
<li>PyList_Size</li>
<li>PyList_GET_ITEM or PyList_GetItem</li>
</ul>
<p>The <code>numpy.array</code> implements the <a href="https://docs.python.org/3/c-api/buffer.html" rel="nofollow">buffer interface</a>, so one can write:... | 0 | 2016-09-13T19:50:41Z | [
"python",
"c++",
"arrays",
"python-3.x",
"numpy"
] |
JRE_HOME not found on pip jnius installation | 38,686,809 | <p>Trying to install <code>jnius</code> from pip (it is a requirement to <code>pip install sikuli</code>). </p>
<p>This is the error I get when I am trying to install:</p>
<p><a href="http://i.stack.imgur.com/iSgvF.png" rel="nofollow"><img src="http://i.stack.imgur.com/iSgvF.png" alt="enter image description here"></... | 1 | 2016-07-31T17:47:37Z | 38,686,897 | <p>The setup.py contains:</p>
<pre><code>jdk_home = environ.get('JDK_HOME')
if not jdk_home:
jdk_home = subprocess.Popen('readlink -f /usr/bin/javac | sed "s:bin/javac::"',
shell=True, stdout=subprocess.PIPE).communicate()[0].strip()
if not jdk_home:
raise Exception('Unable to determine JDK_HOME')
... | 1 | 2016-07-31T17:59:34Z | [
"python",
"sikuli",
"pyjnius"
] |
Deserialize file from multipart post request in Flask | 38,686,826 | <p>In my HTML I have the following code:</p>
<pre><code><form action="editprojects" method="post" enctype="multipart/form-data">
<input type="file" name="pdf"/><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</code></pre>
<p>Now in my Flask I have the endpoint:... | 1 | 2016-07-31T17:49:24Z | 38,698,181 | <p>As @IsmailRBOUH mentioned, this fixed my problem:</p>
<pre><code>pdf.save(path, filename) // path is optional
</code></pre>
<p>This is because <code>request.files</code> gives a file instead of a string or bytes, therefore you can just save the file.</p>
| 0 | 2016-08-01T11:52:42Z | [
"python",
"html",
"file",
"flask"
] |
python basic show and return values | 38,686,830 | <p>I'm using python to input data to my script </p>
<p>then trying to return it back
on demand to show the results</p>
<p>I tried to write it as simple as possible since it's only practicing and trying to get the hang of python</p>
<p>here's how my script looks like</p>
<pre><code>#!/usr/python
## imports #####
... | -3 | 2016-07-31T17:49:39Z | 38,686,851 | <p>You're absolutely misusing globals. Please go back and read a good Python tutorial, for example from python.org.</p>
<p>Python is a programming language that allows you to define <em>functions</em>, i.e. things that <em>return</em> values. You should definitely use that, instead of <code>global</code>izing your inp... | 1 | 2016-07-31T17:52:36Z | [
"python"
] |
python basic show and return values | 38,686,830 | <p>I'm using python to input data to my script </p>
<p>then trying to return it back
on demand to show the results</p>
<p>I tried to write it as simple as possible since it's only practicing and trying to get the hang of python</p>
<p>here's how my script looks like</p>
<pre><code>#!/usr/python
## imports #####
... | -3 | 2016-07-31T17:49:39Z | 38,686,943 | <p>Your <code>getdata()</code> function returns five values. That means when you call it, you can get five values out.</p>
<pre><code>clientname, phone, location, email, website = getdata()
</code></pre>
<p>Then you can pass those into <code>showdata()</code> as arguments, if you change the function definition to say... | 1 | 2016-07-31T18:04:33Z | [
"python"
] |
Django admin: Custom ordering | 38,686,887 | <p>I have version field for a model, a string field. I defined my Django admin ordering by that field ("-version"). <br>
The problem is python's version comparison doesn't work when it comes to strings. For example:<br></p>
<pre><code>vers=['5.10.0.','5.9.0','5.8.0']
vers[0]>vers[1]
>>False
</code></pre>
<p>... | 0 | 2016-07-31T17:58:05Z | 38,692,085 | <p>Here is how I solved this:</p>
<pre><code>class MyModelAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super(MyModelAdmin, self).get_queryset(request)
qs = qs.extra(select={'nversion': "string_to_array(version, '.')::bigint[]"}).order_by('-nversion')
return qs
def ve... | 1 | 2016-08-01T06:17:11Z | [
"python",
"django",
"django-admin",
"django-filter"
] |
Pandas - Unpack column of lists of varying lengths of tuples | 38,686,918 | <p>I would like to take a Pandas Dataframe named <code>df</code> which has an ID column and a lists column of lists that have variable number of tuples, all the tuples have the same length. Looks like this:</p>
<pre><code>ID list
1 [(0,1,2,3),(1,2,3,4),(2,3,4,NaN)]
2 [(Nan,1,2,3),(9,2,3,4)]
3 [(Nan,1,2,3),(9,2,... | 3 | 2016-07-31T18:02:05Z | 38,687,037 | <pre><code>In [38]: (df.groupby('ID')['list']
.apply(lambda x: pd.DataFrame(x.iloc[0], columns=['A', 'B', 'C', 'D']))
.reset_index())
Out[38]:
ID level_1 A B C D
0 1 0 0 1 2 3
1 1 1 1 2 3 4
2 1 2 2 3 4 NaN
3 2 0 NaN 1 2 ... | 3 | 2016-07-31T18:15:52Z | [
"python",
"pandas",
"group-by",
"iterable-unpacking"
] |
Inserting unicode into MySQL database from python script | 38,686,924 | <p>I am trying to retrieve the text, longitude, and latitude from a tweepy StreamListener and then store the data in my SQL database. I am able to store the coordinates fine, but for some reason the unicode is not working.
For the SQL I have: </p>
<pre><code>mysql> CREATE TABLE tweets (tweet nvarchar(140), lat flo... | 0 | 2016-07-31T18:02:37Z | 38,687,034 | <p>You should <em>never</em> use string interpolation to create SQL commands. Use the parameter substitution that is provided by the SQL connector.</p>
<pre><code> mycursor.execute('INSERT INTO tweets (tweet, lat, lng) VALUES (%s,%s,%s)',
(status.text, status.coordinates['coordinates'][0], status.coo... | 0 | 2016-07-31T18:15:18Z | [
"python",
"mysql",
"tweepy"
] |
Write multiple Dataframes to same PDF file using matplotlib | 38,686,926 | <p>I'm stuck at a point where I have to write multiple pandas dataframe's to a PDF file.The function accepts dataframe as input.</p>
<p>However, I'm able to write to PDF for the first time but all the subsequent calls are overriding the existing data, leaving with only one dataframe in the PDF by the end.</p>
<p>Plea... | 0 | 2016-07-31T18:02:42Z | 38,687,054 | <p>Your PDF's are being overwritten, because you're creating a new PDF document every time you call <code>fn_print_pdf()</code>. You can try keep your <code>PdfPages</code> instance open between function calls, and make a call to <code>pp.close()</code> only after all your plots are written. For reference see <a href="... | 1 | 2016-07-31T18:17:50Z | [
"python",
"pdf",
"pandas",
"matplotlib"
] |
Postgresql: migrating local database to the PythonAnywhere database | 38,686,955 | <p>I've followed the Djangogirls tutorial and usually the tutorial calls for you to create a database on <code>pythonanywhere</code>. This usually works without a hitch when using <code>sqlite3</code> however this time I'm using <code>postgresql</code> and I got the below error when I ran the <code>migrate</code> comm... | 2 | 2016-07-31T18:05:43Z | 38,687,181 | <p>According to their <a href="https://help.pythonanywhere.com/pages/Postgres/" rel="nofollow">help page</a> you need to upgrade to a paid account to be able to use postgres.</p>
| 2 | 2016-07-31T18:32:40Z | [
"python",
"django",
"postgresql",
"pythonanywhere"
] |
Postgresql: migrating local database to the PythonAnywhere database | 38,686,955 | <p>I've followed the Djangogirls tutorial and usually the tutorial calls for you to create a database on <code>pythonanywhere</code>. This usually works without a hitch when using <code>sqlite3</code> however this time I'm using <code>postgresql</code> and I got the below error when I ran the <code>migrate</code> comm... | 2 | 2016-07-31T18:05:43Z | 38,704,048 | <p>To clarify, you should not be trying to connect to your local postgres. Instead, you should setup postgres on pythonanywhere, and make sure that your django settings.py is pointing the database address and port to the pythonanywhere database. Which is not local to the console/webapp server that you are running your ... | 2 | 2016-08-01T16:46:14Z | [
"python",
"django",
"postgresql",
"pythonanywhere"
] |
Python 3 from CMD | 38,687,032 | <p>I am attempting to run this .PY file from Command Prompt:</p>
<pre><code># Merge two .BSG files
# Starting block and world position are taken from the first file
# Example: "bsgmerge input.bsg output.bsg merged.bsg"
import io, sys
one = open(sys.argv[1]).readlines()
two = open(sys.argv[2]).readlines()
for n in [... | -2 | 2016-07-31T18:15:00Z | 38,687,170 | <p>I was probably same problem with python launcher.</p>
<p>If you use Linux, first line shoud be: </p>
<pre><code>#! /path/to/your/python/3
</code></pre>
<p>In Windows it some more complicated: </p>
<p>In registry by <strong>regedit</strong> change
<code>HKEY_CLASSES_ROOT\Python.File\shell\open\command</code> from... | 0 | 2016-07-31T18:31:57Z | [
"python",
"python-3.x",
"cmd"
] |
NLTK issue in deriving sql query using fcfg | 38,687,056 | <p>I'm using NLTK to get sql query from english text using feature based cfg. I followed this link <a href="http://www.nltk.org/book/ch10.html" rel="nofollow">http://www.nltk.org/book/ch10.html</a>. I can run the example stated where fcfg is stored in the sql0.fcfg file.</p>
<p>After that I tried to modify it for my o... | 0 | 2016-07-31T18:18:10Z | 38,713,635 | <p>The issue was that I was modifying the \grammars\book_grammars\sql0.fcfg. When I saved it as separate file and loaded grammar from there, the problem got solved.</p>
<p>Don't know why it happened, but it resolved the issue.</p>
| 0 | 2016-08-02T06:55:29Z | [
"python",
"parsing",
"nlp",
"nltk",
"information-extraction"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.