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 |
|---|---|---|---|---|---|---|---|---|---|
How to call a python function on an Ubuntu 12.04.5 LTS | 37,949,209 | <p>I have a python function that generates Json files according to the arguments that are passed to it. </p>
<p>We decided to make the argument selection part of a webpage in HTML. After that we want to pass the arguments to the python function on the server. The function generates the specific Json files for the brow... | -2 | 2016-06-21T15:56:11Z | 38,121,050 | <p>After a week of research, I discovered that I had to do the following </p>
<p>I set up the python function using flask and I followed this tutorial to get me started</p>
<blockquote>
<p><a href="http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask" rel="nofollow">http://blog.miguelgr... | 0 | 2016-06-30T10:54:34Z | [
"python",
"ubuntu",
"web-applications",
"https"
] |
How to calculate % of a polygon that is covered by another polygon | 37,949,247 | <p>I have a set of polygons, each one as a dictionary in python (coordinate points conforming NON convex polygons) and i would like to know what % of one polygon is covered by every other polygons.</p>
<p>I want to make an example to make it clearer. I have different delivery coverages accross a city and i have the po... | -1 | 2016-06-21T15:57:32Z | 37,961,962 | <p>There are many complications to what you require.</p>
<ol>
<li>Longitudinal length between points decreases with latitude.</li>
<li>Do polygons overlap or is one fully contained within another.</li>
<li>Does any polygon cross over itself.</li>
</ol>
<p>In your case item 1 can be ignored in most cases.</p>
<p>If p... | 0 | 2016-06-22T08:00:07Z | [
"python",
"geolocation",
"geocoding",
"polygon"
] |
Dictionary in a numpy array? | 37,949,409 | <p>How do I access the dictionary inside the array?</p>
<pre><code>import numpy as np
x = np.array({'x': 2, 'y': 5})
</code></pre>
<p>My initial thought:</p>
<pre><code>x['y']
</code></pre>
<blockquote>
<p>Index Error: not a valid index</p>
</blockquote>
<pre><code>x[0]
</code></pre>
<blockquote>
<p>Index Err... | 0 | 2016-06-21T16:05:16Z | 37,949,466 | <p>You have a 0-dimensional array of object dtype. Making this array at all is probably a mistake, but if you want to use it anyway, you can extract the dictionary by indexing the array with a tuple of no indices:</p>
<pre><code>x[()]
</code></pre>
| 2 | 2016-06-21T16:08:22Z | [
"python",
"numpy",
"ipython"
] |
Dictionary in a numpy array? | 37,949,409 | <p>How do I access the dictionary inside the array?</p>
<pre><code>import numpy as np
x = np.array({'x': 2, 'y': 5})
</code></pre>
<p>My initial thought:</p>
<pre><code>x['y']
</code></pre>
<blockquote>
<p>Index Error: not a valid index</p>
</blockquote>
<pre><code>x[0]
</code></pre>
<blockquote>
<p>Index Err... | 0 | 2016-06-21T16:05:16Z | 37,949,666 | <p>If you add square brackets to the array assignment you will have a 1-dimensional array:</p>
<pre><code>x = np.array([{'x': 2, 'y': 5}])
</code></pre>
<p>then you could use:</p>
<pre><code>x[0]['y']
</code></pre>
<p>I believe it would make more sense.</p>
| 0 | 2016-06-21T16:19:59Z | [
"python",
"numpy",
"ipython"
] |
Calling agg without first calling groupby | 37,949,434 | <p>Is there a function similar to <code>agg</code>, that doesn't require a <code>groupby</code> call first?</p>
<p>For example, I often already have an agg map written, and want to evaluate the map for the entire table.</p>
<p>So I want to change</p>
<p><code>data = data.groupby("key").agg({"foo1":"sum", "foo2":"mea... | 1 | 2016-06-21T16:06:34Z | 37,949,550 | <p><strong>UPDATE:</strong> as @root proposed in the comment, it would be easier and more elegant to group by <code>np.repeat(0, len(df))</code>:</p>
<pre><code>In [5]: df.groupby(np.repeat(0, len(df))).agg({'A':'sum', 'B':'mean', 'C':'min'})
Out[5]:
B A C
0 42.9 484 21
</code></pre>
<p><strong>OLD answ... | 1 | 2016-06-21T16:13:34Z | [
"python",
"pandas"
] |
Flask Rate-limiting without Redis | 37,949,507 | <p>I want to rate limit my flask API.
I found 2 documentations.</p>
<p>One is simple flask limiter : <a href="https://flask-limiter.readthedocs.io/en/stable/" rel="nofollow">https://flask-limiter.readthedocs.io/en/stable/</a></p>
<p>Second is using redis : <a href="http://flask.pocoo.org/snippets/70/" rel="nofollow">... | -1 | 2016-06-21T16:11:15Z | 37,949,667 | <p>Redis allows you to store the rate-limiting state in a persistent store.</p>
<p>This means you can:</p>
<ol>
<li>Restart your web server or web application and still have the rate-limitation work. You won't lose the records of the last requests made because of the working process being destroyed and a new one bein... | 4 | 2016-06-21T16:20:01Z | [
"python",
"flask",
"redis",
"rate-limiting"
] |
How to topic model a sentence? | 37,949,554 | <p>I have a list of hobbies.
e.g : Speed cubing, Numismatics, Philately, Photography etc.</p>
<p>I am trying to take a sentence as input and categorize that to one of the hobbies that I have enlisted.</p>
<p>Currently, I have a list of keywords for every hobby. I am ranking the hobbies in terms of the number of thes... | 0 | 2016-06-21T16:13:42Z | 38,614,807 | <p>That is a somewhat hard NLP problem, and it is going to be hard to find a solution that works in the majority of cases, but you can start trying to use some tricks:</p>
<p>1) Use a stemmer to compare the roots of the keywords with the root of the words in your input sentence (instead of doing an exact match of wor... | 0 | 2016-07-27T13:47:24Z | [
"python",
"topic-modeling",
"data-science"
] |
Trouble creating PIL Image object from canvas tag with Selenium | 37,949,643 | <p>I am trying to create a PIL Image object based on a <code>canvas</code> tag extracted with Selenium from <a href="http://www.trt22.jus.br/portal/home.jsp" rel="nofollow">this</a> website. The goal is to use <code>pytesseract</code> and get the captcha content. My code doesn't raise any errors, but the image created ... | 0 | 2016-06-21T16:18:49Z | 37,950,010 | <p>All I needed to do is extract the background following <a href="http://stackoverflow.com/questions/35859140/remove-transparency-alpha-from-any-image-using-pil">this</a> answer: </p>
<pre><code>def remove_transparency(im, bg_colour=(255, 255, 255)):
# Only process if image has transparency (http://stackoverflo... | 0 | 2016-06-21T16:36:23Z | [
"python",
"selenium",
"selenium-webdriver",
"python-imaging-library",
"pillow"
] |
Trouble creating PIL Image object from canvas tag with Selenium | 37,949,643 | <p>I am trying to create a PIL Image object based on a <code>canvas</code> tag extracted with Selenium from <a href="http://www.trt22.jus.br/portal/home.jsp" rel="nofollow">this</a> website. The goal is to use <code>pytesseract</code> and get the captcha content. My code doesn't raise any errors, but the image created ... | 0 | 2016-06-21T16:18:49Z | 37,950,164 | <p>You should create a RGB white image and paste your RGBA image into it. Solution may be <a href="http://stackoverflow.com/questions/9166400/convert-rgba-png-to-rgb-with-pil/9459208#9459208">this</a>, but there are other ways too. I suggest numpy and opencv.</p>
| 0 | 2016-06-21T16:45:31Z | [
"python",
"selenium",
"selenium-webdriver",
"python-imaging-library",
"pillow"
] |
Matplotlib setting xlabels | 37,949,647 | <p>I'm having trouble setting the x/ylabel for my matplotlib plot, which is using data from a sql query. </p>
<p>My code: </p>
<pre><code>import matplotlib.pyplot as plt
import pyodbc
import pandas
conn = pyodbc.connect(r'DRIVER={SQL Server Native Client 11.0};SERVER=servername;DATABASE=dbname;Trusted_Connection=Yes... | 1 | 2016-06-21T16:19:13Z | 37,949,679 | <p>Pass the argument <code>ax</code> to <code>df.plot</code>,</p>
<pre><code>fig, ax = plt.subplots()
df.plot(kind='bar', ax=ax, title="BirthMonthCounts", figsize=(15,10), legend=False, fontsize=12, x='BirthMonth', y='Cnt', xticks='BirthMonth')
</code></pre>
| 0 | 2016-06-21T16:20:30Z | [
"python",
"python-3.x",
"numpy",
"matplotlib"
] |
convert postgres query to django query | 37,949,764 | <p>I need some help with this query.</p>
<pre><code>SELECT s.nombre as 'habilidad',
GROUP_CONCAT( a.carrera_id )
FROM perfiles_alumno a,
perfiles_alumno_habilidades h,
perfiles_universidad u,
segmentacion_habilidad s
WHERE u.user_id = %s
AND a.universidad_id = u.id
AND a.i... | -2 | 2016-06-21T16:24:24Z | 37,950,217 | <p>To convert this SQL to Postgres, change <code>group_concat</code> to <code>string_agg(s.carrera_id, ',')</code>. But then it won't work on SQLite anymore. You will probably suffer less if you use the same database in both development and production.</p>
<p>Also I think you need to <code>GROUP BY h.habilidad_id, s.n... | 0 | 2016-06-21T16:47:50Z | [
"python",
"django",
"postgresql",
"sqlite"
] |
Optimization: finding optimal inputs | 37,949,838 | <p>Posted a similar question earlier but was much too vague, hope this clears up my query:</p>
<p>I have a function <code>IVcal(rho,alpha,K)</code> and I want to find the optimal values of <code>rho</code> and <code>alpha</code> such that the data list <code>smiledata</code> (the output of the function for varying K) ... | 0 | 2016-06-21T16:28:00Z | 37,952,244 | <h1>Unconstrained</h1>
<p>You could try using <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html" rel="nofollow">scipy.optimize.leastsq</a></p>
<p>This is an optimisation method that aims to reduce the difference between a current set of values and a target set of values.</p>
<p... | 1 | 2016-06-21T18:44:01Z | [
"python",
"numpy",
"optimization"
] |
Pandas: Storing a DataFrame object inside another DataFrame i.e. nested DataFrame | 37,950,087 | <p>I want to store a <code>DataFrame</code> object as a value of the column of a row:
Here's a simplified analogy of what I want to achieve.</p>
<pre><code>>>> df = pd.DataFrame([[1,2,3],[2,4,6]], columns=list('DEF'))
>>> df
166: D E F
0 1 2 3
1 2 4 6
</code></pre>
<p>I crea... | 0 | 2016-06-21T16:41:15Z | 37,950,770 | <p>Create a Dict first: </p>
<pre><code>x = pd.DataFrame()
y = {'a':[5,4,5],'b':[6,9,7], 'c':[7,3,x]}
# {'a': [5, 4, 5], 'b': [6, 9, 7], 'c': [7, 3, Empty DataFrame
# Columns: []
# Index: []]}
z = pd.DataFrame(y)
# a b c
# 0 5 6 7
... | 1 | 2016-06-21T17:21:25Z | [
"python",
"pandas",
"dataframe"
] |
Pandas: Storing a DataFrame object inside another DataFrame i.e. nested DataFrame | 37,950,087 | <p>I want to store a <code>DataFrame</code> object as a value of the column of a row:
Here's a simplified analogy of what I want to achieve.</p>
<pre><code>>>> df = pd.DataFrame([[1,2,3],[2,4,6]], columns=list('DEF'))
>>> df
166: D E F
0 1 2 3
1 2 4 6
</code></pre>
<p>I crea... | 0 | 2016-06-21T16:41:15Z | 37,951,115 | <p>You are on shaky ground relying on this behavior. pandas does a lot of work trying to infer what you mean or want when passing array like things to its constructors and assignment functions. This is pressing on those boundaries, seemingly intentionally.</p>
<p>It seems that direct assignment via <code>loc</code> ... | 1 | 2016-06-21T17:41:55Z | [
"python",
"pandas",
"dataframe"
] |
Add a Loop to an existing YouTube API Python script | 37,950,184 | <p>As confirmed with YouTube Support, unfortunately the way the YouTube API is set up, you canât pull both Country and Device Type as dimension at the same time, and the only work-around is to pull a Device Type report, and add 1 Country at a time in the filter.
Therefore, you need to fire an API call for each count... | 0 | 2016-06-21T16:46:21Z | 37,973,504 | <p>Was able to answer my own question, this is the revised code in case anyone is interested:
<a href="https://1drv.ms/u/s!AlgTM2giFod43m3plTrfSRHOfaCz" rel="nofollow">https://1drv.ms/u/s!AlgTM2giFod43m3plTrfSRHOfaCz</a></p>
<pre><code>#!/usr/bin/python
from datetime import datetime, timedelta
import httplib2
import... | 0 | 2016-06-22T16:21:07Z | [
"python",
"youtube",
"youtube-api"
] |
Updating records with Python 3 through API on Rails 4 application | 37,950,230 | <p>I'm working on a Rails 4 / mongoid application which needs to expose APIs for other applications and scripts. I need to be able to update documents in one of the models through an API with Python 3 script. I'm a bit fresh with Python hence asking for help here.</p>
<p>I already found out how to query Rails APIs wit... | 0 | 2016-06-21T16:48:43Z | 37,968,844 | <p>I figured out who to send a PATCH request with Python 3 and update the the record's <code>status</code> by <code>name</code>.</p>
<p>Thanks to <a href="http://stackoverflow.com/questions/6853050/how-do-i-make-a-patch-request-in-python#answer-7112444">this</a> post found out about <code>requests</code> module. I us... | 0 | 2016-06-22T13:00:59Z | [
"python",
"ruby-on-rails",
"api",
"python-3.x",
"ruby-on-rails-4"
] |
Stuck Coding a Python web crawler using BeautifulSoup | 37,950,240 | <p>regarding this video by bucky roberts on programming a webcrawler in python:</p>
<p><a href="https://www.youtube.com/watch?v=sVNJOiTBi_8" rel="nofollow">https://www.youtube.com/watch?v=sVNJOiTBi_8</a></p>
<p>Here is my question:</p>
<p>If i want to crawl a particular item but it isnt inside of < a> < /a></... | 0 | 2016-06-21T16:49:14Z | 37,950,416 | <p>It is the <code>td</code> that has the class <code>list-title</code>, not the anchor tag.
You just need to select the <em>td</em> tags with the class <code>list-title</code> inside the table rows then extract the href from the anchor inside each td:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
fro... | 1 | 2016-06-21T16:59:42Z | [
"python",
"html",
"beautifulsoup",
"web-crawler"
] |
Forcing Tkinter window to stay on top of fullscreen - Windows 10 | 37,950,272 | <p>I have a Tkinter window that I need to stay on top of everything else - including fullscreen windows.</p>
<p>Things I have tried:</p>
<p><code>root.attributes('-topmost', True)</code> before mainloop - doesn't work</p>
<p><code>self.root.wm_attributes("-topmost", True)</code> inside the class - doesn't work</p>
... | 2 | 2016-06-21T16:51:17Z | 38,029,318 | <p>As TessellatingHeckler pointed out in the comments, it's not possible to ensure a window stays on top of another fullscreen one. I solved this by combining a looping <code>root.lift()</code> and asking my users to run their applications in a borderless window.</p>
| 0 | 2016-06-25T14:02:58Z | [
"python",
"windows",
"tkinter",
"windows-10"
] |
Formating mp3 files to spectrograms for CNN machine learning | 37,950,354 | <p>I've had a lot of fun and have learned a lot from playing with the MNIST dataset but I want to branch out into working with my own training data, I'm using theano with keras. However I'm having an extremly difficult time conceptualizing how to create training data.</p>
<p>I looked over the structure of MNIST and sa... | 3 | 2016-06-21T16:56:14Z | 37,958,910 | <p>I may not be able to answer this question accurately. </p>
<p>I will try to explain the format of the MNIST dataset for which I will take the following example. </p>
<p>Consider that you wish to classify images with four distinct class labels in your training data -> <strong>car</strong>, <strong>bike</strong>, <s... | 1 | 2016-06-22T05:01:10Z | [
"python",
"python-2.7",
"machine-learning",
"theano",
"keras"
] |
python & litesql: unicode, utf8, how to do it properly? | 37,950,466 | <p>I have a csv file encoded as utf8 and it has some accented characters, like <code>Ningún</code> if I read these lines using the standard <code>.read()</code> python function, and then print the results, it works as intended, it prints the accented characters correctly.</p>
<p>Now, I want to insert those lines into... | 0 | 2016-06-21T17:02:35Z | 37,951,033 | <p>Everything should just work. <code>csv.reader()</code> decodes its input lines into a Unicode-aware <code>str</code>. <code>sqlite3.execute</code> accepts <code>str</code> as its input type. Consider this program:</p>
<pre><code>import csv
import sqlite3
with sqlite3.connect('sample.db') as conn:
conn.execute... | 0 | 2016-06-21T17:37:59Z | [
"python",
"sqlite",
"encoding",
"utf-8"
] |
ImportError: Failed to import msrest.authentication | 37,950,504 | <p>I have Python 2.7.9 with azure-2.0.0rc4 and msrest-0.4.0. My code failed to import from msrest.authentication. I checked the two files from azure and msrest packages, and could not find any issues.</p>
<p>Appreciate any advice and direction.</p>
<p>John</p>
<pre><code>Traceback (most recent call last):
File "... | 0 | 2016-06-21T17:04:35Z | 37,971,931 | <p>I found the issue. When I sudo pip install, read permission was not set for the others group. Once I fixed that, the issue went away. </p>
| 0 | 2016-06-22T15:07:37Z | [
"python",
"azure"
] |
pandas or numpy to mean the sum of three months. Return as list | 37,950,516 | <pre><code>Date
2013-11-30 30
2013-12-31 40
2014-01-31 50
2014-02-28 10
2014-03-31 20
2014-04-30 30
2014-05-31 80
2014-06-30 90
2014-07-31 10
df = pandas.Dataframe()
</code></pre>
<p>Lets say I have a <code>Dataframe</code> as above. How can I make a mean of the months for every third month... | 1 | 2016-06-21T17:05:38Z | 37,950,851 | <p>try this:</p>
<pre><code>In [21]: df.groupby(df.index // 3)['val'].sum().tolist()
Out[21]: [120, 60, 180]
</code></pre>
<p>if you want to group by quarter:</p>
<pre><code>In [24]: df.groupby(df.Date.dt.quarter)['val'].sum()
Out[24]:
Date
1 80
2 200
3 10
4 70
Name: val, dtype: int64
</code></pre>
<... | 1 | 2016-06-21T17:26:57Z | [
"python",
"numpy",
"pandas"
] |
pandas or numpy to mean the sum of three months. Return as list | 37,950,516 | <pre><code>Date
2013-11-30 30
2013-12-31 40
2014-01-31 50
2014-02-28 10
2014-03-31 20
2014-04-30 30
2014-05-31 80
2014-06-30 90
2014-07-31 10
df = pandas.Dataframe()
</code></pre>
<p>Lets say I have a <code>Dataframe</code> as above. How can I make a mean of the months for every third month... | 1 | 2016-06-21T17:05:38Z | 37,950,894 | <p>Make sure <strong>Date</strong> is your index</p>
<p>Than you can perform a resample:</p>
<pre><code>df_resampled = df.resample('90D').mean()
</code></pre>
<p>df_resampled will look like:</p>
<pre><code>Date
2013-11-30 40
2014-02-28 20
2014-05-29 60
</code></pre>
<p>Then you can access it with </p>
<pre... | 1 | 2016-06-21T17:29:12Z | [
"python",
"numpy",
"pandas"
] |
Using deep learning models from TensorFlow in other language environments | 37,950,525 | <p>I have a decent amount of experience with TensorFlow, and I am about to embark on a project which will ultimately culminate in using a TensorFlow trained model in a C# production environment. Essentially, I will have live data which will come into the C# environment, and I will ultimately need to output decisions / ... | 5 | 2016-06-21T17:06:06Z | 37,960,328 | <p>This is a prime use case for <a href="https://tensorflow.github.io/serving/" rel="nofollow">TensorFlow Serving</a>, which lets you create a C++ process that can run inference on a trained TensorFlow model, and serves inference requests over <a href="http://www.grpc.io/" rel="nofollow">gRPC</a>. You can write client ... | 2 | 2016-06-22T06:37:52Z | [
"c#",
"python",
"tensorflow",
"tensorflow-serving"
] |
Python: How can I restart a method without capturing any values? | 37,950,526 | <p>I created a Rock, Paper, Scissors game in Python, but I had trouble restarting the method if the player typed an invalid command. If the user types anything other than an 'r', 'p', or 's' the first time it asks, the value None will always be returned when a proper value is entered. I found I could just restart the r... | 0 | 2016-06-21T17:06:13Z | 37,950,553 | <p>To fix your current code, you should <code>return</code> the value.</p>
<pre><code>def get_input():
choice = input("[R]ock, [P]aper, or [S]cissors? ").lower()
if choice == 'r':
return 'rock'
elif choice == 'p':
return 'paper'
elif choice == 's':
return 'scissors'
else:
... | 1 | 2016-06-21T17:07:59Z | [
"python",
"methods",
"nonetype"
] |
Python: How can I restart a method without capturing any values? | 37,950,526 | <p>I created a Rock, Paper, Scissors game in Python, but I had trouble restarting the method if the player typed an invalid command. If the user types anything other than an 'r', 'p', or 's' the first time it asks, the value None will always be returned when a proper value is entered. I found I could just restart the r... | 0 | 2016-06-21T17:06:13Z | 37,950,627 | <p>When validating text input from an interactive shell, I recommend using a loop:</p>
<pre><code>def get_input():
while True:
choice = input("[R]ock, [P]aper, or [S]cissors? ").lower()
if choice == 'r':
return 'rock'
elif choice == 'p':
return 'paper'
elif c... | 3 | 2016-06-21T17:13:22Z | [
"python",
"methods",
"nonetype"
] |
PyQt5 set a QLabel x axis automatically center of the window | 37,950,537 | <p>How can I set <code>x</code> axis of the QLabel the exact center of the window? I have this example</p>
<pre><code>from PyQt5.QtWidgets import QMainWindow,QApplication,QLabel
from PyQt5 import QtCore
import sys
class cssden(QMainWindow):
def __init__(self):
super().__init__()
self.mwidget = QM... | 0 | 2016-06-21T17:06:38Z | 37,952,008 | <p>Use a vertical layout. The label will expand to fill the available space, and the text will be aligned centrally by default:</p>
<pre><code>from PyQt5.QtWidgets import QWidget, QVBoxLayout
class cssden(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowFlags(QtCore.Qt.Frameless... | 0 | 2016-06-21T18:30:45Z | [
"python",
"centering",
"pyqt5",
"qmainwindow",
"qlabel"
] |
How can I properly match a private message on IRC? | 37,950,685 | <p>I'm making a irc lib and I can't seem to match just private messages, it also matches the version string.</p>
<p><strong>REGEX</strong></p>
<pre><code>:(?P<from>.*?)!\S+\sPRIVMSG\s(?P<to>.*?)\s:(?P<msg>.+)
</code></pre>
<p><strong>VERSION MATCH</strong></p>
<pre><code>VERSION_STRING: :AkaneSenr... | -1 | 2016-06-21T17:15:56Z | 37,951,139 | <pre><code>:(?P<from>.*?)!\S+\sPRIVMSG\s(?P<to>.*?)\s+:(?!VERSION)(?P<msg>.*)$
</code></pre>
<p>It's looking for <code>: not followed by VERSION</code> with a negative lookahead <code>(?!...)</code></p>
<p>See it here: <a href="https://regex101.com/r/sQ7eS6/2" rel="nofollow">https://regex101.com/r/s... | 0 | 2016-06-21T17:42:45Z | [
"python",
"regex",
"irc"
] |
Form editing in Django UpdateView | 37,950,707 | <p>I'm trying to alter the form like its label and possibly more.
I'm using get_form method of UpdateView to alter the form but it's not working</p>
<p>views.py</p>
<pre><code>class SystemUpdateView(SuccessMessageMixin, PermissionRequiredMixin, UpdateView):
"""CRUD update view for :class:`~.System` objects"""
form_c... | 0 | 2016-06-21T17:17:03Z | 37,954,168 | <p>You need to instantiate an instance of form_class and return it. <a href="https://docs.djangoproject.com/en/1.9/ref/class-based-views/mixins-editing/#django.views.generic.edit.FormMixin.get_form" rel="nofollow">See the documentation</a></p>
<pre><code>def get_form(self, form_class=SystemForm):
form = form_class... | 0 | 2016-06-21T20:39:12Z | [
"python",
"django"
] |
Plotting a graph and a table in the same window on tkinter | 37,950,709 | <p>I want a top level window that displays an image and a table of information about the image next to it. </p>
<p>I have successfully got the image to appear using imshow(). I was wondering two things:</p>
<ul>
<li>How do I build a table in tkinter? I can't find a widget for this. </li>
<li>How do I show the two sid... | 1 | 2016-06-21T17:17:15Z | 37,957,044 | <p>For the Table, I'm assuming you want rows of records with values. For this I would recommend the <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-Treeview.html" rel="nofollow">Treeview Widget out of tkinter.ttk</a>.</p>
<p>When it comes to sitting the two next to each other, I'm assuming that you cons... | 1 | 2016-06-22T01:18:51Z | [
"python",
"user-interface",
"matplotlib",
"tkinter",
"tkinter-canvas"
] |
Python Seaborn JointGrid IndexError | 37,950,727 | <p>I am trying to draw a scatter plot with histograms of each dimension (above and to the right, using Seaborn's JointGrid function). </p>
<p>A very basic example: </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.rand(100)
y = np.random.rand(100)
sns.jointplot(x,... | 0 | 2016-06-21T17:18:36Z | 37,951,400 | <p>I downgraded to Matplotlib 1.5.1 and it is working now. Presumably some error in the rc2 version?</p>
| 0 | 2016-06-21T17:57:17Z | [
"python",
"numpy",
"matplotlib",
"seaborn"
] |
Plotting Chrominance by Boundary And Background | 37,950,740 | <p>Post I am referring to: <a href="http://stackoverflow.com/questions/36700674/how-to-extract-rgb-from-a-image-and-plot-only-rg-as-a-graph-r-for-x-and-g-for-y/37950005#37950005">How to extract RGB from a image and plot only RG as a graph? R for X and G for Y</a></p>
<p>I modified it to just be 2d and read the Y Cr Cb... | 0 | 2016-06-21T17:19:22Z | 38,038,969 | <p>Please replace the last 3 lines of your code, with these lines:</p>
<pre><code>crit0 = Y > Y_MIN
crit1 = np.logical_and(Cb > Cb_MIN, Cb < Cb_MAX)
crit2 = np.logical_and(Cr > Cr_MIN, Cr < Cr_MAX)
tot_crit = np.logical_and(np.logical_and(crit0, crit1), crit2)
i = np.where(tot_crit)
j = np.where(np.inv... | 0 | 2016-06-26T13:30:35Z | [
"python",
"matplotlib"
] |
Parallelizing a dictionary comprehension | 37,950,778 | <p>I have the following function and dictionary comprehension:</p>
<pre><code>def function(name, params):
results = fits.open(name)
<do something more to results>
return results
dictionary = {name: function(name, params) for name in nameList}
</code></pre>
<p>and would like to parallelize this. Any... | 3 | 2016-06-21T17:21:59Z | 37,951,070 | <p>The dictionary comprehension itself can not be parallelized. Here is an example how to use the <code>multiprocessing</code> module with Python 2.7.</p>
<pre><code>from __future__ import print_function
import time
import multiprocessing
params = [0.5]
def function(name, params):
print('sleeping for', name)
... | 4 | 2016-06-21T17:39:37Z | [
"python",
"python-2.7",
"dictionary",
"multiprocessing"
] |
Simplest but bulletproof way do deduce timezone of a webpage using python (based on URL)? | 37,950,889 | <p>I'm writing Django based RSS/Atom reader which is Time Zone aware - and i consider it necessary. But some websites use TZ naive format (even the big ones - Hello The Guardian) what is the best way to deduce a proper timezone based on website? </p>
| -2 | 2016-06-21T17:29:03Z | 37,955,557 | <blockquote>
<p>what is the best way to deduce a proper timezone based on website? </p>
</blockquote>
<p>You cannot deduce a time zone based on a web site. A web site can be served from anywhere in the world, and contain content about anywhere in the world, or multiple different places.</p>
<blockquote>
<p>I go... | -1 | 2016-06-21T22:22:13Z | [
"python",
"django",
"timezone"
] |
Writing list of dictionaries in python to csv with specific field order | 37,950,905 | <p>I have a list of dictionaries, lst with random key:value pairs. I also have a list - the order in which I want to write fields into the csv file(Essentialy keys of dictionary). I used the code below to write the csv file. </p>
<pre><code>lst=[{"b":2,"d":3},{"a":1,"b":1,"c":5},{"d":7,"c":1}...]
order = ["a","b","... | -1 | 2016-06-21T17:29:54Z | 37,951,028 | <p>You never used <code>order</code>. Just pass that instead of <code>keys</code> when you create your DictWriter.</p>
| 1 | 2016-06-21T17:37:33Z | [
"python",
"csv"
] |
Writing list of dictionaries in python to csv with specific field order | 37,950,905 | <p>I have a list of dictionaries, lst with random key:value pairs. I also have a list - the order in which I want to write fields into the csv file(Essentialy keys of dictionary). I used the code below to write the csv file. </p>
<pre><code>lst=[{"b":2,"d":3},{"a":1,"b":1,"c":5},{"d":7,"c":1}...]
order = ["a","b","... | -1 | 2016-06-21T17:29:54Z | 37,951,335 | <p>first get all the keys from list of dict<br>
second sort the list of keys base on your order list<br>
final write the header based on sorted keys </p>
<pre><code>lst = [{'b': 2, 'd': 3}, {'a': 1, 'c': 5, 'b': 1}, {'c': 1, 'd': 7}]
flatLst = set([ k for ele in lst for k in ele.keys()])
def sortKey(x):
return ord... | 0 | 2016-06-21T17:54:25Z | [
"python",
"csv"
] |
Writing list of dictionaries in python to csv with specific field order | 37,950,905 | <p>I have a list of dictionaries, lst with random key:value pairs. I also have a list - the order in which I want to write fields into the csv file(Essentialy keys of dictionary). I used the code below to write the csv file. </p>
<pre><code>lst=[{"b":2,"d":3},{"a":1,"b":1,"c":5},{"d":7,"c":1}...]
order = ["a","b","... | -1 | 2016-06-21T17:29:54Z | 37,951,749 | <p>This snippet produces your desired output</p>
<pre><code>lst=[{"b":2,"d":3},{"a":1,"b":1,"c":5},{"d":7,"c":1}]
order = ["a","b","c","d"]
with open('file.csv', 'w') as output_file:
dict_writer = csv.DictWriter(output_file, order)
dict_writer.writeheader()
dict_writer.writerows(lst)
</code></pre>
| 1 | 2016-06-21T18:17:19Z | [
"python",
"csv"
] |
Python 2.7 (Anaconda 2) - IndentationError: unexpected indent Notepad++ auto separating code | 37,950,917 | <p>Okay, so this code is for an online class, and I feel the issue is caused by Notepad++, but I can't prove anything. </p>
<p>Actual Error is:
<code>[Anaconda2] C:\Users\ia566\Desktop\Python>python countorgdb.py
File "countorgdb.py", line 20
print pieces
^
IndentationError: unexpected indent</code></p>
... | 1 | 2016-06-21T17:31:05Z | 37,951,133 | <p>Indentation Error occurs when you are not using spaces or tabs properly. You should indent your code with four spaces. Try it out and see if it helps.</p>
| 0 | 2016-06-21T17:42:32Z | [
"python",
"notepad++"
] |
Not able to print the dictionary returned from view function in template | 37,950,936 | <p>my view function returns a dictionary . I am trying to print the dictionary in my template. But nothing gets printed. It prints application/json instead of printing the values of dictionary .Can anyone help me solve this ? </p>
<pre><code>def display(request):
if request.method == 'POST' or 'GET' :
form = displ... | 0 | 2016-06-21T17:32:25Z | 37,951,129 | <p>In django template you use <code>.items</code> to access dictionary:</p>
<pre><code> {% for k,v in res.items %}
<li> {{ v }} </li>
{% endfor %}
</code></pre>
| 0 | 2016-06-21T17:42:22Z | [
"python",
"django"
] |
Not able to print the dictionary returned from view function in template | 37,950,936 | <p>my view function returns a dictionary . I am trying to print the dictionary in my template. But nothing gets printed. It prints application/json instead of printing the values of dictionary .Can anyone help me solve this ? </p>
<pre><code>def display(request):
if request.method == 'POST' or 'GET' :
form = displ... | 0 | 2016-06-21T17:32:25Z | 37,951,151 | <p>You aren't passing <code>res</code> to the template response if <code>form.is_valid()</code> returns false. Instead you are only passing the form back to the template.</p>
<p>This is most likely why you aren't seeing your iteration get printed out.</p>
<p>You need <code>.items</code> rather than <code>.iteritems</... | 0 | 2016-06-21T17:43:23Z | [
"python",
"django"
] |
Row sum of a dataframe returns zero. (when there are N/As in only a few rows) | 37,950,961 | <pre><code>df['total'] =df.sum(axis=1)
print(df.tail(5))
Apr 2015 May 2015 Jun 2015 Jul 2015 \
Redmond, WA 21.2594 21.0405 Division by zero Division by zero
Plantation, FL 23.8435 25.0725 28.834 23.527
Lawrenceville, GA 10.7847 10.161... | 1 | 2016-06-21T17:34:05Z | 37,951,612 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow">replace</a> to remove all the strings in dataframe.
Try this I have only taken a part of your data.</p>
<pre><code>df
Out[35]:
Apr 2015 May 2015 Jun 2015 Jul 2015 Aug 2015... | 1 | 2016-06-21T18:09:47Z | [
"python",
"pandas",
"dataframe",
"sum",
"row"
] |
Twitter oauth with flask_oauthlib, Failed to generate request token | 37,950,999 | <p>I tried to use flask_oauthlib to access my twitter api, but all I get is the error : Failed to generate request token. Here is the code.</p>
<pre>
from flask_oauthlib.client import OAuth
from flask import Flask, url_for, request, jsonify
app = Flask(__name__)
oauth = OAuth()
twitter = oauth.re... | 1 | 2016-06-21T17:36:17Z | 37,953,944 | <p>Ok I found the problem. It appears that the callback URL is mandatory when using flask-oauthlib. So I added a fake one since i'm still on localhost, and it solved this problem.</p>
| 0 | 2016-06-21T20:25:34Z | [
"python",
"twitter",
"oauth",
"flask",
"flask-oauthlib"
] |
Adding multiple images and multiple content area in a form | 37,951,143 | <p>I am trying to create a blog where I want to be able to upload multiple images and/or multiple content. It could be in any order for e.g. content1, image1, image2, content2, content3 whatever is necessary according to need.</p>
<p>Once I go to the form I want to be able to add the content area or images. I have tri... | 0 | 2016-06-21T17:42:54Z | 37,953,404 | <p>I think you need to install package to do this.
Here is what I found : <a href="https://github.com/Chive/django-multiupload" rel="nofollow">Django-multiupload</a></p>
<p>Hope it helps.</p>
| 0 | 2016-06-21T19:52:12Z | [
"python",
"django"
] |
Add a timestamp to data simulator | 37,951,159 | <p>I am simulating time series data using <a href="https://github.com/arieb/python-testdata" rel="nofollow">Python TestData</a> and trying to add a new key value (event_time) that includes a time stamp when the record is generated. The issue is that the field is not incrementing as the script runs, just at first execut... | 2 | 2016-06-21T17:43:55Z | 37,951,420 | <p>So the <a href="https://docs.python.org/2/library/datetime.html#timedelta-objects" rel="nofollow"><code>timedelta()</code></a> is how much into the future you want the event to happen. Notice that the <code>timedelta(minutes=12)</code> causes the time between each <code>start_time</code> generated to be 12 minutes f... | 1 | 2016-06-21T17:58:46Z | [
"python",
"datetime"
] |
Add a timestamp to data simulator | 37,951,159 | <p>I am simulating time series data using <a href="https://github.com/arieb/python-testdata" rel="nofollow">Python TestData</a> and trying to add a new key value (event_time) that includes a time stamp when the record is generated. The issue is that the field is not incrementing as the script runs, just at first execut... | 2 | 2016-06-21T17:43:55Z | 38,188,412 | <pre><code>for event in EventsFactory().generate(10):
event["event_time"] = datetime.datetime.now()
print event
</code></pre>
| 0 | 2016-07-04T15:44:07Z | [
"python",
"datetime"
] |
Inserting newaxis at variable position in NumPy arrays | 37,951,219 | <p>Normally, when we know where should we insert the newaxis, we can do <code>a[:, np.newaxis,...]</code>. Is there any good way to insert the newaxis at certain axis?</p>
<p>Here is how I do it now. I think there must be some much better ways than this:</p>
<pre><code>def addNewAxisAt(x, axis):
_s = list(x.shape... | 3 | 2016-06-21T17:47:31Z | 37,951,395 | <p>That singleton dimension <code>(dim length = 1)</code> could be added as a shape criteria to the original array shape with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.insert.html" rel="nofollow"><code>np.insert</code></a> and thus directly change its shape, like so -</p>
<pre><code>x.shape = ... | 3 | 2016-06-21T17:57:06Z | [
"python",
"arrays",
"numpy"
] |
Inserting newaxis at variable position in NumPy arrays | 37,951,219 | <p>Normally, when we know where should we insert the newaxis, we can do <code>a[:, np.newaxis,...]</code>. Is there any good way to insert the newaxis at certain axis?</p>
<p>Here is how I do it now. I think there must be some much better ways than this:</p>
<pre><code>def addNewAxisAt(x, axis):
_s = list(x.shape... | 3 | 2016-06-21T17:47:31Z | 37,951,402 | <p>As far as I can tell you could just use tuple indexing and an Ellipsis object</p>
<p>For example, to put in at position 4 that would be like:</p>
<pre><code>>>> a = np.ones((3,3,3,3,3,3,3))
>>> a.shape
(3, 3, 3, 3, 3, 3, 3)
>>> t = tuple([slice(None)]*4 + [np.newaxis, Ellipsis])
>>... | 0 | 2016-06-21T17:57:23Z | [
"python",
"arrays",
"numpy"
] |
Inserting newaxis at variable position in NumPy arrays | 37,951,219 | <p>Normally, when we know where should we insert the newaxis, we can do <code>a[:, np.newaxis,...]</code>. Is there any good way to insert the newaxis at certain axis?</p>
<p>Here is how I do it now. I think there must be some much better ways than this:</p>
<pre><code>def addNewAxisAt(x, axis):
_s = list(x.shape... | 3 | 2016-06-21T17:47:31Z | 37,953,162 | <p><code>np.insert</code> does</p>
<pre><code>slobj = [slice(None)]*ndim
...
slobj[axis] = slice(None, index)
...
new[slobj] = arr[slobj2]
</code></pre>
<p>Like you it constructs a list of slices, and modifies one or more elements. </p>
<p><code>apply_along_axis</code> constructs an array, and converts it to indexi... | 1 | 2016-06-21T19:37:25Z | [
"python",
"arrays",
"numpy"
] |
'KeyError: 0' accessing items | 37,951,229 | <p>I am converting the XML data into JSON and then storing it in the database.
I am getting a key error 0. Error occurs in line12. The related code files are-</p>
<pre><code>from django.core.management.base import BaseCommand, CommandError
import boxer.utils3 as utils3
class Command(BaseCommand):
help = "it save... | 0 | 2016-06-21T17:48:23Z | 37,951,332 | <p>It looks like <code>items</code> is a dictionary, which do have a length corresponding to the number of (key, value) pairs they contain. However those items are referenced by their keys, which are arbitrary and not necessarily sequential numeric indices starting from <code>0</code> like they would be for a <code>lis... | 0 | 2016-06-21T17:54:12Z | [
"python",
"json",
"xml",
"dictionary"
] |
'KeyError: 0' accessing items | 37,951,229 | <p>I am converting the XML data into JSON and then storing it in the database.
I am getting a key error 0. Error occurs in line12. The related code files are-</p>
<pre><code>from django.core.management.base import BaseCommand, CommandError
import boxer.utils3 as utils3
class Command(BaseCommand):
help = "it save... | 0 | 2016-06-21T17:48:23Z | 37,951,358 | <p><code>processor</code> returns a dictionary, not a list: it has keys like <code>title</code>, <code>link</code>, etc.</p>
<p>There's no reason to have that for loop at all. Just pass <code>items</code> directly back to <code>saver</code>.</p>
<p>Note that if you did need to iterate, you should never do it with <co... | 0 | 2016-06-21T17:55:17Z | [
"python",
"json",
"xml",
"dictionary"
] |
Fatal error C1083: Cannot open include file: 'openssl/opensslv.h' | 37,951,303 | <p>I'm trying to install Scrapy, but got this error during installing: build\temp.win-amd64-2.7\Release_openssl.c(429) : fatal error C1083: Cannot open include file: 'openssl/opensslv.h': No such file or directory</p>
<p>I've checked that the file "opensslv.h" is in here "C:\OpenSSL-Win64\include\openssl". And I've al... | 2 | 2016-06-21T17:52:26Z | 38,144,434 | <p>Copy "openssl" folder from C:\OpenSSL-Win32\include\ to C:\Pyhton27\include\</p>
<p>and copy all libs from C:\OpenSSL-win32\lib to C:\Python27\Libs\</p>
| 0 | 2016-07-01T11:34:53Z | [
"python",
"openssl",
"scrapy"
] |
How do I have a bash script continually run during business hours? | 37,951,368 | <p>I have a Python program I run at all times of the day that alerts me when something I am looking for online is posted. I want to give this to my employees but I only want to have it email them during business hours.</p>
<p>I have a Ubuntu server and use a .sh. I have a command in crontab that runs on startup.</p>
... | -1 | 2016-06-21T17:55:44Z | 37,951,458 | <p>You could create a cronjob that starts the script every 5 minutes (or whatever often you want it to run) and additionally modify the script such that it creates a <code>.lock</code> file which it removes on exiting, but if it encounters it at the beginning it won't do anything (this way you don't have a long-running... | 0 | 2016-06-21T18:00:53Z | [
"python",
"bash",
"crontab",
"ubuntu-server"
] |
Remove elements according to text content using BeautifulSoup | 37,951,431 | <p>I want to delete table row (tr) elements that contain the word "Amend". How can I change the code below to make that happen?</p>
<pre><code>for e in soup.findAll("tr"):
e.extract()
</code></pre>
<p>*** Edit:</p>
<p>I have tried the following to no avail:</p>
<pre><code>for e in soup.findAll('tr', text = re.co... | 1 | 2016-06-21T17:59:31Z | 37,951,606 | <p>How about you find all nodes having <code>Amend</code>, go <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-parents-and-find-parent" rel="nofollow">up the tree</a> to the <code>tr</code> and remove:</p>
<pre><code>for amend in soup.find_all(text=re.compile("Amend")):
tr = amend.find_parent("... | 1 | 2016-06-21T18:09:35Z | [
"python",
"html",
"beautifulsoup",
"html-parsing"
] |
Looking for a super explanation /tkinter direction (getting max recursion depth without super) | 37,951,446 | <p>So I'm trying to use my "controller" to call my "view." But if I don't use super, I get an infinite recursion when buildTK tries to build iiBar. Using Super everything is fine. I'd just like to understand why that is.</p>
<pre><code>import inputhandler as iH
import buildtk as tA
import scanhandler as aS
class Cont... | -1 | 2016-06-21T18:00:06Z | 37,952,122 | <p>What you show here is not a good example of inheritance - it is somehwat messed up. The same thing goes for yout attempeted uses of super - it just does not crash because you are not doing anything with the super-object at all, after creating it.</p>
<p>So., first, define if you are inheriting Tkinter components of... | 0 | 2016-06-21T18:36:50Z | [
"python",
"tkinter"
] |
Looking for a super explanation /tkinter direction (getting max recursion depth without super) | 37,951,446 | <p>So I'm trying to use my "controller" to call my "view." But if I don't use super, I get an infinite recursion when buildTK tries to build iiBar. Using Super everything is fine. I'd just like to understand why that is.</p>
<pre><code>import inputhandler as iH
import buildtk as tA
import scanhandler as aS
class Cont... | -1 | 2016-06-21T18:00:06Z | 37,977,784 | <p>Found my issues. Some python oversights. </p>
<ol>
<li>the import seems to take care of the instantiation</li>
</ol>
<p>part of this has to do with the inconsistency I used at the end of my classes, i.e;</p>
<p>a. #if <strong>name</strong> == "<strong>main</strong>": ControlHandler()
forgot that was commented out... | 0 | 2016-06-22T20:33:40Z | [
"python",
"tkinter"
] |
How to choose option on a web drop down box? | 37,951,528 | <p>I'm using Python 3.5.1, and I need to automate the download of a bunch of reports every morning (through Python). These are imported from a web platform, which is of restricted access. I started with the following piece of code, which works fine:</p>
<pre><code>import webbrowser, time
webbrowser.open('mylink')
time... | 0 | 2016-06-21T18:05:00Z | 37,978,875 | <p>I'm assuming they don't work because you're trying to select using the wrong text or value using <code>select_by_value()</code> or <code>select_by_visible_text()</code>. Try selecting by index instead. </p>
<p>It's also strange that your <code>select</code> html element doesn't have quotes surrounding the <code>id<... | 0 | 2016-06-22T21:51:09Z | [
"python",
"python-3.x"
] |
How to find the intersection points of a straight line and a curve-like set of two dimensional points? | 37,951,631 | <p>Suppose we have:</p>
<ol>
<li>A curve described by a two-dimensional dataset that describes approximately a high order polynomial curve.</li>
<li>A line defined by two points.</li>
</ol>
<p>This is a sample image:</p>
<p><img src="http://i.stack.imgur.com/SSxTK.png"></p>
<p>Supposing the line and the curve inter... | 1 | 2016-06-21T18:10:43Z | 37,961,550 | <p>Since the curve data appears to be dense and not scattered (as for example the result of a numerically solved differential equation), interpolating or approximating the whole curve dataset is overkill. In the following, I assume that the points of the dataset are ordered along the curve (as if they were the result o... | 0 | 2016-06-22T07:40:17Z | [
"python",
"numpy",
"set-intersection"
] |
How to find the intersection points of a straight line and a curve-like set of two dimensional points? | 37,951,631 | <p>Suppose we have:</p>
<ol>
<li>A curve described by a two-dimensional dataset that describes approximately a high order polynomial curve.</li>
<li>A line defined by two points.</li>
</ol>
<p>This is a sample image:</p>
<p><img src="http://i.stack.imgur.com/SSxTK.png"></p>
<p>Supposing the line and the curve inter... | 1 | 2016-06-21T18:10:43Z | 37,965,131 | <p>As per my comment above</p>
<pre><code>import numpy as np
A = np.random.random((20, 2))
A[:,0] = np.arange(20)
A[:,1] = A[:,1] * (7.5 + A[:,0]) # some kind of wiggly line
p0 = [-1.0,-6.5] # point 0
p1 = [22.0, 20.0] # point 1
b = (p1[1] - p0[1]) / (p1[0] - p0[0]) # gradient
a = p0[1] - b * p0[0] # intercept
B = (... | 0 | 2016-06-22T10:19:58Z | [
"python",
"numpy",
"set-intersection"
] |
Read and write ID's with pandas | 37,951,711 | <p>I'm new in Python and need help for following Problem:</p>
<p>I have two csv files, which named <strong><em>bib.csv</em></strong> and <strong><em>id.csv</em></strong> . The files have up to 15,000 Data inside.</p>
<p><strong><em>bib.csv</em></strong> looks like:</p>
<pre><code>WKT A_ID length
10 5 200
11... | 2 | 2016-06-21T18:15:13Z | 37,953,573 | <p>This could obviously use a some refactoring, but it accomplishes what you are trying to accomplish. The key is that you need a good map from rows in your <code>id.csv</code> file to rows in your desired output file. That is what <code>getBibMap</code> creates, then it's just a matter of iterating through and mapping... | 0 | 2016-06-21T20:01:57Z | [
"python",
"csv",
"pandas"
] |
Read and write ID's with pandas | 37,951,711 | <p>I'm new in Python and need help for following Problem:</p>
<p>I have two csv files, which named <strong><em>bib.csv</em></strong> and <strong><em>id.csv</em></strong> . The files have up to 15,000 Data inside.</p>
<p><strong><em>bib.csv</em></strong> looks like:</p>
<pre><code>WKT A_ID length
10 5 200
11... | 2 | 2016-06-21T18:15:13Z | 37,953,608 | <pre><code>import pandas as pd
bib = pd.DataFrame({'WKT':[10,11,12], 'A_ID':[5,6,7], 'length':[200,201,202]})
# A_ID WKT length
# 0 5 10 200
# 1 6 11 201
# 2 7 12 202
ids = pd.DataFrame({'Master_ID':[1,2], 'A_ID_1':[5,5], 'A_ID_2':[6,7]})
# A_ID_1 A_ID_2 Master_ID
# 0 5 ... | 1 | 2016-06-21T20:04:09Z | [
"python",
"csv",
"pandas"
] |
Python Dropbox API - Invalid "cursor" parameter | 37,951,779 | <p>I've been migrating some Python 2.7.11 code to 3.5.1 after running into trouble with unicode. This was the last straw - since I started using the venv module there's no reason to be on 2.7 just because someone doesn't like 3!</p>
<p>The problem occurs while trying to run a one-way sync (ie. downloading changes only... | 0 | 2016-06-21T18:18:59Z | 37,951,780 | <p><code>u"b\'\'"</code> is the key here. I just couldn't understand how that representation had ended up being sent as a string.</p>
<p>The issue was in reading the old cursor from a file (which for this example is empty): in Python 2 I had opened the file in mode <code>rb</code> - in Python 3 just <code>r</code> is ... | 0 | 2016-06-21T18:18:59Z | [
"python",
"dropbox-api"
] |
PyInstaller Assertion Error - used to work fine, now it doesn't | 37,951,808 | <p>I'm trying to use PyInstaller. I've used it several times in the past on this same system and been able to successfully package my programs to .exe files, but now something isn't working and I'm not sure what changed. </p>
<p>It gives me some errors ("<code>TypeError: a bytes-like object is required, not 'str'</c... | 0 | 2016-06-21T18:20:13Z | 37,953,001 | <p>Just run the repair function in on the python installer. It should remove the ugly.</p>
<p><a href="http://i.stack.imgur.com/QhNPt.png" rel="nofollow">python3.5.1thing</a></p>
<p><a href="http://i.stack.imgur.com/Skx4j.png" rel="nofollow">pythonrepair3.5.1thing</a></p>
| 0 | 2016-06-21T19:27:03Z | [
"python",
"python-3.x",
"windows-10",
"pyinstaller"
] |
PyInstaller Assertion Error - used to work fine, now it doesn't | 37,951,808 | <p>I'm trying to use PyInstaller. I've used it several times in the past on this same system and been able to successfully package my programs to .exe files, but now something isn't working and I'm not sure what changed. </p>
<p>It gives me some errors ("<code>TypeError: a bytes-like object is required, not 'str'</c... | 0 | 2016-06-21T18:20:13Z | 38,703,372 | <p>I had this same problem when trying to make a version 4.1 of my program. There is something about the "." between 4 and 1 that is throwing a wrench in the operation. I renamed my file "Program_V4_1.py" and it worked. </p>
| 0 | 2016-08-01T16:05:18Z | [
"python",
"python-3.x",
"windows-10",
"pyinstaller"
] |
PyInstaller Assertion Error - used to work fine, now it doesn't | 37,951,808 | <p>I'm trying to use PyInstaller. I've used it several times in the past on this same system and been able to successfully package my programs to .exe files, but now something isn't working and I'm not sure what changed. </p>
<p>It gives me some errors ("<code>TypeError: a bytes-like object is required, not 'str'</c... | 0 | 2016-06-21T18:20:13Z | 39,562,128 | <p>I also got the same error when i wanted to build an .exe with Pyinstaller.</p>
<p>I used this command to build it:</p>
<pre><code>pyinstaller.exe --onefile --noconsole --icon=icon.ico appbuilder.py
</code></pre>
<p>That gave me the folowing error:</p>
<pre><code>(...)python35-32\lib\site-packages\PyInstaller\bui... | 1 | 2016-09-18T20:02:46Z | [
"python",
"python-3.x",
"windows-10",
"pyinstaller"
] |
Extracting first rows from multiple tables and add one column (Python) | 37,951,890 | <p>I`m trying to generate a list of the latest currency quotes from Investing.com.</p>
<p>I have the following code:</p>
<pre><code>head = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36",
"X-Requested-With": "XMLHttpRequest"}
ISO_Code=... | 1 | 2016-06-21T18:24:36Z | 37,952,421 | <p>I think this is a cleaner way to accomplish what you are trying to do</p>
<pre><code>head = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36",
"X-Requested-With": "XMLHttpRequest"}
latest_data=[]
for item in ISO_CURR_ID.ISO_Code:
... | 1 | 2016-06-21T18:54:04Z | [
"python",
"pandas",
"dataframe"
] |
Extracting first rows from multiple tables and add one column (Python) | 37,951,890 | <p>I`m trying to generate a list of the latest currency quotes from Investing.com.</p>
<p>I have the following code:</p>
<pre><code>head = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36",
"X-Requested-With": "XMLHttpRequest"}
ISO_Code=... | 1 | 2016-06-21T18:24:36Z | 37,952,893 | <p>I would recommend you to use <a href="http://pandas.pydata.org/pandas-docs/stable/cookbook.html#panels" rel="nofollow">pandas.Panel</a> for that, similar to pandas_datareader:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import pandas as pd
head = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) ... | 0 | 2016-06-21T19:21:04Z | [
"python",
"pandas",
"dataframe"
] |
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 2860: ordinal not in range(128) | 37,951,919 | <p>I have the following record from JSON file that is giving me the error- </p>
<blockquote>
<p>{"categoryId":"mpc-pc-optimization",
"categoryName":"PC Optimization",
"productMap":
{"mpp-aol-computer-checkup":"AOL Computer Checkup®",
"mpp-assist-by-aol-free-scan":"Assist by AOL Free Scan",
... | -1 | 2016-06-21T18:26:33Z | 37,952,105 | <p>The error comes from that ⢠(trademark symbol), which is not part of the ascii code.
The byte 0xe2 is 11100010 in binary, which is outside the range of 128 (01111111 in binary).</p>
<p>The problem is that you are trying to decode with ascii, and instead should decode with unicode (e.g. UTF-8).</p>
<p>You could u... | 1 | 2016-06-21T18:35:51Z | [
"python",
"json"
] |
Leave Non-Declared Arguments to Their Default Values | 37,951,975 | <p>I am creating a RESTful API using Flask and Flask-Restful and am running into a problem with PUT requests and the arguments. I have a JSON file that contains:</p>
<pre><code>{
"checked": 1465628401,
"number": 21600,
}
</code></pre>
<p>When the user sends <code>"/api/v1/status?checked=10"</code> it changes ... | 0 | 2016-06-21T18:28:50Z | 38,027,115 | <p>I did not try it but the <a href="http://flask-restful-cn.readthedocs.io/en/0.3.4/api.html#reqparse.Argument" rel="nofollow">documentation</a> sais that you can add default values.</p>
<p>The <code>Argument</code> class and thus the <code>add_argument</code> function accepts a <code>default</code> keyword argument ... | 0 | 2016-06-25T09:46:25Z | [
"python",
"flask",
"put",
"flask-restful"
] |
Edit python script without reloading libraries | 37,952,055 | <p>I am working on a project that involves some huge libraries. Every time I want to make minor changes to my script, I have to reload <em>all</em> the dependencies, which takes a very long time. Is there a way to make edits and reload without reloading all the dependencies?</p>
<p>Possibly related, but doesn't fully ... | 0 | 2016-06-21T18:33:16Z | 37,952,407 | <p>I found the answer myself. For other searching:</p>
<p>suppose I make a script called <code>HurrDurr</code></p>
<p><code>HurrDurr = reload(HurrDurr)</code> will reload just that script. So move the big dependencies to another file and make your minor changes by reloading.</p>
| 0 | 2016-06-21T18:53:01Z | [
"python"
] |
value not getting updated in ElementTree in lxml | 37,952,119 | <p>I'm using lxml in python.</p>
<pre><code>from lxml import etree
d = etree.parse("input.xml")
t1 = etree.Element('year')
t2 = etree.Element('gdppc')
t1.text = '2016'
t2.text = '123456'
</code></pre>
<p>When I print t1 and t2, </p>
<pre><code>print etree.tostring(t1)
print etree.tostring(t2)
</code></pre>
<p>Corre... | 0 | 2016-06-21T18:36:43Z | 37,952,213 | <p><code>d</code> is not related to <code>t1</code> or <code>t2</code> in any way. By doing <code>etree.Element('year')</code> or <code>etree.Element('gdppc')</code> you are <em>initializing new independent elements</em>. Instead, if you want to update existing <code>year</code> or <code>gdppc</code> elements inside <c... | 0 | 2016-06-21T18:42:21Z | [
"python",
"xml",
"lxml"
] |
Handling milli vs micro seconds in python | 37,952,202 | <p>In python we could convert from UTC time ( Micro seconds since 1970) to a datetime object using</p>
<pre><code>time_in_micro=1000000000
dt=datetime.fromtimestamp(time_in_micro)
</code></pre>
<p>time could also be in Milli Seconds. In that case we can multiply it by 1000 and use the fromtimestamp method.</p>
<p>ho... | 1 | 2016-06-21T18:41:29Z | 37,952,298 | <p>Any such method would still require a way to indicate whether the argument was in milliseconds or microseconds:</p>
<pre><code># For example
datetime.hypothetical_fromtimestamp(100, units="milliseconds")
datetime.hypothetical_fromtimestamp(100, units="microseconds")
</code></pre>
<p>This doesn't seem to be ... | 1 | 2016-06-21T18:47:01Z | [
"python",
"utc",
"milliseconds"
] |
reading matrices cotaining dictionaries in python | 37,952,226 | <p>I have two matrices (I want them for part of speech tagging). The first one contains the pos tags probabilities and the second contains the words probabilities. I need to extract numbers and sum the matrices. The problem is when I call each cell the string part appears, too. But I need the numbers. How can I call th... | 0 | 2016-06-21T18:43:05Z | 37,952,514 | <p>I think you could achieve this task by using just 2 dictionaries, one for each array which you are currently making:</p>
<pre><code>A = {'ARTART':0, 'ARTN':1, 'ARTV': 0} # and so on
</code></pre>
<p>Then you can grab the values of each entry in the dictionary with:</p>
<pre><code>A_val = A.values()
</code></pre>
... | 0 | 2016-06-21T18:58:42Z | [
"python",
"matrix",
"nlp"
] |
Cannot use a string in Django ManyToManyField through value | 37,952,235 | <p>(Apologies if I'm missing some critical info to help diagnose this -- I'm new to Python and Django.)</p>
<p>Django complains when I try to use a string in my ManyToManyField through attribute:</p>
<pre><code>File "/vagrant/flamingo_env/lib/python3.4/site-packages/django/db/models/fields/related.py", line 1366, in ... | 0 | 2016-06-21T18:43:32Z | 37,952,313 | <p>To fix your ordering issue you can give a string value to the <code>ForeignKey</code> class.</p>
<pre><code>class VoterAddress(models.Model):
voter_id = models.ForeignKey("Voter")
address_id = models.ForeignKey("Address")
class Meta:
db_table = 'voter_addresses'
</code></pre>
<p>This is a way ... | 0 | 2016-06-21T18:47:51Z | [
"python",
"django",
"django-models"
] |
Cannot use a string in Django ManyToManyField through value | 37,952,235 | <p>(Apologies if I'm missing some critical info to help diagnose this -- I'm new to Python and Django.)</p>
<p>Django complains when I try to use a string in my ManyToManyField through attribute:</p>
<pre><code>File "/vagrant/flamingo_env/lib/python3.4/site-packages/django/db/models/fields/related.py", line 1366, in ... | 0 | 2016-06-21T18:43:32Z | 37,952,462 | <p>You need to fix the name passed to your <code>through</code></p>
<pre><code>addresses = models.ManyToManyField(Address, through='VoterAddress')
</code></pre>
<p>It has to be the exact name of the <em>custom</em> <code>throughmodel</code></p>
<p>You will not be required to create a <code>throughmodel</code> if you... | 2 | 2016-06-21T18:56:19Z | [
"python",
"django",
"django-models"
] |
SFrame Kmeans - Covert to Int, Float, Dict | 37,952,270 | <p>I'm preparting data to run KMEAMS from Graphlab, and am running into the following error:</p>
<pre><code> tmp = data.select_columns(['a.item_id'])
tmp['sku'] = tmp['a.item_id'].apply(lambda x: x.split(','))
tmp = tmp.unpack('sku')
kmeans_model = gl.kmeans.create(tmp, num_clusters=K)
Feature 'sku.0' excluded b... | 0 | 2016-06-21T18:45:28Z | 37,973,395 | <p>The kmeans model does allow features in <em>dictionary</em> form, just not in list form. This is slightly different from what you've got now, because the dictionary loses the order of your SKUs, but in terms of model quality I suspect it actually makes more sense. They key function is <code>count_words</code>, in t... | 0 | 2016-06-22T16:16:38Z | [
"python",
"graphlab",
"sframe"
] |
Python using "IN" in a "IF ELSE" loop | 37,952,418 | <p>i have a list of tuples that i loop through in a simple for loop to identify tuples that contain some conditions.</p>
<pre><code> mytuplist =
[(1, 'ABC', 'Today is a great day'), (2, 'ABC', 'The sky is blue'),
(3, 'DEF', 'The sea is green'), (4, 'ABC', 'There are clouds in the sky')]
</code></pre>
<p... | 1 | 2016-06-21T18:53:46Z | 37,952,469 | <p>You don't, because <code>in</code> with a sequence only matches the whole element.</p>
<pre><code>if tup[1] =='ABC' and any(el in tup[2] for el in ('Today is', 'The sky')):
</code></pre>
| 3 | 2016-06-21T18:56:38Z | [
"python",
"loops",
"operators"
] |
Python using "IN" in a "IF ELSE" loop | 37,952,418 | <p>i have a list of tuples that i loop through in a simple for loop to identify tuples that contain some conditions.</p>
<pre><code> mytuplist =
[(1, 'ABC', 'Today is a great day'), (2, 'ABC', 'The sky is blue'),
(3, 'DEF', 'The sea is green'), (4, 'ABC', 'There are clouds in the sky')]
</code></pre>
<p... | 1 | 2016-06-21T18:53:46Z | 37,952,471 | <p>You should use the built-in <a href="https://docs.python.org/2/library/functions.html#any"><code>any()</code></a> function:</p>
<pre><code>mytuplist = [
(1, 'ABC', 'Today is a great day'),
(2, 'ABC', 'The sky is blue'),
(3, 'DEF', 'The sea is green'),
(4, 'ABC', 'There are clouds in the sky')
]
key... | 7 | 2016-06-21T18:56:39Z | [
"python",
"loops",
"operators"
] |
Python using "IN" in a "IF ELSE" loop | 37,952,418 | <p>i have a list of tuples that i loop through in a simple for loop to identify tuples that contain some conditions.</p>
<pre><code> mytuplist =
[(1, 'ABC', 'Today is a great day'), (2, 'ABC', 'The sky is blue'),
(3, 'DEF', 'The sea is green'), (4, 'ABC', 'There are clouds in the sky')]
</code></pre>
<p... | 1 | 2016-06-21T18:53:46Z | 37,952,513 | <p>Your second approach (which, however, needs to be parenthesized as <code>x and (y or z)</code> to be correct) is necessary <code>tup[2]</code> <em>contains</em> one of your key phrases, rather than being an element of your set of key phrases. You could use regular-expression matching at the cost of some performance:... | 1 | 2016-06-21T18:58:39Z | [
"python",
"loops",
"operators"
] |
multiple plots with function matplotlib | 37,952,564 | <p>I created a function that creates a plot, basically the function looks like this:</p>
<pre><code>def draw_line(array):
fig, ax = plt.subplots()
ax.plot(array)
</code></pre>
<p>I wanted to know if there is a way to call this function when wanting to do multiple plots in a figure. In particular, I wanted to ... | 1 | 2016-06-21T19:01:38Z | 37,952,862 | <p>You don't want to call a new plt.subplots() each time you call draw_line(). Instead, you want to use an existing axis object. In this case you want to pass in the axis for each subplot with its corresponding data. Then plot the two together. </p>
<pre><code>from matplotlib import pyplot as plt
import numpy as np
d... | 2 | 2016-06-21T19:19:21Z | [
"python",
"matplotlib",
"plot"
] |
multiple plots with function matplotlib | 37,952,564 | <p>I created a function that creates a plot, basically the function looks like this:</p>
<pre><code>def draw_line(array):
fig, ax = plt.subplots()
ax.plot(array)
</code></pre>
<p>I wanted to know if there is a way to call this function when wanting to do multiple plots in a figure. In particular, I wanted to ... | 1 | 2016-06-21T19:01:38Z | 37,952,947 | <p>Alternative to @user2241910,</p>
<pre><code>from matplotlib import pyplot as plt
fig = plt.figure()
example_list = [[1,2,3],[4,5,6],[3,2,5],[5,2,3],[1,3,1],[5,3,5]]
for i,data in enumerate(example_list):
ax = plt.subplot(2,3,i+1)
ax.plot(data)
</code></pre>
<p>Produces:</p>
<p><a href="http://i.stack.im... | 2 | 2016-06-21T19:24:12Z | [
"python",
"matplotlib",
"plot"
] |
concatenated string format in Python? | 37,952,724 | <p>I am trying to set the width of a concatenated string. This is what I am trying to do:</p>
<pre><code>>>> "{{a}_{b}:<10s}".format(a='xx', b='yy')
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: Single '}' encountered in format string
</code></pre>
<p>I k... | 0 | 2016-06-21T19:10:52Z | 37,953,015 | <p>You could subtract the length of a and b from the padding and pad b, adding one for the <code>_</code>: </p>
<pre><code>a, b ='xx','yy'
"{a}_{b:<{ln}s}".format(a=a, b=b, ln= 11 - (len(a) + len(b)))
</code></pre>
<p>Or ljust:</p>
<pre><code>"{a}_{b}".format(a='xx', b='yy').ljust(10, " ")
</code></pre>
| 0 | 2016-06-21T19:27:58Z | [
"python",
"string",
"format"
] |
Object ids in python data type | 37,952,728 | <p>If I have a object in python that has a unique id such as </p>
<pre><code>{"id":"123141222151",....}
</code></pre>
<p>What is the best data type for something like this? Should it be passed as a string or as an int? I was thinking string but I want to hear what others have to say about it.</p>
| 0 | 2016-06-21T19:11:11Z | 37,953,175 | <p>In my opinion it is better to use int as it saves space, also it is quicker when matching keys on integers than string. </p>
<p>Hope this helps </p>
| 0 | 2016-06-21T19:38:24Z | [
"python"
] |
differences between each row for all columns setting index column | 37,952,829 | <p>I have this pandas data frame named ndf2:</p>
<pre><code> ds sc
0 1000 0.516512
1 1100 0.542311
2 1200 0.552666
3 1300 0.567540
4 1400 0.585531
5 1500 0.595928
6 1600 0.601140
7 1700 0.602802
8 1800 0.605209
9 1900 0.616163
10 2000 0.627078
11 2100 0.632283... | 2 | 2016-06-21T19:17:18Z | 37,952,879 | <p>I think you need only <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.diff.html" rel="nofollow"><code>diff</code></a>:</p>
<pre><code>print (df.diff())
ds sc
0 NaN NaN
1 100.0 0.025799
2 100.0 0.010355
3 100.0 0.014874
4 100.0 0.017991
5 100.0 0... | 3 | 2016-06-21T19:20:08Z | [
"python",
"pandas",
"indexing",
"dataframe",
"difference"
] |
How to get the time since post published on praw | 37,952,909 | <p>I'm writing a bot using <code>praw</code> and I want to know how time has past since a post have been published. The naive solution is to use <code>datetime</code></p>
<pre><code>import datetime
import praw
... """read a list of submission"""
date = datetime.datetime.fromtimestamp(submission.created)
dif = dateti... | 1 | 2016-06-21T19:22:07Z | 38,202,254 | <p>There is special function that will return utc epoch time.</p>
<pre><code>import datetime
import praw
... #stuff
date = datetime.datetime.fromtimestamp(submission.created_utc)
dif = datetime.datetime.utcnow() - date
</code></pre>
<p>utcnow() returns your current time as it appears in Universal Time. Same with su... | 1 | 2016-07-05T11:25:16Z | [
"python",
"bots",
"reddit",
"praw"
] |
How to have two variables in one regrex? | 37,952,928 | <p>How can I get two variables into one regular expression?</p>
<p>So far:</p>
<pre><code>var1 = "Taco"
x = re.findall('(?<=\|)%s\|(?=\|)' % var1, string)
</code></pre>
<p>This works great for the one variable but I need to have something like:</p>
<pre><code>x = re.findall('(?<=\|)%s\|%s(?=\|)' % var1 % var2... | -4 | 2016-06-21T19:23:07Z | 37,952,985 | <pre><code>x = re.findall('(?<=\|)%s\|%s(?=\|)' % (var1, var2), string)
</code></pre>
| 1 | 2016-06-21T19:26:12Z | [
"python",
"regex"
] |
Segmentation fault when using ctypes and threading | 37,953,055 | <p>I wrote a Python wrapper for a C library using <code>ctypes</code>. Everything worked fine, until I tried it with the <code>threading</code> module.</p>
<p>Here is a small example to reproduce it:</p>
<h1>foo.c</h1>
<pre><code>#include <stdlib.h>
#include <assert.h>
char *foo_init() {
char *resul... | 2 | 2016-06-21T19:30:37Z | 37,953,969 | <p>@user2357112 gave me the answer in comments: adding the (good) return type and the arguments types is important.</p>
<p>Replacing the beginning of <code>foo.py</code> by the following fix the problem:</p>
<pre><code>libfoo.foo_init.restype = ctypes.POINTER(ctypes.c_char)
libfoo.foo_init.argtypes = []
libfoo.foo_ge... | 0 | 2016-06-21T20:27:12Z | [
"python",
"c",
"multithreading",
"segmentation-fault",
"ctypes"
] |
Numpy linspace and plotting, ValueError: an array element with a sequence | 37,953,090 | <p>I was trying to get 60 lines joining center of the circle to 60 different equispaced points on the circumference in the following program, </p>
<pre class="lang-python prettyprint-override"><code>import matplotlib.pyplot as plt
import numpy as np
figure = plt.figure(figsize=(10, 10))
theta = np.linspace(0, 2 * ... | 3 | 2016-06-21T19:33:23Z | 37,953,178 | <p>The x and y elements of your <code>plot()</code> command need to have the same number of elements. Replace the line</p>
<pre><code>plt.plot([0, x1], [0, y1], color='gray')
</code></pre>
<p>with the following:</p>
<pre><code>plt.plot([np.zeros(60,), x1], [np.zeros(60,), y1], color='gray')
</code></pre>
<p>the res... | 2 | 2016-06-21T19:38:33Z | [
"python",
"numpy"
] |
How to read NFC tag in Kivy + Python? | 37,953,101 | <p>I'm trying to read NFC tags, and if tag has just text, reading goes well. However, it doesn't work if the tag contains a URL or is empty. I believe the problem is with the nfc_filter.xml file.</p>
<pre><code><intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED"/>
<action androi... | 2 | 2016-06-21T19:34:04Z | 37,985,571 | <p>Your app currently receives NFC events due to the intent filter in the manifest:</p>
<pre><code><intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED"/>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<action android:name="android.nfc.action.TECH_DISCOVERED"/... | 2 | 2016-06-23T08:03:35Z | [
"android",
"python",
"nfc",
"kivy",
"ndef"
] |
Mock a shell command in a script called from Python subprocess.Popen() | 37,953,143 | <p>I have a situation where I need to mock an executable (pip) with a shell script I wrote (mock_pip) for a unit test, so I use the subprocess module to get access to the shell. I've tried a lot of things like:</p>
<pre><code>subprocess.Popen("alias pip='/some/dir/mock_pip'", shell=True) # Create alias
subprocess.Pope... | 0 | 2016-06-21T19:36:39Z | 37,953,495 | <p>If your goal here is to provide a mock implementation of pip, you can do that in a few ways:</p>
<ul>
<li>Generate it as an exported function</li>
<li>Set a PATH value pointing to a directory containing wrapper as an executable script</li>
</ul>
<hr>
<p>The former is shell-version-specific, so we'll cover the lat... | 2 | 2016-06-21T19:57:34Z | [
"python",
"bash",
"shell",
"subprocess"
] |
Multiple linear regression scikit-learn and statsmodel | 37,953,148 | <p>I'm attempting to use multiple linear regression on a data set using scikit-learn, but I am having trouble with getting the correct coefficients. I'm using the Lake Huron data which can be found here:</p>
<p><a href="https://vincentarelbundock.github.io/Rdatasets/datasets.html" rel="nofollow">https://vincentarelbun... | 0 | 2016-06-21T19:36:53Z | 37,956,185 | <p>The problem is the line</p>
<pre><code>a = np.array([nvalues["x1"], nvalues["x2"]])
</code></pre>
<p>as it does not sort the data the way you intend. Instead it will generate a dataset</p>
<pre><code>x1_new x2_new
-----------------
x1[0] x1[1]
x1[2] x1[3]
[...]
x1[94] x1[95]
x2[0] x2[1]
[...... | 1 | 2016-06-21T23:28:28Z | [
"python",
"scikit-learn",
"statsmodels"
] |
Multiple linear regression scikit-learn and statsmodel | 37,953,148 | <p>I'm attempting to use multiple linear regression on a data set using scikit-learn, but I am having trouble with getting the correct coefficients. I'm using the Lake Huron data which can be found here:</p>
<p><a href="https://vincentarelbundock.github.io/Rdatasets/datasets.html" rel="nofollow">https://vincentarelbun... | 0 | 2016-06-21T19:36:53Z | 37,958,040 | <p>as per @Orange suggestion, I've changed the code to something I thing is more efficient: </p>
<pre><code>#### using scikit-learn ####
a = []
for i in range(0, len(nvalues["x1"])):
a.append([nvalues["x1"][i], nvalues["x2"][i]])
a = np.array(a)
b = np.array(nvalues["y"])
a = a.reshape(len(a), 2)
b = b.reshape(l... | 0 | 2016-06-22T03:29:01Z | [
"python",
"scikit-learn",
"statsmodels"
] |
How do I wait through a wait page and then download a PDF, using Python? | 37,953,182 | <h2>The Problem</h2>
<p>I'm trying to download PDF files from a website built over a crotchety old mainframe, and in order to support the traffic the website implements wait pages. The wait page will render and you will spend a few second looking at that instead of the PDF you want, and then it will disappear and you'... | 0 | 2016-06-21T19:38:43Z | 37,954,371 | <p>I would just ignore the wait page. Find a specific element that exists on the download page that does NOT exist on the wait page and wait for it. Just make sure you wait long enough that the wait page will for sure be gone (maybe 30s or more? You might have to try it and see how it goes).</p>
<p>From the HTML you p... | 1 | 2016-06-21T20:52:33Z | [
"python",
"http",
"selenium",
"pdf",
"download"
] |
How do I wait through a wait page and then download a PDF, using Python? | 37,953,182 | <h2>The Problem</h2>
<p>I'm trying to download PDF files from a website built over a crotchety old mainframe, and in order to support the traffic the website implements wait pages. The wait page will render and you will spend a few second looking at that instead of the PDF you want, and then it will disappear and you'... | 0 | 2016-06-21T19:38:43Z | 37,954,928 | <p>I can get the page source consistently using requests, this will get the pdf link and save it:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
from urlparse import urljoin
# gets the page when you click the pdf link in your browser
post_url = "http://a810-bisweb.nyc.gov/bisweb/CofoJobDocumentServlet"... | 1 | 2016-06-21T21:31:34Z | [
"python",
"http",
"selenium",
"pdf",
"download"
] |
What is wrong with XPath expression | 37,953,230 | <p>Sorry I`m new for this stuff.
I have this (was unable to format my code properly so I splitted it in two blocks bellow):</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<bulkCmConfigDataFile xmlns:es="EricssonSpecificAttributes.14.04.xsd"
xmlns:un="utranNrm.xsd" xmlns:xn="genericNrm.xsd"
xmlns:... | 0 | 2016-06-21T19:41:37Z | 37,966,355 | <p>The xml context for variable "root" is already positioned at <bulkCmConfigDataFile> node so the xpath should be written relative to this node.</p>
<p>eg.</p>
<pre><code>ucells = root.findall("un:UtranCell", namespaces={'un':'utranNrm.xsd'} )
</code></pre>
<p>or</p>
<pre><code>ucells = root.findall("{utranNrm.... | 0 | 2016-06-22T11:12:25Z | [
"python",
"xml",
"xpath"
] |
Parameterise functions to automate website using selenium webdriver with Python | 37,953,270 | <p>I want to automate the login functionality of a site in such a way that i just pass the different values of username and password as parameters and the login functionality is tested for each pair of values.</p>
<p>example:</p>
<pre><code>def login(username,password):
driver.find_element(BYelemantLocator1).send... | -1 | 2016-06-21T19:43:58Z | 37,976,261 | <p>class LoginDetails(object):
def <strong>init</strong>(self):</p>
<pre><code> self.driver = webdriver.Firefox()
self.homePageURL = "http://hulk.iwanto.in/"
def logindetails(self, username, password):
driver = self.driver
wait = WebDriverWait(driver, 10)
driver.maximize_window()
driver.ge... | 0 | 2016-06-22T19:00:02Z | [
"python",
"selenium",
"selenium-webdriver",
"python-unittest",
"parameterized"
] |
Python - tempfile module creates a file that cannot be opened? | 37,953,310 | <p>I'm using the <code>tempfile</code> module and <code>imagemagick</code> and when i try to run this code:</p>
<pre><code>width = height = 100
temp_file = tempfile.NamedTemporaryFile()
canvas = "convert -size {}x{} canvas:black {}/canvas.png".format(scale_width, scale_height, temp_file.name)
os.system(canvas)
</code>... | 0 | 2016-06-21T19:46:45Z | 37,953,386 | <p>You have to leave the <code>/canvas.png</code> bit. The temporary file created by <code>tempfile.NamedTemporaryFile()</code> was <code>/var/folders/jn/phqf2ygs0wlgflgfvvv0ctbw0009tb/T/tmpeMcIuh</code>. So using it as parent directory for the output file raises the error by imagemagick.</p>
<p>To specify the output ... | 1 | 2016-06-21T19:51:19Z | [
"python",
"imagemagick",
"temporary-files"
] |
Plotting a 3D quiver plot and ode | 37,953,525 | <p>I am trying to do a 3D quiver plot and combining it with odeint to solve a linearized equation. Basically, I want something similar to <a href="https://commons.wikimedia.org/wiki/File:Van_der_pols_equation_phase_portrait.svg" rel="nofollow">this</a> but in 3D. The particular issue I am having is that near the end of... | 1 | 2016-06-21T19:59:00Z | 37,953,758 | <p>Looks like you have an extra argument in ax.quiver(). From what I can tell, it looks like "M" is the extra argument. Taking that out, your quiver call looks like:</p>
<pre><code>ax.quiver(x,y,z,X,Y,Z,cmap=plt.cm.jet)
</code></pre>
<p>The resulting image looks like:
<a href="http://i.stack.imgur.com/xqNHw.png" rel=... | 0 | 2016-06-21T20:13:23Z | [
"python",
"matplotlib",
"plot",
"ode"
] |
Writing to a text file from a list of a list | 37,953,557 | <p>CS student here, extremely confused about how to solve this problem...
The <code>mailingLabels.txt</code> is simply a blank text file.</p>
<p>Here is one sample line from <code>customerData.txt</code>:</p>
<blockquote>
<p><code>Eric,A,Stutler,568 Nuzum Court,East Aurora,NY,14052,US,Eric.A.Stutler@trashymail.com,... | 1 | 2016-06-21T20:00:59Z | 37,953,715 | <p>You define <code>mailingList</code> in the <code>main()</code> function, but <code>generateMailingLabels</code> doesn't get it. (for one, you don't seem to be calling it)</p>
<p>If you add it in so your main looks more like:</p>
<pre><code>def main():
""" Opens file, reads customer information into a list, closes ... | 0 | 2016-06-21T20:10:12Z | [
"python",
"python-2.7"
] |
Writing to a text file from a list of a list | 37,953,557 | <p>CS student here, extremely confused about how to solve this problem...
The <code>mailingLabels.txt</code> is simply a blank text file.</p>
<p>Here is one sample line from <code>customerData.txt</code>:</p>
<blockquote>
<p><code>Eric,A,Stutler,568 Nuzum Court,East Aurora,NY,14052,US,Eric.A.Stutler@trashymail.com,... | 1 | 2016-06-21T20:00:59Z | 37,953,767 | <p>Before we get started, I'd like to point out that with Python, you can let the interpreter handle the opening and closing of file streams:</p>
<pre><code>with open('customerData.txt','r') as custFile:
## do some stuff here that requires the file to be open
doSomeStuff()
## once outside the loop, Python clo... | 0 | 2016-06-21T20:14:02Z | [
"python",
"python-2.7"
] |
Writing to a text file from a list of a list | 37,953,557 | <p>CS student here, extremely confused about how to solve this problem...
The <code>mailingLabels.txt</code> is simply a blank text file.</p>
<p>Here is one sample line from <code>customerData.txt</code>:</p>
<blockquote>
<p><code>Eric,A,Stutler,568 Nuzum Court,East Aurora,NY,14052,US,Eric.A.Stutler@trashymail.com,... | 1 | 2016-06-21T20:00:59Z | 37,960,463 | <p>Your comments in your methods should be meaningful and describe what the method is doing. For example, the comment on your <code>generateMailingList</code> method has nothing to do with what the method is actually doing.</p>
<p>Further, as you are using Python, you should follow the <a href="https://www.python.org/... | 0 | 2016-06-22T06:45:46Z | [
"python",
"python-2.7"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.