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 |
|---|---|---|---|---|---|---|---|---|---|
Running Flask app on Windows raises "an operation was attempted on something that is not a socket" | 39,067,544 | <p>When running a basic Flask app I am getting this error in the shell and can't find how to solve this.</p>
<pre><code> Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) <br/>
Restarting with stat<br/>
Debugger is active!<br/>
Debugger pin code: 295-257-376<br/>
Exception in thread Thread-1:<br/>
Traceback (most recent call last):<br/>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\threading.py", line 923, in _bootstrap_inner
self.run()<br/>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\threading.py", line 871, in run
self._target(*self._args, **self._kwargs) <br/>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\site-packages\werkzeug\serving.py", line 656, in inner
fd=fd)<br/>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\site-packages\werkzeug\serving.py", line 550, in make_server
passthrough_errors, ssl_context, fd=fd)<br/>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\site-packages\werkzeug\serving.py", line 462, in __init__
socket.SOCK_STREAM)<br/>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\socket.py", line 446, in fromfd
nfd = dup(fd)<br/>
OSError: [WinError 10038] An operation was attempted on something that is not a socket
</code></pre>
<pre><code>from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def main():
return render_template('main.html')
app.run(debug=True)
</code></pre>
| 3 | 2016-08-21T18:29:10Z | 39,111,936 | <p>You're currently trying to execute this from a global python installation. It is a "good practice" to use virtual environments for python projects to keep each projects' pip install separate.</p>
<p>Start by running <code>pip install virtualenv</code></p>
<p>Then, navigate to your projects folder and execute <code>virtualenv example-virtual-env</code>. This will create a new folder with its own python and pip installation. (It supports virtual environments for Python 3 as well.) </p>
<p>Now in shell, execute <code><projects_folder>\Scripts\activate</code> which activates your virtual environment. Now every <code>pip install</code> you execute will be within this environment (Note the environment name before your shell cursor.)</p>
<p>In here, run your <code>pip install flask</code> and run your flask application.</p>
<p>If you're still experiencing the issue, try running CMD in administrator mode. </p>
| 0 | 2016-08-23T22:55:17Z | [
"python",
"flask"
] |
Running Flask app on Windows raises "an operation was attempted on something that is not a socket" | 39,067,544 | <p>When running a basic Flask app I am getting this error in the shell and can't find how to solve this.</p>
<pre><code> Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) <br/>
Restarting with stat<br/>
Debugger is active!<br/>
Debugger pin code: 295-257-376<br/>
Exception in thread Thread-1:<br/>
Traceback (most recent call last):<br/>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\threading.py", line 923, in _bootstrap_inner
self.run()<br/>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\threading.py", line 871, in run
self._target(*self._args, **self._kwargs) <br/>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\site-packages\werkzeug\serving.py", line 656, in inner
fd=fd)<br/>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\site-packages\werkzeug\serving.py", line 550, in make_server
passthrough_errors, ssl_context, fd=fd)<br/>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\site-packages\werkzeug\serving.py", line 462, in __init__
socket.SOCK_STREAM)<br/>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\socket.py", line 446, in fromfd
nfd = dup(fd)<br/>
OSError: [WinError 10038] An operation was attempted on something that is not a socket
</code></pre>
<pre><code>from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def main():
return render_template('main.html')
app.run(debug=True)
</code></pre>
| 3 | 2016-08-21T18:29:10Z | 39,236,998 | <p>i know it is not a solution to the core problem, but for me the issue only occurs when setting the debug flag to True. If you can use your app without the debug/reloading features you might want to give it a try:</p>
<pre><code>app.run(debug=False)
</code></pre>
<p>Meanwhile i am too searching for a way to actually use the debug mode on windows.</p>
| 0 | 2016-08-30T20:58:58Z | [
"python",
"flask"
] |
Create a new dict with means from a dict of dicts | 39,067,562 | <p>I have a dictionary like:</p>
<pre><code>dict = {'abc':{'a':1,'b':2,'c':3},
'bla':{'a':0,'b':9},
'ind':{'b':3,'c':4}
}
</code></pre>
<p>And I want to use list or dictionary comprehension to create a new dictionary which contains every inner key, and then the mean across all values for that inner key, e.g.:</p>
<pre><code>result = {'a':(1+0/2),'b':(2+9+3/3),'c':(3+4/2)}
</code></pre>
<p>How can I do this? I was trying to experiment with </p>
<pre><code>import numpy as np
result = {key: np.mean([inner_value for key,inner_value for inner_dict.items() for outer_key,inner_dict in dict.items()]) for key,inner_value for inner_dict.items() for outer_key,inner_dict in dict.items()}
</code></pre>
<p>But this doesn't work.</p>
| 0 | 2016-08-21T18:31:20Z | 39,067,665 | <p>I know you specifically asked for dictionary/list comprehension, but I'm not sure it's possible to solve this problem with only those tools in an efficient way.</p>
<p>I think the code below is clear and reasonably succinct:</p>
<pre><code>from collections import defaultdict
outer = {
'abc': { 'a': 1, 'b': 2, 'c': 3 },
'bla': { 'a': 0, 'b': 9},
'ind': { 'b': 3, 'c': 4},
}
grouped = defaultdict(list)
for inner in outer.values():
for key, value in inner.items():
grouped[key].append(value)
means = { key: sum(values) / len(values)
for key, values in grouped.items() }
print(means) # {'c': 3.5, 'a': 0.5, 'b': 4.666666666666667}
</code></pre>
| 2 | 2016-08-21T18:42:10Z | [
"python",
"dictionary",
"list-comprehension",
"mean",
"dictionary-comprehension"
] |
Find all lines beginning with a digit | 39,067,585 | <p>What is the regex to extract all lines beginning with a digit?</p>
<p>I know the <code>^</code> character is used to match anything at the beginning of the line but I am not constructing it correct.</p>
<p>Here is what I have tried :</p>
<pre><code>re.findall('^[0-9]+',mystring).
</code></pre>
| -3 | 2016-08-21T18:33:20Z | 39,067,642 | <p>I'm guessing you want to match the entire the line but it is only matching the starting number. You need to include the greedy wildcard as well as the multiline argument to tell it you want to search many lines. Try:</p>
<pre><code>re.findall('^[0-9].*', mystring, re.MULTILINE)
</code></pre>
| 2 | 2016-08-21T18:39:09Z | [
"python",
"regex",
"python-2.7",
"python-3.x"
] |
Find all lines beginning with a digit | 39,067,585 | <p>What is the regex to extract all lines beginning with a digit?</p>
<p>I know the <code>^</code> character is used to match anything at the beginning of the line but I am not constructing it correct.</p>
<p>Here is what I have tried :</p>
<pre><code>re.findall('^[0-9]+',mystring).
</code></pre>
| -3 | 2016-08-21T18:33:20Z | 39,067,673 | <p>You forget the <code>re.MULTILINE</code> modifier and <code>.*</code> after <code>[0-9]</code> to match the rest of the line. If you <em>were</em> to use a regex, you would use <code>r"(?m)^[0-9].*"</code>. However, it is not the best way. Split with \n and iterate through the lines checking if the first char is a digit.</p>
<p>Here is what I suggest:</p>
<pre><code>with open('file', 'r') as f:
for line in f:
if len(line) > 0 and line[0].isdigit():
print(line)
</code></pre>
<p>See <a href="http://ideone.com/dO4AYB" rel="nofollow">this Python demo</a></p>
| 3 | 2016-08-21T18:43:35Z | [
"python",
"regex",
"python-2.7",
"python-3.x"
] |
Scrapy crawler doesnt work with a website i get partial results | 39,067,592 | <p>I'm new to Scrapy and Python. I have been working to extract data from 2 websites and they work really well if I do it directly with python. I have investigated and I want to crawl these websites:</p>
<ol>
<li>homedepot.com.mx/comprar/es/miguel-aleman/home (works perfectly)</li>
<li>vallenproveedora.com.mx/ (doesn't work)</li>
</ol>
<p>Can someone tell me how can I make the the second link work?</p>
<p>I see this message:</p>
<pre><code>DEBUG: Crawled (200) allenproveedora.com.mx/> (referer: None) ['partial']
</code></pre>
<p>but I can't find out how to solve it.</p>
<p>I would appreciate any help and support. Here is the code and the log:</p>
<pre><code>items.py
from scrapy.item import Item, Field
class CraigslistSampleItem(Item):
title = Field()
link = Field()
</code></pre>
<p>Test.py (spider folder)</p>
<pre><code>from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from craigslist_sample.items import CraigslistSampleItem
class MySpider(BaseSpider):
name = "craig"
allowed_domains = ["vallenproveedora.com.mx"]
#start_urls = ["http://www.homedepot.com.mx/webapp/wcs/stores/servlet/SearchDisplay?searchTermScope=&filterTerm=&orderBy=&maxPrice=&showResultsPage=true&langId=-5&beginIndex=0&sType=SimpleSearch&pageSize=&manufacturer=&resultCatEntryType=2&catalogId=10052&pageView=table&minPrice=&urlLangId=-5&storeId=13344&searchTerm=guante"]
start_urls = ["http://www.vallenproveedora.com.mx/"]
def parse(self, response):
titles = response.xpath('//ul/li')
for titles in titles:
title = titles.select("a/text()").extract()
link = titles.select("a/@href").extract()
print (title, link)
</code></pre>
| 2 | 2016-08-21T18:34:26Z | 39,113,822 | <p>You're seeing <code>['partial']</code> in your logs because the server at vallenproveedora.com.mx doesn't set the Content-Length header in its response; run <code>curl -I</code> to see for yourself. For more detail on the cause of the <code>partial</code> flag, see <a href="http://stackoverflow.com/questions/33606080/portia-spider-logs-showing-partial-during-crawling/39007029#39007029">my answer here</a>.</p>
<p>However, you don't actually have to worry about this. The response body is all there and Scrapy will parse it. The problem you're really encountering is that there are no elements selected by the XPath <code>//ul/li/a</code>. You should look at the page source and modify your selectors accordingly. I would recommend writing a specific spider for each site, because sites usually need different selectors.</p>
| 0 | 2016-08-24T03:14:14Z | [
"python",
"scrapy",
"web-crawler",
"partial"
] |
Determine if a day is a business day in Python / Pandas | 39,067,626 | <p>I currently have a program setup to run two different ways. One way is to run over a specified time frame, and the other way is to run everyday. However, when I have it set to run everyday, I only want it to continue if its a business day. Now from research I've seen that you can iterate through business days using Pandas like so:</p>
<pre><code>start = 2016-08-05
end = datetime.date.today().strftime("%Y-%m-%d")
for day in pd.bdate_range(start, end):
print str(day) + " is a business Day"
</code></pre>
<p>And this works great when I run my program over the specified period.</p>
<p>But when I want to have the program ran everyday, I can't quite figure out how to test one specific day for being a business day. Basically I want to do something like this:</p>
<pre><code>start = datetime.date.today().strftime("%Y-%m-%d")
end = datetime.date.today().strftime("%Y-%m-%d")
if start == end:
if not Bdate(start)
print "Not a Business day"
</code></pre>
<p>I know I could probably setup pd.bdate_range() to do what I'm looking for, but in my opinion would be sloppy and not intuitive. I feel like there must be a simpler solution to this. Any advice?</p>
| 0 | 2016-08-21T18:37:31Z | 39,068,260 | <p>Since <code>len</code> of <code>pd.bdate_range()</code> tells us how many business days are in the supplied range of dates, we can cast this to a <code>bool</code> to determine if a range of a single day is a business day:</p>
<pre><code>def is_business_day(date):
return bool(len(pd.bdate_range(date, date)))
</code></pre>
| 0 | 2016-08-21T19:47:32Z | [
"python",
"date",
"datetime",
"pandas"
] |
Determine if a day is a business day in Python / Pandas | 39,067,626 | <p>I currently have a program setup to run two different ways. One way is to run over a specified time frame, and the other way is to run everyday. However, when I have it set to run everyday, I only want it to continue if its a business day. Now from research I've seen that you can iterate through business days using Pandas like so:</p>
<pre><code>start = 2016-08-05
end = datetime.date.today().strftime("%Y-%m-%d")
for day in pd.bdate_range(start, end):
print str(day) + " is a business Day"
</code></pre>
<p>And this works great when I run my program over the specified period.</p>
<p>But when I want to have the program ran everyday, I can't quite figure out how to test one specific day for being a business day. Basically I want to do something like this:</p>
<pre><code>start = datetime.date.today().strftime("%Y-%m-%d")
end = datetime.date.today().strftime("%Y-%m-%d")
if start == end:
if not Bdate(start)
print "Not a Business day"
</code></pre>
<p>I know I could probably setup pd.bdate_range() to do what I'm looking for, but in my opinion would be sloppy and not intuitive. I feel like there must be a simpler solution to this. Any advice?</p>
| 0 | 2016-08-21T18:37:31Z | 39,068,368 | <p>Please check this module - <a href="https://pypi.python.org/pypi/bdateutil/0.1" rel="nofollow">bdateutil</a></p>
<p>Please check the below code using above module :</p>
<pre><code>from bdateutil import isbday
from datetime import datetime,date
now = datetime.now()
val = isbday(date(now.year, now.month, now.day))
print val
</code></pre>
<p>Please let me know if this help.</p>
| 0 | 2016-08-21T20:01:51Z | [
"python",
"date",
"datetime",
"pandas"
] |
I can't install matplotlib | 39,067,640 | <p>Collecting matplotlib
Using cached matplotlib-1.5.2.tar.gz
Complete output from command python setup.py egg_info:
============================================================================
Edit setup.cfg to change the build options</p>
<pre><code>BUILDING MATPLOTLIB
matplotlib: yes [1.5.2]
python: yes [3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015,
01:38:48) [MSC v.1900 32 bit (Intel)]]
platform: yes [win32]
REQUIRED DEPENDENCIES AND EXTENSIONS
numpy: yes [version 1.11.1]
dateutil: yes [using dateutil version 2.5.3]
pytz: yes [using pytz version 2016.6.1]
cycler: yes [cycler was not found. pip will attempt to
install it after matplotlib.]
tornado: yes [tornado was not found. It is required for the
WebAgg backend. pip/easy_install may attempt to
install it after matplotlib.]
pyparsing: yes [pyparsing was not found. It is required for
mathtext support. pip/easy_install may attempt to
install it after matplotlib.]
libagg: yes [pkg-config information for 'libagg' could not
be found. Using local copy.]
freetype: no [The C/C++ header for freetype (ft2build.h)
could not be found. You may need to install the
development package.]
png: no [The C/C++ header for png (png.h) could not be
found. You may need to install the development
package.]
qhull: yes [pkg-config information for 'qhull' could not be
found. Using local copy.]
OPTIONAL SUBPACKAGES
sample_data: yes [installing]
toolkits: yes [installing]
tests: yes [nose 0.11.1 or later is required to run the
matplotlib test suite. Please install it with pip or
your preferred tool to run the test suite / using
unittest.mock]
toolkits_tests: yes [nose 0.11.1 or later is required to run the
matplotlib test suite. Please install it with pip or
your preferred tool to run the test suite / using
unittest.mock]
OPTIONAL BACKEND EXTENSIONS
macosx: no [Mac OS-X only]
qt5agg: no [PyQt5 not found]
qt4agg: no [PySide not found; PyQt4 not found]
gtk3agg: no [Requires pygobject to be installed.]
gtk3cairo: no [Requires cairocffi or pycairo to be installed.]
gtkagg: no [Requires pygtk]
tkagg: yes [installing; run-time loading from Python Tcl /
Tk]
wxagg: no [requires wxPython]
gtk: no [Requires pygtk]
agg: yes [installing]
cairo: no [cairocffi or pycairo not found]
windowing: yes [installing]
OPTIONAL LATEX DEPENDENCIES
dvipng: no
ghostscript: no
latex: no
pdftops: no
OPTIONAL PACKAGE DATA
dlls: no [skipping due to configuration]
============================================================================
* The following required packages can not be built:
* freetype, png
----------------------------------------
</code></pre>
<p>Command "python setup.py egg_info" failed with error code 1 in C:\Users\User\AppData\Local\Temp\pycharm-packaging\matplotlib\</p>
<p>I have tried uninstalling and installing again the pip, but it did not work. I do not know what to do. :(
If you can comment in spanish would help me a lot, my English is not so good, thanks in advance.</p>
| 0 | 2016-08-21T18:39:03Z | 39,067,856 | <p>I installed matplotlib with the .whl file and it worked for me. I got it from this website <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#matplotlib" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#matplotlib</a>. Download the right .whl package ( i.e If you have Python 3.5.1 64 bit download matplotlib-2.0.0b3-cp35-cp35m-win_amd64.whl) Then go to File Explorer and go to the folder where you downloaded the .whl file. On file explorer click File -> open command prompt -> open as adminstrator. Then type this</p>
<pre><code>pip install (fileName.whl)
</code></pre>
<p>If it says that pip is not found then go to the place where you downloaded python in file explorer. Go to the scripts folder and open it there. You can copy and paste the .whl file in the scripts folder. Then type the pip install command again. After that's done you can check if it works by going to IDLE and try importing it</p>
<pre><code>import matplotlib
</code></pre>
<p>if it runs that means you installed it correctly. That is the only way I know to install matplotlib so sorry if it doesn't work. </p>
| 0 | 2016-08-21T19:04:38Z | [
"python",
"matplotlib",
"install"
] |
Django form not calling clean_<fieldname> (in this case clean_email) | 39,067,677 | <p>I couldn't find an answer to the following question, it took me a couple of hours to find out, hence I'm adding it. I'll add my approach of solving it and the answer.</p>
<p>I'm following a YouTube tutorial from <a href="https://www.youtube.com/watch?v=g0tvJsUAx7g&list=PLEsfXFp6DpzRcd-q4vR5qAgOZUuz8041S&index=11" rel="nofollow">This person</a>. For some reason I'm typing the same code, and I checked every single letter. Yet for some reason my cleaning functions aren't called. It's probably something simple, especially since a <a href="http://stackoverflow.com/questions/1871746/django-form-not-calling-clean-fieldname">related question</a> showed something similar. It's probably a framework thing that I get wrong, but I wouldn't know what it is.</p>
<p>Here is the relevant code.</p>
<p>forms.py (complete copy/paste from <a href="https://github.com/codingforentrepreneurs/Try-Django-1.8/blob/master/src/newsletter/forms.py" rel="nofollow">his Github</a>)</p>
<pre><code>from django import forms
from .models import SignUp
class ContactForm(forms.Form):
full_name = forms.CharField(required=False)
email = forms.EmailField()
message = forms.CharField()
class SignUpForm(forms.ModelForm):
class Meta:
model = SignUp
fields = ['full_name', 'email']
### exclude = ['full_name']
def clean_email(self):
email = self.cleaned_data.get('email')
email_base, provider = email.split("@")
domain, extension = provider.split('.')
# if not domain == 'USC':
# raise forms.ValidationError("Please make sure you use your USC email.")
if not extension == "edu":
raise forms.ValidationError("Please use a valid .EDU email address")
return email
# Final part is ommited, since it's not relevant.
</code></pre>
<p>admin.py (typed over from the tutorial)</p>
<pre><code>from django.contrib import admin
# Register your models here.
from .models import SignUp
from .forms import SignUpForm
class SignUpAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'timestamp', 'updated']
class Meta:
model = SignUp
form = SignUpForm
admin.site.register(SignUp, SignUpAdmin)
</code></pre>
| 0 | 2016-08-21T18:43:54Z | 39,067,784 | <p>After using print statements for a while and reading questions that seemed similar but eventually didn't solve my problem, I decided to look into the source of Django (idea inspired by the <a href="http://stackoverflow.com/questions/1871746/django-form-not-calling-clean-fieldname">most similar question I could find</a>).</p>
<p>Then, I decided to debug the source, since I wanted to know how Django is treating my customized function (thanks to a <a href="https://mike.tig.as/blog/2010/09/14/pdb/" rel="nofollow">tutorial</a> + <a href="http://stackoverflow.com/questions/1118183/how-to-debug-in-django-the-good-way">SO answer</a>). In the source I found that the customized functions were called around <code>return super(EmailField, self).clean(value)</code> (line 585, django/forms/fields.py, Django 1.8). When I was stepping through the code I found the critical line <code>if hasattr(self, 'clean_%s' % name):</code> (line 409, django/forms/forms.py, Django 1.8). I checked for the value <code>name</code> which was <code>"email"</code>. Yet, the if-statement evaluated as <code>False</code> (<code>(Pdb) p hasattr(self, 'clean_%s' % name)</code>). I didn't understand why, until I figured out that the function name was not registered ((Pdb) <code>pp dir(self)</code>).</p>
<p>I decided to take a look at the whole source code repository and cross-checked every file and then I found that </p>
<pre><code>class Meta:
model = SignUp
form = SignUpForm
</code></pre>
<p>means that <code>form</code> / <code>SignUpForm</code> were nested inside the Meta class. At first, I didn't think much of it but slowly I started to realize that it should be outside the Meta class while staying main class (<code>SignUpAdmin</code>).</p>
<p>So <code>form = SignUpForm</code> should have been idented one tab back. For me, as a Django beginner, it still kind of baffles me, because I thought the Meta class was supposed to encapsulate both types of data (models and forms). Apparently it shouldn't, that's what I got wrong.</p>
| 0 | 2016-08-21T18:55:59Z | [
"python",
"django"
] |
Different counters in one pass of list of dicts | 39,067,732 | <p>I have a list of dictionaries in Python. Every element of the list corresponds to one day, and every element of the dictionary has information on a user's minute-by-minute activity.</p>
<p>Example:</p>
<pre><code>list_of_dicts = [
{u'activity':
{u'values': [
[1407729600, 3.0],
[1407729660, 2.0],
[1407729720, 2.0],
[1407729780, 3.0],
[1407729840, 1.0],
[1407729900, 4.0],
[1407729960, 2.0],
[1407730020, 5.0],
[1407730080, 6.0],
[1407730140, 2.0],
[1407730200, 1.0],
[1407730260, 2.0],
[1407730320, 1.0],
[1407730380, 2.0],
[1407730440, 1.0]]}},
{u'activity':
{u'values': [
[1407788340, 2.0],
[1407788400, 2.0],
[1407788460, 3.0],
[1407788520, 2.0],
[1407788580, 2.0],
[1407788640, 2.0],
[1407788700, 2.0],
[1407788760, 2.0],
[1407788820, 2.0],
[1407788880, 3.0],
[1407788940, 2.0],
[1407789000, 3.0],
[1407789060, 2.0],
[1407789120, 3.0],
[1407789180, 3.0],
[1407789240, 2.0],
[1407789300, 3.0],
[1407789360, 3.0],
[1407789420, 2.0],
[1407789480, 3.0],
[1407789540, 2.0]]}}]
</code></pre>
<p>Now, I want to have different aggregations of the data. For example, I would like to have the count of activity per hour per day of the week. This I can do with the following piece of code:</p>
<pre><code>c = Counter()
step_values_unlist = list(itertools.chain.from_iterable(
[d['activity']['values']
for d in list_of_dicts]))
week_hour_dict = [{(time.gmtime(x[0])[3], time.gmtime(x[0])[6]):x[1]}
for x in step_values_unlist]
for d in week_hour_dict:
c.update(d)
</code></pre>
<p>Whilst this is OK, I will need to do other aggregations also, since this is part of a feature vector generation for the subsequent ML step. As an example, I would like to have counts of weeks with activity on all seven days etc. These can also be done individually via various counters by reading the list of dictionaries again for a new counter. However, this will be time-consuming since the list of dictionaries is large and this is running (via PySpark) for 1M+ users. It is preferable that we not read through this large list of dicts multiple times. Is there a way to compute these measures in one single pass of the list of dicts ?</p>
| 0 | 2016-08-21T18:50:26Z | 39,067,879 | <p>Correct me if I'm wrong, but I would summarize your question as follows:</p>
<blockquote>
<p>Is there a way to compute multiple operations in one single pass of a list of dicts?</p>
</blockquote>
<p>In the general case this shouldn't really matter. If you're computing 15 operations, you're going to have to do a computation with each element 15 different times.</p>
<p>In the case when you have a detailed idea of the operations of each of your metrics, you may be able to factor out some of the operations to eliminate redundant work. For example you may need to take into account the average per minute in multiple metrics for normalization purposes. It's up to you to write your functions so they can share this average value: compute it first and then pass it to each one.</p>
| 0 | 2016-08-21T19:06:43Z | [
"python",
"list",
"dictionary",
"counter"
] |
Python one liner with if in a loop | 39,067,759 | <p>I'm having a problem .</p>
<p>How can I write below one liner using function?</p>
<pre><code>def onlyPairs(string):
for x in string:
if int(x)%2:
return False
return True
print [string for string in map(str, myList) if onlyPairs(string) ]
</code></pre>
<p>I've been on it for hours, I feel I'm getting close but I can't see the solution involving only one line.</p>
<p>I'm trying to have a list of numbers with each figure of the number that is even.</p>
<p>For example if mylist is [1200,3520,2002,2006,1230] then the line should produce a new list with only [2002,2006] in it.</p>
| -4 | 2016-08-21T18:53:58Z | 39,067,798 | <p>Use a generator expression with <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow"><code>all()</code></a>:</p>
<pre><code>[item for item in myList if all(not int(x)%2 for x in str(item))]
</code></pre>
<p>But it seems that you want to check if all digits of a number are even. Which in that case converting the number to string is not a good idea. Instead you can use following function, which works with integers:</p>
<pre><code>def check_all_even(num):
while num:
n = num % 10
num = num / 10
if n % 2:
return False
return True
</code></pre>
<p>The filter your list with it:</p>
<pre><code>filter(check_all_even, myList)
</code></pre>
<p>Demo:</p>
<pre><code>lst = [1200, 3520, 2002, 2006, 1230]
print filter(check_all_even, lst) # In python 3.x print(list(filter(check_all_even, lst)))
[2002, 2006]
</code></pre>
| 1 | 2016-08-21T18:57:40Z | [
"python",
"python-2.7",
"python-3.x",
"list-comprehension"
] |
Python one liner with if in a loop | 39,067,759 | <p>I'm having a problem .</p>
<p>How can I write below one liner using function?</p>
<pre><code>def onlyPairs(string):
for x in string:
if int(x)%2:
return False
return True
print [string for string in map(str, myList) if onlyPairs(string) ]
</code></pre>
<p>I've been on it for hours, I feel I'm getting close but I can't see the solution involving only one line.</p>
<p>I'm trying to have a list of numbers with each figure of the number that is even.</p>
<p>For example if mylist is [1200,3520,2002,2006,1230] then the line should produce a new list with only [2002,2006] in it.</p>
| -4 | 2016-08-21T18:53:58Z | 39,067,866 | <p>Here's a possible solution:</p>
<pre><code>myList = [1200, 3520, 2002, 2006, 1230]
print map(str, filter(lambda x: all([int(d) % 2 == 0 for d in str(x)]), myList))
</code></pre>
| 0 | 2016-08-21T19:05:11Z | [
"python",
"python-2.7",
"python-3.x",
"list-comprehension"
] |
Python one liner with if in a loop | 39,067,759 | <p>I'm having a problem .</p>
<p>How can I write below one liner using function?</p>
<pre><code>def onlyPairs(string):
for x in string:
if int(x)%2:
return False
return True
print [string for string in map(str, myList) if onlyPairs(string) ]
</code></pre>
<p>I've been on it for hours, I feel I'm getting close but I can't see the solution involving only one line.</p>
<p>I'm trying to have a list of numbers with each figure of the number that is even.</p>
<p>For example if mylist is [1200,3520,2002,2006,1230] then the line should produce a new list with only [2002,2006] in it.</p>
| -4 | 2016-08-21T18:53:58Z | 39,068,229 | <p>use sets:</p>
<pre><code>myList = [1200, 3520, 2002, 2006, 1230]
print [num for num in myList if not set(str(num)) - set('02468')]
</code></pre>
| 2 | 2016-08-21T19:44:57Z | [
"python",
"python-2.7",
"python-3.x",
"list-comprehension"
] |
DataFrame with MultiIndex to dict | 39,067,831 | <p>I have a dataframe with a MultiIndex. I am wondering whether I created the data frame in the correct manner (see below).</p>
<pre><code> 01.01 02.01 03.01 04.01
bar total1 40 52 18 11
total2 36 85 5 92
baz total1 23 39 45 70
total2 50 49 51 65
foo total1 23 97 17 97
total2 64 56 94 45
qux total1 13 73 38 4
total2 80 8 61 50
</code></pre>
<p><code>df.index.values</code> results in:</p>
<pre><code>array([('bar', 'total1'), ('bar', 'total2'), ('baz', 'total1'),
('baz', 'total2'), ('foo', 'total1'), ('foo', 'total2'),
('qux', 'total1'), ('qux', 'total2')], dtype=object)
</code></pre>
<p><code>df.index.get_level_values</code> results in:</p>
<pre><code><bound method MultiIndex.get_level_values of MultiIndex(levels=[[u'bar', u'baz', u'foo', u'qux'], [u'total1', u'total2']],
labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]],names=[]
</code></pre>
<p>I am ultimately looking to transform the df into a dict of dictionaries such that the first dict key are one of ['bar','baz', 'foo','qux'] and values are the dates and the inner dictionary is made of 'total1' and 'totals2' as key and the values are the integers of the df.
Alternative explanation, is for example if dict1 is the dict then calling:</p>
<pre><code>dict1['bar']
</code></pre>
<p>would result in the output:</p>
<pre><code>{u'bar':{'01.01':{'total1':40,'total2':36},'02.01':{'total1':52,'total2':85},'03.01':{'total1':18,'total2':5},'04.01':{'total1':11,'total2':92} } }
</code></pre>
<p>How and what would I need to alter in order to achieve this? Is this an indexing issue?
I am relatively new to pandas and dictionaries so I hope you can bare with me.</p>
| 1 | 2016-08-21T19:02:05Z | 39,074,579 | <p>Try:</p>
<pre><code>df.groupby(level=0).apply(lambda df: df.xs(df.name).to_dict()).to_dict()
{'bar': {'01.01': {'total1': 40, 'total2': 36},
'02.01': {'total1': 52, 'total2': 85},
'03.01': {'total1': 18, 'total2': 5},
'04.01': {'total1': 11, 'total2': 92}},
'baz': {'01.01': {'total1': 23, 'total2': 50},
'02.01': {'total1': 39, 'total2': 49},
'03.01': {'total1': 45, 'total2': 51},
'04.01': {'total1': 70, 'total2': 65}},
'foo': {'01.01': {'total1': 23, 'total2': 64},
'02.01': {'total1': 97, 'total2': 56},
'03.01': {'total1': 17, 'total2': 94},
'04.01': {'total1': 97, 'total2': 45}},
'qux': {'01.01': {'total1': 13, 'total2': 80},
'02.01': {'total1': 73, 'total2': 8},
'03.01': {'total1': 38, 'total2': 61},
'04.01': {'total1': 4, 'total2': 50}}}
</code></pre>
| 1 | 2016-08-22T08:25:19Z | [
"python",
"pandas",
"dictionary"
] |
'QuerySet' object has no attribute 'filter_on_search' Python Django | 39,067,834 | <p>Can anyone please suggest me why I am getting this error. </p>
<p>Following is model with Manager</p>
<pre><code>class Customer(models.Model):
customer_id = models.AutoField(primary_key=True)
customer_name = models.CharField(max_length=256)
customer_mobile = models.CharField(max_length=10)
customer_email = models.CharField(max_length=100,null=True)
customer_dob = models.DateField()
customer_remarks= models.CharField(max_length=256,null=True)
row_status = models.BooleanField(choices=ROW_STATUS, default=True)
created_date = models.DateTimeField()
updated_date = models.DateTimeField()
objects = MyClassManager()
def __unicode__(self):
return self.customer_name
def as_dict(self):
"""
Create data for datatables ajax call.
"""
return {'customer_name': self.customer_name,
'customer_mobile': self.customer_mobile,
'customer_dob': self.customer_dob,
}
</code></pre>
<p>Manager Starts here ---------</p>
<pre><code>class MyClassMixin(object):
def q_for_search_word(self, word):
"""
Given a word from the search text, return the Q object which you can filter on,
to show only objects containing this word.
Extend this in subclasses to include class-specific fields, if needed.
"""
return Q(name__icontains=word) | Q(supplier__name__icontains=word)
def q_for_search(self, search):
"""
Given the text from the search box, search on each word in this text.
Return a Q object which you can filter on, to show only those objects with _all_ the words present.
Do not expect to override/extend this in subclasses.
"""
q = Q()
if search:
searches = search.split()
for word in searches:
q = q & self.q_for_search_word(word)
return q
def filter_on_search(self, search):
"""
Return the objects containing the search terms.
Do not expect to override/extend this in subclasses.
"""
return self.filter(self.q_for_search(search))
class MyClassQuerySet(QuerySet, MyClassMixin):
pass
class MyClassManager(models.Manager, MyClassMixin):
def get_query_set(self):
return MyClassQuerySet(self.model, using=self._db)
</code></pre>
<p>This is my view -----</p>
<pre><code>class MyAPI(JSONViewMixin, View):
"Return the JSON representation of the objects"
def get(self, request, *args, **kwargs):
class_name = kwargs.get('cls_name')
params = request.GET
# make this api general enough to handle different classes
klass = getattr(sys.modules['mudraapp.models'], class_name)
# TODO: this only pays attention to the first sorting column
sort_col_num = params.get('iSortCol_0', 0)
# default to value column
sort_col_name = params.get('mDataProp_{0}'.format(sort_col_num), 'value')
search_text = params.get('sSearch', '').lower()
sort_dir = params.get('sSortDir_0', 'asc')
start_num = int(params.get('iDisplayStart', 0))
num = int(params.get('iDisplayLength', 25))
obj_list = klass.objects.all()
sort_dir_prefix = (sort_dir=='desc' and '-' or '')
if sort_col_name in col_name_map:
sort_col = col_name_map[sort_col_name]
obj_list = obj_list.order_by('{0}{1}'.format(sort_dir_prefix, sort_col))
filtered_obj_list = obj_list
if search_text:
filtered_obj_list = obj_list.filter_on_search(search_text) //Here I am getting error
d = {"iTotalRecords": obj_list.count(), # num records before applying any filters
"iTotalDisplayRecords": filtered_obj_list.count(), # num records after applying filters
"sEcho":params.get('sEcho',1), # unaltered from query
"aaData": [obj.as_dict() for obj in filtered_obj_list[start_num:(start_num+num)]] # the data
}
return self.json_response(d)
</code></pre>
<p>I am using this code for datatable pagination and search pagination works good but while search it gives error
I am following following Tutorial for this
<a href="http://racingtadpole.com/blog/datatables-with-ajax-and-django/" rel="nofollow">http://racingtadpole.com/blog/datatables-with-ajax-and-django/</a></p>
| 0 | 2016-08-21T19:02:16Z | 39,071,427 | <p>The method you have created in <code>MyClassManager</code> has the <a href="https://docs.djangoproject.com/en/stable/topics/db/managers/#modifying-a-manager-s-initial-queryset" rel="nofollow">wrong name</a>:</p>
<pre><code>def get_query_set(self):
</code></pre>
<p>Which should instead be:</p>
<pre><code># query_set -> queryset
def get_queryset(self):
</code></pre>
| 1 | 2016-08-22T04:28:41Z | [
"python",
"django"
] |
'QuerySet' object has no attribute 'filter_on_search' Python Django | 39,067,834 | <p>Can anyone please suggest me why I am getting this error. </p>
<p>Following is model with Manager</p>
<pre><code>class Customer(models.Model):
customer_id = models.AutoField(primary_key=True)
customer_name = models.CharField(max_length=256)
customer_mobile = models.CharField(max_length=10)
customer_email = models.CharField(max_length=100,null=True)
customer_dob = models.DateField()
customer_remarks= models.CharField(max_length=256,null=True)
row_status = models.BooleanField(choices=ROW_STATUS, default=True)
created_date = models.DateTimeField()
updated_date = models.DateTimeField()
objects = MyClassManager()
def __unicode__(self):
return self.customer_name
def as_dict(self):
"""
Create data for datatables ajax call.
"""
return {'customer_name': self.customer_name,
'customer_mobile': self.customer_mobile,
'customer_dob': self.customer_dob,
}
</code></pre>
<p>Manager Starts here ---------</p>
<pre><code>class MyClassMixin(object):
def q_for_search_word(self, word):
"""
Given a word from the search text, return the Q object which you can filter on,
to show only objects containing this word.
Extend this in subclasses to include class-specific fields, if needed.
"""
return Q(name__icontains=word) | Q(supplier__name__icontains=word)
def q_for_search(self, search):
"""
Given the text from the search box, search on each word in this text.
Return a Q object which you can filter on, to show only those objects with _all_ the words present.
Do not expect to override/extend this in subclasses.
"""
q = Q()
if search:
searches = search.split()
for word in searches:
q = q & self.q_for_search_word(word)
return q
def filter_on_search(self, search):
"""
Return the objects containing the search terms.
Do not expect to override/extend this in subclasses.
"""
return self.filter(self.q_for_search(search))
class MyClassQuerySet(QuerySet, MyClassMixin):
pass
class MyClassManager(models.Manager, MyClassMixin):
def get_query_set(self):
return MyClassQuerySet(self.model, using=self._db)
</code></pre>
<p>This is my view -----</p>
<pre><code>class MyAPI(JSONViewMixin, View):
"Return the JSON representation of the objects"
def get(self, request, *args, **kwargs):
class_name = kwargs.get('cls_name')
params = request.GET
# make this api general enough to handle different classes
klass = getattr(sys.modules['mudraapp.models'], class_name)
# TODO: this only pays attention to the first sorting column
sort_col_num = params.get('iSortCol_0', 0)
# default to value column
sort_col_name = params.get('mDataProp_{0}'.format(sort_col_num), 'value')
search_text = params.get('sSearch', '').lower()
sort_dir = params.get('sSortDir_0', 'asc')
start_num = int(params.get('iDisplayStart', 0))
num = int(params.get('iDisplayLength', 25))
obj_list = klass.objects.all()
sort_dir_prefix = (sort_dir=='desc' and '-' or '')
if sort_col_name in col_name_map:
sort_col = col_name_map[sort_col_name]
obj_list = obj_list.order_by('{0}{1}'.format(sort_dir_prefix, sort_col))
filtered_obj_list = obj_list
if search_text:
filtered_obj_list = obj_list.filter_on_search(search_text) //Here I am getting error
d = {"iTotalRecords": obj_list.count(), # num records before applying any filters
"iTotalDisplayRecords": filtered_obj_list.count(), # num records after applying filters
"sEcho":params.get('sEcho',1), # unaltered from query
"aaData": [obj.as_dict() for obj in filtered_obj_list[start_num:(start_num+num)]] # the data
}
return self.json_response(d)
</code></pre>
<p>I am using this code for datatable pagination and search pagination works good but while search it gives error
I am following following Tutorial for this
<a href="http://racingtadpole.com/blog/datatables-with-ajax-and-django/" rel="nofollow">http://racingtadpole.com/blog/datatables-with-ajax-and-django/</a></p>
| 0 | 2016-08-21T19:02:16Z | 39,071,454 | <p>You are using <code>filter_on_search</code> on your queryset. Instead, you need to use it in lieu of <code>objects</code>. </p>
<p>So, you would star by doing </p>
<pre><code>obj_list = klass.filter_on_search
</code></pre>
<p>However, looks like you may want to move all of your logic from the view to the manager. </p>
<p>For what it's worth, there is an awesome package that does exactly what you want in integrating Django with Datatables: <a href="https://pypi.python.org/pypi/django-datatables-view" rel="nofollow">https://pypi.python.org/pypi/django-datatables-view</a></p>
| 0 | 2016-08-22T04:31:11Z | [
"python",
"django"
] |
Rename pandas column values from unstacked pivot table | 39,067,839 | <p>I have pandas pivot table <code>merge2</code> that looks like:</p>
<pre><code> Site TripDate Volume Early_Vol Percent_Vol
0 024l 2004-12-02 1117.134948 1117.134948 0.000000
1 024l 2005-05-07 390.980708 1117.134948 -0.650015
2 024l 2006-10-07 321.110175 1117.134948 -0.712559
3 024l 2007-10-13 527.631767 1117.134948 -0.527692
4 024l 2008-02-02 597.165065 1117.134948 -0.465449
</code></pre>
<p>I then subset <code>merge2</code> into <code>sub1</code></p>
<pre><code>sub1 = merge2[['Site','TripDate','Percent_Vol']]
sub1= sub1.set_index(['Site','TripDate'])
</code></pre>
<p><code>sub1</code> looks like:</p>
<pre><code> Percent_Vol
Site TripDate
024l 2004-12-02 0.000000
2005-05-07 -0.650015
2006-10-07 -0.712559
2007-10-13 -0.527692
2008-02-02 -0.465449
</code></pre>
<p>I then unstack <code>sub1</code> into <code>t</code> to look like:</p>
<pre><code> Percent_Vol
Site 024l 029l 033l 035l_r 035l_s 041r_r
TripDate
2004-06-01 NaN NaN NaN NaN NaN NaN
2004-11-13 NaN NaN NaN NaN NaN NaN
2004-12-02 0.000000 0.000000 0.000000 0.0 0.000000 0.000000
2005-05-07 -0.650015 -0.290539 -0.300276 -1.0 -0.075511 -0.298801
2006-10-07 -0.712559 -0.769020 -0.393304 -1.0 -0.520052 -0.284686
</code></pre>
<p>It seems like I have two levels for my columns names in <code>t</code> (i.e. <code>Percent_Vol</code> and <code>Site</code>) and I only what <code>Site</code>. Is there a way to change the column names to just <code>Site</code>?</p>
| 1 | 2016-08-21T19:02:58Z | 39,067,909 | <p>try this:</p>
<pre><code>t.columns = t.columns.droplevel()
</code></pre>
| 1 | 2016-08-21T19:08:51Z | [
"python",
"pandas",
"rename"
] |
NameError: name 'file' is not defined | 39,067,840 | <p>This works in Python 2.7 but not in 3.5.</p>
<pre><code>def file_read(self, input_text):
doc = (file.read(file(input_text))).decode('utf-8', 'replace')
</code></pre>
<p>I'm trying to open this file, input_text is a path value from argparse.</p>
<p>I get this error.</p>
<pre><code>NameError: name 'file' is not defined
</code></pre>
<p>I gather that Python 3.5 uses "open" instead of "file", but I don't quite get how to use open in a situation like this.</p>
| -1 | 2016-08-21T19:02:59Z | 39,067,943 | <p>Your original code works in Python 2.7 but it is bad style there. The <code>file</code> for this use was deprecated long time ago in favour of using <code>open</code>, and instead of calling the <code>file.read</code> passing the file as the argument you should have just called the <code>.read</code> method on the returned object.</p>
<p>The correct way to write the code you did on Python 2 would have been</p>
<pre><code>with open(input_text) as docfile:
doc = docfile.read().decode('utf-8', 'replace')
</code></pre>
<hr>
<p>This does not work as such in Python 3, because <code>open</code> without mode would now default to reading unicode text. Furthermore it would assume the file is in native encoding and decode it with <em>strict</em> error handling. However, Python 3 actually makes working with text files easier than in Python 2, as you can pass the encoding and errors behaviour as arguments to <a href="https://docs.python.org/3/library/functions.html#open" rel="nofollow"><code>open</code></a> itself:</p>
<pre><code>with open(input_text, encoding='utf-8', errors='replace') as docfile:
doc = docfile.read()
</code></pre>
| 2 | 2016-08-21T19:12:43Z | [
"python",
"file",
"python-3.x"
] |
Calling a function, stored as a value in a dictionary, if the user's input matches the value's key | 39,067,842 | <p>I'm currently creating a simple interactive fiction (IF) game in Python. In addition to the commands relevant to each room they explore, I would like for the player to have access to a list of "global commands" that can be called at anytime (inventory, help, etc).</p>
<p>I used <a href="http://stackoverflow.com/questions/5134482/python-call-function-from-user-input">this</a> thread to get started, but I don't think it's quite what I'm looking for. </p>
<p>Essentially, what I want is something like this (obviously, not all of this is valid code):</p>
<pre><code>def inventory():
# Shows the user's inventory
def game_help():
# shows a list of available commands
global_commands = {
'inventory': inventory(),
'help': game_help(),
}
command = raw_input().downcase()
if command == "get item":
print "You take the item"
elif command == "open door":
print "You open the door"
elif command in global_commands:
# execute the function that is tied to the user's input
</code></pre>
<p>Any and all help is appreciated!</p>
| 3 | 2016-08-21T19:03:18Z | 39,068,016 | <p>Make the values in the global_commands dictionary the functions. Don't include parentheses as you don't want to call them yet.</p>
<pre><code>global_commands = {
'inventory': inventory,
'help': game_help,
}
</code></pre>
<p>Then look up the command in the dictionary and execute the corresponding function:</p>
<pre><code>elif command in global_commands:
global_commands[command]()
</code></pre>
| 6 | 2016-08-21T19:21:17Z | [
"python"
] |
Is removeWidget() necessary | 39,067,900 | <p>I just started with PyQt and I'm trying to sort elements in a <code>QGridLayout</code>. In the code below, I'm moving an existing button from the cell <code>(4,1)</code> to <code>(0,0)</code>. My confusion arises because either using <code>removeWidget</code> or not, both pieces of code behave exactly the same:</p>
<pre><code> myButton = self.myGridLayout.itemAtPosition(4, 1).widget()
self.myGridLayout.removeWidget(myButton)
self.myGridLayout.addWidget(myButton, 0, 0)
</code></pre>
<p>is the same as:</p>
<pre><code> myButton = self.myGridLayout.itemAtPosition(4, 1).widget()
self.myGridLayout.addWidget(myButton, 0, 0)
</code></pre>
<p>Is PyQt handling everything behind the scenes or is there something that I have not noticed happening?</p>
<p>Thanks</p>
| 1 | 2016-08-21T19:08:23Z | 39,069,593 | <p>A widget can only belong to one layout. Before a widget is added to a layout, Qt will check to see if it has ever been in a layout, and if so, it will remove it from whatever layout it currently belongs to. The widget will also be automatically reparented to the layout's current parent-widget.</p>
<p>A widget also cannot be added to the same layout twice - but that is really no different from the case above, and so it is treated in exactly the same way.</p>
| 1 | 2016-08-21T23:03:30Z | [
"python",
"user-interface",
"pyqt",
"pyqt4"
] |
How can I create a matrix from a list? | 39,067,946 | <p>I am given a list which somehow represents a matrix, but it is in the list format, like</p>
<pre><code>["OOX","XOX","XOX"]
</code></pre>
<p>Is there any way i can convert it into a matrix?
I have gone through numpy, but could not figure out!</p>
| 0 | 2016-08-21T19:12:57Z | 39,068,021 | <p>numpy is overkill for this. For something like Tic-tac-toe, a list of lists is enough.</p>
<p>If <code>'OOX'</code> is a string, then <code>list('OOX')</code> is the list <code>['O','O','O']</code>.</p>
<p>You can combine <code>list</code> with a list comprehension:</p>
<p>Something like:</p>
<pre><code>>>> rows = ["OOX","XOX","XOX"]
>>> board = [list(row) for row in rows]
>>> board
[['O', 'O', 'X'], ['X', 'O', 'X'], ['X', 'O', 'X']]
</code></pre>
<p>Used like:</p>
<pre><code>>>> board[0][2]
'X' (3rd entry in first row).
</code></pre>
<p>Note that lists are mutable, so the elements can be changed as well as read:</p>
<p><code>board[0][2] = 'O'</code> will change the <code>'X'</code> in that position to an <code>'O'</code>.</p>
| 1 | 2016-08-21T19:21:44Z | [
"python",
"matrix"
] |
How can I create a matrix from a list? | 39,067,946 | <p>I am given a list which somehow represents a matrix, but it is in the list format, like</p>
<pre><code>["OOX","XOX","XOX"]
</code></pre>
<p>Is there any way i can convert it into a matrix?
I have gone through numpy, but could not figure out!</p>
| 0 | 2016-08-21T19:12:57Z | 39,068,322 | <p>As simple as this:</p>
<pre><code>In [4]: a = ["OOX","XOX","XOX"]
In [5]: m = np.array([*map(list, a)])
In [6]: m
Out[6]:
array([['O', 'O', 'X'],
['X', 'O', 'X'],
['X', 'O', 'X']],
dtype='<U1')
</code></pre>
| 0 | 2016-08-21T19:55:42Z | [
"python",
"matrix"
] |
Error : Can't multiply sequence by non-int of type 'Mul' | 39,067,978 | <p>I defined a method below that is supposed to take 5 integer/float values as input, and one list object (the <code>lst</code> parameter) and return only the positive solutions for <code>r</code> in the equation <code>F</code>. The formula for F should return a list where each element is multiplied/subtracted using the equation given. </p>
<p>I got the error <code>Error : Can't multiply sequence by non-int of type 'Mul'</code> mentioned above. What am I missing?</p>
<pre><code>from sympy import *
from math import pi
class solarheating:
def circular_rr(T0,T,lst,m,Cp,Eg):
r = var('r')
F = T0+pi*r**2*Eg/(m*Cp)*lst-T
r = solve(F,r)
return r[1]
lst = [0,0.25,0.5,0.75,1.0,1.25]
a = circular_rr(20,15,lst,.24,4.2,.928)
print(a)
</code></pre>
| 1 | 2016-08-21T19:17:01Z | 39,068,120 | <p>You forgot to pass the instance of the object (or <code>self</code>) on which the code is being called to the method. Since there was no <code>self</code>, you were getting the non-int error, because T0 became <code>self</code>, <code>T</code> became <code>T0</code>, and then your <code>lst</code> was being used as <code>T</code>. Since you cannot subtract a int from a list, this produced an error. </p>
<p>Here's the corrected code. </p>
<pre><code>from sympy import *
from math import pi
class solar heating:
def circular_rr(self,T0,T,lst,m,Cp,Eg):
r = var('r')
F = T0+pi*r**2*Eg/(m*Cp)*lst-T
r = solve(F,r)
return r[1]
lst = [0,0.25,0.5,0.75,1.0,1.25]
my_instance = solarheating()
a = my_instance.circular_rr(20,15,lst,.24,4.2,.928)
print(a)
</code></pre>
<p>The reason you need to use <code>self</code> is because Python does not use the @syntax to refer to instance attributes. The method is called on the instance you pass in the <code>self</code> attribute. You don't actually write instance methods in Python; what you write is class methods which (must) take an instance as a first parameter. And therefore, youâll have to place the instance parameter somewhere explicitly.</p>
<p>Edit:
Besides the obvious <code>self</code> error I've described above, you're multiplying a float by a list. That's what's causing the <code>can't multiply sequence by non-int of type 'Mul'</code> error. </p>
<p>If you want to multiply each item in the list by the float, your corrected method code will be: </p>
<pre><code> def circular_rr(self,T0,T,lst,m,Cp,Eg):
r = var('r')
temp_val = T0+pi*r**2*Eg/(m*Cp)
F = [x*temp_val-T for x in lst]
r = solve(F,r)
return r[1]
</code></pre>
| 1 | 2016-08-21T19:32:14Z | [
"python",
"list",
"python-2.7"
] |
Linking numpy extensions | 39,068,018 | <p>I am trying to compile an extension with the numpy C api and setuptools. The code compiles fine, but when running it from python, I get:</p>
<pre><code>ImportError: ./_pyav.so: undefined symbol: PyArray_SimpleNewFromData
</code></pre>
<p>My setup.py looks roughly as follows:</p>
<pre><code>import numpy
from setuptools import setup, Extension
...
d=[]
...
d.append(numpy.get_include())
...
Extension("_pyav",sources=["pyav.i","pyav.c"],include_dirs=d,extra_compile_args=c,extra_link_args=l,libraries=lib,swig_opts=s)
</code></pre>
<p>Obviously, the linker has not included the numpy C api objects into the resulting .so file.</p>
<p>Where do I get the stuff for "extra_link_args" (like "-L ..") and for "libraries" (i.e. linker switches "-llibraryname"), so that the linker can find them?</p>
<p>I tried fooling around with numpy.distutils.*, but found nothing there.</p>
| 0 | 2016-08-21T19:21:33Z | 39,068,866 | <p>Silly me,</p>
<p>I had forgotten "#include "numpy/arrayobject.h".</p>
| 0 | 2016-08-21T21:06:25Z | [
"python",
"c",
"numpy",
"linker"
] |
Filter rows in Spark dataframe from the words in RDD | 39,068,065 | <p>I have the following commands in spark,</p>
<pre><code>data = sqlContext.sql("select column1, column2, column3 from table_name")
words = sc.textFile("words.txt")
</code></pre>
<p><code>words.txt</code> has a bunch of words and data has three string columns taken from <code>table_name</code>.</p>
<p>Now I want to filter out rows in data (spark dataframe) whenever the word pattern of each word from <code>words.txt</code> occurs in any of the three columns of data. </p>
<p>For example if <code>words.txt</code> has word such as <code>gon</code> and if any of the three columns of data contains values as <code>bygone</code>, <code>gone</code> etc, I want to filter out that row. </p>
<p>I've tried the following:</p>
<pre><code>data.filter(~data['column1'].like('%gon%') | data['column2'].like('%gon%') | data['column3'].like('%gon%')).toPandas()
</code></pre>
<p>This works for one word. But I want to check all the words from the <code>words.txt</code> and remove it. Is there a way to do this?</p>
<p>I am new to PySpark. Any suggestions would be helpful.</p>
| 4 | 2016-08-21T19:26:29Z | 39,069,180 | <p>You may read the words from the <code>words.txt</code>, and build a regex pattern like this:</p>
<pre><code>(?s)^(?=.*word1)(?=.*word2)(?=.*word3)
</code></pre>
<p>etc. where <code>(?s)</code> allows <code>.</code> to match <em>any</em> symbol, <code>^</code> matches the string start position and then each <code>(?=...)</code> lookahead requires the presence of each word in the string.</p>
<p>So, if you place the regex into a <code>rx</code> var, it will look like:</p>
<pre><code>data.filter(~data['column1'].rlike(rx) | data['column2'].rlike(rx) | data['column3'].rlike(rx)).toPandas()
</code></pre>
<p>where the regex pattern is passed to <code>rlike</code> method that is similar to <code>like</code> but performs a search based on a regex expression.</p>
| 4 | 2016-08-21T21:52:58Z | [
"python",
"regex",
"apache-spark",
"pyspark",
"spark-dataframe"
] |
Trouble running new Python version after uninstalling older and installing new (MAC) | 39,068,070 | <p>I was trying to uninstall my Anaconda version of Python and reinstall the regular Python 3.5 version (mac). I used the answer from <a href="http://stackoverflow.com/questions/22585235/python-anaconda-how-to-safely-uninstall">this SO question</a> to remove the Anaconda folder using <code>rm -rf ~/anaconda</code> and using the Python website installed version 3.5.</p>
<p>But running <code>python --version</code> or <code>python</code> from command line returns this error:</p>
<pre><code>Pauls-MacBook-Pro:~ paul$ python --version
-bash: /Users/paul/anaconda/bin/python: No such file or directory
</code></pre>
<p>Is there some bash script that is pointing the old deleted /Anaconda folder that is causing the 3.5 version to not run? I really don't want to mess with system files if I don't know what I'm doing</p>
| 1 | 2016-08-21T19:27:05Z | 39,068,165 | <p>Based on your comments, it seems like bash has stored <code>/Users/paul/anaconda/bin/python</code> as the entry for <code>python</code> for performance reasons. <code>hash -d python</code> should remove this entry and use normal path resolution.</p>
| 3 | 2016-08-21T19:37:02Z | [
"python",
"bash",
"osx",
"anaconda",
"python-install"
] |
How to append a dataframe to existing excel sheet? | 39,068,124 | <p>The function gets called several times. I have kept a count so that if its called for the first time, A workbook is created. Then I write to that workbook using <code>pd.ExcelWrite()</code>. Next time <code>else:</code> gets executed and the same workbook is opened. Its first sheet is selected, its last row is found. And DataFrame is written on that row.
This is my code:</p>
<pre><code>def WriteFile (df):
if count1 == 1:
workbook = xlsxwriter.Workbook('pandas_simple.xlsx')
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
df.to_excel(writer, index=False )
workbook.close()
else:
book = open_workbook('pandas_simple.xlsx')
sheet_names = book.sheet_names()
sheet = book.sheet_by_name(sheet_names[0])
row = sheet.nrows
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
df.to_excel(writer, index=False, header=False, startrow = row )
</code></pre>
<p>I get this exception:</p>
<pre><code>Exception Exception: Exception('Exception caught in workbook destructor. Explicit close()
may be required for workbook.',) in <bound method Workbook.__del__ of <xlsxwriter.workbook.Workbook
object at 0x000000000A143860>> ignored Exception
</code></pre>
<p>And my pandas_simple.xlsx is also empty after execution of code. What am I doing wrong? </p>
| 1 | 2016-08-21T19:32:36Z | 39,068,188 | <p>Thanks to @ski.</p>
<p>Please refer his ans on the same question</p>
<p><a href="http://stackoverflow.com/questions/20219254/how-to-write-to-an-existing-excel-file-without-overwriting-data-using-pandas">How to write to an existing excel file without overwriting data (using pandas)?</a></p>
<pre><code>import pandas
from openpyxl import load_workbook
book = load_workbook('Masterfile.xlsx')
writer = pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])
writer.save()
</code></pre>
| 1 | 2016-08-21T19:39:06Z | [
"python",
"pandas",
"xlrd",
"xlsxwriter"
] |
How to append a dataframe to existing excel sheet? | 39,068,124 | <p>The function gets called several times. I have kept a count so that if its called for the first time, A workbook is created. Then I write to that workbook using <code>pd.ExcelWrite()</code>. Next time <code>else:</code> gets executed and the same workbook is opened. Its first sheet is selected, its last row is found. And DataFrame is written on that row.
This is my code:</p>
<pre><code>def WriteFile (df):
if count1 == 1:
workbook = xlsxwriter.Workbook('pandas_simple.xlsx')
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
df.to_excel(writer, index=False )
workbook.close()
else:
book = open_workbook('pandas_simple.xlsx')
sheet_names = book.sheet_names()
sheet = book.sheet_by_name(sheet_names[0])
row = sheet.nrows
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
df.to_excel(writer, index=False, header=False, startrow = row )
</code></pre>
<p>I get this exception:</p>
<pre><code>Exception Exception: Exception('Exception caught in workbook destructor. Explicit close()
may be required for workbook.',) in <bound method Workbook.__del__ of <xlsxwriter.workbook.Workbook
object at 0x000000000A143860>> ignored Exception
</code></pre>
<p>And my pandas_simple.xlsx is also empty after execution of code. What am I doing wrong? </p>
| 1 | 2016-08-21T19:32:36Z | 39,068,733 | <p>you can do it this way:</p>
<pre><code>df = pd.DataFrame(np.arange(1, 31), columns=['val'])
fn = 'd:/temp/test.xlsx'
count = 0
writer = pd.ExcelWriter(fn)
for chunk in np.split(df, 3):
chunk.to_excel(writer, index=False, header=(count==0), startrow=count+(count!=0))
count += len(chunk)
writer.save()
</code></pre>
<p>Result:</p>
<p><a href="http://i.stack.imgur.com/iXulK.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/iXulK.jpg" alt="enter image description here"></a></p>
| 0 | 2016-08-21T20:49:15Z | [
"python",
"pandas",
"xlrd",
"xlsxwriter"
] |
Closing a browser using python | 39,068,146 | <p>I am trying to make an internet radio based on opening and closing the web browser to start and stop the radio but I can't for some reason close the browser using different methods.</p>
<p>I have already tried using the <strong>subprocess</strong> method.</p>
<pre><code>import subprocess as sp
web = sp.Popen("epiphany http://www.google.com", shell=True)
</code></pre>
<p>but after doing that i could neither close the process with</p>
<pre><code>web.kill()
</code></pre>
<p>nor with</p>
<pre><code>web.terminate()
</code></pre>
<p>It simply did nothing.</p>
<p>I also tried using the selenium method but as I am trying to do this on a raspberry pi, so the only browser is epiphany that is not supported and I could not get a different supported browser to install.</p>
<p>The webbrowser module in python does not seem to have any closing function</p>
<p>Is there a way I could manage to close the browser?</p>
| 2 | 2016-08-21T19:35:18Z | 39,087,332 | <p>It seems like you want to close the browser that just opened. Assuming that you only have one epiphany instance open, you can use</p>
<pre><code>sp.Popen("killall epiphany")
</code></pre>
<p>Which will kill all instance of epiphany.
If you have multiple instances you will need to get the id of the running epiphany that you want to kill.</p>
<pre><code>sp.Popen("epiphany http://www.google.com & export PID=$!", shell=True)
# Do Stuff Here With Epiphany
sp.Popen("kill -9 $PID")
</code></pre>
<p>This should open a new epiphany instance to www.google.com, and save PID into your environment variables. Then, you can get the value of PID using $PID and kill the browser process.</p>
| 0 | 2016-08-22T19:29:45Z | [
"python",
"selenium",
"raspberry-pi3"
] |
Closing a browser using python | 39,068,146 | <p>I am trying to make an internet radio based on opening and closing the web browser to start and stop the radio but I can't for some reason close the browser using different methods.</p>
<p>I have already tried using the <strong>subprocess</strong> method.</p>
<pre><code>import subprocess as sp
web = sp.Popen("epiphany http://www.google.com", shell=True)
</code></pre>
<p>but after doing that i could neither close the process with</p>
<pre><code>web.kill()
</code></pre>
<p>nor with</p>
<pre><code>web.terminate()
</code></pre>
<p>It simply did nothing.</p>
<p>I also tried using the selenium method but as I am trying to do this on a raspberry pi, so the only browser is epiphany that is not supported and I could not get a different supported browser to install.</p>
<p>The webbrowser module in python does not seem to have any closing function</p>
<p>Is there a way I could manage to close the browser?</p>
| 2 | 2016-08-21T19:35:18Z | 39,107,243 | <p>after doing alot of research i found out that i could kill the browser by typing</p>
<pre><code>pkill epiphany
</code></pre>
<p>into the terminal so i just used this code to close it in python:</p>
<pre><code>import os
os.system("pkill epiphany")
</code></pre>
| 0 | 2016-08-23T17:19:35Z | [
"python",
"selenium",
"raspberry-pi3"
] |
Why doesn't QtConsole echo next()? | 39,068,174 | <p>I found this question about iterator behavior in Python: </p>
<p><a href="https://stackoverflow.com/questions/16814984/python-list-iterator-behavior-and-nextiterator">Python list iterator behavior and next(iterator)</a></p>
<p>When I typed in the code: </p>
<pre><code>a = iter(list(range(10)))
for i in a:
print a
next(a)
</code></pre>
<p>into the <code>jupyter-qtconsole</code> it returned:</p>
<pre><code>0
2
4
6
8
</code></pre>
<p>exactly as Martijn Pieters said it should when the interpreter doesn't echo the call to <code>next(a)</code>.</p>
<p>However, when I ran the same the code again in my Bash interpreter and IDLE, the code printed:</p>
<pre><code>0
1
2
3
4
5
6
7
8
9
</code></pre>
<p>to the console. </p>
<p>I ran the code:</p>
<pre><code>import platform
platform.python_implementation()
</code></pre>
<p>in all three environments and they all said I ran <code>'CPython'</code>.</p>
<p><strong>So why does the QtConsole suppress the <code>next(a)</code> call when IDLE and Bash don't?</strong></p>
<p>If it helps, I'm running Python 2.7.9 on Mac OSX and using the Anaconda distribution. </p>
| 6 | 2016-08-21T19:37:47Z | 39,084,476 | <p>This is just a choice the developers of <code>IPython</code> (on which the <code>QtConsole</code> is based) made regarding what should be echoed back to the user. </p>
<p>Specifically, in the <a href="https://github.com/ipython/ipython/blob/master/IPython/core/interactiveshell.py#L198" rel="nofollow"><code>InteractiveShell</code></a> class that is used, function <a href="https://github.com/ipython/ipython/blob/master/IPython/core/interactiveshell.py#L2770" rel="nofollow"><code>run_ast_nodes</code></a> is, by default, defined with an <code>interactivity='last_expr'</code>. The documentation on this attribute states:</p>
<pre><code>interactivity : str
'all', 'last', 'last_expr' or 'none', specifying which nodes should be
run interactively (displaying output from expressions). 'last_expr'
will run the last node interactively only if it is an expression (i.e.
expressions in loops or other blocks are not displayed. Other values
for this parameter will raise a ValueError.
</code></pre>
<p>As you can see: <strong><em>expressions in loops or other blocks are not displayed</em></strong>.</p>
<p>You can change this in the config files for <code>IPython</code> and get it to work like your <code>repl</code> if you really need to. Point is, it was just a preference the designers made.</p>
| 2 | 2016-08-22T16:28:50Z | [
"python",
"interpreter",
"jupyter",
"python-internals"
] |
Google App Engine Send Mail Not Working | 39,068,177 | <p>I'm trying to use Python and Google App Engine to send automated emails to certain addresses:</p>
<pre><code> message = mail.EmailMessage(sender="noreply@"+app_identity.get_application_id()+".appspotmail.com",subject="Verify Email",to="Bob Person <bob.person@gmail.com>")
message.body = "Hey, someone tried to register an account with this email."
message.send()
</code></pre>
<p>I have removed my own email and replaced it with Bob Person, but my email is correct. Also, I can confirm that using an invalid sender email gives an invalid sender error, so that isn't the problem. Can anyone shed any light on this?</p>
| 0 | 2016-08-21T19:37:55Z | 39,068,224 | <p>The sender's email ID should be added as a owner in the appengine project or use service account ID as sender.</p>
| 2 | 2016-08-21T19:44:22Z | [
"python",
"email",
"google-app-engine"
] |
Google App Engine Send Mail Not Working | 39,068,177 | <p>I'm trying to use Python and Google App Engine to send automated emails to certain addresses:</p>
<pre><code> message = mail.EmailMessage(sender="noreply@"+app_identity.get_application_id()+".appspotmail.com",subject="Verify Email",to="Bob Person <bob.person@gmail.com>")
message.body = "Hey, someone tried to register an account with this email."
message.send()
</code></pre>
<p>I have removed my own email and replaced it with Bob Person, but my email is correct. Also, I can confirm that using an invalid sender email gives an invalid sender error, so that isn't the problem. Can anyone shed any light on this?</p>
| 0 | 2016-08-21T19:37:55Z | 39,192,003 | <p>It turns out, the solution was to remove an appspot.com link. I ended up using a bitly API to replace the links with bitly ones. Thank you everyone for helping with this one, it'd be really helpful if this behaviour was officially documented.</p>
| 0 | 2016-08-28T13:53:30Z | [
"python",
"email",
"google-app-engine"
] |
Setting the alpha value of a custom palette in seaborn | 39,068,206 | <p>I am modifying a piece of code I found in the seaborn documentation, in order to design a palette that is common to matplotlib and seaborn. The code below work great, however, if you plot many points (5000 in my example), the darker color dominates the chart.
A quick fix to that is to set the alpha value of one (or both) colors, to something low. </p>
<pre><code>custom = ["#D1EC9C", "#F1EBF4"]
sns.set_palette(custom)
# construct cmap
my_cmap = ListedColormap(custom)
N = 5000
data1 = np.random.randn(N)
data2 = np.random.randn(N)
colors = np.linspace(0,1,N)
plt.scatter(data1, data2, c=colors, cmap=my_cmap)
plt.colorbar()
plt.show()
</code></pre>
<p>Does anybody know how to set the alpha value of a custom Seaborn palette?
<a href="http://i.stack.imgur.com/Kwlel.png" rel="nofollow"><img src="http://i.stack.imgur.com/Kwlel.png" alt="enter image description here"></a>
Thanks</p>
| 0 | 2016-08-21T19:41:16Z | 39,070,407 | <p>You can set the alpha as part of the colors in your colormap:</p>
<pre><code>custom = [(0xD1/0xFF, 0xEC/0xFF, 0x9C/0xFF, 1), (0xF1/0xFF, 0xEB/0xFF, 0xF4/0xFF, 0.5)]
my_cmap = mpl.colors.ListedColormap(custom)
</code></pre>
<p>Here I gave the second color alpha of 0.5; you can do it with the other color if you want.</p>
<p>Note that seaborn is not really involved here. The colors of the plot are determined by the colors you passed in the colormap; seaborn's palette has no impact. The only effect seaborn has on your plot is in the formatting of the background, axes, grid, etc.</p>
<p>As I said in a comment, though, I believe that using alpha for only one color will not make your plot look good. If one color is still opaque, it will still cover up dots of the other color, only more so (because now the other color will be fainter). Also, if you are going to use alpha (and maybe even if you aren't), the grayish color you chose is probably not a good idea, because it is similar to the gray background seaborn provides, making it difficult to distinguish the gray dots from the gray background.</p>
| 2 | 2016-08-22T01:50:55Z | [
"python",
"seaborn"
] |
How to count outliers for all columns in Python? | 39,068,214 | <p>I have dataset with three columns in Python notebook. It seems there are too many outliers out of 1.5 times IQR. I'm think how can I count the outliers for all columns?</p>
<p>If there are too many outliers, I may consider to remove the points considered as outliers for more than one feature. If so, how I can count it in that way?</p>
<p>Thanks!</p>
<p><a href="http://i.stack.imgur.com/KAqOG.png" rel="nofollow"><img src="http://i.stack.imgur.com/KAqOG.png" alt="enter image description here"></a></p>
| 0 | 2016-08-21T19:42:02Z | 39,068,451 | <p>Similar to <a href="http://stackoverflow.com/a/35606727/2285236">Romain X.'s answer</a> but operates on the DataFrame instead of Series.</p>
<p>Random data:</p>
<pre><code>np.random.seed(0)
df = pd.DataFrame(np.random.randn(100, 5), columns=list('ABCDE'))
df.iloc[::10] += np.random.randn() * 2 # this hopefully introduces some outliers
df.head()
Out:
A B C D E
0 2.529517 1.165622 1.744203 3.006358 2.633023
1 -0.977278 0.950088 -0.151357 -0.103219 0.410599
2 0.144044 1.454274 0.761038 0.121675 0.443863
3 0.333674 1.494079 -0.205158 0.313068 -0.854096
4 -2.552990 0.653619 0.864436 -0.742165 2.269755
</code></pre>
<p>Quartile calculations:</p>
<pre><code>Q1 = df.quantile(0.25)
Q3 = df.quantile(0.75)
IQR = Q3 - Q1
</code></pre>
<p>And these are the numbers for each column:</p>
<pre><code>((df < (Q1 - 1.5 * IQR)) | (df > (Q3 + 1.5 * IQR))).sum()
Out:
A 1
B 0
C 0
D 1
E 2
dtype: int64
</code></pre>
<p>In line with seaborn's calculations:</p>
<p><a href="http://i.stack.imgur.com/hmql9.png" rel="nofollow"><img src="http://i.stack.imgur.com/hmql9.png" alt="enter image description here"></a></p>
<p>Note that the part before the sum (<code>(df < (Q1 - 1.5 * IQR)) | (df > (Q3 + 1.5 * IQR))</code>) is a boolean mask so you can use it directly to remove outliers. This sets them to NaN, for example:</p>
<pre><code>mask = (df < (Q1 - 1.5 * IQR)) | (df > (Q3 + 1.5 * IQR))
df[mask] = np.nan
</code></pre>
| 2 | 2016-08-21T20:14:29Z | [
"python",
"pandas"
] |
Passing a numpy array to a tensorflow Queue | 39,068,259 | <p>I have a NumPy array and would like to read it in TensorFlow's code using a <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/io_ops.html#queues" rel="nofollow">Queue</a>. I would like the queue to return the whole data shuffled, some specified number of epochs and throw an error after that. It would be best if I'd not need to hardcode the size of an example nor the number of examples.
I think <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/io_ops.html#shuffle_batch" rel="nofollow">shuffle batch</a> is meant to serve that purpose. I have tried using it as follows:</p>
<pre><code>data = tf.constant(train_np) # train_np is my numpy array of shape (num_examples, example_size)
batch = tf.train.shuffle_batch([data], batch_size=5, capacity=52200, min_after_dequeue=10, num_threads=1, seed=None, enqueue_many=True)
sess.run(tf.initialize_all_variables())
tf.train.start_queue_runners(sess=sess)
batch.eval()
</code></pre>
<p>The problem with that approach is that it reads all the data continuously and I cannot specify it to finish after some number of epochs. I am aware I could use the <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/io_ops.html#RandomShuffleQueue" rel="nofollow">RandomShuffleQueue</a> and insert the data into it few times, but:
a) I don't want to waste epoch*data of memory and b) it will allow the queue to shuffle between epochs.</p>
<p>Is there a nice way to read the shuffled data in epochs in Tensorflow without writing your own Queue?</p>
| 0 | 2016-08-21T19:47:25Z | 39,068,577 | <p>You could create another queue, enqueue your data onto it <code>num_epoch</code> times, close it, and then hook it up to your <code>batch</code>. To save memory, you can make this queue small, and enqueue items onto it in parallel. There will be a bit of mixing between epochs. To fully prevent mixing, you could take code below with <code>num_epochs=1</code> and call it <code>num_epochs</code> times.</p>
<pre><code>tf.reset_default_graph()
data = np.array([1, 2, 3, 4])
num_epochs = 5
queue1_input = tf.placeholder(tf.int32)
queue1 = tf.FIFOQueue(capacity=10, dtypes=[tf.int32], shapes=[()])
def create_session():
config = tf.ConfigProto()
config.operation_timeout_in_ms=20000
return tf.InteractiveSession(config=config)
enqueue_op = queue1.enqueue_many(queue1_input)
close_op = queue1.close()
dequeue_op = queue1.dequeue()
batch = tf.train.shuffle_batch([dequeue_op], batch_size=4, capacity=5, min_after_dequeue=4)
sess = create_session()
def fill_queue():
for i in range(num_epochs):
sess.run(enqueue_op, feed_dict={queue1_input: data})
sess.run(close_op)
fill_thread = threading.Thread(target=fill_queue, args=())
fill_thread.start()
# read the data from queue shuffled
tf.train.start_queue_runners()
try:
while True:
print batch.eval()
except tf.errors.OutOfRangeError:
print "Done"
</code></pre>
<p>BTW, <code>enqueue_many</code> pattern above will hang when the queue is not large enough to load the entire numpy dataset into it. You could give yourself flexibility to have a smaller queue by loading the data in chunks as below.</p>
<pre><code>tf.reset_default_graph()
data = np.array([1, 2, 3, 4])
queue1_capacity = 2
num_epochs = 2
queue1_input = tf.placeholder(tf.int32)
queue1 = tf.FIFOQueue(capacity=queue1_capacity, dtypes=[tf.int32], shapes=[()])
enqueue_op = queue1.enqueue_many(queue1_input)
close_op = queue1.close()
dequeue_op = queue1.dequeue()
def dequeue():
try:
while True:
print sess.run(dequeue_op)
except:
return
def enqueue():
for i in range(num_epochs):
start_pos = 0
while start_pos < len(data):
end_pos = start_pos+queue1_capacity
data_chunk = data[start_pos: end_pos]
sess.run(enqueue_op, feed_dict={queue1_input: data_chunk})
start_pos += queue1_capacity
sess.run(close_op)
sess = create_session()
enqueue_thread = threading.Thread(target=enqueue, args=())
enqueue_thread.start()
dequeue_thread = threading.Thread(target=dequeue, args=())
dequeue_thread.start()
</code></pre>
| 2 | 2016-08-21T20:29:56Z | [
"python",
"numpy",
"tensorflow"
] |
How to retrieve the value of a many2many field for each sale order? | 39,068,266 | <p>I've created a many2many field in the sale.order model that it's related with fleet.vehicle model (id).</p>
<p>How it's showed in the follow image:</p>
<p>IMAGE 1: <a href="http://i.stack.imgur.com/747Jz.png" rel="nofollow"><img src="http://i.stack.imgur.com/747Jz.png" alt="enter image description here"></a></p>
<p>Well, the 'x_vehiculo' field is a multi-selection field, How it's showed in the follow image:</p>
<p>IMAGE 2: <a href="http://i.stack.imgur.com/nfnHq.png" rel="nofollow"><img src="http://i.stack.imgur.com/nfnHq.png" alt="enter image description here"></a></p>
<p>The idea is that for each sale order i can to store more that 1 vehicle.</p>
<p>The trouble is that i can't see the value for of x_vehiculo' field for each sale order when i make a query in the SGB Postgresql (PgAdmin III).</p>
<p>IMAGE 3: <a href="http://i.stack.imgur.com/BqHUP.png" rel="nofollow"><img src="http://i.stack.imgur.com/BqHUP.png" alt="enter image description here"></a></p>
<p>There is any way to can retrieve values of 'x_vehicle' multi-selection field for each sale.order?</p>
<p>Please if somebody could help me. I'd be very gratefull.</p>
<p>Thanks you so much</p>
| 1 | 2016-08-21T19:48:12Z | 39,069,273 | <p>The field isn't going to be available on the table you declared it, it's a Many2many relationship so a separate 'join' table is going to be created for it, the name of that table is</p>
<p><code>x_fleet_vehicle_sale_order_rel</code></p>
<p>That table will contain the fields <code>sale_order_id</code> and <code>fleet_vehicle_id</code></p>
<p>So you should be querying that table instead of the table where you declared <code>x_vehiculo</code></p>
| 1 | 2016-08-21T22:06:14Z | [
"python",
"openerp",
"odoo-8",
"odoo-9"
] |
How to retrieve the value of a many2many field for each sale order? | 39,068,266 | <p>I've created a many2many field in the sale.order model that it's related with fleet.vehicle model (id).</p>
<p>How it's showed in the follow image:</p>
<p>IMAGE 1: <a href="http://i.stack.imgur.com/747Jz.png" rel="nofollow"><img src="http://i.stack.imgur.com/747Jz.png" alt="enter image description here"></a></p>
<p>Well, the 'x_vehiculo' field is a multi-selection field, How it's showed in the follow image:</p>
<p>IMAGE 2: <a href="http://i.stack.imgur.com/nfnHq.png" rel="nofollow"><img src="http://i.stack.imgur.com/nfnHq.png" alt="enter image description here"></a></p>
<p>The idea is that for each sale order i can to store more that 1 vehicle.</p>
<p>The trouble is that i can't see the value for of x_vehiculo' field for each sale order when i make a query in the SGB Postgresql (PgAdmin III).</p>
<p>IMAGE 3: <a href="http://i.stack.imgur.com/BqHUP.png" rel="nofollow"><img src="http://i.stack.imgur.com/BqHUP.png" alt="enter image description here"></a></p>
<p>There is any way to can retrieve values of 'x_vehicle' multi-selection field for each sale.order?</p>
<p>Please if somebody could help me. I'd be very gratefull.</p>
<p>Thanks you so much</p>
| 1 | 2016-08-21T19:48:12Z | 39,069,278 | <p>The relation is not stored in the <code>sale_order</code> table. Since it's <code>many2many</code>, it is stored in a relational table. Based on your screenshot, your relational table is this one: <code>x_fleet_vehicle_sale_order_rel</code></p>
<p>To query for the vehicles, you have to join through this table like so:</p>
<pre><code>select so.name, fv.name
from sale_order so
left join x_fleet_vehicle_sale_order_rel rel on (rel.sale_order_id = so.id)
left join fleet_vehicle fv on (fv.id = rel.fleet_vehicle_id);
</code></pre>
<p>This will give you a row for each combination of <code>sale.order</code> and <code>fleet.vehicle</code>. If you want to group them by sale order you can do this:</p>
<pre><code>select so.name, array_agg(fv.name) as vehicles
from sale_order so
left join x_fleet_vehicle_sale_order_rel rel on (rel.sale_order_id = so.id)
left join fleet_vehicle fv on (fv.id = rel.fleet_vehicle_id)
group by so.name;
</code></pre>
<p>This will return one row for each <code>sale.order</code> with a list of <code>fleet.vehicle</code> names attached to that order.</p>
| 2 | 2016-08-21T22:07:50Z | [
"python",
"openerp",
"odoo-8",
"odoo-9"
] |
How to apply a proxy in libtorrent? | 39,068,376 | <p>I am creating a torrent client and would like to add a proxy to it. I just can't seem to get it to work.i am using "<a href="http://ipmagnet.services.cbcdn.com" rel="nofollow">http://ipmagnet.services.cbcdn.com</a>" to check what IP address my client is handing out to peers and trackers.How can I fix my code to apply my proxy to the client correctly?</p>
<pre><code>import libtorrent as lt
import time
import os
ses = lt.session()
ses.listen_on(6881, 6891)
r = lt.proxy_settings()
r.proxy_hostnames = True
r.proxy_peer_connections = True
r.hostname = "*myproxyinfo*"
r.username = "*myproxyinfo*"
r.password = "*myproxyinfo*"
r.proxy_port = 1080
r.proxy_type = lt.proxy_type().socks5_pw
#print lt.proxy_type().socks5_pw
ses.set_dht_proxy(r)
ses.set_peer_proxy(r)
ses.set_tracker_proxy(r)
ses.set_web_seed_proxy(r)
ses.set_proxy(r)
t = ses.settings()
t.force_proxy = True
t.proxy_hostnames = True
t.proxy_peer_connections = True
t.proxy_tracker_connections = True
#t.anonymous_mode = True
#ses.set_settings(t)
#print ses.get_settings()
ses.dht_proxy()
ses.peer_proxy()
ses.tracker_proxy()
ses.web_seed_proxy()
ses.proxy()
ses.set_settings(t)
magnet_link = "magnet:?xt=urn:btih:1931ced5c4e20047091742905f30f8d0b69c9ca9&dn=ipMagnet+Tracking+Link&tr=http%3A%2F%2Fipmagnet.services.cbcdn.com%3A80%2F"
params = {"save_path": os.getcwd() + r"\torrents",
"storage_mode": lt.storage_mode_t.storage_mode_sparse,
"url": magnet_link}
h = ses.add_torrent(params)
s = h.status()
while (not s.is_seeding):
s = h.status()
state_str = ['queued', 'checking', 'downloading metadata', \
'downloading', 'finished', 'seeding', 'allocating']
print '%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % \
(s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, \
s.num_peers, state_str[s.state])
time.sleep(1)
</code></pre>
| 0 | 2016-08-21T20:03:26Z | 39,069,606 | <p>I would suggest you look at alerts generated by your session, to see if anything is failing to use the proxy.</p>
<p>By default, libtorrent considers the proxy to be best-effort. If it fails for any reason, libtorrent will fall back to attempting direct connections.</p>
<p>If you would like to force using the proxy, and fail if the proxy fails, set the <a href="http://libtorrent.org/reference-Settings.html#force_proxy" rel="nofollow">force_proxy</a> setting to true.</p>
| 0 | 2016-08-21T23:07:27Z | [
"python",
"proxy",
"libtorrent"
] |
Absolute Import Not Working, But Relative Import Does | 39,068,391 | <p>Here is my app structure:</p>
<pre><code>foodo/
setup.py
foodo/
__init__.py
foodo.py
models.py
</code></pre>
<p><code>foodo/foodo/foodo.py</code> imports classes from the <code>models.py</code> module:</p>
<pre><code>from foodo.models import User
</code></pre>
<p>which throws an <code>ImportError</code>:</p>
<pre><code>ImportError: No module named models
</code></pre>
<p>However, it does work if I use a relative import:</p>
<pre><code>from models import User
</code></pre>
<p>And it also works if I put in an pdb breakpoint before the import and continue.</p>
<p>I should be able to use both absolute and relative imports right?</p>
| 0 | 2016-08-21T20:06:25Z | 39,068,432 | <p>You have a <em>local</em> module <code>foodoo</code> inside the <code>foodoo</code> package. Imports in Python 2 always first look for names in the current package before looking for a top-level name.</p>
<p>Either rename the <code>foodoo</code> module inside the <code>foodoo</code> package (eliminating the possibility that a local <code>foodoo</code> is found first) or use:</p>
<pre><code>from __future__ import absolute_imports
</code></pre>
<p>at the top of your modules in your package to enable Python-3 style imports where the top-level modules are the only modules searched unless you prefix the name with <code>.</code> to make a name relative. See <a href="https://www.python.org/dev/peps/pep-0328/" rel="nofollow">PEP 328 -- <em>Imports: Multi-Line and Absolute/Relative</em></a> for more details.</p>
| 4 | 2016-08-21T20:11:38Z | [
"python",
"python-2.7",
"python-import",
"importerror"
] |
Using apply() method on SFrame issues | 39,068,428 | <p><strong>Background:</strong> I have an SFrame that contains numbers indicting how close a dog image is to other images. Usually the dog image should be closest to another dog image but the point is to test the evaluation method</p>
<p>My SFrame is called dog_distances (1000 rows x 4 columns):</p>
<pre><code>dog-automobile dog-bird dog-cat dog-dog
41.9579761457 41.7538647304 36.4196077068 33.4773590373
46.0021331807 41.3382958925 38.8353268874 32.8458495684
42.9462290692 38.6157590853 36.9763410854 35.0397073189
41.6866060048 37.0892269954 34.5750072914 33.9010327697
39.2269664935 38.272288694 34.778824791 37.4849250909
40.5845117698 39.1462089236 35.1171578292 34.945165344
</code></pre>
<p>I want to write a function that checks if dog-dog is the lowest number and apply this function to the whole SFrame</p>
<p>Accessing a row of an SFrame normally outputs a dict...
sframe_name[row#]['column_name']</p>
<p>Adding .values() to the end of that line just outputs values in a list.
This allows you to apply math methods like min() or max() which is useful for creating the function is_dog_correct.</p>
<p>Thus my function is:</p>
<pre><code>def is_dog_correct(row):
#checking if dog-dog is smallest value
if dog_distances[row]['dog-dog'] == min(dog_distances[row].values()):
return 1
else:
return 0
</code></pre>
<p>My function takes row as in input, and returns 1 if the value of dog-dog for that row is equal to the min value in that row. It returns 0 if this is not true.</p>
<p>Running is_dog_correct(0) outputs 1. We expect this because, as you can see above, the value in dog-dog for the zeroth row is the smallest number in that row.</p>
<p>Running is_dog_correct(4) outputs 0. We expect this because the value in dog-dog for the zeroth row is NOT the smallest number in that row.</p>
<p>So the function is_dog_correct works perfectly on a row by row basis!</p>
<p>When I run as suggested on the whole sFrame: dog_distances.apply(is_dog_correct)</p>
<p>I get an attribute error: </p>
<pre><code>'SFrame' object has no attribute 'values'
</code></pre>
<p>Please someone explain why the function works row by row but not on the whole SFrame??</p>
| 0 | 2016-08-21T20:11:19Z | 39,074,868 | <p>Please try this:</p>
<pre><code>dog_distances['new_column'] = dog_distances.apply(lambda row: 1 if row['dog-dog'] == min(row.values()) else 0)
</code></pre>
<p>Add</p>
<p>Hi Steven,</p>
<p>This code works correctly in my laptop. Please see the link below.</p>
<ol>
<li><p><a href="http://i.stack.imgur.com/9gFjy.jpg" rel="nofollow"><strong>Your data</strong></a> (Probably your actual data is much longer than this)</p></li>
<li><p>Applying a Lambda</p>
<p>dog_distances['new_column'] = dog_distances.apply(lambda row: 1 if row['dog-dog'] == min(row.values()) else 0)</p></li>
<li><p><a href="http://i.stack.imgur.com/Tweaa.jpg" rel="nofollow"><strong>Result</strong></a></p></li>
</ol>
| 0 | 2016-08-22T08:40:48Z | [
"python",
"apply",
"graphlab",
"sframe"
] |
Using apply() method on SFrame issues | 39,068,428 | <p><strong>Background:</strong> I have an SFrame that contains numbers indicting how close a dog image is to other images. Usually the dog image should be closest to another dog image but the point is to test the evaluation method</p>
<p>My SFrame is called dog_distances (1000 rows x 4 columns):</p>
<pre><code>dog-automobile dog-bird dog-cat dog-dog
41.9579761457 41.7538647304 36.4196077068 33.4773590373
46.0021331807 41.3382958925 38.8353268874 32.8458495684
42.9462290692 38.6157590853 36.9763410854 35.0397073189
41.6866060048 37.0892269954 34.5750072914 33.9010327697
39.2269664935 38.272288694 34.778824791 37.4849250909
40.5845117698 39.1462089236 35.1171578292 34.945165344
</code></pre>
<p>I want to write a function that checks if dog-dog is the lowest number and apply this function to the whole SFrame</p>
<p>Accessing a row of an SFrame normally outputs a dict...
sframe_name[row#]['column_name']</p>
<p>Adding .values() to the end of that line just outputs values in a list.
This allows you to apply math methods like min() or max() which is useful for creating the function is_dog_correct.</p>
<p>Thus my function is:</p>
<pre><code>def is_dog_correct(row):
#checking if dog-dog is smallest value
if dog_distances[row]['dog-dog'] == min(dog_distances[row].values()):
return 1
else:
return 0
</code></pre>
<p>My function takes row as in input, and returns 1 if the value of dog-dog for that row is equal to the min value in that row. It returns 0 if this is not true.</p>
<p>Running is_dog_correct(0) outputs 1. We expect this because, as you can see above, the value in dog-dog for the zeroth row is the smallest number in that row.</p>
<p>Running is_dog_correct(4) outputs 0. We expect this because the value in dog-dog for the zeroth row is NOT the smallest number in that row.</p>
<p>So the function is_dog_correct works perfectly on a row by row basis!</p>
<p>When I run as suggested on the whole sFrame: dog_distances.apply(is_dog_correct)</p>
<p>I get an attribute error: </p>
<pre><code>'SFrame' object has no attribute 'values'
</code></pre>
<p>Please someone explain why the function works row by row but not on the whole SFrame??</p>
| 0 | 2016-08-21T20:11:19Z | 39,089,515 | <p>I figured out the solution:</p>
<p>The problem I think is all documentation suggests that .apply() goes row by row.
I assumed that this meant, as it ran a function on a given row, the variable passed was the row number as an integer.</p>
<p>In fact, the variable/object/text that is passed to .apply() is <code>sframe_name[row_#]</code></p>
<p>So in your function if you want to access/act on a given index </p>
<pre><code>sframe_name[row_#]['column_name']
</code></pre>
<p>A generic form would be this: </p>
<pre><code>passed_variable['column_name']
</code></pre>
<p>Just to be utterly transparent, in my function the exact code was:</p>
<pre><code>if dog-dog[row]['dog-bird'] <= dog-dog[row]['dog-dog']:
</code></pre>
<p>When the code should have been:</p>
<pre><code>if row['dog-bird'] <= row['dog-dog']:
</code></pre>
| 0 | 2016-08-22T22:12:28Z | [
"python",
"apply",
"graphlab",
"sframe"
] |
Python logger doesn't adhere to the set level | 39,068,465 | <p>I created a logger in the Python3 interactive prompt:</p>
<pre><code>>>> import logging
>>> logger = logging.getLogger('foo')
>>> logger.setLevel(logging.INFO)
>>> logger.warn('bar')
bar
>>> logger.info('bar')
>>>
</code></pre>
<p>I'd expect <code>logger.info</code> to output the <code>bar</code> in this case, since I've explicitly set the logging level. But it's not the case here. Why?</p>
| 2 | 2016-08-21T20:16:42Z | 39,068,547 | <p>Actually, in your case neither should output anything since you haven't configured logging. You'll need to run <code>logging.basicConfig()</code> or add a handler to your logger to expect any output:</p>
<pre><code>In [1]: import logging
In [2]: logger = logging.getLogger('foo')
In [3]: logger.setLevel(logging.INFO)
In [4]: logger.warn('foo')
No handlers could be found for logger "foo"
In [5]: logger.info('foo')
In [6]: logging.basicConfig()
In [7]: logger.info('foo')
INFO:foo:foo
In [8]: logger.warn('foo')
WARNING:foo:foo
</code></pre>
<p>As mentioned by larsks in the comments, in Python 3 logging is configured by default with level <code>WARNING</code> (which means you'll get output if you use <code>warning()</code> or any higher level by default). In your case, you either can call <code>logging.basicConfig()</code> to add a default handler to all loggers as in the example above, or add a handler to your logger:</p>
<pre><code>logger.addHandler(logging.StreamHandler())
</code></pre>
| 1 | 2016-08-21T20:26:03Z | [
"python",
"python-3.x",
"logging"
] |
Python: Python.h file missing | 39,068,598 | <p>I am using Ubuntu 16.04. I am trying to install Murmurhash python library but it is throwing error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 . I looked on Internet and it is says that this error is due to missing python header files. So i did </p>
<pre><code>sudo apt-get install python-dev
</code></pre>
<p>but still the error is there. Is the error because i have Anaconda installed or what ? Can somebody help me as in how to rectify this error. Error is as follow :</p>
<pre><code>running install
running build
running build_ext
building 'mmh3' extension
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c mmh3module.cpp -o build/temp.linux-x86_64-2.7/mmh3module.o
cc1plus: warning: command line option â-Wstrict-prototypesâ is valid for C/ObjC but not for C++
In file included from /usr/include/python2.7/Python.h:81:0,
from mmh3module.cpp:3:
mmh3module.cpp: In function âint mmh3_traverse(PyObject*, visitproc, void*)â:
mmh3module.cpp:107:63: error: âPyModule_GetStateâ was not declared in this scope
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
^
/usr/include/python2.7/objimpl.h:326:13: note: in definition of macro âPy_VISITâ
if (op) { \
^
mmh3module.cpp:134:14: note: in expansion of macro âGETSTATEâ
Py_VISIT(GETSTATE(m)->error);
^
In file included from /usr/include/python2.7/Python.h:80:0,
from mmh3module.cpp:3:
mmh3module.cpp: In function âint mmh3_clear(PyObject*)â:
mmh3module.cpp:107:63: error: âPyModule_GetStateâ was not declared in this scope
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
^
/usr/include/python2.7/object.h:816:13: note: in definition of macro âPy_CLEARâ
if (op) { \
^
mmh3module.cpp:139:14: note: in expansion of macro âGETSTATEâ
Py_CLEAR(GETSTATE(m)->error);
^
mmh3module.cpp: At global scope:
mmh3module.cpp:143:27: error: variable âPyModuleDef mmh3moduleâ has initializer but incomplete type
static struct PyModuleDef mmh3module = {
^
mmh3module.cpp:144:5: error: âPyModuleDef_HEAD_INITâ was not declared in this scope
PyModuleDef_HEAD_INIT,
^
mmh3module.cpp: In function âvoid PyInit_mmh3()â:
mmh3module.cpp:157:51: error: âPyModule_Createâ was not declared in this scope
PyObject *module = PyModule_Create(&mmh3module);
^
In file included from /usr/include/wchar.h:51:0,
from /usr/include/python2.7/unicodeobject.h:120,
from /usr/include/python2.7/Python.h:85,
from mmh3module.cpp:3:
mmh3module.cpp:160:16: error: return-statement with a value, in function returning 'void' [-fpermissive]
return NULL;
^
mmh3module.cpp:107:63: error: âPyModule_GetStateâ was not declared in this scope
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
^
mmh3module.cpp:164:31: note: in expansion of macro âGETSTATEâ
struct module_state *st = GETSTATE(module);
^
mmh3module.cpp:166:60: warning: deprecated conversion from string constant to âchar*â [-Wwrite-strings]
st->error = PyErr_NewException("mmh3.Error", NULL, NULL);
^
In file included from /usr/include/wchar.h:51:0,
from /usr/include/python2.7/unicodeobject.h:120,
from /usr/include/python2.7/Python.h:85,
from mmh3module.cpp:3:
mmh3module.cpp:169:16: error: return-statement with a value, in function returning 'void' [-fpermissive]
return NULL;
^
mmh3module.cpp:172:12: error: return-statement with a value, in function returning 'void' [-fpermissive]
return module;
^
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
</code></pre>
| 0 | 2016-08-21T20:32:33Z | 39,089,092 | <p>I just tried a docker container with <code>ubuntu 16.04</code></p>
<pre><code>apt-get update
apt-get install -y python-pip
pip install mmh3
</code></pre>
<p>That seems to be working. In your machine, you can just try.</p>
<pre><code>sudo apt-get install -y python-pip
sudo pip install mmh3
</code></pre>
<p>With this you will be sure whether it is or not an anaconda problem with <code>gcc</code>.</p>
<p>I also checked anaconda with ubuntu 14.04 with the command <code>pip install mmh3</code>. It appears to be working too.</p>
| 0 | 2016-08-22T21:34:49Z | [
"python",
"gcc",
"anaconda",
"murmurhash"
] |
Skip XML tag if attribute is missing | 39,068,602 | <p>I am trying to get data from the XML file underneath. For each type the explanation should be right next to it. </p>
<p>For example:</p>
<p>Orange They belong to the Citrus.They cannot grow at a temperature below
Lemon They belong to the Citrus.They cannot grow at a temperature below</p>
<pre><code><Fruits>
<Fruit>
<Family>Citrus</Family>
<Explanation>They belong to the Citrus.They cannot grow at a temperature below</Explanation>
<Type>Orange</Type>
<Type>Lemon</Type>
<Type>Lime</Type>
<Type>Grapefruit</Type>
</Fruit>
<Fruit>
<Family>Pomes</Family>
<Type>Apple</Type>
<Type>Pear</Type>
</Fruit>
</Fruits>
</code></pre>
<p>This works well with the code underneath. However, for the second Fruit Family I have a problem, because there is no Explanation.</p>
<pre><code>import os
from xml.etree import ElementTree
file_name = "example.xml"
full_file = os.path.abspath(os.path.join("xml", file_name))
dom = ElementTree.parse(full_file)
Fruit = dom.findall("Fruit")
for f in Fruit:
Explanation = f.find("Explanation").text
Types = f.findall("Type")
for t in Types:
Type = t.text
print ("{0}, {1}".format(Type, Explanation))
</code></pre>
<p>How could I skip the tags like Fruit Family(Pomes), if the attribute Explanation is missing?</p>
| 1 | 2016-08-21T20:33:03Z | 39,068,649 | <p>Using <em>xml.etree</em>, just try to find the <em>Explanation</em> child:</p>
<pre><code>from xml.etree import ElementTree as et
root = et.fromstring(xml)
for node in root.iter("Fruit"):
if node.find("Explanation") is not None:
print(node.find("Family").text)
</code></pre>
<p>You could also use an xpath where you get Fruit nodes only if they have an <em>Explanation</em> child using <a href="http://lxml.de/" rel="nofollow">lxml</a>:</p>
<pre><code>import lxml.etree as et
root = et.fromstring(xml)
for node in root.xpath("//Fruit[Explanation]"):
print(node.xpath("Family/text()"))
</code></pre>
<p>If we run it on your sample you will see we just get Citrus:</p>
<pre><code>In [1]: xml = """<Fruits>
...: <Fruit>
...: <Family>Citrus</Family>
...: <Explanation>They belong to the Citrus.They cannot grow at a temperature below</Explanation>
...: <Type>Orange</Type>
...: <Type>Lemon</Type>
...: <Type>Lime</Type>
...: <Type>Grapefruit</Type>
...: </Fruit>
...: <Fruit>
...: <Family>Pomes</Family>
...: <Type>Apple</Type>
...: <Type>Pear</Type>
...: </Fruit>
...: </Fruits>"""
In [2]: import lxml.etree as et
In [3]: root = et.fromstring(xml)
In [4]: for node in root.xpath("//Fruit[Explanation]"):
...: print(node.xpath("Family/text()"))
...:
['Citrus']
</code></pre>
| 1 | 2016-08-21T20:38:36Z | [
"python",
"xml"
] |
List Index Out Of Range error when not out of range | 39,068,665 | <p>I have a data file which only contains the following line:</p>
<pre><code>"testA" "testB":1:"testC":2
</code></pre>
<p>Now when I split this line, and print the resulting list(w) I get the following:</p>
<pre><code>['"testA"', '"testB":1:"testC":2']
[]
</code></pre>
<p>Now when I want to access <code>w[0]</code>, it returns <code>"testA"</code> just fine, but when I print <code>w[1]</code>, it crashes and gives a list index out of range error, but <em>still prints it out</em> <code>"testB":1:"testC":2</code></p>
<p>Any help would be much appreciated!</p>
| 0 | 2016-08-21T20:40:29Z | 39,068,691 | <p>working for me without any error:</p>
<pre><code>>>> a = '"testA" "testB":1:"testC":2'
>>> b = a.split(' ')
>>> b
['"testA"', '"testB":1:"testC":2']
>>> b[0]
'"testA"'
>>> b[1]
'"testB":1:"testC":2'
</code></pre>
<p>ae you doing anything different?</p>
| 0 | 2016-08-21T20:44:23Z | [
"python",
"list",
"indexing"
] |
List Index Out Of Range error when not out of range | 39,068,665 | <p>I have a data file which only contains the following line:</p>
<pre><code>"testA" "testB":1:"testC":2
</code></pre>
<p>Now when I split this line, and print the resulting list(w) I get the following:</p>
<pre><code>['"testA"', '"testB":1:"testC":2']
[]
</code></pre>
<p>Now when I want to access <code>w[0]</code>, it returns <code>"testA"</code> just fine, but when I print <code>w[1]</code>, it crashes and gives a list index out of range error, but <em>still prints it out</em> <code>"testB":1:"testC":2</code></p>
<p>Any help would be much appreciated!</p>
| 0 | 2016-08-21T20:40:29Z | 39,068,862 | <p>Your code does not crash on <code>w[1]</code> on the <code>"testA" "testB":1:"testC":2</code> line, otherwise it would <em>not</em> print <code>"testB":1:"testC":2</code>. Note the additional <code>[]</code> in your output? Your file contains some more empty lines, which are split to <code>[]</code>, and which will then produce that error even on <code>w[0]</code>.</p>
<p>To fix the problem, you should check whether the <code>line</code> and/or the list created from that line is non-empty. (When testing the line, make sure to strip away any whitespace, such as the trailing newline character.) Your code should then look somewhat like this:</p>
<pre><code>with open("test.txt") as f:
for line in f:
if line.strip(): # strip the `\n` before checking whether line is empty
w = line.split()
print(w[0], w[1])
</code></pre>
| 1 | 2016-08-21T21:04:56Z | [
"python",
"list",
"indexing"
] |
List Index Out Of Range error when not out of range | 39,068,665 | <p>I have a data file which only contains the following line:</p>
<pre><code>"testA" "testB":1:"testC":2
</code></pre>
<p>Now when I split this line, and print the resulting list(w) I get the following:</p>
<pre><code>['"testA"', '"testB":1:"testC":2']
[]
</code></pre>
<p>Now when I want to access <code>w[0]</code>, it returns <code>"testA"</code> just fine, but when I print <code>w[1]</code>, it crashes and gives a list index out of range error, but <em>still prints it out</em> <code>"testB":1:"testC":2</code></p>
<p>Any help would be much appreciated!</p>
| 0 | 2016-08-21T20:40:29Z | 39,108,912 | <p>I also cannot reproduce your error but want to share a tip that I use in situations where I'm reading from a file and splitting on a delimiter.</p>
<pre><code>cleaned_list = [ a.strip() for a in input_line.split(' ') if a ]
</code></pre>
<p>Simple and sanitizes the split list well. </p>
| 0 | 2016-08-23T19:07:41Z | [
"python",
"list",
"indexing"
] |
List Index Out Of Range error when not out of range | 39,068,665 | <p>I have a data file which only contains the following line:</p>
<pre><code>"testA" "testB":1:"testC":2
</code></pre>
<p>Now when I split this line, and print the resulting list(w) I get the following:</p>
<pre><code>['"testA"', '"testB":1:"testC":2']
[]
</code></pre>
<p>Now when I want to access <code>w[0]</code>, it returns <code>"testA"</code> just fine, but when I print <code>w[1]</code>, it crashes and gives a list index out of range error, but <em>still prints it out</em> <code>"testB":1:"testC":2</code></p>
<p>Any help would be much appreciated!</p>
| 0 | 2016-08-21T20:40:29Z | 39,133,133 | <p>The answer was that the program read the next line after the first one which it split, and that line was empty. So as soon as it tried to index the content of that (empty line) it crashed. That's why it DID print the first line, and then crashed. Thanks a lot for your help, though!</p>
| 0 | 2016-08-24T21:13:54Z | [
"python",
"list",
"indexing"
] |
Tensorflow: Using weights trained in one model inside another, different model | 39,068,703 | <p>I'm trying to train an LSTM in Tensorflow using minibatches, but after training is complete I would like to use the model by submitting one example at a time to it. I can set up the graph within Tensorflow to train my LSTM network, but I can't use the trained result afterward in the way I want.</p>
<p>The setup code looks something like this:</p>
<pre><code>#Build the LSTM model.
cellRaw = rnn_cell.BasicLSTMCell(LAYER_SIZE)
cellRaw = rnn_cell.MultiRNNCell([cellRaw] * NUM_LAYERS)
cell = rnn_cell.DropoutWrapper(cellRaw, output_keep_prob = 0.25)
input_data = tf.placeholder(dtype=tf.float32, shape=[SEQ_LENGTH, None, 3])
target_data = tf.placeholder(dtype=tf.float32, shape=[SEQ_LENGTH, None])
initial_state = cell.zero_state(batch_size=BATCH_SIZE, dtype=tf.float32)
with tf.variable_scope('rnnlm'):
output_w = tf.get_variable("output_w", [LAYER_SIZE, 6])
output_b = tf.get_variable("output_b", [6])
outputs, final_state = seq2seq.rnn_decoder(input_list, initial_state, cell, loop_function=None, scope='rnnlm')
output = tf.reshape(tf.concat(1, outputs), [-1, LAYER_SIZE])
output = tf.nn.xw_plus_b(output, output_w, output_b)
</code></pre>
<p>...Note the two placeholders, input_data and target_data. I haven't bothered including the optimizer setup. After training is complete and the training session closed, I would like to set up a new session that uses the trained LSTM network whose input is provided by a completely different placeholder, something like:</p>
<pre><code>with tf.Session() as sess:
with tf.variable_scope("simulation", reuse=None):
cellSim = cellRaw
input_data_sim = tf.placeholder(dtype=tf.float32, shape=[1, 1, 3])
initial_state_sim = cell.zero_state(batch_size=1, dtype=tf.float32)
input_list_sim = tf.unpack(input_data_sim)
outputsSim, final_state_sim = seq2seq.rnn_decoder(input_list_sim, initial_state_sim, cellSim, loop_function=None, scope='rnnlm')
outputSim = tf.reshape(tf.concat(1, outputsSim), [-1, LAYER_SIZE])
with tf.variable_scope('rnnlm'):
output_w = tf.get_variable("output_w", [LAYER_SIZE, nOut])
output_b = tf.get_variable("output_b", [nOut])
outputSim = tf.nn.xw_plus_b(outputSim, output_w, output_b)
</code></pre>
<p>This second part returns the following error:</p>
<pre><code>tensorflow.python.framework.errors.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float
[[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
</code></pre>
<p>...Presumably because the graph I'm using still has the old training placeholders attached to the trained LSTM nodes. What's the right way to 'extract' the trained LSTM and put it into a new, different graph that has a different style of inputs? The Varible scoping features that Tensorflow has seem to address something like this, but the examples <a href="https://www.tensorflow.org/versions/r0.10/how_tos/variable_scope/index.html" rel="nofollow">in the documentation</a> all talk about using variable scope as a way of managing variable names so that the same piece of code will generate similar subgraphs within the same graph. The 'reuse' feature seems to be close to what I want, but I don't find the Tensorflow documentation linked above to be clear at all on what it does. The cells themselves cannot be given a name (in other words, </p>
<pre><code>cellRaw = rnn_cell.MultiRNNCell([cellRaw] * NUM_LAYERS, name="multicell")
</code></pre>
<p>is not valid), and while I can give a name to a seq2seq.rnn_decoder(), I presumably wouldn't be able to remove the rnn_cell.DropoutWrapper() if I used that node unchanged. </p>
<p>Questions:</p>
<p>What is the proper way to move trained LSTM weights from one graph to another?</p>
<p>Is it correct to say that starting a new session "releases resources", but doesn't erase the graph built in memory?</p>
<p>It seems to me like the 'reuse' feature allows Tensorflow to search outside of the current variable scope for variables with the same name (existing in a different scope), and use them in the current scope. Is this correct? If it is, what happens to all of the graph edges from the non-current scope that link to that variable? If it isn't, why does Tensorflow throw an error if you try to have the same variable name within two different scopes? It seems perfectly reasonable to define two variables with identical names in two different scopes, e.g. conv1/sum1 and conv2/sum1.</p>
<p>In my code I'm working within a new scope but the graph won't run without data to be fed into a placeholder from the initial, default scope. Is the default scope always 'in-scope' for some reason? </p>
<p>If graph edges can span different scopes, and names in different scopes can't be shared unless they refer to the exact same node, then that would seem to defeat the purpose of having different scopes in the first place. What am I misunderstanding here?</p>
<p>Thanks!</p>
| 2 | 2016-08-21T20:45:53Z | 39,079,555 | <p><strong>What is the proper way to move trained LSTM weights from one graph to another?</strong></p>
<p>You can create your decoding graph first (with a saver object to save the parameters) and create a GraphDef object that you can import in your bigger training graph:</p>
<pre><code>basegraph = tf.Graph()
with basegraph.as_default():
***your graph***
traingraph = tf.Graph()
with traingraph.as_default():
tf.import_graph_def(basegraph.as_graph_def())
***your training graph***
</code></pre>
<p>make sure you load your variables when you start a session for a new graph.</p>
<p>I don't have experience with this functionality so you may have to look into it a bit more</p>
<p><strong>Is it correct to say that starting a new session "releases resources", but doesn't erase the graph built in memory?</strong></p>
<p>yep, the graph object still hold it</p>
<p><strong>It seems to me like the 'reuse' feature allows Tensorflow to search outside of the current variable scope for variables with the same name (existing in a different scope), and use them in the current scope. Is this correct? If it is, what happens to all of the graph edges from the non-current scope that link to that variable? If it isn't, why does Tensorflow throw an error if you try to have the same variable name within two different scopes? It seems perfectly reasonable to define two variables with identical names in two different scopes, e.g. conv1/sum1 and conv2/sum1.</strong></p>
<p>No, reuse is to determine the behaviour when you use get_variable on an existing name, when it is true it will return the existing variable, otherwise it will return a new one. Normally tensorflow should not throw an error. Are you sure your using tf.get_variable and not just tf.Variable?</p>
<p><strong>In my code I'm working within a new scope but the graph won't run without data to be fed into a placeholder from the initial, default scope. Is the default scope always 'in-scope' for some reason?</strong></p>
<p>I don't really see what you mean. The do not always have to be used. If a placeholder is not required for running an operation you don't have to define it.</p>
<p><strong>If graph edges can span different scopes, and names in different scopes can't be shared unless they refer to the exact same node, then that would seem to defeat the purpose of having different scopes in the first place. What am I misunderstanding here?</strong></p>
<p>I think your understanding or usage of scopes is flawed, see above</p>
| 1 | 2016-08-22T12:27:34Z | [
"python",
"tensorflow",
"lstm"
] |
Kombu, RabbitMQ: Ack message more than once in a consumer mixin | 39,068,790 | <p>I have stumbled upon this problem <a class='doc-link' href="http://stackoverflow.com/documentation/python/drafts/6079">while I was documenting Kombu</a> for the new SO documentation project.</p>
<p>Consider the following Kombu code of a <a href="http://docs.celeryproject.org/projects/kombu/en/latest/reference/kombu.mixins.html" rel="nofollow">Consumer Mixin</a>:</p>
<pre class="lang-python prettyprint-override"><code>from kombu import Connection, Queue
from kombu.mixins import ConsumerMixin
from kombu.exceptions import MessageStateError
import datetime
# Send a message to the 'test_queue' queue
with Connection('amqp://guest:guest@localhost:5672//') as conn:
with conn.SimpleQueue(name='test_queue') as queue:
queue.put('String message sent to the queue')
# Callback functions
def print_upper(body, message):
print body.upper()
message.ack()
def print_lower(body, message):
print body.lower()
message.ack()
# Attach the callback function to a queue consumer
class Worker(ConsumerMixin):
def __init__(self, connection):
self.connection = connection
def get_consumers(self, Consumer, channel):
return [
Consumer(queues=Queue('test_queue'), callbacks=[print_even_characters, print_odd_characters]),
]
# Start the worker
with Connection('amqp://guest:guest@localhost:5672//') as conn:
worker = Worker(conn)
worker.run()
</code></pre>
<p>The code fails with:</p>
<pre><code>kombu.exceptions.MessageStateError: Message already acknowledged with state: ACK
</code></pre>
<p>Because the message was ACK-ed twice, on <code>print_even_characters()</code> and <code>print_odd_characters()</code>.</p>
<p>A simple solution that works would be ACK-ing only the last callback function, but it breaks modularity if I want to use the same functions on other queues or connections.</p>
<p><strong>How to ACK a queued Kombu message that is sent to more than one callback function?</strong></p>
| 1 | 2016-08-21T20:56:53Z | 39,072,173 | <h1>Solutions</h1>
<h2>1 - Checking <code>message.acknowledged</code></h2>
<p>The <code>message.acknowledged</code> flag checks whether the message is already ACK-ed:</p>
<pre class="lang-python prettyprint-override"><code>def print_upper(body, message):
print body.upper()
if not message.acknowledged:
message.ack()
def print_lower(body, message):
print body.lower()
if not message.acknowledged:
message.ack()
</code></pre>
<p><strong>Pros</strong>: Readable, short.</p>
<p><strong>Cons</strong>: Breaks <a href="https://docs.python.org/3/glossary.html" rel="nofollow">Python EAFP idiom</a>.</p>
<h2>2 - Catching the exception</h2>
<pre class="lang-python prettyprint-override"><code>def print_upper(body, message):
print body.upper()
try:
message.ack()
except MessageStateError:
pass
def print_lower(body, message):
print body.lower()
try:
message.ack()
except MessageStateError:
pass
</code></pre>
<p><strong>Pros:</strong> Readable, Pythonic.</p>
<p><strong>Cons:</strong> A little long - 4 lines of boilerplate code per callback.</p>
<h2>3 - ACKing the last callback</h2>
<p>The documentation guarantees that the <a href="http://docs.celeryproject.org/projects/kombu/en/latest/userguide/consumers.html#reference" rel="nofollow">callbacks are called in order</a>. Therefore, we can simply <code>.ack()</code> only the last callback:</p>
<pre class="lang-python prettyprint-override"><code>def print_upper(body, message):
print body.upper()
def print_lower(body, message):
print body.lower()
message.ack()
</code></pre>
<p><strong>Pros:</strong> Short, readable, no boilerplate code.</p>
<p><strong>Cons:</strong> Not modular: the callbacks can not be used by another queue, unless the last callback is always last. This implicit assumption can break the caller code.</p>
<p>This can be solved by moving the callback functions into the <code>Worker</code> class. We give up some modularity - these functions will not be called from outside - but gain safety and readability.</p>
<h1>Summary</h1>
<p>The difference between 1 and 2 is merely a matter of style.</p>
<p>Solution 3 should be picked if the order of execution matters, and whether a message should not be ACK-ed before it went through all the callbacks successfully.</p>
<p>1 or 2 should be picked if the message should always be ACK-ed, even if one or more callbacks failed.</p>
<p>Note that there are other possible designs; this answer refers to callback functions that reside outside the worker.</p>
| 0 | 2016-08-22T05:55:05Z | [
"python",
"rabbitmq",
"kombu",
"message-ack"
] |
Does tkinter arrowshape require a tuple but stores as text? | 39,068,796 | <p>I ran into a problem, since pulling <em>options["arrowshape"]</em> from the tkinter canvas resulted in a string "x y z", while setting the arrowshape in <em>create_line</em> will use a tuple [x,y,z] and not a string...
Is this correct in Python 2.7.10+</p>
| 0 | 2016-08-21T20:57:36Z | 39,068,870 | <p>This is how you create an arrow:</p>
<pre><code>from tkinter import *
root = Tk()
can = Canvas(root, bg='white')
ar = can.create_line(5, 5, 100, 70, arrow='last', arrowshape='20 40 10')
can.pack()
root.mainloop()
</code></pre>
<p>You need to pass a string (or a list or a tuple) representing the shape of the arrow head. The first is the length, the last is the width, and the middle one relates to the amount of arc the arrow base has. You can play with it to get the taste.</p>
<p>You can designate the arrow shape also by</p>
<pre><code>arrowshape=[20, 40, 10]
</code></pre>
<p>or</p>
<pre><code>arrowshape=(20, 40, 10)
</code></pre>
| 0 | 2016-08-21T21:06:36Z | [
"python"
] |
Cannot compare type 'Timestamp' with type 'int' | 39,068,813 | <p>When running the following code:</p>
<pre><code>for row,hit in hits.iterrows():
forwardRows = data[data.index.values > row];
</code></pre>
<p>I get this error:</p>
<pre><code>TypeError: Cannot compare type 'Timestamp' with type 'int'
</code></pre>
<p>If I look into what is being compared here I have these variables:</p>
<pre><code>type(row)
pandas.tslib.Timestamp
row
Timestamp('2015-09-01 09:30:00')
</code></pre>
<p>is being compared with:</p>
<pre><code>type(data.index.values[0])
numpy.datetime64
data.index.values[0]
numpy.datetime64('2015-09-01T10:30:00.000000000+0100')
</code></pre>
<p>I would like to understand whether this is something that can be easily fixed or should I upload a subset of my data? thanks</p>
| 3 | 2016-08-21T20:59:55Z | 39,069,304 | <p>Although this isn't a direct answer to your question, I have a feeling that this is what you're looking for: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.truncate.html" rel="nofollow">pandas.DataFrame.truncate</a></p>
<p>You could use it as follows:</p>
<pre><code>for row, hit in hits.iterrows():
forwardRows = data.truncate(before=row)
</code></pre>
<hr>
<p>Here's a little toy example of how you might use it in general:</p>
<pre><code>import pandas as pd
# let's create some data to play with
df = pd.DataFrame(
index=pd.date_range(start='2016-01-01', end='2016-06-01', freq='M'),
columns=['x'],
data=np.random.random(5)
)
# example: truncate rows before Mar 1
df.truncate(before='2016-03-01')
# example: truncate rows after Mar 1
df.truncate(after='2016-03-01')
</code></pre>
| 1 | 2016-08-21T22:11:57Z | [
"python",
"pandas"
] |
Cannot compare type 'Timestamp' with type 'int' | 39,068,813 | <p>When running the following code:</p>
<pre><code>for row,hit in hits.iterrows():
forwardRows = data[data.index.values > row];
</code></pre>
<p>I get this error:</p>
<pre><code>TypeError: Cannot compare type 'Timestamp' with type 'int'
</code></pre>
<p>If I look into what is being compared here I have these variables:</p>
<pre><code>type(row)
pandas.tslib.Timestamp
row
Timestamp('2015-09-01 09:30:00')
</code></pre>
<p>is being compared with:</p>
<pre><code>type(data.index.values[0])
numpy.datetime64
data.index.values[0]
numpy.datetime64('2015-09-01T10:30:00.000000000+0100')
</code></pre>
<p>I would like to understand whether this is something that can be easily fixed or should I upload a subset of my data? thanks</p>
| 3 | 2016-08-21T20:59:55Z | 39,069,325 | <p>When using <code>values</code> you put it into <code>numpy</code> world. Instead, try</p>
<pre><code>for row,hit in hits.iterrows():
forwardRows = data[data.index > row];
</code></pre>
| 2 | 2016-08-21T22:15:25Z | [
"python",
"pandas"
] |
Return diagonal elements of scipy sparse matrix | 39,068,833 | <p>Given a <code>scipy.sparse.csr.csr_matrix</code>, is there a quick way to return the elements on the diagonal?</p>
<p>The reason I would like to do this is to compute <code>inv(D) A</code>, where <code>D</code> is a diagonal matrix whose diagonal entries agree with <code>A</code> (<code>A</code> is my sparse matrix, guaranteed to have nonzeros on the diagonal).</p>
| 1 | 2016-08-21T21:02:15Z | 39,068,857 | <p>Use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.diagonal.html#scipy.sparse.csr_matrix.diagonal" rel="nofollow">csr_matrix.diagonal()</a>:</p>
<blockquote>
<p>Returns the main diagonal of the matrix</p>
</blockquote>
<p>Example:</p>
<pre><code>>>> import numpy as np
>>> from scipy.sparse import csr_matrix
>>> mymat = csr_matrix((4, 4), dtype=np.int8)
>>> mymat.diagonal()
array([0, 0, 0, 0], dtype=int8)
</code></pre>
| 2 | 2016-08-21T21:04:45Z | [
"python",
"numpy",
"matrix",
"scipy",
"diagonal"
] |
How to append to a file from stream rather than overwrite in Python | 39,068,864 | <p>I am new to python so this maybe a simple question but I have a kafka consumer from which I read in messages. Every time a new message comes in it rewrites the previous message into the order.json file however I want to append it instead. Additionally, I want to make sure the messages do not get read in no faster than every 1 second using possible some sort of pause. Any tips on how to do this would be much appreciated. Here is my current code</p>
<pre><code>for message in consumer:
with open('order.json', 'w') as file:
file.write(message.value.decode('UTF-8'))
</code></pre>
| 0 | 2016-08-21T21:05:07Z | 39,068,879 | <p>Open outside the loop:</p>
<pre><code>with open('order.json', 'w') as file:
for message in consumer:
file.write(message.value.decode('UTF-8'))
</code></pre>
<p>Or open outside and use <code>a</code> if you are going to be appending for each run:</p>
<pre><code>with open('order.json', 'a') as file:
for message in consumer:
file.write(message.value.decode('UTF-8'))
</code></pre>
| 0 | 2016-08-21T21:07:42Z | [
"python",
"file",
"stream",
"message"
] |
How to append to a file from stream rather than overwrite in Python | 39,068,864 | <p>I am new to python so this maybe a simple question but I have a kafka consumer from which I read in messages. Every time a new message comes in it rewrites the previous message into the order.json file however I want to append it instead. Additionally, I want to make sure the messages do not get read in no faster than every 1 second using possible some sort of pause. Any tips on how to do this would be much appreciated. Here is my current code</p>
<pre><code>for message in consumer:
with open('order.json', 'w') as file:
file.write(message.value.decode('UTF-8'))
</code></pre>
| 0 | 2016-08-21T21:05:07Z | 39,068,881 | <p>You want to open your file in <a href="http://man7.org/linux/man-pages/man2/open.2.html" rel="nofollow">append mode</a>. Also, you may not want to open the file on each message, since it can be an expensive operation (e.g. you will need to change file metadata like modification time every time you close the file):</p>
<pre><code># open file in append mode, once
with open('order.json', 'a') as file:
for message in consumer:
file.write(message.value.decode('UTF-8'))
</code></pre>
<p>As for rate limiting, you could start with something simple, like the following:</p>
<pre><code>import time
def ratelimit(it, sleep=1.0):
for v in it:
yield v
time.sleep(sleep)
if __name__ == '__main__':
for i in ratelimit(range(10)):
print(i)
</code></pre>
<p>This would ensure, there is <em>at least</em> one second delay between successive values from an iterator. Here's a <a href="https://asciinema.org/a/6bo7i6vrx9joiigr3k75ir6r0?autoplay=1" rel="nofollow">asciicast</a> showing the rate-limiter in action.</p>
| 0 | 2016-08-21T21:07:57Z | [
"python",
"file",
"stream",
"message"
] |
How to append to a file from stream rather than overwrite in Python | 39,068,864 | <p>I am new to python so this maybe a simple question but I have a kafka consumer from which I read in messages. Every time a new message comes in it rewrites the previous message into the order.json file however I want to append it instead. Additionally, I want to make sure the messages do not get read in no faster than every 1 second using possible some sort of pause. Any tips on how to do this would be much appreciated. Here is my current code</p>
<pre><code>for message in consumer:
with open('order.json', 'w') as file:
file.write(message.value.decode('UTF-8'))
</code></pre>
| 0 | 2016-08-21T21:05:07Z | 39,068,893 | <p>Open the file in <code>append</code> mode as '<code>w'</code> (write mode) truncates the file each time it exists</p>
<pre><code>for message in consumer:
with open('order.json', 'a') as file:
file.write(message.value.decode('UTF-8'))
</code></pre>
| 0 | 2016-08-21T21:10:08Z | [
"python",
"file",
"stream",
"message"
] |
Using a recursive call in If-condition in Python | 39,068,912 | <p>I have written a function to perform lasso regression using coordinate descent. </p>
<p>The code is as follows:</p>
<pre><code>def lasso_cyclical_coordinate_descent(feature_matrix, output, weights, l1_penalty, tolerance):
for i in range(len(weights)):
old_weights_i = weights[i]
weights[i] = lasso_coordinate_descent_step(i, feature_matrix, output, weights, l1_penalty)
diff = []
diff.append(abs(old_weights_i - weights[i]))
if max(diff) > tolerance:
weights = lasso_cyclical_coordinate_descent(feature_matrix, output, weights, l1_penalty, tolerance)
return weights
</code></pre>
<p>My thinking here was that running a recursive call inside an If-condition will result in the weights being returned only when the condition is not satisfied, that is when I have my desired result. Until then, the function will just continue calling itself recursively. </p>
<p>Is my logic correct? I discussed this with someone else, he said it wasn't, but did not explain further. </p>
| -3 | 2016-08-21T21:12:14Z | 39,069,084 | <p>You are right. Your if statement and your implicite else is your recursion "stopping condition". As soon as the if condition is false, it will exit the function and end recursion by exiting all parent calls.</p>
<p>You have to make sure this statement can be false at least once to avoid a max depth recursion exception.</p>
| 0 | 2016-08-21T21:37:20Z | [
"python",
"recursion"
] |
Printing the values in a nested dictionary in Python 2.x | 39,068,943 | <p>I have a dictionary type variable returned in my Python 2.x script that contains the below values:-</p>
<pre><code>{u'image': u'/users/me/Desktop/12345_507630509400555_869403269181768452_n.jpg', u'faces': [{u'gender': {u'gender': u'FEMALE', u'score': 0.731059}, u'age': {u'max': 17, u'score': 0.983185}, u'face_location': {u'width': 102, u'top': 102, u'left': 426, u'height': 106}}]}
</code></pre>
<p>What I want to do is extract the following values for the given keys:-</p>
<ul>
<li>'gender' (the value being 'female') </li>
<li>'score' (the value being '0.731059') </li>
<li>'age'[max] (the value being '17') </li>
<li>'age'[score] (the value being '0.983185)</li>
</ul>
<p>I tried the below but it doesn't seem to return what I am looking for:</p>
<pre><code> if key == 'faces':
for k, v in key:
print(k['gender'], k['max'], k['age'][0], k['age'][1])
</code></pre>
<p>Any suggestions on how I can access and print the values I am interested in? </p>
| 1 | 2016-08-21T21:16:21Z | 39,068,962 | <p>You have nested dicts and lists:</p>
<pre><code>d = {u'image': u'/users/me/Desktop/12345_507630509400555_869403269181768452_n.jpg', u'faces': [{u'gender': {u'gender': u'FEMALE', u'score': 0.731059}, u'age': {u'max': 17, u'score': 0.983185}, u'face_location': {u'width': 102, u'top': 102, u'left': 426, u'height': 106}}]}
# iterate over the list of dict(s)
for dct in d["faces"]:
gender, age = dct['gender'], dct["age"]
print(gender["gender"], gender["score"], age["max"], age["score"])
</code></pre>
<p>The gender dict looks like:</p>
<pre><code>{u'gender': u'FEMALE', u'score': 0.731059}
</code></pre>
<p>So we use the keys <em>"gender"</em> and <em>"score"</em> to get the values, the age dict looks like:</p>
<pre><code> {u'max': 17, u'score': 0.983185}
</code></pre>
<p>Again we just grab the values using the keys <em>"max"</em> and <em>"score"</em></p>
| 2 | 2016-08-21T21:18:57Z | [
"python",
"json",
"python-2.7",
"dictionary",
"nested"
] |
Printing the values in a nested dictionary in Python 2.x | 39,068,943 | <p>I have a dictionary type variable returned in my Python 2.x script that contains the below values:-</p>
<pre><code>{u'image': u'/users/me/Desktop/12345_507630509400555_869403269181768452_n.jpg', u'faces': [{u'gender': {u'gender': u'FEMALE', u'score': 0.731059}, u'age': {u'max': 17, u'score': 0.983185}, u'face_location': {u'width': 102, u'top': 102, u'left': 426, u'height': 106}}]}
</code></pre>
<p>What I want to do is extract the following values for the given keys:-</p>
<ul>
<li>'gender' (the value being 'female') </li>
<li>'score' (the value being '0.731059') </li>
<li>'age'[max] (the value being '17') </li>
<li>'age'[score] (the value being '0.983185)</li>
</ul>
<p>I tried the below but it doesn't seem to return what I am looking for:</p>
<pre><code> if key == 'faces':
for k, v in key:
print(k['gender'], k['max'], k['age'][0], k['age'][1])
</code></pre>
<p>Any suggestions on how I can access and print the values I am interested in? </p>
| 1 | 2016-08-21T21:16:21Z | 39,068,996 | <p>It's a bit complex dict. This is how you extract the desired values:</p>
<p>Let <code>d</code> be your dict:</p>
<pre><code>key = 'faces'
inner = d[key][0]
print(inner['gender']['gender'], inner['gender']['score'], inner['age']['max'], inner['age']['score'])
</code></pre>
<p>Output:</p>
<pre><code>FEMALE 0.731059 17 0.983185
</code></pre>
| 1 | 2016-08-21T21:23:56Z | [
"python",
"json",
"python-2.7",
"dictionary",
"nested"
] |
python use lazy assignment when passing lists to methods | 39,068,974 | <p>I have a python class A and its child B. I make an object of class B passing some list-type arguments, which are appended in B and the result stored in class A. I would like to be able to change one of those initial arguments and see the change reflected without further ado. Let me explain with an example:</p>
<pre><code>class A():
def __init__(self,data):
self.a=data
class B(A):
def __init__(self,x,y):
self.x=x
self.y=y
A.__init__(self,self.x+self.y)
def change_x(self,x):
self.x = x
</code></pre>
<p>Now, wen i run</p>
<pre><code>test = B([1, 2], [3,4])
print(test.a)
</code></pre>
<p>I obviously get [1,2,3,4]. If I change part of the list as follows:</p>
<pre><code>test.change_x([3,4])
print(test.a)
</code></pre>
<p>I would like to get [3,4,3,4], instead of course, I receive [1,2,3,4]. Of course test.a is only evaluated during instantiation.</p>
<p>I understand why this is not the case and I read about generators but don't manage to figure out how to implement this. I don't want to end up with an iterable that i can only iterate once.</p>
<p>Could anyone help me? A clean way to solve this?</p>
| 2 | 2016-08-21T21:20:33Z | 39,069,026 | <p>You need to implement it "manually". For example, like so:</p>
<pre><code>class B(A):
def __init__(self,x,y):
self.x=x
self.y=y
self.spread_changes()
def change_x(self,x):
self.x = x
self.spread_changes()
def spread_changes(self):
A.__init__(self,self.x+self.y)
</code></pre>
| 1 | 2016-08-21T21:28:49Z | [
"python",
"generator"
] |
python use lazy assignment when passing lists to methods | 39,068,974 | <p>I have a python class A and its child B. I make an object of class B passing some list-type arguments, which are appended in B and the result stored in class A. I would like to be able to change one of those initial arguments and see the change reflected without further ado. Let me explain with an example:</p>
<pre><code>class A():
def __init__(self,data):
self.a=data
class B(A):
def __init__(self,x,y):
self.x=x
self.y=y
A.__init__(self,self.x+self.y)
def change_x(self,x):
self.x = x
</code></pre>
<p>Now, wen i run</p>
<pre><code>test = B([1, 2], [3,4])
print(test.a)
</code></pre>
<p>I obviously get [1,2,3,4]. If I change part of the list as follows:</p>
<pre><code>test.change_x([3,4])
print(test.a)
</code></pre>
<p>I would like to get [3,4,3,4], instead of course, I receive [1,2,3,4]. Of course test.a is only evaluated during instantiation.</p>
<p>I understand why this is not the case and I read about generators but don't manage to figure out how to implement this. I don't want to end up with an iterable that i can only iterate once.</p>
<p>Could anyone help me? A clean way to solve this?</p>
| 2 | 2016-08-21T21:20:33Z | 39,069,040 | <p>Is there a reason to have the class <code>A</code> at all? You could create a property or method <code>a</code> that returns what you want within class <code>B</code>.</p>
<pre><code>class B():
def __init__(self, x, y):
self.x = x
self.y = y
def change_x(self, x):
self.x = x
@property
def a(self):
return self.x + self.y
test = B([1, 2], [3, 4])
print(test.a) # [1, 2, 3, 4]
test.change_x([3, 4])
print(test.a) # [3, 4, 3, 4]
</code></pre>
<p><strong>Small note</strong>: With this implementation, the <code>change_x</code> method shouldn't be necessary. It's generally more Pythonic to just access attributes directly (e.g. <code>test.x = x</code>) than to use getters and setters.</p>
| 7 | 2016-08-21T21:30:10Z | [
"python",
"generator"
] |
python use lazy assignment when passing lists to methods | 39,068,974 | <p>I have a python class A and its child B. I make an object of class B passing some list-type arguments, which are appended in B and the result stored in class A. I would like to be able to change one of those initial arguments and see the change reflected without further ado. Let me explain with an example:</p>
<pre><code>class A():
def __init__(self,data):
self.a=data
class B(A):
def __init__(self,x,y):
self.x=x
self.y=y
A.__init__(self,self.x+self.y)
def change_x(self,x):
self.x = x
</code></pre>
<p>Now, wen i run</p>
<pre><code>test = B([1, 2], [3,4])
print(test.a)
</code></pre>
<p>I obviously get [1,2,3,4]. If I change part of the list as follows:</p>
<pre><code>test.change_x([3,4])
print(test.a)
</code></pre>
<p>I would like to get [3,4,3,4], instead of course, I receive [1,2,3,4]. Of course test.a is only evaluated during instantiation.</p>
<p>I understand why this is not the case and I read about generators but don't manage to figure out how to implement this. I don't want to end up with an iterable that i can only iterate once.</p>
<p>Could anyone help me? A clean way to solve this?</p>
| 2 | 2016-08-21T21:20:33Z | 39,093,097 | <p>I ended up storing all parts of self.a (in A) directly by slicing/indexing from it's inheriting classes. I added a method "B.update_crc(self)" as suggested by Israel Unterman to reevaluate certain parts of self.a in case of a modification.</p>
<p>Thanks, my first approach just wan't the right one :)</p>
| 0 | 2016-08-23T05:35:53Z | [
"python",
"generator"
] |
Reading CONNECT headers | 39,068,998 | <p>I'm using a proxy service (proxymesh) that puts useful information into the headers sent in response to a CONNECT request. For whatever reason, <a href="https://bugs.python.org/issue24964" rel="nofollow">Python's <code>httplib</code> doesn't parse them</a>:</p>
<pre><code>> CONNECT example.com:443 HTTP/1.1
> Host: example.com:443
>
< HTTP/1.1 200 Connection established
< X-Useful-Header: value # completely ignored
<
</code></pre>
<p>The <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a> module uses <code>httplib</code> internally, so it ignores them as well. How do I extract headers from a <code>CONNECT</code> request?</p>
| 1 | 2016-08-21T21:24:12Z | 39,068,999 | <p>Python's <code>httplib</code> actually ignores these headers when creating the tunnel. It's hacky, but you can intercept them and merge the "header" lines with the actual HTTP response's headers:</p>
<pre><code>import socket
import httplib
import requests
from requests.packages.urllib3.connection import HTTPSConnection
from requests.packages.urllib3.connectionpool import HTTPSConnectionPool
from requests.packages.urllib3.poolmanager import ProxyManager
from requests.adapters import HTTPAdapter
class ProxyHeaderHTTPSConnection(HTTPSConnection):
def __init__(self, *args, **kwargs):
super(ProxyHeaderHTTPSConnection, self).__init__(*args, **kwargs)
self._proxy_headers = []
def _tunnel(self):
self.send("CONNECT %s:%d HTTP/1.0\r\n" % (self._tunnel_host, self._tunnel_port))
for header, value in self._tunnel_headers.iteritems():
self.send("%s: %s\r\n" % (header, value))
self.send("\r\n")
response = self.response_class(self.sock, strict=self.strict, method=self._method)
version, code, message = response._read_status()
if version == "HTTP/0.9":
# HTTP/0.9 doesn't support the CONNECT verb, so if httplib has
# concluded HTTP/0.9 is being used something has gone wrong.
self.close()
raise socket.error("Invalid response from tunnel request")
if code != 200:
self.close()
raise socket.error("Tunnel connection failed: %d %s" % (code, message.strip()))
self._proxy_headers = []
while True:
line = response.fp.readline(httplib._MAXLINE + 1)
if len(line) > httplib._MAXLINE:
raise LineTooLong("header line")
if not line or line == '\r\n':
break
# The line is a header, save it
if ':' in line:
self._proxy_headers.append(line)
def getresponse(self, buffering=False):
response = super(ProxyHeaderHTTPSConnection, self).getresponse(buffering)
response.msg.headers.extend(self._proxy_headers)
return response
class ProxyHeaderHTTPSConnectionPool(HTTPSConnectionPool):
ConnectionCls = ProxyHeaderHTTPSConnection
class ProxyHeaderProxyManager(ProxyManager):
def _new_pool(self, scheme, host, port):
assert scheme == 'https'
return ProxyHeaderHTTPSConnectionPool(host, port, **self.connection_pool_kw)
class ProxyHeaderHTTPAdapter(HTTPAdapter):
def proxy_manager_for(self, proxy, **proxy_kwargs):
if proxy in self.proxy_manager:
manager = self.proxy_manager[proxy]
else:
proxy_headers = self.proxy_headers(proxy)
manager = self.proxy_manager[proxy] = ProxyHeaderProxyManager(
proxy_url=proxy,
proxy_headers=proxy_headers,
num_pools=self._pool_connections,
maxsize=self._pool_maxsize,
block=self._pool_block,
**proxy_kwargs)
return manager
</code></pre>
<p>You can then install the adapter onto a session:</p>
<pre><code>session = requests.Session()
session.mount('https://', ProxyHeaderHTTPAdapter())
response = session.get('https://example.com', proxies={...})
</code></pre>
<p>The proxy's headers will be merged in with the response headers, so it should behave as if the proxy modified the response headers directly.</p>
| 1 | 2016-08-21T21:24:12Z | [
"python",
"proxy",
"http-headers",
"python-requests",
"httplib"
] |
wxPython : Soundboard panel [NOW PLAYING] just like in winamp | 39,069,001 | <p>I am almost done my wxPython soundboard and want to implement one quick feature. </p>
<p>How does one add another panel to a wxPython window, and how do you implement the text, [ NOW PLAYING ] within that panel. </p>
<p>Here is my code so far:
import wx
import os
import pygame</p>
<pre><code>pygame.init()
##SOUNDS##
##SOUNDS##
class windowClass(wx.Frame):
__goliathwav = pygame.mixer.Sound("goliath.wav")
__channelopen = pygame.mixer.Sound("channelopen.wav")
def __init__(self, *args, **kwargs):
super(windowClass,self).__init__(*args,**kwargs)
self.__basicGUI()
def __basicGUI(self):
panel = wx.Panel(self)
menuBar = wx.MenuBar()
fileButton = wx.Menu()
aboutButton = wx.Menu()
exitItem = fileButton.Append(wx.ID_EXIT, 'Exit','status msg...')
aboutItem = aboutButton.Append(wx.ID_ABOUT, "About")
menuBar.Append(fileButton, 'File')
menuBar.Append(aboutButton, 'About this program')
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.__quit, exitItem)
self.Bind(wx.EVT_MENU, self.__onmenuhelpabout, aboutItem)
self.__sound_dict = { "Goliath" : self.__goliathwav,
"Goliath2" : self.__channelopen
}
self.__sound_list = sorted(self.__sound_dict.keys())
self.__list = wx.ListBox(panel,pos=(20,20), size=(250,150))
for i in self.__sound_list:
self.__list.Append(i)
self.__list.Bind(wx.EVT_LISTBOX,self.__on_click)
textarea = wx.TextCtrl(self, -1,
style=wx.TE_MULTILINE|wx.BORDER_SUNKEN|wx.TE_READONLY|
wx.TE_RICH2, size=(250,150))
self.usertext = textarea
#self.__list2 = wx.ListBox(panel,pos=(19.5,180), size=(251,21)) #second panel
#for j in self.__sound_list:
# self.__list2.Append(i)
#self.__list2.Bind(wx.EVT_LISTBOX,self.__on_click)
#wx.TextCtrl(panel,pos=(10,10), size=(250,150))
self.SetTitle("Soundboard")
self.Show(True)
def __onmenuhelpabout(self,event):
dialog = wx.Dialog(self, -1, "[Soundboard]") # ,
#style=wx.DIALOG_MODAL | wx.STAY_ON_TOP)
dialog.SetBackgroundColour(wx.WHITE)
panel = wx.Panel(dialog, -1)
panel.SetBackgroundColour(wx.WHITE)
panelSizer = wx.BoxSizer(wx.VERTICAL)
boldFont = wx.Font(panel.GetFont().GetPointSize(),
panel.GetFont().GetFamily(),
wx.NORMAL,wx.BOLD)
lab1 = wx.StaticText(panel, -1, " SOUNDBOARD ")
lab1.SetFont(wx.Font(36,boldFont.GetFamily(), wx.ITALIC, wx.BOLD))
lab1.SetSize(lab1.GetBestSize())
imageSizer = wx.BoxSizer(wx.HORIZONTAL)
imageSizer.Add(lab1, 0, wx.ALL | wx.ALIGN_CENTRE_VERTICAL, 5)
lab2 = wx.StaticText(panel, -1, "Created by youonlylegoonce(cyrex)(Kommander000) for the glory " + \
"of the republic.")
panelSizer.Add(imageSizer, 0, wx.ALIGN_CENTRE)
panelSizer.Add((10, 10)) # Spacer.
panelSizer.Add(lab2, 0, wx.ALIGN_CENTRE)
panel.SetAutoLayout(True)
panel.SetSizer(panelSizer)
panelSizer.Fit(panel)
topSizer = wx.BoxSizer(wx.HORIZONTAL)
topSizer.Add(panel, 0, wx.ALL, 10)
dialog.SetAutoLayout(True)
dialog.SetSizer(topSizer)
topSizer.Fit(dialog)
dialog.Centre()
btn = dialog.ShowModal()
dialog.Destroy()
def __on_click(self,event):
event.Skip()
name = self.__sound_list[self.__list.GetSelection()]
sound = self.__sound_dict[name]
print("[ NOW PLAYING ] ... %s" % name)
pygame.mixer.Sound.play(sound)
def __quit(self, e):
self.Close()
def main():
app = wx.App()
windowClass(None, -1, style=wx.MAXIMIZE_BOX | wx.CAPTION | wx.CENTRE)
app.MainLoop()
main()
</code></pre>
| 0 | 2016-08-21T21:24:23Z | 39,084,943 | <p>Before:</p>
<pre><code>print("[ NOW PLAYING ] ... %s" % name)
</code></pre>
<p>input:</p>
<pre><code>self.usertext.SetValue("[ NOW PLAYING ] ... %s" % name)
</code></pre>
<p>P.S. Your indentation is a mess</p>
| 0 | 2016-08-22T16:57:56Z | [
"python",
"wxpython"
] |
Append list value to corresponding value in another list | 39,069,013 | <p>So I'm trying to attach a bunch of values in a huge list to their corresponding headings stored in another list. For example, right now I have a list with only the headings (e.g. ['Target'],['Choice']) and I want to take values corresponding with those headings (e.g. 'Target':3, 'Choice':1) and append them to the corresponding value in the headings list while also stripping off the headings from the values in the second list--so everything after the ':' needs to be attached to it's corresponding value in the original list. Then I want to take each of these strings in the new list (e.g. [Target: 1, 2, 1, 3 . . .]) and import them into a column in a csv or excel file. I'm admittedly a bit of a noob, but I've worked really hard thus far. Here is what I have that doesn't word (excluding exporting to csv, as I have no idea how to do that).</p>
<pre><code>key_name = ['distractor_shape','stimulus_param','prompt_format','test_format','d0_type','d1_type','d2_type','encoding_rt','verification_rt', 'target', 'choice','correct','debrief','response','CompletionCode']
def headers(list):
brah_list = []
for dup in list:
z = dup.count(',')
nw = dup.split(',',z)
brah_list.append(nw)
return brah_list
def parse_data(filename):
big_list = []
with open(filename) as f:
for word in f:
x = word.count(',')
new_word = word.split(',',x)
big_list.append(new_word)
return big_list
b_list = parse_data('A1T6RFUU0OTS0M.txt')
k_list = headers(key_name)
def f_un(things):
for t in things:
return t
h_list = f_un(k_list)
def f_in(stuff):
for sf in stuff:
for s in sf:
print(s)
z = 0
head_r = "h_list[z]"
if s.startswith(head_r):
s.strip(head_r)
h_list.append(s)
z += 1
print(stuff)
f_in(b_list)
</code></pre>
| 0 | 2016-08-21T21:26:41Z | 39,069,114 | <p>If i understand your question correctly, you have a list, and you have some corresponding values in another list retaliative to the first list. If that is the case, and assuming that all your values corresponded in the correct order you could use list comprehension:</p>
<pre><code>lst1 = ['th', 'an', 'bu']
lst2 = ['e', 'd', 't']
#here
lst1 = [lst1[i] + lst2[i] for i in range(len(lst1))]
#here
print(lst1) #output: ['the', 'and', 'but']
</code></pre>
| 0 | 2016-08-21T21:42:27Z | [
"python",
"list",
"csv"
] |
Append list value to corresponding value in another list | 39,069,013 | <p>So I'm trying to attach a bunch of values in a huge list to their corresponding headings stored in another list. For example, right now I have a list with only the headings (e.g. ['Target'],['Choice']) and I want to take values corresponding with those headings (e.g. 'Target':3, 'Choice':1) and append them to the corresponding value in the headings list while also stripping off the headings from the values in the second list--so everything after the ':' needs to be attached to it's corresponding value in the original list. Then I want to take each of these strings in the new list (e.g. [Target: 1, 2, 1, 3 . . .]) and import them into a column in a csv or excel file. I'm admittedly a bit of a noob, but I've worked really hard thus far. Here is what I have that doesn't word (excluding exporting to csv, as I have no idea how to do that).</p>
<pre><code>key_name = ['distractor_shape','stimulus_param','prompt_format','test_format','d0_type','d1_type','d2_type','encoding_rt','verification_rt', 'target', 'choice','correct','debrief','response','CompletionCode']
def headers(list):
brah_list = []
for dup in list:
z = dup.count(',')
nw = dup.split(',',z)
brah_list.append(nw)
return brah_list
def parse_data(filename):
big_list = []
with open(filename) as f:
for word in f:
x = word.count(',')
new_word = word.split(',',x)
big_list.append(new_word)
return big_list
b_list = parse_data('A1T6RFUU0OTS0M.txt')
k_list = headers(key_name)
def f_un(things):
for t in things:
return t
h_list = f_un(k_list)
def f_in(stuff):
for sf in stuff:
for s in sf:
print(s)
z = 0
head_r = "h_list[z]"
if s.startswith(head_r):
s.strip(head_r)
h_list.append(s)
z += 1
print(stuff)
f_in(b_list)
</code></pre>
| 0 | 2016-08-21T21:26:41Z | 39,069,295 | <p>I'm still having a hard time understanding the question, but if my guess is right, I think this is what you need. Note that this code uses the excellent <a href="http://docs.python-tablib.org/en/latest/" rel="nofollow"><code>tablib</code> module</a>:</p>
<pre><code>from collections import defaultdict
import re
import tablib
data = defaultdict(list)
# input.txt:
# [t_show:[1471531808217,1471531809222,1471531809723,147153181ââ2159,1471531815049],âât_remove:[1471531809ââ222,1471531809722,14ââ71531812158,14715318ââ15046,null],param:taâârget:0,distractor_shââape:square,stimulus_ââparam:shape1:star,shââape2:plus,relation:bââelow,negate:false,prââompt_format:verbal,tââest_format:visual,d0ââ_type:shape:false,orââder:false,relation:tâârue,d1_type:shape:2,ââorder:true,relation:ââfalse,d2_type:shape:ââ2,order:true,relatioâân:true,encoding_rt:2ââ435,verification_rt:ââ2887,target:0,choiceââ:0,correct:true]
# I had to remove "debrief", "response", and "CompletionCode", since those weren't in the example data
headers = ['distractor_shape','stimulus_param','prompt_format','test_format','d0_type','d1_type','d2_type','encoding_rt','verification_rt', 'target', 'choice','correct']#,'debrief','response','CompletionCode']
with open('input.txt', 'rt') as f:
# The input data seems to have some zero-width unicode characters interspersed.
# This next line removes them.
input = f.read()[1:-1].replace('\u200c\u200b', '')
# This matches things like foo:bar,... as well as foo:[1,2,3],...
for item in re.findall(r'[^,\[]+(?:\[[^\]]*\])?[^,\[]*', input):
# Split on the first colon
key, value = item.partition(':')[::2]
data[key].append(value)
dataset = tablib.Dataset()
dataset.headers = headers
for row in zip(*(data[header] for header in headers)):
dataset.append(row)
with open('out.csv', 'wt') as f:
f.write(dataset.csv)
# out.csv:
# distractor_shape,stimulus_param,prompt_format,test_format,d0_type,d1_type,d2_type,encoding_rt,verification_rt,target,choice,correct
# square,shape1:star,verbal,visual,shape:false,shape:2,shape:2,2435,2887,0,0,true
with open('out.xlsx', 'wb') as f:
f.write(dataset.xlsx)
</code></pre>
| 0 | 2016-08-21T22:10:10Z | [
"python",
"list",
"csv"
] |
Including the same blocks in several pages in Django | 39,069,025 | <p>On my website, blog posts appear in multiple places across the site. I want to create a template like <code>blog_posts.html</code> that given the list of blog posts (as an argument to <code>render</code>) creates the block with these posts, formatted and processed.</p>
<p>There are several disconnected pages to which I want to display <code>blog_posts</code>. Thus, I can not say that <code>blog_posts</code> extend any of them. I wonder if there is a way to insert whatever template processed to arbitrary page? If yes, how to I pass variables (which may be instances of the classes) to the blog_posts template?</p>
| 0 | 2016-08-21T21:28:23Z | 39,069,197 | <p>You can either render <code>blog_posts.html</code> to string and pass it as a variable to the other template:</p>
<pre><code>from django.template.loader import get_template
blog_posts = get_template('/path/to/blog_posts.htm')
somevar = blog_posts.render({'foo': 'foo', 'bar': 'baz'})
</code></pre>
<p>then place <code>{{ somevar }}</code> in the other template - or just <code>{% include '/path/to/blog_posts.html' %}</code> in the other; the included template will have access to all variables passed to the 'parent' one.</p>
| 1 | 2016-08-21T21:54:34Z | [
"python",
"django",
"django-templates"
] |
Including the same blocks in several pages in Django | 39,069,025 | <p>On my website, blog posts appear in multiple places across the site. I want to create a template like <code>blog_posts.html</code> that given the list of blog posts (as an argument to <code>render</code>) creates the block with these posts, formatted and processed.</p>
<p>There are several disconnected pages to which I want to display <code>blog_posts</code>. Thus, I can not say that <code>blog_posts</code> extend any of them. I wonder if there is a way to insert whatever template processed to arbitrary page? If yes, how to I pass variables (which may be instances of the classes) to the blog_posts template?</p>
| 0 | 2016-08-21T21:28:23Z | 39,069,425 | <p>you might want to consider using template tags. Something like the inclusion tag should serve you well (see here for docs <a href="https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#inclusion-tags" rel="nofollow">https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#inclusion-tags</a>)</p>
<p>You could use the takes_context argument to pass the data. So that any page you want to use the inclusion tag on you could already populate that page with a context variable of 'data' in the view then this function would pickup on it like this</p>
<pre><code>@register.inclusion_tag('/path/to/blog_posts.html', takes_context=True)
def blog_posts(context):
return {
'blog_posts': context['data'],
}
</code></pre>
<p>Then usage in you html file you want to pull blog posts into</p>
<pre><code>{% blog_posts %}
</code></pre>
<p>Usage from any views. make sure you set data anywhere you want to also use the template tag</p>
<pre><code>def example_view(request):
context = {'data': Blog.objects.all()}
return render(request, 'example.html', context)
</code></pre>
<p>Another option is to explicitly pass it in as an argument like this</p>
<pre><code>@register.inclusion_tag('/path/to/blog_posts.html')
def blog_posts(context, data):
return {
'blog_posts': data,
}
</code></pre>
<p>Then usage</p>
<pre><code>{% blog_posts data %}
</code></pre>
<p>and of course your blog_posts.html file that is used in the inclusion tag would do something like looping over the data</p>
<pre><code><div>
{% for post in blog_posts %}
<p>{{ post.name}}
{% endfor %}
</div>
</code></pre>
| 0 | 2016-08-21T22:33:39Z | [
"python",
"django",
"django-templates"
] |
Files are corrupted after transfer them to a FTP server using ftplib | 39,069,038 | <p>I've got a problem with the ftplib library when I'm uploading .gz files.</p>
<p>The script was working before but somehow in one of my thousands of editions, I changed something that is causing to transfer corrupted files.
The files is successfully transferred to the ftp server, however, that files when is being used in the ftp won't open because is corrupted.</p>
<p>The files which are going to be transferred are without any issues. Also if the files are not compressed, the transfer has not any issues. It's something with the way it reads .gz</p>
<p>Can anyone let me know what is wrong with the code?</p>
<pre><code>for filename in dir:
os.system("gzip %s/%s" % (Path, filename))
time.sleep(5) # Wait up to 4 seconds to compress file
zip_filename = filename + '.gz'
try:
# Connect to the host
ftp = ftplib.FTP(host)
# Login to the ftp server
ftp.login(username, password)
# Transfer the file
myfile = open(zip_filename, 'rb')
ftp.storlines("STOR temp/" + zip_filename, myfile)
myfile.close()
except ftplib.all_errors as e:
print(e)
</code></pre>
| 0 | 2016-08-21T21:29:46Z | 39,069,217 | <p>The issue was the use of storlines. In this case, needs to be use storbinary</p>
| 1 | 2016-08-21T21:57:09Z | [
"python",
"ftp",
"ftplib"
] |
Employing Post Method in Flask | 39,069,061 | <p>Using the following:</p>
<pre><code>from flask import Flask, render_template
import beautiful_soup_tidal
app = Flask(__name__)
@app.route('/')
def form():
return render_template('form_submit.html')
@app.route('/richmond', methods=['POST'])
def richmond():
someTides = beautiful_soup_tidal.getTides()
return render_template('richmond.html',someTides=someTides)
if __name__ == "__main__":
app.run(debug=True)
</code></pre>
<p>And attempting to render the following (richmond.html):</p>
<pre><code><div id="content" class="form-group">
<form method="post" action="/richmond">
<label style="vertical-align: middle;">channel depth at mean low water
<input type="number" step="0.1" value = "34.5" name="channelDepth"/>FEET</label><br><br>
<label style="vertical-align: middle;">required underkeel clearance
<input type="number" step="0.1" value = "2" name="underkeelClearance"/>FEET</label><br><br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</code></pre>
<p>I get the following error: 'The method is not allowed for the requested URL.'</p>
<p>If I delete ', methods=['POST']' in the first section the template renders.</p>
<p>The question: How do I render the template successfully using the post method?</p>
| -1 | 2016-08-21T21:33:47Z | 39,069,465 | <p>i believe this line should also include GET so that you can render the html form first time round before you actually click submit to post it.</p>
<pre><code>@app.route('/richmond', methods=['POST'])
</code></pre>
<p>so it would change to</p>
<pre><code>@app.route('/richmond', methods=['GET', 'POST'])
</code></pre>
| 0 | 2016-08-21T22:39:42Z | [
"python",
"flask"
] |
PyQT QFileDialog - get full directory including IP of disk | 39,069,089 | <p>I'd like to get full path of my directory, something like:</p>
<pre><code>//192.168.1.23/D/test/test/aaaa/
</code></pre>
<p>or</p>
<pre><code>//192.168.1.23/D:/test/test/aaaa/
</code></pre>
<p>How can I get QFileDialog to give me the IP address of the HDD that I have selected? </p>
<p>Currently using </p>
<pre><code>self.project= str(QtGui.QFileDialog.getExistingDirectory(self, "Select Directory", lastDir))
</code></pre>
<p>tried going via <code>os.path.dirname(self.project)</code> but that only ever goes down to <code>D:\</code></p>
<p>Thanks!</p>
| 0 | 2016-08-21T21:37:51Z | 39,069,172 | <p>What you want to do is not possible in PyQt directly with <code>QFileDialog</code> what you can do instead is to get the ip address of your machine with another method and then concatenate that with the file path, something like this. QFileDialog isn't 'Network aware'</p>
<pre><code>import socket
def get_ip_addr():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
ip = get_ip_addr()
path = self.project= str(QtGui.QFileDialog.getExistingDirectory(self, "Select Directory", lastDir))
file_path = '//{}/{}'.format(ip, path) # or what ever formatting suits you
</code></pre>
<p>You can also take a look at QNetworkInterface <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qnetworkinterface.html#interfaceFromName" rel="nofollow">http://pyqt.sourceforge.net/Docs/PyQt4/qnetworkinterface.html#interfaceFromName</a> if you're interested in other addresses on your machine, but the example above just returns the ip address that's used to route to <code>8.8.8.8</code></p>
| 1 | 2016-08-21T21:52:09Z | [
"python",
"pyqt",
"pyqt4",
"qfiledialog"
] |
PyQT QFileDialog - get full directory including IP of disk | 39,069,089 | <p>I'd like to get full path of my directory, something like:</p>
<pre><code>//192.168.1.23/D/test/test/aaaa/
</code></pre>
<p>or</p>
<pre><code>//192.168.1.23/D:/test/test/aaaa/
</code></pre>
<p>How can I get QFileDialog to give me the IP address of the HDD that I have selected? </p>
<p>Currently using </p>
<pre><code>self.project= str(QtGui.QFileDialog.getExistingDirectory(self, "Select Directory", lastDir))
</code></pre>
<p>tried going via <code>os.path.dirname(self.project)</code> but that only ever goes down to <code>D:\</code></p>
<p>Thanks!</p>
| 0 | 2016-08-21T21:37:51Z | 39,450,031 | <p>Not sure where I found it but here is the option I followed at the end. I let user decide then which device to use for location</p>
<pre><code>from netifaces import interfaces, ifaddresses, AF_INET
p =[]
for ifaceName in interfaces():
addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
p.append(ifaceName.join(addresses))
print p[0],p[1]
print p
</code></pre>
| 0 | 2016-09-12T12:11:23Z | [
"python",
"pyqt",
"pyqt4",
"qfiledialog"
] |
When do I have to initialize variables in Tensorflow? | 39,069,130 | <p>I am trying to understand tensor flow and how understand it one has to first create ops and variables add them to the graph and then in a session those operations will be performed.
Then why in this piece of code I don't have to use the method initialize_all_variables()?
I was trying to add <code>init = tf.initialize_all_variables()</code> and then <code>sess.run(init)</code> but it was wrong. Why is this working without the initialization??</p>
<pre><code>import tensorflow as tf
import numpy as np
x = tf.placeholder('float', [2,3])
y = x*2
z = tf.Variable([[1,1,1],[1,1,1]], name = "z")
with tf.Session() as sess:
x_data = np.arange(1,7).reshape((2,3))
z.assign(x_data)
res = sess.run(y, feed_dict = {x:x_data})
print(res.dtype, z.dtype, z.get_shape())`
</code></pre>
| 0 | 2016-08-21T21:45:08Z | 39,069,688 | <p>You are not allowed to read an uninitialized value. In the case above you are not reading <code>z</code> hence you don't need to initialize it.</p>
<p>If you look at at <code>variables.py</code> you see that <code>initialize_all_variables is a group node connected to all initializers</code></p>
<pre><code>def initialize_variables(var_list, name="init"):
...
return control_flow_ops.group(
*[v.initializer for v in var_list], name=name)
</code></pre>
<p>Looking at <code>z.initializer</code>, you can see it's an <code>Assign</code> node. So evaluating <code>tf.initialize_all_variables</code> in TensorFlow is the same as doing <code>session.run</code> on <code>z.assign(...</code></p>
| 0 | 2016-08-21T23:23:33Z | [
"python",
"tensorflow"
] |
pip install python-libtorrent==1.1.0 fails on linux | 39,069,168 | <p>Title is self explanatory. I get the following error in linux and python2.7:</p>
<pre><code>Could not find a version that satisfies the requirement python-libtorrent (from versions: )
No matching distribution found for python-libtorrent
</code></pre>
<p>I can see it listed on pypi:</p>
<p><a href="https://pypi.python.org/pypi/python-libtorrent/" rel="nofollow">https://pypi.python.org/pypi/python-libtorrent/</a></p>
<p>so, why would it not install?</p>
<p>Thanks!</p>
| 2 | 2016-08-21T21:51:34Z | 39,069,220 | <p>The package in question, and its version, has been registered to PyPI. However there is no downloadable distribution file at all. Either the author/maintainer forgot to upload it (or them), or it was later removed.</p>
<p>If a distribution was uploaded, it should show up on the <a href="https://pypi.python.org/pypi/python-libtorrent/1.1.0" rel="nofollow">1.1.0 release page</a>; there should be a table that lists all distribution files, their formats, Python version, upload date and the size of that individual file. Compare with say (just a random linked package) <a href="https://pypi.python.org/pypi/PyTorrent/0.1.1" rel="nofollow">PyTorrent-0.1.1</a> that has an .egg binary distribution file <code>PyTorrent-0.1.1-py2.5.egg</code> in there.</p>
| 2 | 2016-08-21T21:57:49Z | [
"python",
"libtorrent"
] |
I´m getting the error, "atan2() takes exactly 2 arguments (1 given)" | 39,069,376 | <p>I´m new to programing so I have no idea what went wrong. please help</p>
<pre><code>from math import atan2, pi
x = int(input("value of x"))
y = int(input("value of y"))
r = (x**2 + y**2) ** 0.5
ang = atan2(y/x)
print("Hypotenuse is", r, "angle is", ang)
</code></pre>
| 2 | 2016-08-21T22:23:55Z | 39,069,394 | <p>The reason for that error is that <code>atan2</code> requires two arguments. Observe:</p>
<pre><code>>>> from math import atan, atan2
>>> atan(2)
1.1071487177940904
>>> atan2(4, 2)
1.1071487177940904
</code></pre>
<p>Note that <code>atan(y/x)</code> does not work if <code>x</code> is zero but <code>atan2(y, x)</code> will continue to work just fine:</p>
<pre><code>>>> atan(4/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> atan2(4, 0)
1.5707963267948966
</code></pre>
| 2 | 2016-08-21T22:27:29Z | [
"python",
"atan2"
] |
I´m getting the error, "atan2() takes exactly 2 arguments (1 given)" | 39,069,376 | <p>I´m new to programing so I have no idea what went wrong. please help</p>
<pre><code>from math import atan2, pi
x = int(input("value of x"))
y = int(input("value of y"))
r = (x**2 + y**2) ** 0.5
ang = atan2(y/x)
print("Hypotenuse is", r, "angle is", ang)
</code></pre>
| 2 | 2016-08-21T22:23:55Z | 39,069,397 | <p>In Python, there are 2 arctangent functions: <code>atan</code> is simply the inverse of <code>tan</code>; but <code>atan2</code> takes 2 arguments. In your case since you know both catheti, you could as well use the 2-argument function <code>atan2</code>:</p>
<pre><code>ang = atan2(y, x)
</code></pre>
<p>Alternatively, you might write</p>
<pre><code>ang = atan(y / x)
</code></pre>
<hr>
<p>The rationale for <code>atan2</code> is that it works correctly even if <code>x</code> is 0; while with <code>atan(y / x)</code> a <code>ZeroDivisionError: float division by zero</code> would be raised. </p>
<p>Additionally, <code>atan</code> can only give an angle between -Ï/2 ... +Ï/2, whereas <code>atan2</code> knows the signs of both <code>y</code> and <code>x</code>, and thus can know which of the 4 quadrants the value falls to; its value ranges from -Ï to +Ï. Though, of course you wouldn't have a triangle with negative width or height...</p>
| 4 | 2016-08-21T22:28:11Z | [
"python",
"atan2"
] |
How do I detect where dlib's correlation_tracker lost the target image? | 39,069,480 | <p>I added a correlation_tracker to a multithreaded face <a href="http://blog.dlib.net/2015/02/dlib-1813-released.html" rel="nofollow">tracking script</a>, and oddly enough, it generally does well tracking a face on the screen, but when you put your hand over the camera it keeps saying the same coordinates and highlighting the same area. Is there a good way to detect when the tracked object actually leaves? Or does this require processing the slower detect-all-the-faces detector object once in awhile?</p>
<pre><code>from __future__ import division
import sys
from time import time, sleep
import threading
import dlib
#from skimage import io
detector = dlib.get_frontal_face_detector()
win = dlib.image_window()
def adjustForOpenCV( image ):
""" OpenCV use bgr not rgb. odd. """
for row in image:
for px in row:
#rgb expected... but the array is bgr?
r = px[2]
px[2] = px[0]
px[0] = r
return image
class webCamGrabber( threading.Thread ):
def __init__( self ):
threading.Thread.__init__( self )
#Lock for when you can read/write self.image:
#self.imageLock = threading.Lock()
self.image = False
from cv2 import VideoCapture, cv
from time import time
self.cam = VideoCapture(0) #set the port of the camera as before
#Doesn't seem to work:
self.cam.set(cv.CV_CAP_PROP_FRAME_WIDTH, 160)
self.cam.set(cv.CV_CAP_PROP_FRAME_WIDTH, 120)
#self.cam.set(cv.CV_CAP_PROP_FPS, 1)
def run( self ):
while True:
start = time()
#self.imageLock.acquire()
retval, self.image = self.cam.read() #return a True bolean and and the image if all go right
#print( "readimage: " + str( time() - start ) )
#sleep(0.1)
if len( sys.argv[1:] ) == 0:
#Start webcam reader thread:
camThread = webCamGrabber()
camThread.start()
#Setup window for results
detector = dlib.get_frontal_face_detector()
win = dlib.image_window()
while True:
#camThread.imageLock.acquire()
if camThread.image is not False:
print( "enter")
start = time()
myimage = camThread.image
for row in myimage:
for px in row:
#rgb expected... but the array is bgr?
r = px[2]
px[2] = px[0]
px[0] = r
dets = detector( myimage, 0)
#camThread.imageLock.release()
print "your faces:" +str( len(dets) )
nearFace = None
nearFaceArea = 0
for i, d in enumerate( dets ):
#print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
# i, d.left(), d.top(), d.right(), d.bottom()))
screenArea = (d.right() - d.left()) * (d.bottom() - d.top())
#print 'area', screenArea
if screenArea > nearFaceArea:
nearFace = d
print( "face-find-time: " + str( time() - start ) )
print("from left: {}".format( ( (nearFace.left() + nearFace.right()) / 2 ) / len(camThread.image[0]) ))
print("from top: {}".format( ( (nearFace.top() + nearFace.bottom()) / 2 ) / len(camThread.image)) )
start = time()
win.clear_overlay()
win.set_image(myimage)
win.add_overlay(nearFace)
print( "show: " + str( time() - start ) )
if nearFace != None:
points = (nearFace.left(), nearFace.top(), nearFace.right(), nearFace.bottom() )
tracker = dlib.correlation_tracker()
tracker.start_track( myimage, dlib.rectangle(*points))
while True:
myImage = adjustForOpenCV( camThread.image )
tracker.update( myImage )
rect = tracker.get_position()
cx = (rect.right() + rect.left()) / 2
cy = (rect.top() + rect.bottom()) / 2
print( 'correlationTracker %s,%s' % (cx, cy) )
print rect
win.clear_overlay()
win.set_image( myImage )
win.add_overlay( rect )
sleep( 0.1 )
#dlib.hit_enter_to_continue()
for f in sys.argv[1:]:
print("Processing file: {}".format(f))
img = io.imread(f)
# The 1 in the second argument indicates that we should upsample the image
# 1 time. This will make everything bigger and allow us to detect more
# faces.
dets = detector(img, 1)
print("Number of faces detected: {}".format(len(dets)))
for i, d in enumerate(dets):
print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
i, d.left(), d.top(), d.right(), d.bottom()))
win.clear_overlay()
win.set_image(img)
win.add_overlay(dets)
dlib.hit_enter_to_continue()
# Finally, if you really want to you can ask the detector to tell you the score
# for each detection. The score is bigger for more confident detections.
# Also, the idx tells you which of the face sub-detectors matched. This can be
# used to broadly identify faces in different orientations.
if (len(sys.argv[1:]) > 0):
img = io.imread(sys.argv[1])
dets, scores, idx = detector.run(img, 1)
for i, d in enumerate(dets):
print("Detection {}, score: {}, face_type:{}".format(
d, scores[i], idx[i]))
</code></pre>
| 1 | 2016-08-21T22:41:52Z | 39,069,633 | <p>You must run the face detector every now and then to see if the face is still there. </p>
| 1 | 2016-08-21T23:13:42Z | [
"python",
"computer-vision",
"dlib"
] |
How to extract the strong elements which are in div tag | 39,069,497 | <p>I am new to web scraping. I am using Python to scrape the data.
Can someone help me in how to extract data from:</p>
<pre><code><div class="dept"><strong>LENGTH:</strong> 15 credits</div>
</code></pre>
<p>My output should be LENGTH: <code>15 credits</code></p>
<p>Here is my code:</p>
<pre><code>from urllib.request import urlopen
from bs4 import BeautifulSoup
length=bsObj.findAll("strong")
for leng in length:
print(leng.text,leng.next_sibling)
</code></pre>
<p>Output:</p>
<pre><code>DELIVERY: Campus
LENGTH: 2 years
OFFERED BY: Olin Business School
</code></pre>
<p>but I would like to have only LENGTH.</p>
<p>Website: <a href="http://www.mastersindatascience.org/specialties/business-analytics/" rel="nofollow">http://www.mastersindatascience.org/specialties/business-analytics/</a></p>
| 1 | 2016-08-21T22:44:55Z | 39,069,502 | <p>You should improve your code a bit to locate the <code>strong</code> element <a class='doc-link' href="http://stackoverflow.com/documentation/beautifulsoup/1940/locating-elements/6339/locate-a-text-after-an-element-in-beautifulsoup#t=20160821225134749343"><em>by text</em></a>:</p>
<pre><code>soup.find("strong", text="LENGTH:").next_sibling
</code></pre>
<p>Or, for multiple lengths:</p>
<pre><code>for length in soup.find_all("strong", text="LENGTH:"):
print(length.next_sibling.strip())
</code></pre>
<p>Demo:</p>
<pre><code>>>> import requests
>>> from bs4 import BeautifulSoup
>>>
>>> url = "http://www.mastersindatascience.org/specialties/business-analytics/"
>>> response = requests.get(url)
>>> soup = BeautifulSoup(response.content, "html.parser")
>>> for length in soup.find_all("strong", text="LENGTH:"):
... print(length.next_sibling.strip())
...
33 credit hours
15 months
48 Credits
...
12 months
1 year
</code></pre>
| 2 | 2016-08-21T22:46:29Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Python Tkinter Scrollbar Not Working | 39,069,544 | <p>I'm working on a new program in Python 3 with tkinter. I'm trying to add a scrollbar to the whole window, but it isn't working. Right now I'm just trying to make the window 1000 pixels tall (will be set later in the program) and use the a vertical scrollbar to access the parts not seen on screen. I've read multiple other threads trying to figure it out and have attempted. Could someone tell how to get it to work and what I did wrong. No error is displayed, but also no scrollbar is displayed. Here's the code:</p>
<pre><code>from tkinter import *
class MusicPlayer:
def __init__(self):
self.tk = Tk()
self.tk.title("Bass Blaster")
self.screen_width, self.screen_height = self.tk.winfo_screenwidth(), self.tk.winfo_screenheight()
self.frame = Frame(self.tk, width=self.screen_width, height=self.screen_height)
self.frame.grid(row=0, column=0)
self.canvas = Canvas(self.frame, bg="#585858", width=self.screen_width, height=self.screen_height, scrollregion=(0, 0, self.screen_width, 1000))
vbar = Scrollbar(self.frame, orient=VERTICAL)
vbar.pack(side=RIGHT, fill=Y)
vbar.config(command=self.canvas.yview)
self.canvas.config(width=self.screen_width, height=self.screen_height)
self.canvas.config(yscrollcommand=vbar.set)
self.canvas.pack(side=LEFT, expand=True, fill=BOTH)
self.tk.update()
bass_blaster = MusicPlayer()
bass_blaster.tk.mainloop()
</code></pre>
| 0 | 2016-08-21T22:54:48Z | 39,177,453 | <p>The scroll bar was there the whole time, the problem was that I made the canvas width the screen's size and the scroll bar was adding onto the width, therefore going off the screen. I just had to make the width a little less.</p>
| 0 | 2016-08-27T04:26:48Z | [
"python",
"tkinter"
] |
How to use override parameters of a fixture in Pytest? | 39,069,551 | <p>Let's say I have a parameterized fixture like this:</p>
<pre><code>@pytest.fixture(params=[1, 2, 800]):
def resource(request):
return Resource(capacity=request.param)
</code></pre>
<p>When I use the fixture as parameter in a test function, Pytest runs the test with all three versions:</p>
<pre><code>def test_resource(resource): # Runs for capacities 1, 2, and 800.
assert resource.is_okay()
</code></pre>
<p>However, for some tests I want to change the parameters for which the fixture gets built:</p>
<pre><code>def test_worker(resource, worker): # Please run this for capacities 1 and 5.
worker.use(resource)
assert worker.is_okay()
</code></pre>
<p>How can I specify to only receive certain versions of the specified fixture?</p>
| 0 | 2016-08-21T22:56:57Z | 39,069,653 | <p>I don't think that you can configure it <em>"to only receive certain versions"</em>, but you can explicitly ignore some of them:</p>
<pre><code>def test_worker(resource, worker):
if resource.capacity == 800:
pytest.skip("reason why that value won't work")
worker.use(resource)
assert worker.is_okay()
</code></pre>
| 2 | 2016-08-21T23:17:02Z | [
"python",
"python-3.x",
"py.test",
"fixtures"
] |
How to use override parameters of a fixture in Pytest? | 39,069,551 | <p>Let's say I have a parameterized fixture like this:</p>
<pre><code>@pytest.fixture(params=[1, 2, 800]):
def resource(request):
return Resource(capacity=request.param)
</code></pre>
<p>When I use the fixture as parameter in a test function, Pytest runs the test with all three versions:</p>
<pre><code>def test_resource(resource): # Runs for capacities 1, 2, and 800.
assert resource.is_okay()
</code></pre>
<p>However, for some tests I want to change the parameters for which the fixture gets built:</p>
<pre><code>def test_worker(resource, worker): # Please run this for capacities 1 and 5.
worker.use(resource)
assert worker.is_okay()
</code></pre>
<p>How can I specify to only receive certain versions of the specified fixture?</p>
| 0 | 2016-08-21T22:56:57Z | 39,378,910 | <p>If you want to use different set of parameters for different tests then <code>pytest.mark.parametrize</code> is helpful. </p>
<pre><code>@pytest.mark.parametrize("resource", [1, 2, 800], indirect=True)
def test_resource(resource):
assert resource.is_okay()
@pytest.mark.parametrize("resource", [1, 5], indirect=True)
def test_resource_other(resource):
assert resource.is_okay()
</code></pre>
| 1 | 2016-09-07T20:59:40Z | [
"python",
"python-3.x",
"py.test",
"fixtures"
] |
How to install mesos.native python module in Mac OS and Ubuntu | 39,069,553 | <p>I would like to write and run a Mesos framework with Python, so I need mesos.native module.</p>
<p>On Ubuntu:</p>
<p>I can build mesos from source code. I tried to easy_install all the generated egg files but none of them made it possible for Python to import mesos.native.</p>
<p>I also tried to download the egg from <a href="http://downloads.mesosphere.io/master/ubuntu/14.04/mesos-0.20.1-py2.7-linux-x86_64.egg" rel="nofollow">http://downloads.mesosphere.io/master/ubuntu/14.04/mesos-0.20.1-py2.7-linux-x86_64.egg</a> and easy_install it, which didn't work as well.</p>
<p>On Max OS:</p>
<p>Got some problem building the mesos source code because of <a href="https://issues.apache.org/jira/browse/MESOS-799" rel="nofollow">the issue</a>. So I am wondering whether there is an easy way to install the Python module without building the source code.</p>
<p>BTW, why don't they make the mesos.native pip-installable like mesos.interface?</p>
| 0 | 2016-08-21T22:57:23Z | 39,072,413 | <p>Problem solved: <a href="https://github.com/RobinDong/mesos-python-examples/blob/master/calculate_pi/pi_run" rel="nofollow">https://github.com/RobinDong/mesos-python-examples/blob/master/calculate_pi/pi_run</a></p>
<p>I just need to set PYTHONPATH as that in the file and run python. Mesos.native can be successfully loaded.</p>
| 0 | 2016-08-22T06:13:49Z | [
"python",
"mesos",
"mesosphere"
] |
What is this "join" doing? | 39,069,701 | <p>I just installed retext via pip. I have to download icons for it but I realise it doesn't work (no icons on the menu) unless i run "retext" in the folder of retext.</p>
<p>I tried to fix it but my python skills are not very strong.</p>
<p>At the moment, I force the icon_path to have the path I want.</p>
<pre><code>#icon_path = 'icons/'
icon_path = '/usr/local/lib/python3.5/site-packages/retext/icons/'
</code></pre>
<p>Can someone enlighten me how this line works?</p>
<pre><code>datadirs = [join(d, 'retext') for d in datadirs]
</code></pre>
<p>Thanks.</p>
<pre><code>import sys
import markups
import markups.common
from os.path import dirname, exists, join
from PyQt5.QtCore import QByteArray, QLocale, QSettings, QStandardPaths
from PyQt5.QtGui import QFont
app_version = "6.0.1"
settings = QSettings('ReText project', 'ReText')
if not str(settings.fileName()).endswith('.conf'):
# We are on Windows probably
settings = QSettings(QSettings.IniFormat, QSettings.UserScope,
'ReText project', 'ReText')
datadirs = QStandardPaths.standardLocations(QStandardPaths.GenericDataLocation)
datadirs = [join(d, 'retext') for d in datadirs]
if sys.platform == "win32":
# Windows compatibility: Add "PythonXXX\share\" path
datadirs.append(join(dirname(sys.executable), 'share', 'retext'))
if '__file__' in locals():
datadirs = [dirname(dirname(__file__))] + datadirs
#icon_path = 'icons/'
icon_path = '/usr/local/lib/python3.5/site-packages/retext/icons/'
for dir in datadirs:
if exists(join(dir, 'icons')):
icon_path = join(dir, 'icons/')
break
</code></pre>
| 1 | 2016-08-21T23:26:15Z | 39,069,786 | <p>This is <a href="https://docs.python.org/3/library/os.path.html#os.path.join" rel="nofollow"><code>os.path.join()</code></a>:</p>
<blockquote>
<p><code>os.path.join(path, *paths)</code></p>
<p>Join one or more path components intelligently. The return value is the concatenation of path and any members of <code>*paths</code> with exactly one directory separator (<code>os.sep</code>) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.</p>
</blockquote>
<p>It is imported here:</p>
<pre><code>from os.path import dirname, exists, join
</code></pre>
<p>So, the line in question:</p>
<pre><code>datadirs = [join(d, 'retext') for d in datadirs]
</code></pre>
<p>The <code>[</code>...<code>]</code> is a <a class='doc-link' href="https://stackoverflow.com/documentation/python/196/comprehensions/737/list-comprehensions">List Comprehension</a> that builds a list of the results of <code>join(d, 'retext')</code> applied to each directory in the <code>datadirs</code> list.</p>
<p>So, if <code>datadirs</code> contained:</p>
<pre><code>['/usr/local/test', '/usr/local/testing', '/usr/local/tester']
</code></pre>
<p>Then:</p>
<pre><code>[join(d, 'retext') for d in datadirs]
</code></pre>
<p>Would produce:</p>
<pre><code>['/usr/local/test/retext', '/usr/local/testing/retext', '/usr/local/tester/retext']
</code></pre>
<p>The problem with setting:</p>
<pre><code>icon_path = '/usr/local/lib/python3.5/site-packages/retext/icons/'
</code></pre>
<p>Is that it's being overwritten in the <code>for</code> loop, so unless a proper path is not found, it will be overwritten.</p>
| 0 | 2016-08-21T23:41:26Z | [
"python",
"list",
"join",
"expression"
] |
Python thread won't start using socket | 39,069,704 | <p>i have a problem with my progam using socket and thread.</p>
<p>I have made a socket server who add client in a thread, but the client thread never start...</p>
<p>here is my code:</p>
<p>socket server</p>
<pre><code>import socket, threading, logging, sys
from client_thread import ClientThread
class SocketServer:
CLIENTS = list()
def __init__(self, server_ip, server_port, max_connections):
try:
self.tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.tcpsock.bind((server_ip, server_port))
self.tcpsock.listen(10)
logging.info('Socket server successfully started !')
except Exception as e:
logging.error(format(e))
def start(self):
from src.realmserver.core.hetwan import EmulatorState, Core
while (Core.STATE == EmulatorState.IN_RUNNING):
try:
(clientsock, (ip, port)) = self.tcpsock.accept()
new_client = threading.Thread(target=ClientThread, args=[len(self.CLIENTS), ip, port, clientsock])
self.CLIENTS.append(new_client)
new_client.start()
except Exception as e:
print format(e)
for client in self.CLIENTS:
client.join()
</code></pre>
<p>and client thread</p>
<pre><code>import logging, string, random
class ClientThread:
def __init__(self, client_id, client_ip, client_port, socket):
self.client_id = client_id
self.client_ip = client_ip
self.client_port = client_port
self.socket = socket
logging.debug('(%d) Client join us !', client_id)
def run(self):
key = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(32))
print self.send('HC%s' % key)
while True:
entry = self.socket.recv(4096)
entry.replace("\n", "")
if not entry:
break
else:
logging.debug('(%d) Packet received : %s', self.client_id, str(entry))
self.kill()
def send(self, packet):
return self.socket.send("%s\x00" % packet)
def kill(self):
self.socket.close()
logging.debug('(%d) Client is gone...', self.client_id)
</code></pre>
<p>sorry for bad indentation, it's the form, not my file.</p>
<p>Please help me :(</p>
<p>Thank you in advance (sorry for bad english i'm french....)</p>
| 2 | 2016-08-21T23:26:52Z | 39,070,010 | <p>You have this line of code in your <code>Server</code> instance <code>start</code> function:</p>
<pre><code>new_client = threading.Thread(target=ClientThread,
args=[len(self.CLIENTS), ip, port, clientsock])
</code></pre>
<p>The <code>target=</code> argument to <code>threading.Thread</code> needs to be a callable function. Here <code>ClientThread</code> is the name of the constructor function for your class <code>ClientThread</code>, so it <em>is</em> a callable function, returning an instance of that class. Note that it is not actually called yet! The <code>args=</code> argument is more normally a tuple, but a list actually works. These are the arguments that will be passed to the <code>target</code> function once it's eventually called, when you use this particular threading model. (You can also pass keyword arguments using <code>kwargs=</code> and a dictionary.)</p>
<p>What happens now is a bit tricky. Now that the two parameters (<code>target=</code> and <code>args=</code>) have been evaluated, the Python runtime creates a new instance of a <code>threading.Thread</code> class. This new instance is, at the moment, <em>just</em> a data object.</p>
<p>If we add a <code>print</code> statement/function (it's not clear whether this is py2k or py3k code) we can see the object itself:</p>
<pre><code>print('new_client id is', id(new_client))
</code></pre>
<p>which will print something like:<sup>1</sup></p>
<pre><code>new_client id is 34367605072
</code></pre>
<p>Next, you add this to a list and then invoke its <code>start</code>:</p>
<pre><code>self.CLIENTS.append(new_client)
new_client.start()
</code></pre>
<p>The list add is straightforward enough, but the <code>start</code> is pretty tricky.</p>
<p>The <code>start</code> call itself actually creates a new OS/runtime thread (whose ID is not related to the data object's IDâthe raw thread ID is an internal implementation detail). This new thread starts running at its <code>run</code> method.<sup>2</sup> The default <code>run</code> method is in fact:<sup>3</sup></p>
<pre><code>try:
if self.__target:
self.__target(*self.__args, **self.__kwargs)
finally:
# Avoid a refcycle if the thread is running a function with
# an argument that has a member that points to the thread.
del self.__target, self.__args, self.__kwargs
</code></pre>
<p>Since you are using a regular <code>threading.Thread</code> instance object, you are getting this default behavior, where <code>new_thread.start()</code> creates the new thread itself, which then calls the default <code>run</code> method, which calls its <code>self.__target</code> which is your <code>ClientThread</code> class-instance-creation function.</p>
<p>So <em>now</em>, inside the new thread, Python creates an instance of a <code>ClientThread</code> object, calling its <code>__init__</code> with the <code>self.__args</code> and <code>self.__kwargs</code> saved in the <code>new_thread</code> instance (which is itself shared between the original Python, and the new thread).</p>
<p>This new <code>ClientThread</code> object executes its <code>__init__</code> code and returns. This is the equivalent of having the <code>run</code> method read:</p>
<pre><code>def run(self):
ClientThread(**saved_args)
</code></pre>
<p>Note that this is <em>not</em>:</p>
<pre><code>def run(self):
tmp = ClientThread(**saved_args)
tmp.run()
</code></pre>
<p>That is, the <code>run</code> method of the <code>ClientThread</code> instance <em>is never called</em>. Only the <code>run</code> method of the <code>threading.Thread</code> instance is called. If you modify your <code>ClientThread</code>'s <code>__init__</code> method to print out <em>its</em> ID, you will see that this ID differs from that of the <code>threading.Thread</code> instance:</p>
<pre><code>class ClientThread:
def __init__(self, client_id, client_ip, client_port, socket):
print('creating', id(self), 'instance')
</code></pre>
<p>which will print a different ID (and definitely print <em>after</em> the <code>new_client id is</code> line):</p>
<pre><code>new_client id is 34367605072
creating 34367777464 instance
</code></pre>
<p>If you add additional <code>print</code>s to your <code>run</code> method you will see that it is never invoked.</p>
<h3>What to do about this</h3>
<p>You have two main options here.</p>
<ul>
<li><p>You can either make your <code>ClientThread</code> a <em>subclass</em> of <code>threading.Thread</code>:</p>
<pre><code>class ClientThread(threading.Thread):
def __init__(self, client_id, client_ip, client_port, socket):
...
threading.Thread.__init__(self)
</code></pre>
<p>In this case, you would create the client object yourself, rather than using <code>threading.Thread</code> to create it:</p>
<pre><code>new_thread = ClientThread(...)
...
new_thread.start()
</code></pre>
<p>The <code>.start</code> method would be <code>threading.Thread.start</code> since you have not overridden that, and that method would then create the actual OS/runtime thread and then call your <code>run</code> method, whichâsince you <em>did</em> override itâwould be <em>your</em> <code>run</code>.</p></li>
<li><p>Or, you can create a standard <code>threading.Thread</code> object, supply it with a <code>target</code>, and have this <code>target</code> invoke your object's <code>run</code> method, e.g.:</p>
<pre><code>new_client = ClientThread(...)
new_thread = threading.Thread(target=new_client.run, ...)
...
new_thread.start()
</code></pre>
<p>The choice is yours: to subclass, or to use separate objects.</p></li>
</ul>
<hr>
<p><sup>1</sup>The actual ID is highly implementation-dependent.</p>
<p><sup>2</sup>The path by which it reaches this <code>run</code> function is somewhat convoluted, passing through bootstrap code that does some internal initialization, then calls <code>self.run</code> for you, passing no arguments. You are only promised that <code>self.run</code> gets entered somehow; you should not rely on the "how".</p>
<p><sup>3</sup>At least, this is the code in Python 2.7 and 3.4; other implementations could vary slightly.</p>
| 3 | 2016-08-22T00:28:22Z | [
"python",
"multithreading",
"sockets"
] |
What is the python way to iterate two list and compute by position? | 39,069,782 | <p>What is the Pythonic way to iterate two list and compute?</p>
<pre><code>a, b=[1,2,3], [4,5,6]
c=[]
for i in range(3):
c.append(a[i]+b[i])
print(c)
[5,7,9]
</code></pre>
<p>Is there a one-liner for <code>c</code> without a for loop?</p>
| 3 | 2016-08-21T23:40:29Z | 39,069,789 | <p>One possibility:</p>
<pre><code>a, b = [1, 2, 3], [4, 5, 6]
c = list(map(sum, zip(a,b)))
</code></pre>
<p>Another option (if it's always just two lists):</p>
<pre><code>c = [x + y for x, y in zip(a, b)]
</code></pre>
<p>Or probably my favorite, which is equivalent to my first example but uses list comprehension instead of <code>map</code>:</p>
<pre><code>c = [sum(numbers) for numbers in zip(a, b)]
</code></pre>
<p>To generalize to a list of lists (rather than a fixed number of lists in different variables):</p>
<pre><code>lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
c = [sum(numbers) for numbers in zip(*lists)]
</code></pre>
| 8 | 2016-08-21T23:42:00Z | [
"python"
] |
What is the python way to iterate two list and compute by position? | 39,069,782 | <p>What is the Pythonic way to iterate two list and compute?</p>
<pre><code>a, b=[1,2,3], [4,5,6]
c=[]
for i in range(3):
c.append(a[i]+b[i])
print(c)
[5,7,9]
</code></pre>
<p>Is there a one-liner for <code>c</code> without a for loop?</p>
| 3 | 2016-08-21T23:40:29Z | 39,069,792 | <p>Use <code>zip</code> and list comprehension:</p>
<pre><code>[x+y for (x,y) in zip(a, b)]
</code></pre>
| 9 | 2016-08-21T23:42:20Z | [
"python"
] |
What is the python way to iterate two list and compute by position? | 39,069,782 | <p>What is the Pythonic way to iterate two list and compute?</p>
<pre><code>a, b=[1,2,3], [4,5,6]
c=[]
for i in range(3):
c.append(a[i]+b[i])
print(c)
[5,7,9]
</code></pre>
<p>Is there a one-liner for <code>c</code> without a for loop?</p>
| 3 | 2016-08-21T23:40:29Z | 39,069,803 | <p>If you are doing this sort of thing often, you should be using <code>numpy</code>:</p>
<pre><code>>>> import numpy as np
>>> a, b=[1,2,3], [4,5,6]
>>> c = np.array(a) + b
>>> c
array([5, 7, 9])
</code></pre>
| 4 | 2016-08-21T23:45:09Z | [
"python"
] |
What is the python way to iterate two list and compute by position? | 39,069,782 | <p>What is the Pythonic way to iterate two list and compute?</p>
<pre><code>a, b=[1,2,3], [4,5,6]
c=[]
for i in range(3):
c.append(a[i]+b[i])
print(c)
[5,7,9]
</code></pre>
<p>Is there a one-liner for <code>c</code> without a for loop?</p>
| 3 | 2016-08-21T23:40:29Z | 39,069,811 | <p><code>zip</code> is the way to go, but the actual title of your question suggests <code>enumerate</code>:</p>
<pre><code>[x+b[i] for i, x in enumerate(a)]
</code></pre>
<p>This sort of thing is helpful if you need the actual <em>position</em> (index) in the computation.</p>
| 3 | 2016-08-21T23:46:30Z | [
"python"
] |
win 10 WinPython Script import xlwings get errors | 39,069,794 | <ol>
<li>Python and xlwings in same folder. comtypes folder in xlwings folder</li>
<li>can't find module named 'com types'</li>
</ol>
<p>The xlwings documentation says to install with pip. This puts xlwings in the C:\Python27 folder. WinPython ends up in the Downloads/WinPython-64bit-3.4.4-3Qtr5/ (1.37GB, btw) moved the xlwings to the WinPython installed folder.</p>
<p>This is way too difficult. Is there a straightforward way to set all this up so I can run a python script and get import xlwings as xw to work?</p>
| 0 | 2016-08-21T23:43:22Z | 39,083,271 | <p>maybe this would work better:</p>
<ul>
<li><p>click on the "WinPython Command Prompt" icon of your WinPython distribution</p></li>
<li><p>in the opening DOS windows, type: </p></li>
</ul>
<blockquote>
<p>pip install xlwings</p>
</blockquote>
| 0 | 2016-08-22T15:20:57Z | [
"python",
"xlwings",
"comtypes"
] |
Python - Integrating entire list with the Gaussian distribution | 39,069,846 | <p>I'm trying to plot the integral of this normal distribution for values greater than x defined as</p>
<p><a href="http://i.stack.imgur.com/LRsHj.gif" rel="nofollow"><img src="http://i.stack.imgur.com/LRsHj.gif" alt="enter image description here"></a></p>
<p>where </p>
<p><a href="http://i.stack.imgur.com/l9vnM.gif" rel="nofollow"><img src="http://i.stack.imgur.com/l9vnM.gif" alt="enter image description here"></a></p>
<p>defining both functions in python</p>
<pre><code>import scipy.integrate as integrate
import numpy as np
def gaussian(x, mu, sig):
norm = 1/np.sqrt(2*np.pi*sig*sig)
return norm * np.exp(-np.power(x - mu, 2.) / (2. * sig*sig))
def gaussianGreater(x, mu, sig):
Integrand = lambda x: gaussian(x, mu, sig)
return integrate.quad(Integrand,-np.Inf, x)[0]
</code></pre>
<p>My problem now lies in the integration bounds of my <code>gaussianGreater</code> function while it is being evaluated through the distribution function. When evaluating, this occurs.</p>
<pre><code>y = gaussianGreater(subdist_1, mu_1, sig_1 )
xd = np.argsort(subdist_1)
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)
ax.plot(subdist_1[xd] ,y[xd] )
ValueError: The truth value of an array with more than one element
is ambiguous. Use a.any() or a.all()
</code></pre>
<p>I tried changing the upper bounds to what the error gave me, but that would return the error <code>'float' object has no attribute '__getitem__'
</code> </p>
<p>Applying a for loop does not work either</p>
<pre><code>[gaussianGreater(x, mu_1, sig_1 ) for x in subdist_1]
TypeError: only integer arrays with one element can be converted to an index
</code></pre>
<p>How do I fix this problem?</p>
| 1 | 2016-08-21T23:54:57Z | 39,070,045 | <p>What you've defined will work only when <code>x</code> is a single <code>float</code>. If what you want is to be able to pass a numpy array, say <code>np.array([0.2, 0.3])</code> and get [N(>0.2), N(>0.3)], then you can use the function as you've already defined and just call the <code>vectorize</code> method. So if <code>a</code> was the numpy array you were using, <code>a.vectorize(gaussianGreater)</code> would get you an array with <code>gaussianGreater</code> applied to each element. You could define another function, <code>vectorGausssianGreater</code> that takes an array and just returns the result of that vectorize call on it. If what you really want is a single function that can take an array value, you could define something like the following:</p>
<pre><code>def gaussian_greater(values, mean, standard_deviation):
def greater_float(upper_bound):
integrand = lambda y: gaussian(y, mean, standard_deviation)
return integrate.quad(integrand, -np.inf, upper_bound)[0]
return values.vectorize(greater)
</code></pre>
| 1 | 2016-08-22T00:36:55Z | [
"python",
"integration",
"normal-distribution"
] |
Python - Integrating entire list with the Gaussian distribution | 39,069,846 | <p>I'm trying to plot the integral of this normal distribution for values greater than x defined as</p>
<p><a href="http://i.stack.imgur.com/LRsHj.gif" rel="nofollow"><img src="http://i.stack.imgur.com/LRsHj.gif" alt="enter image description here"></a></p>
<p>where </p>
<p><a href="http://i.stack.imgur.com/l9vnM.gif" rel="nofollow"><img src="http://i.stack.imgur.com/l9vnM.gif" alt="enter image description here"></a></p>
<p>defining both functions in python</p>
<pre><code>import scipy.integrate as integrate
import numpy as np
def gaussian(x, mu, sig):
norm = 1/np.sqrt(2*np.pi*sig*sig)
return norm * np.exp(-np.power(x - mu, 2.) / (2. * sig*sig))
def gaussianGreater(x, mu, sig):
Integrand = lambda x: gaussian(x, mu, sig)
return integrate.quad(Integrand,-np.Inf, x)[0]
</code></pre>
<p>My problem now lies in the integration bounds of my <code>gaussianGreater</code> function while it is being evaluated through the distribution function. When evaluating, this occurs.</p>
<pre><code>y = gaussianGreater(subdist_1, mu_1, sig_1 )
xd = np.argsort(subdist_1)
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)
ax.plot(subdist_1[xd] ,y[xd] )
ValueError: The truth value of an array with more than one element
is ambiguous. Use a.any() or a.all()
</code></pre>
<p>I tried changing the upper bounds to what the error gave me, but that would return the error <code>'float' object has no attribute '__getitem__'
</code> </p>
<p>Applying a for loop does not work either</p>
<pre><code>[gaussianGreater(x, mu_1, sig_1 ) for x in subdist_1]
TypeError: only integer arrays with one element can be converted to an index
</code></pre>
<p>How do I fix this problem?</p>
| 1 | 2016-08-21T23:54:57Z | 39,082,201 | <p>You can directly use <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.stats.norm.html" rel="nofollow">scipy.stats.norm</a>'s survival function for 1 - F(x):</p>
<pre><code>import scipy.stats as ss
x = np.linspace(-3, 3, 100)
y = ss.norm.sf(x) # you can pass its mean and std. dev. as well
plt.plot(x, y)
</code></pre>
<p><a href="http://i.stack.imgur.com/wPysz.png" rel="nofollow"><img src="http://i.stack.imgur.com/wPysz.png" alt="enter image description here"></a></p>
| 1 | 2016-08-22T14:31:07Z | [
"python",
"integration",
"normal-distribution"
] |
Gtk+ FlowBox selection not working | 39,069,891 | <p>I'm currently developing a PyGObject app and I'm having issues selecting specific children in a Gtk+ FlowBox. Even after selecting the FlowBox selection mode (SINGLE) populating the FlowBox and writing code to select a specific child, the first child is always selected.</p>
<pre><code>#!/usr/bin/python
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gio
class App(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="App")
flowbox = Gtk.FlowBox()
flowbox.set_valign(Gtk.Align.START)
flowbox.set_selection_mode(Gtk.SelectionMode.SINGLE)
# Drawing 3 squares
flowbox.add(self.drawing_area())
flowbox.add(self.drawing_area())
flowbox.add(self.drawing_area())
child = flowbox.get_child_at_index(2)
flowbox.select_child(child)
flowbox.queue_draw()
self.add(flowbox)
def drawing_area(self):
preview = Gtk.DrawingArea()
preview.connect("draw", self.draw_square)
preview.set_size_request(150, 150)
return preview
def draw_square(self, widget, cr):
cr.scale(150, 150)
style_context = widget.get_style_context()
color = style_context.get_color(Gtk.StateFlags.NORMAL)
cr.set_source_rgba(*color)
cr.rectangle(0, 0, 1, 1)
cr.fill()
window = App()
window.connect("delete-event", Gtk.main_quit)
window.show_all()
Gtk.main()
</code></pre>
<p>Even though I choose to select the child at index 2, the app only ever shows the first child being selected:
<a href="http://i.stack.imgur.com/mtsbK.png" rel="nofollow">Screenshot of above code running</a></p>
<p>The strange part is that when I check to see which child is selected using the following code (placed before the "self.add(flowbox)" line), the Terminal displays that the child I specified to be selected (at index 2) is the only selected child, even though the window only shows the first child being selected:</p>
<pre><code>for child in flowbox.get_selected_children():
print child.get_index()
</code></pre>
| 1 | 2016-08-22T00:02:46Z | 39,085,154 | <p>I think you have located a bug in GTK, it seems that something in <code>show_all</code> is messing up. My first guess was that it was caused by the fact that the <code>FlowBox</code> wasn't realized so I changed your code to use the <code>show</code> signal (<code>realize</code> but <code>show</code> is emitted later) and checked whether it still happend. Sadly it was..</p>
<p>So I got the feeling that something else was off so just a quick test added <code>self.show()</code> right after <code>Gtk.Window.__init__</code> this made the selection work but made the <code>Flowbox</code> wider than needed (probably because of the default width of a empty window). So I added the <code>self.show()</code> in the listener and this actually solved the issue. </p>
<p>The complete code is as follows, but as it is a dirty workaround you should still report this bug.</p>
<pre><code>#!/usr/bin/python
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gio
class App(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="App")
self.flowbox = Gtk.FlowBox()
self.flowbox.set_valign(Gtk.Align.START)
self.flowbox.set_selection_mode(Gtk.SelectionMode.SINGLE)
# Drawing 3 squares
self.flowbox.add(self.drawing_area())
self.flowbox.add(self.drawing_area())
self.flowbox.add(self.drawing_area())
self.flowbox.connect("show", self.on_realize)
self.add(self.flowbox)
def on_realize(self, flowbox):
# The creative workaround/hack
self.show()
child = self.flowbox.get_child_at_index(2)
self.flowbox.select_child(child)
def drawing_area(self):
preview = Gtk.DrawingArea()
preview.connect("draw", self.draw_square)
preview.set_size_request(150, 150)
return preview
def draw_square(self, widget, cr):
cr.scale(150, 150)
style_context = widget.get_style_context()
color = style_context.get_color(Gtk.StateFlags.NORMAL)
cr.set_source_rgba(*color)
cr.rectangle(0, 0, 1, 1)
cr.fill()
window = App()
window.connect("delete-event", Gtk.main_quit)
window.show_all()
Gtk.main()
</code></pre>
| 1 | 2016-08-22T17:12:25Z | [
"python",
"gtk",
"gtk3",
"gnome",
"pygobject"
] |
Understanding how to specify the newshape parameter for numpy's reshape() | 39,069,988 | <p>I am new to python data analysis, and trying to figure out how to manipulate a multi-dimensional array to a different dimension. Tutorials or forums online don't explain how to specify the parameters of "newshape" for <code>numpy.reshape(a, newshape, order='C')</code> </p>
<p>Here is an example I am trying to understand. It would be very helpful if someone could explain line 4. </p>
<pre><code>import numpy as np
a1 = np.arrange(8).reshape( (8,1) )
b = np.repeat(a1,8,axis=1)
c = b.reshape(2,4,2,4) # line 4
</code></pre>
| 2 | 2016-08-22T00:22:29Z | 39,070,025 | <p>The <code>newshape</code> argument has to be passed as a tuple (or something compatible) to <code>numpy.reshape</code>. But here's the catch: all the non-keyword arguments passed to <code>numpy.ndarray.reshape</code> (e.g. <code>b.reshape</code> in your example) will be caught by the argument <code>newshape</code>. This means that the following are equivalent and valid:</p>
<pre><code># b = np.random.rand(2*4*2*4)
np.reshape(b,(2,4,2,4))
np.ndarray.reshape(b,(2,4,2,4))
np.ndarray.reshape(b,2,4,2,4)
b.reshape((2,4,2,4))
b.reshape(2,4,2,4)
</code></pre>
<p>While this throws an error:</p>
<pre><code>np.reshape(b,2,4,2,4)
</code></pre>
<p>The key difference is that <code>np.reshape</code> and <code>np.ndarray.reshape</code> are different animals, and <code>b.reshape</code> is the bound version of the latter.</p>
<hr>
<p>You should also compare <code>help(np.reshape)</code>:</p>
<pre><code>reshape(a, newshape, order='C')
Gives a new shape to an array without changing its data.
</code></pre>
<p>with <code>help(b.reshape)</code>:</p>
<pre><code>a.reshape(shape, order='C')
Returns an array containing the same data with a new shape.
</code></pre>
<p>As you can see, <code>np.reshape</code> doesn't have any information about specific arrays, so if you want to reshape something using it, you have to <em>explicitly</em> pass it as a first argument. On the other hand, <code>b.reshape</code> is bound to the variable <code>b</code>, so it only has to be given a new shape, and optionally an <code>order</code> keyword argument.</p>
| 1 | 2016-08-22T00:30:43Z | [
"python",
"numpy"
] |
Understanding how to specify the newshape parameter for numpy's reshape() | 39,069,988 | <p>I am new to python data analysis, and trying to figure out how to manipulate a multi-dimensional array to a different dimension. Tutorials or forums online don't explain how to specify the parameters of "newshape" for <code>numpy.reshape(a, newshape, order='C')</code> </p>
<p>Here is an example I am trying to understand. It would be very helpful if someone could explain line 4. </p>
<pre><code>import numpy as np
a1 = np.arrange(8).reshape( (8,1) )
b = np.repeat(a1,8,axis=1)
c = b.reshape(2,4,2,4) # line 4
</code></pre>
| 2 | 2016-08-22T00:22:29Z | 39,070,133 | <p>Here is another perspective for understanding the <code>shape</code> of an array if that is part of what you are asking. The <code>shape</code> parameter <code>(2, 4, 2, 4)</code> specifies the length along each of the four different axises of the array. If you conceptually consider it as list of lists then it means the length from the out most list to inner most list. For example, for your array c here, if you check:</p>
<pre><code>len(c)
# 2
len(c[0]) # same result if you check c[1]
# 4
len(c[0][0])
# 2
len(c[0][0][0])
# 4
</code></pre>
<p>This matches the shape parameter. Or may be a better example is 2D array, which is matrix:</p>
<pre><code>a = np.array(range(9))
a
# array([0, 1, 2, 3, 4, 5, 6, 7, 8])
b = a.reshape(3,3)
b
# array([[0, 1, 2],
# [3, 4, 5],
# [6, 7, 8]])
</code></pre>
<p>As you can see, <code>b</code> has the same data as <code>a</code> but has a two dimension structure and each has length of 3 as specified in the shape parameter. And now if you check:</p>
<pre><code>len(b)
# 3
len(b[0])
# 3
</code></pre>
<p>Which gives the shape parameter back.</p>
| 0 | 2016-08-22T00:56:31Z | [
"python",
"numpy"
] |
Understanding how to specify the newshape parameter for numpy's reshape() | 39,069,988 | <p>I am new to python data analysis, and trying to figure out how to manipulate a multi-dimensional array to a different dimension. Tutorials or forums online don't explain how to specify the parameters of "newshape" for <code>numpy.reshape(a, newshape, order='C')</code> </p>
<p>Here is an example I am trying to understand. It would be very helpful if someone could explain line 4. </p>
<pre><code>import numpy as np
a1 = np.arrange(8).reshape( (8,1) )
b = np.repeat(a1,8,axis=1)
c = b.reshape(2,4,2,4) # line 4
</code></pre>
| 2 | 2016-08-22T00:22:29Z | 39,070,570 | <p>A similar question from a week ago: <a href="http://stackoverflow.com/questions/38928669/how-to-understand-ndarray-reshape-function">How to understand ndarray.reshape function?</a></p>
<p><code>np.reshape(a, newshape)</code> gets recast as <code>a.reshape(newshape)</code>. But <code>a.reshape</code> is a builtin, compiled method. So the details of how it handles <code>newshape</code> are hidden (to Python programmers).</p>
<p>The examples show that <code>newshape</code> can be a tuple, or separate numbers. But in a sense, even the separate numbers case uses a tuple. The arguments to a function are passed as a tuple.</p>
<p>This perhaps is most obvious with indexing. <code>a[:,1,3]</code> is translated by the interpreter into <code>a.__getitem__((slice(None),1,3))</code> call. And in fact <code>a[(:,1,3)]</code> is allowed, as is <code>ind = (slice(None),1,3); a[ind]</code>.</p>
<p>It's easy to write your own function that makes the extra layer of <code>()</code> optional:</p>
<pre><code>In [58]: def foo(*args):
...: if len(args)==1:
...: args = args[0]
...: print(args)
...:
In [59]: foo(1,2,3)
(1, 2, 3)
In [60]: foo((1,2,3))
(1, 2, 3)
</code></pre>
<p>I need to refine it a bit more to treat these 2 cases the same:</p>
<pre><code>In [61]: foo(1)
1
In [62]: foo((1,))
(1,)
</code></pre>
<p>If I'd defined the function as <code>def foo(arg):</code>, then I'd have to use a tuple if I wanted to give it several numbers.</p>
<p>Hopefully this gives a sense of why most experienced Python programmers aren't bothered by these differences. Often a tuple is just a convenient way of grouping values. It can add clarity, but isn't always needed. The coder can go either direction - gloss over their presence or not, or made a big deal of it.</p>
<p>===================</p>
<p>The reshape method is defined in <code>numpy/core/src/multiarray/methods.c</code> (in the github numpy repository). While written in <code>c</code> it appears to be the equivalent of</p>
<pre><code> def reshape(self, *args, **kwargs):
n = len(args)
if n<=1:
newshape = <parse args[0] in one way>
else:
newshape = <parse args in another way>
return PyArray_Newshape(self, newshape, order)
</code></pre>
<p>In any case it's being parsed so these are all the same:</p>
<pre><code>shape=(2,3)
np.arange(6).reshape(shape)
np.arange(6).reshape(*shape)
np.arange(6).reshape(2,3)
np.arange(6).reshape((2,3))
np.arange(6).reshape((2,)+(3,))
</code></pre>
| 2 | 2016-08-22T02:17:30Z | [
"python",
"numpy"
] |
Django Celery Periodic Task not running (Heroku)? | 39,070,042 | <p>I have a Django application that I've deployed with Heroku. I'm trying to user celery to create a periodic task every minute. However, when I observe the logs for the worker using the following command:</p>
<pre><code>heroku logs -t -p worker
</code></pre>
<p>I don't see my task being executed. Perhaps there is a step I'm missing? This is my configuration below...</p>
<p>Procfile</p>
<pre><code>web: gunicorn activiist.wsgi --log-file -
worker: celery worker --app=trending.tasks.app
</code></pre>
<p>Tasks.py</p>
<pre><code>import celery
app = celery.Celery('activiist')
import os
from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
app.conf.update(BROKER_URL=os.environ['REDIS_URL'],
CELERY_RESULT_BACKEND=os.environ['REDIS_URL'])
os.environ['DJANGO_SETTINGS_MODULE'] = 'activiist.settings'
from trending.views import *
@periodic_task(run_every=crontab())
def add():
getarticles(30)
</code></pre>
<p>One thing to add. When I run the task using the python shell and the "delay()" command, the task does indeed run (it shows in the logs) -- but it only runs once and only when executed. </p>
| 0 | 2016-08-22T00:35:26Z | 39,070,229 | <p>You need separate worker for the beat process (which is responsible for executing periodic tasks):</p>
<pre><code>web: gunicorn activiist.wsgi --log-file -
worker: celery worker --app=trending.tasks.app
beat: celery --app=trending.tasks.app
</code></pre>
<p>Worker isn't necessary for periodic tasks so the relevant line can be omitted. The other possibility is to embed beat inside the worker:</p>
<pre><code>web: gunicorn activiist.wsgi --log-file -
worker: celery worker --app=trending.tasks.app -B
</code></pre>
<p>but to quote the <a href="http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html" rel="nofollow">celery documentation</a>:</p>
<blockquote>
<p>You can also start embed beat inside the worker by enabling workers -B option, this is convenient if you will never run more than one worker node, but itâs not commonly used and for that reason is not recommended for production use</p>
</blockquote>
| -1 | 2016-08-22T01:15:38Z | [
"python",
"django",
"heroku",
"celery"
] |
Passing variable for module import and use | 39,070,053 | <p>so I am trying to use a variable brand which is selected by the user. The variable is then to be used to call a given module in Python. currently on line 7 you can see 'apple.solutions()'. However, I essentially want to be able to use something on the lines 'brand.solutions()' - although I know this will not work as it requires the attribute. I am looking for a solution to select the module based on the variable brands. I would appreciate any solutions or advice. Thanks,</p>
<p>Main program:</p>
<pre><code>import apple, android, windows
brands = ["apple", "android", "windows"]
brand = None
def Main():
query = input("Enter your query: ").lower()
brand = selector(brands, query, "brand", "brands")
solutions = apple.solutions()
print(solutions)
</code></pre>
<p>Apple.py Module File (same directory as main program):</p>
<pre><code>def solutions():
solutions = ["screen", "battery", "speaker"]
return solutions
</code></pre>
| 0 | 2016-08-22T00:38:47Z | 39,070,271 | <p>What you may be looking for is a call to your Main() function:</p>
<pre><code>if __name__ == "__main__":
Main()
</code></pre>
<p>The code above should go at the end of your main program. It checks whether the main program is imported or not, then executes the <code>Main()</code> function if it is not imported and runs as a standalone program.</p>
| 0 | 2016-08-22T01:23:16Z | [
"python",
"arrays",
"variables",
"parameter-passing",
"python-module"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.