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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Django: same Comment model for different Post types | 38,813,753 | <p>In my project, I currently have two different post types (but in the future they could be more): <em>Posts</em> and <em>Reviews</em>. Both can be commented, so they could share the same <em>Comment</em> model.</p>
<p>The problem is: if I create two different apps for Post and Review (and eventually other post types), should I share the same Comment model with a GenericForeignKey or should I recreate in each app the same Comment model with a specific ForeignKey? Or maybe I just should put every post type in a unique common app?</p>
| 1 | 2016-08-07T11:41:06Z | 38,813,799 | <p>As another option, you can check django-polymorphic.
<a href="https://django-polymorphic.readthedocs.io/en/stable/" rel="nofollow">https://django-polymorphic.readthedocs.io/en/stable/</a></p>
| 0 | 2016-08-07T11:46:48Z | [
"python",
"django"
] |
Django: same Comment model for different Post types | 38,813,753 | <p>In my project, I currently have two different post types (but in the future they could be more): <em>Posts</em> and <em>Reviews</em>. Both can be commented, so they could share the same <em>Comment</em> model.</p>
<p>The problem is: if I create two different apps for Post and Review (and eventually other post types), should I share the same Comment model with a GenericForeignKey or should I recreate in each app the same Comment model with a specific ForeignKey? Or maybe I just should put every post type in a unique common app?</p>
| 1 | 2016-08-07T11:41:06Z | 38,813,859 | <p>I would set it up in one of the following ways.</p>
<p><strong>Easy solution: use when needed</strong></p>
<p>Directory (app) structure:</p>
<pre><code>post
models.py
review
models.py
common
models.py
</code></pre>
<p>In <code>common/models.py</code>, you then define the comment:</p>
<pre><code>class Comment(models.Model):
title = models.CharField(max_length=128, blank=True, default='')
...
</code></pre>
<p>In <code>post/models.py</code>, you then refer to this class whenever you need it:</p>
<pre><code>from common.models import Comment
class Post(models.Model):
comment = models.ForeignKey(Comment, related_name='comments')
...
</code></pre>
<p><strong>Generic solution: mixins</strong></p>
<p>Another option is to create a <em>mixin behavior</em> inside your common app.</p>
<pre><code>class Commentable(models.Model):
comment = models.ForeignKey(Comment, related_name='comments')
</code></pre>
<p>And mix this behavior in by inheriting from it.</p>
<pre><code>from common.models import Commentable
class Post(Commentable, models.Model):
...
</code></pre>
<p>You should read a bit about mixins before using them all over the place though.</p>
| 0 | 2016-08-07T11:54:02Z | [
"python",
"django"
] |
Namespace - scope python | 38,813,776 | <p>I am pretty confused about how the rules of LEGB apply here. I
understand that Local can be inside a function or class method, for
example. Enclosed can be its enclosing function, e.g., if a function
is wrapped inside another function. Global refers to the uppermost
level of the executing script itself, and Built-in are special names
that Python reserves for itself. I just don't get how it applies here and > why the output is what it is.thanks</p>
<pre><code>a = 'global'
def outer():
def len(in_var):
print('called my len() function: ')
l = 0
for i in in_var:
l += 1
return l
a = 'local'
def inner():
global len
nonlocal a
a += ' variable'
inner()
print('a is', a)
print(len(a))
outer()
print(len(a))
print('a is', a)
</code></pre>
<p>output</p>
<pre><code>('a is', 'local')
called my len() function:
5
15
('a is', 'global variable')
</code></pre>
| 0 | 2016-08-07T11:44:25Z | 38,813,931 | <p>I'm getting following result with 3.4.2</p>
<pre><code>a is local variable
called my len() function:
14
6
a is global
</code></pre>
<p>For the explanation, actually you got almost all the important details but the key point is <code>nonlocal</code> statement causes the identifier to refer to previously bound variable in the nearest enclosing scope, which means <code>a</code> in <code>inner()</code> refers to and affects <code>a = 'local'</code> so after that; <code>print('a is', a)</code> uses a as <code>local variable</code> and have length 14. However in global scope <code>a = 'global'</code> is still effective.</p>
<p>Can you please share the details of your environment that we can investigate the difference?</p>
| 0 | 2016-08-07T12:01:35Z | [
"python",
"scope",
"namespaces",
"closures"
] |
BeautifulSoup find using persian string | 38,813,818 | <p>I want to find all elements containing a string using BeautifulSoup in python.
It works when I use non Persian characters but not when I use Persian characters.</p>
<pre><code>from bs4 import BeautifulSoup
QUERY = 'Ø±Ø´ØªÙ ÙØ§Ø±Ø³Û'
URL = 'http://www.example.com'
headers = {
'User-Agent': "Mozilla/5.0 . . . "
}
request = urllib2.Request(URL, headers=headers)
response = urllib2.urlopen(request)
response_content = response.read().decode('utf8')
soup = BeautifulSoup(response_content, 'html.parser')
fetched = soup.find_all(text=QUERY)
print(fetched)
</code></pre>
<p>For the code above , output is <code>[]</code>
but it works if I use ASCII in QUERY.</p>
<p>Is there any utf8 conversion or some thing to solve it :) ? </p>
| 2 | 2016-08-07T11:48:56Z | 39,109,396 | <pre class="lang-py prettyprint-override"><code> #-*- coding: utf-8 -*-
import urllib2
from bs4 import BeautifulSoup
QUERY = 'خدÙ
ات'
URL = 'https://bayan.ir/service/bayan/'
headers = {
'User-Agent': "Mozilla/5.0 . . . "
}
request = urllib2.Request(URL, headers=headers)
response = urllib2.urlopen(request)
response_content = response.read()
soup = BeautifulSoup(response_content, 'html.parser')
fetched = soup.find_all(string=QUERY)
print(fetched)
</code></pre>
<p>it's work!</p>
| 1 | 2016-08-23T19:37:47Z | [
"python",
"web-scraping",
"beautifulsoup",
"persian"
] |
Can't use flask-moment to show the time on webpage | 38,814,159 | <p>I want to use the Flask-moment to show the time on the web page when I visit the index.html
I've used the bootstrap up, and used the moment.js,but it still doesn't work.
Please give some help , thanks !</p>
<p><strong>my main py</strong></p>
<pre><code>from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask import request
from datetime import datetime
app = Flask(__name__)
bootstrap=Bootstrap(app)
moment=Moment(app)
@app.route('/')
def index():
return render_template('index.html',current_time=datetime.utcnow())
</code></pre>
<p><strong>This is my base.html which extends from the bootstrap</strong></p>
<pre><code>{% extends "bootstrap/base.html" %}
{%block head%}
{{super()}}
<link rel='shortcut icon' href="{{url_for('static',filename='favicon.ico')}}" type='image/x-icon'>
<link rel='icon' href="{{url_for('static',filename='favicon.ico')}}" type="image/x-icon">
{% block scripts %} #Here I use the bootstrap
{{ super() }} #But I dont' whether it works or not
{{ moment.include_moment() }}
{% endblock %}
{%endblock%}
{% block title %}Flasky{% endblock %}
{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle"
data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Flasky</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
</ul>
</div>
</div>
</div>
{% endblock %}
{% block content %}
<div class="container">
{% block page_content %}{% endblock %}
</div>
{% endblock %}
</code></pre>
<p><strong>The last is the index.html</strong></p>
<pre><code><p>The local date and time is {{moment(current_time).format('LLL')}}.</p>
<p>That was {{moment(current_time).fromNow(refresh=True)}}</p>
</code></pre>
<p><a href="http://i.stack.imgur.com/udfde.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/udfde.jpg" alt="enter image description here"></a></p>
| 1 | 2016-08-07T12:31:05Z | 38,814,869 | <p>If <code>index.html</code> only contains those two line, which is clearly reflects the output you got on the screen-shot, then you will need to <em>extend</em> it from <code>base.html</code>:</p>
<pre><code>{% extends 'base.html' %}
{% block title %}Flasky - Home page{% endblock %}
{% block page_content %}
<p>The local date and time is {{moment(current_time).format('LLL')}}.</p>
<p>That was {{moment(current_time).fromNow(refresh=True)}}</p>
{% endblock %}
</code></pre>
| 1 | 2016-08-07T14:00:58Z | [
"python",
"html",
"flask"
] |
how to change default precision in python | 38,814,209 | <p>i have a dataframe with floating type variables, i need to change the values of that variable to a n decimal places. (dummy data)</p>
<pre><code>prod_code sales_avg
122 12332.234233
123 12212.234123
</code></pre>
<p>Currently i am doing the following :</p>
<pre><code>prod_sales_avg=pd.DataFrame(weekly_sales.groupby(['prod_code']).agg({'weekly_sales':{'sales_avg':'mean'}}))
prod_sales_avg.columns=prod_sales_avg.columns.droplevel(0)
prod_sales_avg=prod_sales_avg.reset_index()
prod_sales_avg['sales_avg']=round(prod_sales_avg['sales_avg'],9)
</code></pre>
<p>i am getting the decimal places upto 6 places(i think that is default). I need to increase the decimal place to 9.but the above code does not work. Later i will be using this variable for comparison, so not looking for just <strong>"display"</strong> standpoint. The value should be stored as 9 decimal places. What am i doing wrong here.</p>
| 0 | 2016-08-07T12:37:28Z | 38,814,249 | <p>You can do it as follows:</p>
<p><em>via Dataframe using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.round.html" rel="nofollow"><code>Dataframe.round</code></a></em></p>
<pre><code>prod_sales_avg.round({'sales_avg': 9})
</code></pre>
<p><em>via Series using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.round.html#pandas.Series.round" rel="nofollow"><code>Series.round</code></a></em></p>
<pre><code>prod_sales_avg['sales_avg'] = prod_sales_avg['sales_avg'].round(decimals=9)
</code></pre>
| 1 | 2016-08-07T12:42:19Z | [
"python",
"python-3.x",
"pandas"
] |
Subprocess.call how to espeak the components in a list | 38,814,354 | <pre><code>import subprocess
digit = [1,2,3,4]
subprocess.call('espeak -s 120 -ven ' + str(digit) +'--stdout | aplay', shell=True)
</code></pre>
<p>The sound that i hear is only "One", which is only the first component of the list. How should I write the code to make it announce "One-Two-Three-Four"?</p>
| 0 | 2016-08-07T12:55:09Z | 38,814,385 | <p>Use a loop to iterate over <code>digits</code> (note that I changed the name of the list to <code>digits</code>). While you are at it you may want to use <code>str.format</code> for readability.</p>
<pre><code>import subprocess
digits = [1, 2, 3, 4]
for digit in digits:
subprocess.call('espeak -s 120 -ven {} --stdout | aplay'.format(digit), shell=True)
</code></pre>
| 1 | 2016-08-07T12:58:40Z | [
"python",
"list",
"raspberry-pi",
"subprocess",
"espeak"
] |
Python: Defined new function but it does not print the result | 38,814,543 | <p>Python beginner, trying to:</p>
<ul>
<li>insert two numbers from keyboard</li>
<li>create a sum function of the two</li>
<li>print that sum function.</li>
</ul>
<p>My code looks like this:</p>
<pre><code>number1 = raw_input("Insert number1 = ")
print number1
number2 = raw_input("Insert number2 = ")
print number2
def sumfunction (number1, number2):
print "Were summing number1 and number2 %d + %d" % (number1, number2)
return number1 + number2
print()
</code></pre>
<p>I would like something like print sumfunction, or something that will print the result of the function.
Currently my code only returns the number1 and number2...</p>
<p>edit: edit in syntax</p>
| 0 | 2016-08-07T13:17:00Z | 38,814,564 | <ol>
<li><p>Anything after <code>return</code> statements is not going to be executed.</p></li>
<li><p>You defined the function. Now all you need to do is to call it...</p>
<pre><code>sumfunction(number1, number2)
</code></pre></li>
<li><p>Your function would still not work as you expect it. Since <code>raw_input</code> returns a string, your function will return the numbers concatenated (for the numbers <code>1</code> and <code>2</code> it would return the string <code>'12'</code> instead of the number <code>3</code>). You should convert each number to an <code>int</code> (or <code>float</code>):</p>
<pre><code>number1 = int(raw_input("Insert number1 = "))
</code></pre></li>
</ol>
| 1 | 2016-08-07T13:20:25Z | [
"python",
"function",
"printing"
] |
Python: Defined new function but it does not print the result | 38,814,543 | <p>Python beginner, trying to:</p>
<ul>
<li>insert two numbers from keyboard</li>
<li>create a sum function of the two</li>
<li>print that sum function.</li>
</ul>
<p>My code looks like this:</p>
<pre><code>number1 = raw_input("Insert number1 = ")
print number1
number2 = raw_input("Insert number2 = ")
print number2
def sumfunction (number1, number2):
print "Were summing number1 and number2 %d + %d" % (number1, number2)
return number1 + number2
print()
</code></pre>
<p>I would like something like print sumfunction, or something that will print the result of the function.
Currently my code only returns the number1 and number2...</p>
<p>edit: edit in syntax</p>
| 0 | 2016-08-07T13:17:00Z | 38,814,567 | <p>Let's go over this step by step.</p>
<p>We can start by change your function to:</p>
<pre><code>def add(number1, number2):
print "We're summing number1 and number2 %d + %d = %d" % (number1, number2, number1 + number2)
</code></pre>
<p>Notice that in this version, you're actually adding the numbers and don't exit prematurely. The numbers must get converted from strings to integers before this function is invoked, and we do that in a moment. In your version, you just return a result but don't get to print.</p>
<p>In addition, you need to invoke your function so that it will do its work, i.e., <code>add(number1, number2)</code></p>
<p>If we refactor your script a bit, you can get the following:</p>
<pre><code>def add(number1, number2):
"Only adds the two arguments together and returns the result"
return number1 + number2
# convert inputs from strings to integers
number1 = int(raw_input("Insert number1 = "))
print number1
# convert inputs from strings to integers
number2 = int(raw_input("Insert number2 = "))
print number2
result = add(number1, number2)
print "The result of %d + %d = %d" % (number1, number2, add(number1, number2))
</code></pre>
<p>Notice how the inputs are also converted from strings into actual integers now, so that they get added, instead of concatenated. That is, <code>"2" + "2" = "22"</code> while <code>2 + 2 = 4</code>.</p>
<p>It's also good practice to wrap your code with the following check:</p>
<pre><code>if __name__ == '__main__':
# your main code here
</code></pre>
<p>So the above can be refactored to:</p>
<pre><code>def add(number1, number2):
"Only adds the two arguments together and returns the result"
return number1 + number2
if __name__ == '__main__':
number1 = int(raw_input("Insert number1 = "))
print number1
number2 = int(raw_input("Insert number2 = "))
print number2
result = add(number1, number2)
print "The result of %d + %d = %d" % (number1, number2, add(number1, number2))
</code></pre>
<p>This allows the main part of your code to be executed only when the script is invoked directly, but not when it gets <code>import</code>ed from another Python script as a module. This check is recommended because in Python, every file is considered a module, i.e. it's legal to say <code>from <yourfile> import add</code>, and you don't want the code that actually tests your <code>add</code> implementation to execute in that case.</p>
<p>Notice also that we've removed the <code>print</code> statements from your <code>add</code> function. This is to make sure your function is doing one and <em>only one</em> thing, i.e. <code>add</code>ing the arguments. This makes your function more general and it's easier to re-use your code in other parts, including those where callers don't really want to <code>print</code> anything immediately while calculating something.</p>
<p>This is known as the <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle" rel="nofollow"><strong><em>S</strong>ingle-<strong>R</strong>esponsibility-<strong>P</strong>rinciple</em></a>. Following this principle will allow you to do improve and do better on software design/implementation in the long-term.</p>
<blockquote>
<p>I would like something like print sumfunction, or something that will print the result of the function.</p>
</blockquote>
<p>Now you can just do the following:</p>
<pre><code>x = 5
y = 10
print add(x, y)
</code></pre>
| 1 | 2016-08-07T13:20:39Z | [
"python",
"function",
"printing"
] |
Python: Defined new function but it does not print the result | 38,814,543 | <p>Python beginner, trying to:</p>
<ul>
<li>insert two numbers from keyboard</li>
<li>create a sum function of the two</li>
<li>print that sum function.</li>
</ul>
<p>My code looks like this:</p>
<pre><code>number1 = raw_input("Insert number1 = ")
print number1
number2 = raw_input("Insert number2 = ")
print number2
def sumfunction (number1, number2):
print "Were summing number1 and number2 %d + %d" % (number1, number2)
return number1 + number2
print()
</code></pre>
<p>I would like something like print sumfunction, or something that will print the result of the function.
Currently my code only returns the number1 and number2...</p>
<p>edit: edit in syntax</p>
| 0 | 2016-08-07T13:17:00Z | 38,814,572 | <p>Change your code to use a <code>main</code> function. It will help you understand the code flow better:</p>
<pre><code>def sumfunction(n1, n2):
print "Were summing %d + %d" % (n1, n2)
return n1 + n2
def input_int(prompt):
while True:
try:
return int(raw_input(prompt))
except ValueError:
print "Invalid input! Please try again."
def main():
number1 = input_int("Insert number1 = ")
print number1
number2 = input_int("Insert number2 = ")
print number2
result = sumfunction(number1, number2)
print "Result: %d" % result
if __name__ == '__main__':
main()
</code></pre>
<p>This is the standard way to write Python scripts. See, when the script runs, it actually executes everything along the way. So we put the <code>__name__</code> check at the end, to say "okay, the script is loaded, now actually start running it at this predefined point (<code>main</code>)".</p>
<p>I've changed your variable names so you can understand that they are <em>scoped</em> to the function in which they are declared.</p>
<p>I'm also showing how <code>main</code> gets the return value from <code>sumfunction</code>, and stores it to a variable (just like you did with <code>raw_input</code>). Then, I print that variable.</p>
<p>Finally, I've written a function called <code>input_int</code>. As <a href="http://stackoverflow.com/a/38814564/119527">DeepSpace's answer indicated</a>, <code>raw_input</code> returns a <em>string</em>, but you want to work with <em>integers</em>. Do do this, you need to call <code>int</code> on the string returned by <code>raw_input</code>. The problem with this is, it can raise a <code>ValueError</code> exception, if the user enters an invalid integer, like <code>"snake"</code>. That's why I catch the error, and ask the user to try again.</p>
| 1 | 2016-08-07T13:21:16Z | [
"python",
"function",
"printing"
] |
Python: Defined new function but it does not print the result | 38,814,543 | <p>Python beginner, trying to:</p>
<ul>
<li>insert two numbers from keyboard</li>
<li>create a sum function of the two</li>
<li>print that sum function.</li>
</ul>
<p>My code looks like this:</p>
<pre><code>number1 = raw_input("Insert number1 = ")
print number1
number2 = raw_input("Insert number2 = ")
print number2
def sumfunction (number1, number2):
print "Were summing number1 and number2 %d + %d" % (number1, number2)
return number1 + number2
print()
</code></pre>
<p>I would like something like print sumfunction, or something that will print the result of the function.
Currently my code only returns the number1 and number2...</p>
<p>edit: edit in syntax</p>
| 0 | 2016-08-07T13:17:00Z | 38,814,590 | <p>Your function <code>sumfunction</code> is returning the sum of the two numbers before printing them. A return statement will end the function, so you need to add the numbers and then print the answer before returning anything. Consider creating a third variable to store the sum, eg:</p>
<pre><code>def sumfunction (number1, number2):
print("We're summing number1 and number2: %d + %d" % (number1, number2))
sum = numar1 + numar2
print(sum)
return sum
</code></pre>
| 0 | 2016-08-07T13:23:57Z | [
"python",
"function",
"printing"
] |
Why does the Google App Engine NDB datastore have both "â" and "null" for unkown data? | 38,814,666 | <p>I recently updated an entity model to include some extra properties, and noticed something odd. For properties that have never been written, the Datastore query page shows a "â", but for ones that I've explicitly set to <code>None</code> in Python, it shows "null".</p>
<p>In SQL, both of those cases would be null. When I query an entity that has both types of unknown properties, they both read as <code>None</code>, which fits with that idea. </p>
<p>So why does the NDB datastore viewer differentiate between "never written" and "set to <code>None</code>", if I can't differentiate between them programatically?</p>
| 1 | 2016-08-07T13:35:37Z | 38,815,611 | <p>You have to specifically set the value to NULL, otherwise it will not be stored in the Datastore and you see it as missing in the Datastore viewer.</p>
<p>This is an important distinction. NULL values can be indexed, so you can retrieve a list of entities where date of birth, for example, is null. On the other hand, if you do not set a date of birth when it is unknown, there is no way to retrieve a list of entities with date of birth property missing - you'll have to iterate over all entities to find them.</p>
<p>Another distinction is that NULL values take space in the Datastore, while missing values do not.</p>
| 4 | 2016-08-07T15:20:17Z | [
"python",
"google-app-engine",
null,
"app-engine-ndb"
] |
IPython won't start with locally installed Python 3.5 | 38,814,672 | <p>I am on a linux system that only has Python 2.7 installed globally. I have installed Anaconda with Python 3.5 in my home folder. I also installed the latest version of IPython using <code>conda install ipython</code>. When running <code>ipython</code> at the console, I get:</p>
<pre><code>Traceback (most recent call last):
File "/home/mateinfo/vlad/anaconda3/bin/ipython", line 4, in <module>
import IPython
File "/home/mateinfo/vlad/anaconda3/lib/python3.5/site-packages/IPython/__init__.py", line 49, in <module>
from .terminal.embed import embed
File "/home/mateinfo/vlad/anaconda3/lib/python3.5/site-packages/IPython/terminal/embed.py", line 16, in <module>
from IPython.core.interactiveshell import DummyMod, InteractiveShell
File "/home/mateinfo/vlad/anaconda3/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 31, in <module>
from pickleshare import PickleShareDB
File "/home/mateinfo/vlad/anaconda3/lib/python3.5/site-packages/pickleshare.py", line 41, in <module>
from path import path as Path
File "/opt/pcm/lib/python/path.py", line 919
def mkdir(self, mode=0777):
</code></pre>
<p>As far as I can tell, the problem is with the used <code>path</code> module, which seems to be from Python 2.7, since it uses the old octal format <code>0777</code>.</p>
<p>How can I get IPython working under this setup?</p>
<p>I have this in my <code>.bashrc</code>:</p>
<pre><code># added by Anaconda3 4.0.0 installer
export PATH="/home/mateinfo/vlad/anaconda3/bin:$PATH"
export PATH="/home/mateinfo/vlad/anaconda3/lib:$PATH"
export PATH="/home/mateinfo/vlad/anaconda3/lib/python3.5:$PATH"
</code></pre>
<p>Only the first line was added by the Anaconda installer, the other 2 were added by me, with no success.</p>
| 0 | 2016-08-07T13:36:37Z | 38,814,739 | <p>You might have the <code>PYTHONPATH</code> environment variable set to a location where a python2 library resides.</p>
<p>As general recommendation, never use this variable. Create proper <code>setup.py</code> scripts for your libraries.</p>
<p>To get rid of it, you can do <code>unset PYTHONPATH</code> or eliminate anything that sets this variable in your <code>.bashrc</code>.</p>
| 1 | 2016-08-07T13:45:46Z | [
"python",
"ipython",
"anaconda"
] |
Python - compare 2 columns in 2 different csv/txt files and find match | 38,814,735 | <p>I want to get the price of a stock on its announcement date. So I need to return the row in file 2 that contains the date in file 1.</p>
<ul>
<li>I have two csv files with over 1000 stock prices
<ul>
<li>file 1 'announcement dates' contains:</li>
<li>ANNOUNCEMENT DATES;TICKER </li>
<li>20151116;A UN EQUITY</li>
<li>20141117;A UN EQUITY</li>
<li>20131114;A UN EQUITY
...</li>
</ul></li>
</ul>
<hr>
<ul>
<li>file 2 'prices' contains prices of every trading day of each stock since 2005:</li>
<li>over 1mio. lines</li>
<li>DATE;TICKER;PRICE</li>
<li>20151231;A UN EQUITY;41.81</li>
<li>20151230;A UN EQUITY;42.17</li>
<li><p>20151229;A UN EQUITY;42.36
...</p>
<pre><code>data_prices = "data_prices.csv"
data_ancment = "data_static.csv"
with open(data_ancment, 'rt') as a, open(data_prices, 'rt') as b:
reader1 = csv.reader(a, delimiter=';')
reader2 = csv.reader(b, delimiter=';')
for row2 in reader2:
for row1 in reader1:
if row1[0] == row2[0]:
print(row2[2])
</code></pre></li>
</ul>
<p>I dont know if it is possible to do it this way since the files are huge or if numpy or pandas is a better/faster option.</p>
<p>Thanks in advance for any tips.</p>
| 0 | 2016-08-07T13:45:10Z | 38,814,823 | <p>It's certainly a very common task to perform on <code>pandas</code> <code>DataFrames</code>. Whether or not performance will be an easy is something you could readily test; if I understand your question correctly, you only want to merge on the dates, and the corresponding piece of <code>pandas</code> would be the following (where you should note that I changed your dates a bit to have a non-trivial overlap)</p>
<pre><code>In [1]: import pandas as pd
In [2]: prices = pd.read_csv('data_prices.csv', sep=';')
In [3]: ancment = pd.read_csv('data_static.csv', sep=';')
In [4]: combined = pd.merge(prices, ancment, left_on='ANNOUNCEMENT DATES', right_on='DATE')
In [5]: prices.head()
Out[5]:
ANNOUNCEMENT DATES TICKER
0 20151116 A UN EQUITY
1 20141117 A UN EQUITY
2 20131114 A UN EQUITY
In [6]: ancment.head()
Out[6]:
DATE TICKER PRICE
0 20151116 A UN EQUITY 41.81
1 20151230 A UN EQUITY 42.17
2 20151229 A UN EQUITY 42.36
In [7]: combined.head()
Out[7]:
ANNOUNCEMENT DATES TICKER_x DATE TICKER_y PRICE
0 20151116 A UN EQUITY 20151116 A UN EQUITY 41.81
</code></pre>
<p>Merging the two frames can be done pretty much however you want to -- for instance you might want to only have a single date column, since those are set up to agree anyway. See <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/merging.html</a> for the full collection of possibilities.</p>
| 0 | 2016-08-07T13:56:53Z | [
"python",
"csv",
"pandas",
"numpy"
] |
Python - compare 2 columns in 2 different csv/txt files and find match | 38,814,735 | <p>I want to get the price of a stock on its announcement date. So I need to return the row in file 2 that contains the date in file 1.</p>
<ul>
<li>I have two csv files with over 1000 stock prices
<ul>
<li>file 1 'announcement dates' contains:</li>
<li>ANNOUNCEMENT DATES;TICKER </li>
<li>20151116;A UN EQUITY</li>
<li>20141117;A UN EQUITY</li>
<li>20131114;A UN EQUITY
...</li>
</ul></li>
</ul>
<hr>
<ul>
<li>file 2 'prices' contains prices of every trading day of each stock since 2005:</li>
<li>over 1mio. lines</li>
<li>DATE;TICKER;PRICE</li>
<li>20151231;A UN EQUITY;41.81</li>
<li>20151230;A UN EQUITY;42.17</li>
<li><p>20151229;A UN EQUITY;42.36
...</p>
<pre><code>data_prices = "data_prices.csv"
data_ancment = "data_static.csv"
with open(data_ancment, 'rt') as a, open(data_prices, 'rt') as b:
reader1 = csv.reader(a, delimiter=';')
reader2 = csv.reader(b, delimiter=';')
for row2 in reader2:
for row1 in reader1:
if row1[0] == row2[0]:
print(row2[2])
</code></pre></li>
</ul>
<p>I dont know if it is possible to do it this way since the files are huge or if numpy or pandas is a better/faster option.</p>
<p>Thanks in advance for any tips.</p>
| 0 | 2016-08-07T13:45:10Z | 38,815,872 | <p>You can use <code>dictionaries</code> like hash.</p>
<pre><code>prices = "prices.csv"
ancment = "ancment.csv"
with open(ancment, 'rt') as a, open(prices, 'rt') as b:
reader1 = csv.reader(a, delimiter=';')
reader2 = csv.reader(b, delimiter=';')
dictionary = dict()
for row2 in reader2:
dictionary[row2[0]] = list()
for row1 in reader1:
try:
dictionary[row1[0]].append(row1)
except KeyError:
pass
for k,v in dictionary.iteritems():
print k,v
</code></pre>
| 0 | 2016-08-07T15:53:03Z | [
"python",
"csv",
"pandas",
"numpy"
] |
scrapy mysql returns empty results | 38,814,777 | <p>So my problem is that the information scraped, won't show up in the database. </p>
<p>My spider works fine printing out the information, for example in a .json file.</p>
<p>the pipelines.py</p>
<pre><code>import sys
import MySQLdb
import hashlib
from scrapy.exceptions import DropItem
from scrapy.http import Request
class MySQLStorePipeline(object):
def __init__(self):
self.conn = MySQLdb.connect(host="10.0.2.2", user='root', passwd='', db='mpmf', charset="utf8", use_unicode=True)
self.cursor = self.conn.cursor()
def process_item(self, item, stack):
try:
self.cursor.execute("""INSERT INTO test (pen, name)
VALUES (%s, %s)""",
(item['pen'].encode('utf-8'), item['name'].encode('utf-8')))
self.conn.commit()
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
return item
</code></pre>
<p>and in settings.py i have added</p>
<pre><code>ITEM_PIPELINES = {
'stack.pipelines.MySQLStorePipeline': 300,
}
</code></pre>
<p>and my log show this errors but you can still see that the information gathering works even though it displays this.</p>
<pre><code> File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 577, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "/root/stack/stack/pipelines.py", line 14, in process_item
self.cursor.execute("""INSERT INTO test (pen, name) VALUES (%s, %s)""", (item['pen'].encode('utf-8'), item['name'].encode('utf-8')))
AttributeError: 'list' object has no attribute 'encode'
</code></pre>
<p>so no results are imported to the database</p>
| 0 | 2016-08-07T13:49:47Z | 38,826,063 | <p>solved it
problem was the indentation and list object had no attribute</p>
<pre><code>import sys
import MySQLdb
import hashlib
from scrapy.exceptions import DropItem
from scrapy.http import Request
class MySQLStorePipeline(object):
def __init__(self):
self.conn = MySQLdb.connect(host="10.0.2.2", user='root', passwd='', db='mpmf', charset="utf8", use_unicode=True)
self.cursor = self.conn.cursor()
def process_item(self, item, stack):
try:
self.cursor.execute("""INSERT INTO test (pen, name) VALUES (%s, %s)""", (item['pen'][0].encode('utf-8'), item['name'][0].encode('utf-8')))
self.conn.commit()
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
return item
</code></pre>
| 0 | 2016-08-08T09:50:27Z | [
"python",
"mysql",
"scrapy",
"scrapy-pipeline"
] |
Printing a float value in python not rounding up | 38,814,794 | <p>I have to print a number in python of this form :
n = "35.66667"
The output should be "35.666". Now, I tried round() function in python upto 3 decimal places but its giving me incorrect result of 35.667.</p>
<p>Any idea how can i print <strong>the float value upto 3 decimal places without rounding up</strong>?</p>
| -1 | 2016-08-07T13:52:19Z | 38,814,837 | <blockquote>
<p>Yes, but that's the question asked. To print the float value upto 3 decimal places without rounding up.</p>
</blockquote>
<p>So trim the string representation:</p>
<pre><code>def trim_float(n, d):
n_str = str(n)
point_index = n_str.find('.')
return float(n_str[:point_index + d + 1])
print(trim_float(35.66667, 3))
>> 35.666
</code></pre>
| 3 | 2016-08-07T13:58:42Z | [
"python"
] |
Printing a float value in python not rounding up | 38,814,794 | <p>I have to print a number in python of this form :
n = "35.66667"
The output should be "35.666". Now, I tried round() function in python upto 3 decimal places but its giving me incorrect result of 35.667.</p>
<p>Any idea how can i print <strong>the float value upto 3 decimal places without rounding up</strong>?</p>
| -1 | 2016-08-07T13:52:19Z | 38,814,840 | <p>If you want to coerce 35.66667 to 35.666 (i.e. round down), this could work:</p>
<pre><code>import math
n = 35.6667
print(math.floor(n * 1000) / 1000)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>35.666
</code></pre>
<p>Hopefully someone else can post a more elegant way to accomplish this, though.</p>
| 0 | 2016-08-07T13:58:53Z | [
"python"
] |
Printing a float value in python not rounding up | 38,814,794 | <p>I have to print a number in python of this form :
n = "35.66667"
The output should be "35.666". Now, I tried round() function in python upto 3 decimal places but its giving me incorrect result of 35.667.</p>
<p>Any idea how can i print <strong>the float value upto 3 decimal places without rounding up</strong>?</p>
| -1 | 2016-08-07T13:52:19Z | 38,814,880 | <p>Using <code>format</code>:</p>
<pre><code>n = 35.66667
print "{0!s:.6}".format(n)
# 35.666
</code></pre>
| 0 | 2016-08-07T14:02:44Z | [
"python"
] |
Printing a float value in python not rounding up | 38,814,794 | <p>I have to print a number in python of this form :
n = "35.66667"
The output should be "35.666". Now, I tried round() function in python upto 3 decimal places but its giving me incorrect result of 35.667.</p>
<p>Any idea how can i print <strong>the float value upto 3 decimal places without rounding up</strong>?</p>
| -1 | 2016-08-07T13:52:19Z | 38,814,900 | <p>Seems that you want to truncate the everything past the third decimal. Round up gives you the correct rounded result, but not what you need.</p>
<p>You could just slice the unwanted decimals.</p>
<pre><code>n = "35.66667"
print(float(n[:-2]))
=> 35.666
</code></pre>
| 0 | 2016-08-07T14:04:48Z | [
"python"
] |
Printing a float value in python not rounding up | 38,814,794 | <p>I have to print a number in python of this form :
n = "35.66667"
The output should be "35.666". Now, I tried round() function in python upto 3 decimal places but its giving me incorrect result of 35.667.</p>
<p>Any idea how can i print <strong>the float value upto 3 decimal places without rounding up</strong>?</p>
| -1 | 2016-08-07T13:52:19Z | 38,814,923 | <p>in academic circumstances, the answer might be e.g.:</p>
<p><em>"convert the string to a float, <code>math.floor</code> it to 3 decimal places and convert to back to string"</em></p>
<p>in the real life (or on an interview to any company you WANT to work for), the correct answer is:</p>
<p><strong>"Why?!? Please explain the reasoning behind this business logic before we attempt any implementation."</strong></p>
| 0 | 2016-08-07T14:07:16Z | [
"python"
] |
pickle raises EOFError on Ubuntu 14.04 but works on Mac OS and Linux Mint | 38,814,833 | <p>I am saving some big data using Python's pickle module. To be more precise I am dumping two objects to the same pickle-file as follows:</p>
<pre><code>def save(sim):
if sim.tstamp > 0:
with open(filepath(sim.identifier), 'wb') as f:
pickle.dump(sim.serialize(), f)
pickle.dump(sim, f)
else:
raise ValueError("Simulation not yet simulated")
</code></pre>
<p><code>sim</code> is a self-written class which has different attributes and a method called <code>serialize()</code>. This method converts all attributes and its values to a dictionary by using something like:</p>
<pre><code>def serialize(self):
keys = ['height', 'diameter', 'rpm', 'packaging']
serialized = dict((key, getattr(self, key)) for key in keys)
serialized['sectors'] = [sector.serialize() for sector in self.sectors]
return serialized
</code></pre>
<p>So basically <code>sim.serialize()</code> returns a dictionary which is dumped to the pickle file as the first object. The second object is the sim-object itself. This is due to the large size of each sim object. Providing the dictionary enables a kind of summary in order to prevent loading the complete simulation if not really necessary.</p>
<p>To load the data from the pickle file I use:</p>
<pre><code>def load(fname, params_only=False):
simulation = find(fname) # find returns file name
try:
with open(simulation, 'r') as json_file:
return json.load(json_file)
except (UnicodeDecodeError, ValueError) as e:
with open(simulation, 'rb') as pickle_file:
params = pickle.load(pickle_file)
if params_only:
return params
return pickle.load(pickle_file)
</code></pre>
<p>Since an older API is capable of JSON-files as well I need to handle both JSON- and pickle-files.</p>
<p>Dumping the objects works as desired (no error messages are raised). However, when requesting some data graphs the API needs to unpickle the data which raises the following error:</p>
<pre><code>[2016-08-07 14:39:34,637] ERROR in app: Exception on /api/simulations/20160807_123707581/heatflux_distribution.png [GET]
Traceback (most recent call last):
File "/home/abkos/abkosproject/abkos/_tools.py", line 36, in load
return json.load(json_file)
File "/usr/lib/python3.4/json/__init__.py", line 265, in load
return loads(fp.read(),
File "/usr/lib/python3.4/codecs.py", line 319, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.4/dist-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "./app.py", line 118, in plot_figure
img = plotter(identifier, figname, request.args.items())
File "./app.py", line 122, in plotter
sim = Simulation.from_file(identifier)
File "/home/abkos/abkosproject/abkos/calculation.py", line 56, in from_file
params_or_simulation = load(fname, params_only=new)
File "/home/abkos/abkosproject/abkos/_tools.py", line 42, in load
return pickle.load(pickle_file)
_pickle.UnpicklingError
10.0.2.2 - - [07/Aug/2016 14:39:34] "GET /api/simulations/20160807_123707581/heatflux_distribution.png HTTP/1.1" 500 -
[2016-08-07 14:39:38,691] ERROR in app: Exception on /api/simulations/20160807_123707581/heatmap_axial_temperatures.png [GET]
Traceback (most recent call last):
File "/home/abkos/abkosproject/abkos/_tools.py", line 36, in load
return json.load(json_file)
File "/usr/lib/python3.4/json/__init__.py", line 265, in load
return loads(fp.read(),
File "/usr/lib/python3.4/codecs.py", line 319, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.4/dist-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "./app.py", line 118, in plot_figure
img = plotter(identifier, figname, request.args.items())
File "./app.py", line 122, in plotter
sim = Simulation.from_file(identifier)
File "/home/abkos/abkosproject/abkos/calculation.py", line 56, in from_file
params_or_simulation = load(fname, params_only=new)
File "/home/abkos/abkosproject/abkos/_tools.py", line 42, in load
return pickle.load(pickle_file)
EOFError
10.0.2.2 - - [07/Aug/2016 14:39:38] "GET /api/simulations/20160807_123707581/heatmap_axial_temperatures.png HTTP/1.1" 500 -
</code></pre>
<p>The code is working fine on both MacOS and Linux Mint using Python 3.4.3. However, it does not work on Ubuntu 14.04 (Python 3.4.3).</p>
<p>Any ideas about where to start to investigate the error?</p>
| 0 | 2016-08-07T13:57:41Z | 38,828,632 | <p>Since I was not able to find any coding errors I compared the three systems to each other and found out that there were nearly identically from a software point-of-view. All of them are using Python 3.4.3 64-bit and pickle is part of Python's default modules.</p>
<p>So I came to the conclusion that this might be a hardware related problem. Since both the MacOS-machine and the Mint-machine are 'real' machines and the Ubuntu one is a VM only I compared general hardware specs like number of CPUs and RAM.</p>
<p>The real machines are equipped with 8 GB of RAM resp. 12 GB for the Mint one. So I increased the RAM of the VM from about 1 GB to 3 GB and everything works fine.</p>
<p>So even there was no <code>MemoryError</code> or similar raised, <code>EOFError</code> can be related to memory.</p>
| 0 | 2016-08-08T11:58:09Z | [
"python",
"osx",
"python-3.x",
"ubuntu",
"pickle"
] |
Python & Pandas: Will using many df.copy affect code's performance? | 38,814,873 | <p>I'm doing some data analysis, and the data are in pandas <code>DataFrame</code>, <code>df</code>.</p>
<p>There are several function that I defined to do process on the <code>df</code>.</p>
<p>For encapsulation purpose, I define the functions like this:</p>
<pre><code>def df_process(df):
df=df.copy()
# do some process work on df
return df
</code></pre>
<p>In Jupyter Notebook, I use the function as</p>
<pre><code>df = df_process(df)
</code></pre>
<p>The reason for using <code>df.copy()</code> is that otherwise the original <code>df</code> would be modified, whether you assign it back or not. (see <a href="http://stackoverflow.com/questions/38579921/python-pandas-how-to-return-a-copy-of-a-dataframe">Python & Pandas: How to return a copy of a dataframe?</a>)</p>
<p>My question is:</p>
<ol>
<li><p>Is using <code>df=df.copy()</code> proper here? If not, how should a function handle data be defined?</p></li>
<li><p>Since I use several such data processing function, will it affect my program's performance? And how much?</p></li>
</ol>
| 0 | 2016-08-07T14:02:01Z | 38,815,165 | <p>Far better would be:</p>
<pre><code>def df_process(df):
# do some process work on df
def df_another(df):
# other processing
def df_more(df):
# yet more processing
def process_many(df):
for frame_function in (df_process, df_another, df_more):
df_copy = df.copy()
frame_function(df_copy)
# emit the results to a file or screen or whatever
</code></pre>
<p>The key here is if you must make a copy, make only one, process it, stash the results somewhere and then dispose of it by reassigning <code>df_copy</code>. Your question made no mention of why you are hanging onto processed copies so this assumes you need not.</p>
| 1 | 2016-08-07T14:31:56Z | [
"python",
"pandas"
] |
Refactor a (multi)generator python function | 38,814,896 | <p>I am looking for a pythonic way to further refactor the function <code>event_stream()</code> below. This simplified and abstracted from a python flask web app I am writing to experiment with python.</p>
<p>The function is a generator, with an endless loop checking a number of objects (currently implemented as dicts) for changes (made elsewhere in the application).</p>
<p>If an object has changed, an event is yielded, which the caller function <code>sse_request()</code> will then use to create a server-side-event.</p>
<pre><code>def event_stream():
parrot_old = parrot.copy()
grail_old = grail.copy()
walk_old = walk.copy()
while True:
print("change poller loop")
gevent.sleep(0.5)
parrot_changed, parrot_old = check_parrot(parrot_new=parrot, parrot_old=parrot_old)
if parrot_changed:
yield parrot_event(parrot)
grail_changed, grail_old = check_grail(grail_new=grail, grail_old=grail_old)
if grail_changed:
yield grail_event(grail)
walk_changed, walk_old = check_walk(walk_new=walk, walk_old=walk_old)
if walk_changed:
yield walk_event(walk)
@app.route('/server_events')
def sse_request():
return Response(
event_stream(),
mimetype='text/event-stream')
</code></pre>
<p>While event_stream() is currently short enough to be readable, it breaks the concept of doing "one only, and do that well",
because it is tracking changes to three different objects. If I was to add further objects to track
(e.g. an "inquisitor", or a "brian") it would become unwieldy.</p>
| 0 | 2016-08-07T14:04:07Z | 38,815,480 | <p>How about creating a dict mapping your objects to the change detector function?</p>
<p>It may be something like this:</p>
<pre><code>object_change_checker_events = {
parrot: {
"checker": check_parrot,
"event": parrot_event
},
//grail : ................
.................
}
def event_stream(object_change_checker_events):
copies = {}
for obj in object_change_checker_events:
copies[obj] = obj.copy())
while True:
print("change poller loop")
gevent.sleep(0.5)
for obj in copies:
obj_changed, obj_old = object_change_checker_events[obj]["checker"](obj, copies[obj]
if(obj_changed):
yield object_change_checker_events[obj]["event"](obj)
</code></pre>
<p>Your main job here will be to construct the <b>object_change_checker_events</b> dictionary.</p>
<p></p>
<p>I have changed the structure of the dictionary. Try this:</p>
<pre><code>object_change_checker_events = {
'parrot': {
"object": parrot
"checker": check_parrot,
"event": parrot_event
},
//grail : ................
.................
}
def event_stream(object_change_checker_events):
copies = {}
for obj in object_change_checker_events:
copies[obj] = {
"old": obj["object"].copy(),
"new": obj["object"]
}
while True:
print("change poller loop")
gevent.sleep(0.5)
for obj in copies:
obj_changed, obj_old = object_change_checker_events[obj]["checker"](copies[obj]["new"], copies[obj]["old"])
if(obj_changed):
yield object_change_checker_events[obj]["event"](obj)
</code></pre>
| 1 | 2016-08-07T15:05:08Z | [
"python",
"refactoring",
"generator"
] |
Refactor a (multi)generator python function | 38,814,896 | <p>I am looking for a pythonic way to further refactor the function <code>event_stream()</code> below. This simplified and abstracted from a python flask web app I am writing to experiment with python.</p>
<p>The function is a generator, with an endless loop checking a number of objects (currently implemented as dicts) for changes (made elsewhere in the application).</p>
<p>If an object has changed, an event is yielded, which the caller function <code>sse_request()</code> will then use to create a server-side-event.</p>
<pre><code>def event_stream():
parrot_old = parrot.copy()
grail_old = grail.copy()
walk_old = walk.copy()
while True:
print("change poller loop")
gevent.sleep(0.5)
parrot_changed, parrot_old = check_parrot(parrot_new=parrot, parrot_old=parrot_old)
if parrot_changed:
yield parrot_event(parrot)
grail_changed, grail_old = check_grail(grail_new=grail, grail_old=grail_old)
if grail_changed:
yield grail_event(grail)
walk_changed, walk_old = check_walk(walk_new=walk, walk_old=walk_old)
if walk_changed:
yield walk_event(walk)
@app.route('/server_events')
def sse_request():
return Response(
event_stream(),
mimetype='text/event-stream')
</code></pre>
<p>While event_stream() is currently short enough to be readable, it breaks the concept of doing "one only, and do that well",
because it is tracking changes to three different objects. If I was to add further objects to track
(e.g. an "inquisitor", or a "brian") it would become unwieldy.</p>
| 0 | 2016-08-07T14:04:07Z | 38,831,039 | <h2>Short Answer:</h2>
<hr>
<p>Two steps of refactoring have been applied to the function <code>event_stream()</code>. These are explained in chronological order in the âLong Answerâ below, and in summary here:</p>
<p>The original function had multiple yields: one per âobjectâ whose changes are to be tracked. Adding further objects implied adding further yields. </p>
<ul>
<li>In the first refactoring this was eliminated by looping through a structure storing the objects to be tracked.</li>
<li>In the second refactoring changing the âobjectsâ from dicts to instances of real objects. This allowed the storage structure and the loop to become radically simpler. The "old copies" and the functions used to spot changes and create the resulting server-side-events could be moved into the objects.</li>
</ul>
<p>The fully refactored code is at the bottom of the "Long Answer".</p>
<h2>Long Answer, Step by Step:</h2>
<hr>
<h2>First Refactor:</h2>
<p>Below I have pasted my first refactoring, inspired by <strong>jgr0</strong>'s answer.
His initial suggestion did not work straight away, because it used a dict as a dict key; but keys must be hashable (which dicts are not).
It looks like we both hit on using a string as key, and moving the object/dict to an attribute in parallel.</p>
<p>This solution works where the "object" is either a dict, or a list of dicts (hence use of <code>deepcopy()</code>).</p>
<p>Each object has a "checker" function to check if it has changed (e.g check_parrot),
and an "event" function (e.g. parrot_event) to build the event to be yielded.</p>
<p>Additional arguments can be configured for the xxx_event() functions via the "args" attribute, which is passed as *args.</p>
<p>The objects in <code>copies{}</code> are fixed at the time of copying, while those in configured in <code>change_objects{}</code> are references, and thus reflect the latest state of the objects. Comparing the two allows changes to be identified.</p>
<p>While the <code>event_stream()</code> function is now arguably less readable than my original,
I no longer need to touch it to track the changes of further objects. These are added to <code>change_objects{}</code>.</p>
<pre><code># dictionary of objects whose changes should be tracked by event_stream()
change_objects = {
"parrot": {
"object": parrot,
"checker": check_parrot,
"event": parrot_event,
"args": (walk['sillyness'],),
},
"grail": {
"object": grail,
"checker": check_grail,
"event": grail_event,
},
"walk": {
"object": walk,
"checker": check_walk,
"event": walk_event,
},
}
def event_stream(change_objects):
copies = {}
for key, value in change_objects.items():
copies[key] = {"obj_old": deepcopy(value["object"])} # ensure a true copy, not a reference!
while True:
print("change poller loop")
gevent.sleep(0.5)
for key, value in change_objects.items():
obj_new = deepcopy(value["object"]) # use same version in check and yield functions
obj_changed, copies[key]["obj_old"] = value["checker"](obj_new, copies[key]["obj_old"])
if (obj_changed): # handle additional arguments to the event function
if "args" in value:
args = value["args"]
yield value["event"](obj_new, *args)
else:
yield value["event"](obj_new)
@app.route('/server_events')
def sse_request():
return Response(
event_stream(change_objects),
mimetype='text/event-stream')
</code></pre>
<h2>Edit: Second Refactor, using Objects instead of Dicts:</h2>
<p>If I use objects rather than the original dicts:</p>
<ul>
<li>The change-identification and event-building methods can be moved
into the objects.</li>
<li>The objects can also store the "old" state.</li>
</ul>
<p>Everything becomes simpler and even more readable: <code>event_stream()</code> no longer needs a <code>copies{}</code> dict (so it has only one structure to loop over), and the <code>change_objects{}</code> is now a simple list of tracker objects:</p>
<pre><code>def event_stream(change_objects):
while True:
print("change poller loop")
gevent.sleep(0.5)
for obj in change_objects:
if obj.changed():
yield obj.sse_event()
@app.route('/server_events')
def sse_request():
# List of objects whose changes are tracked by event_stream
# This list is in sse_request, so each client has a 'private' copy
change_objects = [
ParrotTracker(),
GrailTracker(),
WalkTracker(),
...
SpamTracker(),
]
return Response(
event_stream(change_objects),
mimetype='text/event-stream')
</code></pre>
<p>An example tracker class is:</p>
<pre><code>from data.parrot import parrot
class ParrotTracker:
def __init__(self):
self.old = deepcopy(parrot)
self.new = parrot
def sse_event(self):
data = self.new.copy()
data['type'] = 'parrotchange'
data = json.dumps(data)
return "data: {}\n\n".format(data)
def truecopy(self, orig):
return deepcopy(orig) # ensure is a copy, not a reference
def changed(self):
if self.new != self.old:
self.old = self.truecopy(self.new)
return True
else:
return False
</code></pre>
<p>I think it now smells much better!</p>
| 1 | 2016-08-08T13:52:51Z | [
"python",
"refactoring",
"generator"
] |
Set part of a lambda function in advance to avoid repeated code | 38,814,924 | <p>The following sorting method works perfectly.</p>
<pre class="lang-py prettyprint-override"><code>def sort_view_items(self):
cs = self.settings.case_sensitive
if self.settings.sort_by_file_name:
sk = lambda vi: (vi.name if cs else vi.name.lower(), vi.group, vi.tab)
elif self.settings.sort_by_folder:
sk = lambda vi: (vi.folder, vi.name if cs else vi.name.lower())
elif self.settings.sort_by_syntax:
sk = lambda vi: (vi.syntax, vi.name if cs else vi.name.lower())
elif self.settings.sort_by_indexes:
sk = lambda vi: (vi.group, vi.tab)
self.view_items.sort(key = sk)
</code></pre>
<p>However the case sensitive related section of the lambdas <code>vi.name if cs else vi.name.lower()</code> gets used 3 times which irks my repeated code gene.</p>
<p>Out of interest, can the case aspect be set in advance somehow, but without making permenant changes to the <code>name</code> attribute or doing so in a temporary copy of the <code>view_items</code> list?</p>
<p>For example I tried using a lambda within a lambda which I didn't think would work and, guess what, it didn't. Although unexpectedly the syntax was accepted (no exceptions), it just didn't result in any sorting being actually performed.</p>
<pre class="lang-py prettyprint-override"><code>def sort_view_items(self):
cs = self.settings.case_sensitive
name_lambda = lambda vi: vi.name if cs else vi.name.lower()
if self.settings.sort_by_file_name:
sk = lambda vi: (name_lambda, vi.group, vi.tab)
...
</code></pre>
<p>Thanks.</p>
| 9 | 2016-08-07T14:07:23Z | 38,814,961 | <p>You need to actually call <code>name_lambda</code>:</p>
<pre><code>sk = lambda vi: (name_lambda(vi), vi.group, vi.tab)
</code></pre>
<p>In your snippet, <code>name_lambda</code> is defined correctly but it is never going to be called.</p>
| 5 | 2016-08-07T14:11:00Z | [
"python",
"python-3.x"
] |
Set part of a lambda function in advance to avoid repeated code | 38,814,924 | <p>The following sorting method works perfectly.</p>
<pre class="lang-py prettyprint-override"><code>def sort_view_items(self):
cs = self.settings.case_sensitive
if self.settings.sort_by_file_name:
sk = lambda vi: (vi.name if cs else vi.name.lower(), vi.group, vi.tab)
elif self.settings.sort_by_folder:
sk = lambda vi: (vi.folder, vi.name if cs else vi.name.lower())
elif self.settings.sort_by_syntax:
sk = lambda vi: (vi.syntax, vi.name if cs else vi.name.lower())
elif self.settings.sort_by_indexes:
sk = lambda vi: (vi.group, vi.tab)
self.view_items.sort(key = sk)
</code></pre>
<p>However the case sensitive related section of the lambdas <code>vi.name if cs else vi.name.lower()</code> gets used 3 times which irks my repeated code gene.</p>
<p>Out of interest, can the case aspect be set in advance somehow, but without making permenant changes to the <code>name</code> attribute or doing so in a temporary copy of the <code>view_items</code> list?</p>
<p>For example I tried using a lambda within a lambda which I didn't think would work and, guess what, it didn't. Although unexpectedly the syntax was accepted (no exceptions), it just didn't result in any sorting being actually performed.</p>
<pre class="lang-py prettyprint-override"><code>def sort_view_items(self):
cs = self.settings.case_sensitive
name_lambda = lambda vi: vi.name if cs else vi.name.lower()
if self.settings.sort_by_file_name:
sk = lambda vi: (name_lambda, vi.group, vi.tab)
...
</code></pre>
<p>Thanks.</p>
| 9 | 2016-08-07T14:07:23Z | 38,815,221 | <p>Since you want to use it in 3 of 4 conditions, the best way for refusing of this repetition, is computing the name at the top of your <code>if</code> conditions. Also You can use a <code>def</code> key word to create your <code>key</code> function properly, and return the corresponding value, istead of defining a function each time. In this case you can pass the <code>vi</code> to <code>key_func</code> and calculate the <code>name</code> the the top level of this function.</p>
<pre><code>def sort_view_items(self):
def key_func(vi):
name = vi.name if self.settings.case_sensitive else vi.name.lower()
if self.settings.sort_by_file_name:
return name(vi), vi.group, vi.tab
elif self.settings.sort_by_folder:
return vi.folder,name(vi)
elif self.settings.sort_by_syntax:
return vi.syntax, name(vi)
elif self.settings.sort_by_indexes:
return vi.group, vi.tab
self.view_items.sort(key=key_func)
</code></pre>
| 1 | 2016-08-07T14:36:55Z | [
"python",
"python-3.x"
] |
Set part of a lambda function in advance to avoid repeated code | 38,814,924 | <p>The following sorting method works perfectly.</p>
<pre class="lang-py prettyprint-override"><code>def sort_view_items(self):
cs = self.settings.case_sensitive
if self.settings.sort_by_file_name:
sk = lambda vi: (vi.name if cs else vi.name.lower(), vi.group, vi.tab)
elif self.settings.sort_by_folder:
sk = lambda vi: (vi.folder, vi.name if cs else vi.name.lower())
elif self.settings.sort_by_syntax:
sk = lambda vi: (vi.syntax, vi.name if cs else vi.name.lower())
elif self.settings.sort_by_indexes:
sk = lambda vi: (vi.group, vi.tab)
self.view_items.sort(key = sk)
</code></pre>
<p>However the case sensitive related section of the lambdas <code>vi.name if cs else vi.name.lower()</code> gets used 3 times which irks my repeated code gene.</p>
<p>Out of interest, can the case aspect be set in advance somehow, but without making permenant changes to the <code>name</code> attribute or doing so in a temporary copy of the <code>view_items</code> list?</p>
<p>For example I tried using a lambda within a lambda which I didn't think would work and, guess what, it didn't. Although unexpectedly the syntax was accepted (no exceptions), it just didn't result in any sorting being actually performed.</p>
<pre class="lang-py prettyprint-override"><code>def sort_view_items(self):
cs = self.settings.case_sensitive
name_lambda = lambda vi: vi.name if cs else vi.name.lower()
if self.settings.sort_by_file_name:
sk = lambda vi: (name_lambda, vi.group, vi.tab)
...
</code></pre>
<p>Thanks.</p>
| 9 | 2016-08-07T14:07:23Z | 38,815,921 | <p>This requires you to add a new property, "lower_name", to your class, but this one change lets you <em>greatly</em> simplify the rest of the code.</p>
<pre><code>from operator import attrgetter
class Things(object):
@property
def lower_name(self):
return self.name.lower()
def sort_view_items(self):
name_field = "name" if self.settings.case_sensitive else "lower_name"
if self.settings.sort_by_file_name:
fields = (name_field, "group", "tab")
elif self.settings.sort_by_folder:
fields = ("folder", name_field)
elif self.settings.sort_by_syntax:
fields = ("syntax", name_field)
elif self.settings.sort_by_indexes:
fields = ("group", "tab")
self.view_items.sort(key=attrgetter(*fields))
</code></pre>
| 5 | 2016-08-07T15:57:36Z | [
"python",
"python-3.x"
] |
Querying a dict collection in SQLAlchemy by key/value pair | 38,814,995 | <p>I have an SQLAlchemy model that associates tags (key/value pairs) with elements, like so:</p>
<pre><code>from sqlalchemy import create_engine, Column, ForeignKey, Integer, Unicode
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import backref, relationship, sessionmaker
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.orm.collections import attribute_mapped_collection
engine = create_engine("sqlite:///:memory:")
base = declarative_base(bind=engine)
class Tag(base):
__tablename__ = "tags"
tag_id = Column(Integer, primary_key=True)
key = Column(Unicode(256))
value = Column(Unicode(256))
def __init__(self, key="", value="", **kwargs):
self.key = key
self.value = value
base.__init__(self, **kwargs)
class Element(base):
__tablename__ = "elements"
element_id = Column(Integer, primary_key=True)
tags = association_proxy("elements_tags", "tag_value",
creator=lambda k, v: ElementsTags(tag_key=k, tag_value=v))
class ElementsTags(base):
__tablename__ = "elements_tags"
map_id = Column(Integer, primary_key=True)
element_id = Column(Integer, ForeignKey('elements.element_id'))
tag_id = Column(Integer, ForeignKey('tags.tag_id'))
element = relationship(Element, foreign_keys=[element_id],
backref=backref("elements_tags",
collection_class=attribute_mapped_collection("tag_key"),
cascade="all, delete-orphan"))
tag = relationship(Tag, foreign_keys=[tag_id])
tag_key = association_proxy("tag", "key")
tag_value = association_proxy("tag", "value")
base.metadata.create_all()
</code></pre>
<p>Element.tags is a dictionary collection, with some proxying to make it appear just like a plain dict, which works really well:</p>
<pre><code>session = sessionmaker(bind=engine)()
element = Element()
element.tags = {u"foo": u"bar", u"bang": u"baz"}
session.add(element)
session.commit()
</code></pre>
<p>Now, how would I go about getting all <code>Element</code>s that have a certain key/value pair attached as tag, using <code>session.query(Element)</code>?</p>
<p>I found <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/associationproxy.html#querying-with-association-proxies" rel="nofollow">this documentation</a> from which I'd derive <code>session.query(Element).filter(Element.tags.has(key="foo", value="bar")).all()</code>. However, this throws:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/sqlalchemy/ext/associationproxy.py", line 409, in has
if self._target_is_object:
File "/usr/lib/python2.7/dist-packages/sqlalchemy/util/langhelpers.py", line 754, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "/usr/lib/python2.7/dist-packages/sqlalchemy/ext/associationproxy.py", line 244, in _target_is_object
return getattr(self.target_class, self.value_attr).impl.uses_objects
AttributeError: 'AssociationProxy' object has no attribute 'impl'
</code></pre>
| 0 | 2016-08-07T14:14:18Z | 38,917,242 | <p>Unfortunately, such queries are not yet supported in SQLAlchemy up to 1.1.0~b3. One has to construct the query manually by joining the tables otherwise linked through the association proxy.</p>
<p>Support will come in a future version and there is already a patch: <a href="https://bitbucket.org/zzzeek/sqlalchemy/issues/3769/chained-any-has-with-association-proxy" rel="nofollow">https://bitbucket.org/zzzeek/sqlalchemy/issues/3769/chained-any-has-with-association-proxy</a></p>
<p>It is also trivially possible to monkey patch the support into current SQLAlchemy versions: <a href="https://github.com/Natureshadow/OSMAlchemy/blob/master/osmalchemy/util/patch.py" rel="nofollow">https://github.com/Natureshadow/OSMAlchemy/blob/master/osmalchemy/util/patch.py</a></p>
| 0 | 2016-08-12T11:48:47Z | [
"python",
"sqlalchemy"
] |
Error when using two flags OpenCv's calibrateCamera function | 38,815,011 | <p>I am using the <code>calibrateCamera</code> function. </p>
<p>How do I use two flags? I want to use the <code>CALIB_USE_INTRINSIC_GUESS</code>, and <code>CALIB_FIX_PRINCIPAL_POINT</code> together, but I am not sure of the syntax. When I use just the first flag, the code runs fine, but when I use two flags using the following code:</p>
<pre><code>a,camMatrix, c, rvec, tvec = cv2.calibrateCamera([obj_points], [img_points], size, camera_matrix, dist_coefs, flags=(cv2.CALIB_USE_INTRINSIC_GUESS and cv2.CALIB_FIX_PRINCIPAL_POINT))
</code></pre>
<p>I get the error:</p>
<blockquote>
<p>OpenCV Error: Bad argument (For non-planar calibration rigs the initial intrinsic matrix must be specified) in cvCalibrateCamera2, file D:\Build\OpenCV\opencv-3.1.0\modules\calib3d\src\calibration.cpp, line 1440
Traceback (most recent call last):
File "C:/Bdrive/AlgoSurg intern/DLT/CamCalTrial2.py", line 109, in
a,camMatrix, c, rvec, tvec = cv2.calibrateCamera([obj_points], [img_points], size, camera_matrix, dist_coefs, flags=(cv2.CALIB_USE_INTRINSIC_GUESS and cv2.CALIB_FIX_PRINCIPAL_POINT))
cv2.error: D:\Build\OpenCV\opencv-3.1.0\modules\calib3d\src\calibration.cpp:1440: error: (-5) For non-planar calibration rigs the initial intrinsic matrix must be specified in function cvCalibrateCamera2</p>
</blockquote>
<p>Either the syntax is wrong, or maybe there is something that I am missing?</p>
| 0 | 2016-08-07T14:16:00Z | 38,822,673 | <p>You have to do it this way:</p>
<pre><code>a,camMatrix, c, rvec, tvec = cv2.calibrateCamera([obj_points], [img_points], size, camera_matrix, dist_coefs, flags=(cv2.CALIB_USE_INTRINSIC_GUESS + cv2.CALIB_FIX_PRINCIPAL_POINT))
</code></pre>
<p>And there is no need for the parenthesis around the flags, so this is acceptable as well:</p>
<pre><code>a,camMatrix, c, rvec, tvec = cv2.calibrateCamera([obj_points], [img_points], size, camera_matrix, dist_coefs, flags=cv2.CALIB_USE_INTRINSIC_GUESS + cv2.CALIB_FIX_PRINCIPAL_POINT)
</code></pre>
| 0 | 2016-08-08T06:37:51Z | [
"python",
"opencv"
] |
How to use user permissions in django-tables2 Column | 38,815,153 | <p>Using djang-tables2 custom table as:</p>
<p>tables.py:</p>
<pre><code>import django_tables2 as tables
from django_tables2.utils import A
from .models import Person
class PersonTable(tables.Table):
view_column = tables.LinkColumn('person:pessoas_detail', args=[A('pk')])
class Meta:
model = Person
</code></pre>
<p>views.py:</p>
<pre><code>from .models import Person
class ListView(SingleTableView):
model = Person
table_class = PersonTable
</code></pre>
<p>I need to check permission FOO on the view_column.
Because, view_column is a class attribute, I cannot use a decorator as @permission_required.</p>
<p>Probably I could call something other than tables.LinkColumn to test the permission and then return the column. However, in order to do this, I would need to access the user object (probably from the request object), which I wouldn't have access at this point.</p>
<p>Is there a simpler way for doing this?</p>
<p>Basically the idea is to show a column only if there is permission access to it or not show at all.</p>
| 1 | 2016-08-07T14:30:23Z | 38,821,737 | <p>I think that the easier way to do what you want is to simply use a template column (that's what I do): </p>
<pre><code>view_column = tables.TemplateColumn("""
{% if has_perm('FOO') %}
<a href='{% url "person:pessoas_detail" record.id %}>{{ record.id }}</a>
{% else %}
{{ record.id }}
{% endif %}
""", orderable=False)
</code></pre>
<p>Now if the user has the correct permission then it will display the link - if not it will just display the id of each record. </p>
| 0 | 2016-08-08T05:17:37Z | [
"python",
"django",
"permissions",
"django-class-based-views",
"django-tables2"
] |
Python: printing in color and with style | 38,815,176 | <p>If I want to print colored text, I would just do, using codes</p>
<pre><code>green = '\033[0;32m'
print green + 'Hello'
</code></pre>
<p>and that gives me green text. If I want to have bold text, I would just use the code for bold, which is <code>'\033[1m'</code></p>
<p>Now, I tried to combine them as</p>
<pre><code>print bold + green + 'Hello'
</code></pre>
<p>where <code>bold</code> is the aforementioned code, and that didn't work, gave me just green text with no bold style.</p>
<p>Anyway, what am I missing to combine color with style?</p>
| 1 | 2016-08-07T14:32:42Z | 38,815,263 | <p>I can recommand <a href="https://gist.github.com/dnmellen/5584007" rel="nofollow">this gist</a> by Diego Navarro Mellén.</p>
<p>You can combine whatever you like when doing something like this:</p>
<pre><code>with pretty_output(BOLD, FG_GREEN) as out:
out.write('This is a bold text in green')
</code></pre>
| 3 | 2016-08-07T14:42:12Z | [
"python",
"printing",
"stdout",
"ansi-colors"
] |
Python: printing in color and with style | 38,815,176 | <p>If I want to print colored text, I would just do, using codes</p>
<pre><code>green = '\033[0;32m'
print green + 'Hello'
</code></pre>
<p>and that gives me green text. If I want to have bold text, I would just use the code for bold, which is <code>'\033[1m'</code></p>
<p>Now, I tried to combine them as</p>
<pre><code>print bold + green + 'Hello'
</code></pre>
<p>where <code>bold</code> is the aforementioned code, and that didn't work, gave me just green text with no bold style.</p>
<p>Anyway, what am I missing to combine color with style?</p>
| 1 | 2016-08-07T14:32:42Z | 38,816,787 | <p>Following up on Or Duan's answer, turns out that the code I'm using for green works well alone but somehow when concatenated with another code does prevent the combination of styles.</p>
<p>In the reported Gist, the code for green text is </p>
<pre><code>green = '\033[32m'
</code></pre>
<p>so lacks the 0; I have in mine. With this code, the concatenation achieves the result.</p>
<p>It's because the 0 in front is resetting, see <a href="https://en.wikipedia.org/wiki/ANSI_escape_code" rel="nofollow">here</a>.</p>
| 0 | 2016-08-07T17:34:47Z | [
"python",
"printing",
"stdout",
"ansi-colors"
] |
Multiprocessing: How to determine whether a job is waiting or submitted? | 38,815,288 | <h2>Background</h2>
<ul>
<li>A small server which waits for different types of jobs which are represented
as Python functions (<code>async_func</code> and <code>async_func2</code> in the sample code below). </li>
<li>Each job gets submitted to a <code>Pool</code> with <code>apply_async</code> and takes a different amount of time, i.e. I cannot be sure that a job which was submitted first, also finishes first</li>
<li>I can check whether the job was finished with <code>.get(timeout=0.1)</code></li>
</ul>
<h2>Question</h2>
<p>How I can check whether the job is still waiting in the queue or is already running?</p>
<p>Is using a <code>Queue</code> the correct way or is there a more simple way?</p>
<h2>Code</h2>
<pre><code>import multiprocessing
import random
import time
def async_func(x):
iterations = 0
x = (x + 0.1) % 1
while (x / 10.0) - random.random() < 0:
iterations += 1
time.sleep(0.01)
return iterations
def async_func2(x):
return(async_func(x + 0.5))
if __name__ == "__main__":
results = dict()
status = dict()
finished_processes = 0
worker_pool = multiprocessing.Pool(4)
jobs = 10
for i in range(jobs):
if i % 2 == 0:
results[i] = worker_pool.apply_async(async_func, (i,))
else:
results[i] = worker_pool.apply_async(async_func2, (i,))
status[i] = 'submitted'
while finished_processes < jobs:
for i in range(jobs):
if status[i] != 'finished':
try:
print('{0}: iterations needed = {1}'.format(i, results[i].get(timeout=0.1)))
status[i] = 'finished'
finished_processes += 1
except:
# how to distinguish between "running but no result yet" and "waiting to run"
status[i] = 'unknown'
</code></pre>
| 2 | 2016-08-07T14:44:16Z | 38,815,487 | <p>Just send the status dict, to the function, since dicts are mutable all you need to do is change a bit your functions:</p>
<pre><code>def async_func2(status, x):
status[x] = 'Started'
return(async_func(x + 0.5))
</code></pre>
<p>Of course you can change the status to pending just before calling your <code>apply_async</code></p>
| 1 | 2016-08-07T15:05:57Z | [
"python",
"multiprocessing"
] |
performance issue for intermediate merge/join dataframes to compute stats | 38,815,348 | <p>I have a dataframe that is comprised of city airport combination pairs from a total universe of ~4000 airports. The number of combinations is in the millions but I work with a subset of the data which is approximately 1.5 million pairs (rows of df_pairs).</p>
<p><strong>df_pairs:</strong> </p>
<pre><code> city1 city2
0 sfo yyz
1 sfo yvr
2 sfo dfw
3 sfo ewr
4 sfo pdx
</code></pre>
<p><strong>output of df_pairs.to_dict('records'):</strong></p>
<pre><code>[{'index': 0, 'city1': 'sfo', 'city2': 'yyz'},
{'index': 1, 'city1': 'sfo', 'city2': 'yvr'},
{'index': 2, 'city1': 'sfo', 'city2':'dfw'},
{'index': 3, 'city1': 'sfo', 'city2':'ewr'},
{'index': 4, 'city1': 'sfo', 'city2': 'pdx'}]
</code></pre>
<p>For each city pair (row) in the <code>df_pairs</code>, I want to perform various pair level computations. </p>
<p>I have 3 additional dataframes that hold various numerical and categorical information about each airport. </p>
<p>They look like something like (although some dfs are monthly data and others daily data):</p>
<p><strong>df_stats1:</strong></p>
<pre><code>city fuel landings takeoffs passengers
date
2014-05-01 sfo 2.32 4.26 4.87 6.58
2014-05-01 yyz 14.00 1.50 20.00 5.00
2014-05-01 yvr 24.78 2.90 50.55 6.64
2014-05-01 dfw 2.40 4.06 4.06 6.54
2014-05-01 ewr 30.35 9.96 64.24 6.66
2014-05-01 pdx 60.35 5.45 4.12 6.98
</code></pre>
<p><strong>Output of df_stats1.reset_index().to_dict('records'):</strong></p>
<pre><code>[{'date': Timestamp('2014-05-01 00:00:00'),
'city': 'sfo',
'landings': 4.26,
'passengers': 6.58,
'fuel': 2.32,
'takeoffs': 4.87},
{'date': Timestamp('2014-05-01 00:00:00'),
'city': 'yyz',
'landings': 1.5,
'passengers': 5.00,
'fuel': 14.00,
'takeoffs': 20.00},
{'date': Timestamp('2014-05-01 00:00:00'),
'city': 'yvr',
'landings': 2.9,
'passengers': 6.64,
'fuel': 24.78,
'takeoffs': 50.55},
{'date': Timestamp('2014-05-01 00:00:00'),
'city': 'dfw',
'landings': 4.06,
'passengers': 6.54,
'fuel': 2.4,
'takeoffs': 4.06},
{'date': Timestamp('2014-05-01 00:00:00'),
'city': 'ewr',
'landings': 9.96,
'passengers': 6.66,
'fuel': 30.35,
'takeoffs': 64.24},
{'date': Timestamp('2014-05-01 00:00:00'),
'city': 'pdx',
'landings': 5.45,
'passengers': 6.98,
'fuel': 60.35,
'takeoffs': 4.12}]
</code></pre>
<p>Now, I have a function <code>calstats</code> that is executed by:</p>
<pre><code>df_pairs.apply(calstats, axis=1, args=(v1,v2,v3,v4,v5,v6,v7, blah blah))
</code></pre>
<p>The first thing <code>calcstats</code> function does is to construct 3 intermediate/temporary dataframes by selecting the data for each city in the pair from the stat dfs and aligning them side by side in a row by performing a <code>merge</code>. </p>
<p><strong>Example of one of the intermediate/temp dfs:</strong> </p>
<pre><code>city1_df = df_stats1[df_stats1['city'] == row['city1']]
city2_df = df_stats1[df_stats1['city'] == row['city2']]
tmp_city_pair_df = city1_df.merge(city2_df, left_index=True, right_index=True, how = 'right', suffixes=('_1','_2'))
</code></pre>
<p>I then use the 3 intermediate/temp dfs (i.e. tmp_city_pair_df) to perform various computations like the difference between landings between the pairs, the max(of this difference in the time period under question), min() etc.</p>
<p>I have various performance issues that arise. </p>
<p>The first is that the total time required to construct the 3 intermediate dfs is approximately: <code>0:00:00.048481</code>.</p>
<p>I have approximately <code>1.5</code> million rows in <code>df_pairs</code> so the total cost to perform the intermediate dfs is <code>1,500,000 x 0:00:00.048481</code> = <code>72,721.5</code> seconds = <code>20.2</code> hours.</p>
<p>So it takes <code>20</code> hours just to construct the intermediate dfs and does not include the time cost required to use those intermediate dfs in performing further computations. </p>
<p>I'm wondering whether there is a more efficient way to do this. </p>
<p>Essentially, what I'm doing is a lookup of <code>city1</code> and <code>city2</code> in <code>df_stats1</code>, <code>df_stats2</code> and <code>df_stats3</code> and constructing intermediate/temporary dfs which I can work with to perform pair level computations. </p>
<p><strong>UPDATE</strong></p>
<p>I wanted to provide additional information.</p>
<p>So, the intent is to produce a final dataframe on a pair basis that looks something like the following, which I can use for further processing.</p>
<pre><code>city1 city2 stat1, stat2, stat3, stat4, stat5, stat6 ...
0 sfo yyz, x, x, x, x, x, x
1 sfo yvr, y, y, y, y, y, y
2 sfo dfw, z, z, z, z, z, z
3 sfo ewr, a, a, a, a, a, a
4 sfo pdx, b, b, b, b, b, b
</code></pre>
<p>The statistics named stat1 through stat6 above are proprietary statistics that do not exist in the raw data.</p>
<p>The raw data is comprised of 3 dataframes, which I call:</p>
<pre><code>df_stat1
df_stat2
df_stat3
</code></pre>
<p><code>df_stat1</code> = daily data (fuel, landings, takeoffs, passengers) for each airport for the past 24 months</p>
<p><code>df_stat2</code> = <code>df_stat1</code> but aggregated to the month (via <code>df.stat1.groupby(['city',pd.TimeGrouper('M')]</code></p>
<p><code>df_stat3</code> = monthly data time series for each airport for the past 24 months that comprises information such as landing fees, revenue etc</p>
<p>Now, to get to the final dataframe various computations need to take place. I want to compute things like:</p>
<pre><code>1) City1 Landings - City2 Landings (on a daily and monthly basis)
2) Sign of statistic in #1 (positive or negative)
</code></pre>
<p>So for example, in the final dataframe, <code>stat1</code> could be:</p>
<p>Sum of ONLY positive values in #2 above.</p>
<p>So you can see that various operations need to occur to arrive at the final dataframe. </p>
<p>I'm not sure how I can do this to best utilize pandas/python's vectorization capabilities. </p>
<p>For example, to produce the Sum of ONLY positive values in #2 above, I would need to join daily data time series (from df_stat1) for each city pair, compute the subtraction between City1 landings and City2 landings and then Sum the positive values.</p>
| 1 | 2016-08-07T14:50:53Z | 38,815,638 | <p>Python (and pandas) have bad performance when it comes to constructing a large number of objects. Your <code>merge</code> for each row in an <code>apply</code> does just that. Instead, you might try the following:</p>
<pre><code>tmp = pd.merge(df_pairs, df_stats.add_suffix('_1'), left_on='city1', right_on='city_1', how='left')
pd.merge(tmp, df_stats.add_suffix('_2'), left_on='city2', right_on='city_2', how='left')
</code></pre>
<p>This will <em>first</em> perform the merge, effectively (the two-line construction here is in order to save space, and do the merge just on all pairs in <code>df_pairs</code>).</p>
<p>Moreover, you can now do all your analysis vectorically, which should be much faster in any case. If you add more details regarding the analysis you want, then this can be addressed further.</p>
<p><strong>Edit</strong></p>
<p>Based on edits to the question and comments, here is an outline of dealing with daily data. Specifically, let's deal with daily differences in landing dates (which you can adapt for all sorts of variations, e.g., only positive differences).</p>
<p>Say you start with</p>
<pre><code>landings_by_date = df_stats1[['city', 'date', 'landings']].set_index(['city', 'date']).unstack()
landings_by_date.columns = landings_by_date.columns.get_level_values(1)
</code></pre>
<p>To find the differences in landing dates for a specific date, say the first one (index 0), you can do</p>
<pre><code>lhs = pd.merge(df_pairs, landings_by_date.ix[:, [0]], left_on='city1', right_index=True, how='left').set_index(['city1', 'city2'])
rhs = pd.merge(df_pairs, landings_by_date.ix[:, [0]], left_on='city2', right_index=True, how='left').set_index(['city1', 'city2'])
lhs - rhs
</code></pre>
<p>(or, to drop to numpy,</p>
<pre><code>(lhs - rhs).values
</code></pre>
<p>)</p>
<p>To calculate some aggregate for all dates, perform this on a loop (so that the date index is 0, 1, ...), and update the aggregate.</p>
<p>Why should this be more efficient? According to the specifics in your problem, there are ~3000 daily dates, but ~1.5e6 rows. </p>
<ol>
<li><p>Even though you're looping (which is frowned upon in numerical Python), you're doing it for only ~3000 iterations, and vectorially crunching ~1.5e6 entries in each iteration.</p></li>
<li><p>You're not creating small DataFrames ~1.5e6 times (as in your question), you're creating (larger) DataFrames only ~3000 times.</p></li>
<li><p>The memory requirements should be tiny - just an extra ~1.5e6 per aggregate.</p></li>
</ol>
| 1 | 2016-08-07T15:24:27Z | [
"python",
"performance",
"pandas",
"merge"
] |
<Python - Kivy > GridLayout rendering a single Tile | 38,815,349 | <p>I have the following python classes:</p>
<pre><code>import os
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.uix.image import Image
from crawler.settings import ASSETS_DIR
class Map(GridLayout):
SIZE = 5
def __init__(self, **kwargs):
super(Map, self).__init__(**kwargs)
for _ in range(0, self.SIZE**2):
self.add_widget(Tile())
class Tile(Widget):
def __init__(self, **kwargs):
super(Tile, self).__init__(**kwargs)
self.add_widget(Image(source=os.path.join(ASSETS_DIR, 'images/chest.gif')))
</code></pre>
<p>And the following kv language definition:</p>
<pre><code>#:kivy 1.0.9
<Map>:
size: self.parent.size
<Tile>:
size: 20, 20
</code></pre>
<p>This only renders 1 chest (actually the loop runs ok, so maybe they're stacked?):
<a href="http://i.stack.imgur.com/Yvk7a.png" rel="nofollow"><img src="http://i.stack.imgur.com/Yvk7a.png" alt="enter image description here"></a>
While if I change the Tile class for some of the out-of-the-box Widgets like a Button:</p>
<pre><code>class Map(GridLayout):
SIZE = 5
def __init__(self, **kwargs):
super(Map, self).__init__(**kwargs)
for _ in range(0, self.SIZE**2):
self.add_widget(Button(text=str(_)))
</code></pre>
<p>It displays the correct result:
<a href="http://i.stack.imgur.com/vMZS2.png" rel="nofollow"><img src="http://i.stack.imgur.com/vMZS2.png" alt="enter image description here"></a></p>
<p>What am I missing in my Tile class to make this work? I think that's where the problem is, but I couldn't find it so far</p>
| 1 | 2016-08-07T14:50:54Z | 38,815,415 | <pre><code>class Tile(Widget):
def __init__(self, **kwargs):
super(Tile, self).__init__(**kwargs)
self.add_widget(Image(source=os.path.join(ASSETS_DIR, 'images/chest.gif')))
</code></pre>
<p>Each Tile is a Widget <em>containing</em> an Image, but Widget isn't a layout class so the Image just has the default pos of <code>(0, 0)</code> and size of <code>(100, 100)</code>.</p>
<p>You could instead make the Tile <em>be</em> the Image, or replace Widget with a layout like BoxLayout (this latter choice will be less efficient unless you need the extra layout behaviour).</p>
| 2 | 2016-08-07T14:58:26Z | [
"python",
"kivy",
"kivy-language"
] |
Gtk 3 position attribute on insert-text signal from Gtk.Entry is always 0 | 38,815,694 | <p>I am having trouble in managing the insert-text signal emitted by the Gtk.Entry widget. Consider the following example:</p>
<pre><code>from gi.repository import Gtk
def on_insert_text(entry, new_text, new_text_length, position):
print(position)
entry = Gtk.Entry()
entry.connect('insert-text', on_insert_text)
window = Gtk.Window()
window.connect("destroy", lambda q: Gtk.main_quit())
window.add(entry)
window.show_all()
Gtk.main()
</code></pre>
<p>The position attribute I am receiving on the signal handler is always 0. Unless I am misunderstanding this should it not be the position where the next text should be inserted?</p>
<p>In the end what I want to do is to validate the entry of text in the widget to restrict the characters that will be accepted. The way I plan to do this is similar to the example provided in the documentation in which all characters are transformed to uppercase.</p>
| 1 | 2016-08-07T15:31:06Z | 38,831,655 | <p>The handler of 'insert-text' is expected to update the value received in the position parameter (which we have seen in incorrect) to reflect the position from which future text should be inserted and return it. This is important so the cursor is changed to the right place after the signal handler returns (this is done by <code>gtk</code>). If you don't update and return then the cursor remains at position 0.</p>
<p>After following the suggestion of using <code>entry.get_position()</code> to obtain the right position value I found out that the update and return of position in my handler was being ignored by <code>pygobject</code>. It behaved as if I was not returning anything (the cursor remained at position 0). Setting the position inside the handler did not help, because <code>gtk</code> would change it back again to 0 after the handler returned.</p>
<p>After some further investigation I learned that the issue lies with the handling of in/out parameters in <code>pygobject</code> which works well in most cases but not with signals (see <a href="https://bugzilla.gnome.org/show_bug.cgi?id=644927" rel="nofollow">bug 644927</a>)</p>
<p><em>If you use connect to attach a handler to the signal and the signal has an in/out parameter you may not receive what you expect in the handler and even if you return a value this value will probably not be handled correctly by <code>pygobject</code> either. Anything that depends on that value will probably not work as expected (e.g. advance the cursor to the new position)</em></p>
<p>There is a solution though which is to override the associated vfunc (the default handler) instead of connecting with <code>connect()</code>. This solution implies deriving from the base class but it does work.</p>
<p>You can use this method for input validation/transformation on <code>Gtk.Entry</code>. An example handling my use case would be:</p>
<pre><code>import re
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class MyEntry(Gtk.Entry, Gtk.Editable):
def __init__(self):
super(MyEntry, self).__init__()
def do_insert_text(self, new_text, length, position):
regexp = re.compile('^(\d*\.?\d*)$')
if new_text == '.' and '.' in self.get_text():
return position
elif regexp.match(new_text) is not None:
self.get_buffer().insert_text(position, new_text, length)
return position + length
return position
entry = MyEntry()
window = Gtk.Window()
window.connect("destroy", lambda q: Gtk.main_quit())
window.add(entry)
window.show_all()
Gtk.main()
</code></pre>
<p>In this case the position parameter is received correctly and the return value is seen and used by pygobject so the cursor is correctly positioned.</p>
<p><strong>Important Note</strong>
You have to inherit from Gtk.Editable in addition to Gtk.Entry. If you do not do so you will start seeing the validation or whatever you do inside <code>do_insert_text</code> applying to every other <code>Gtk.Entry</code> in your application. If you do not inherit you are overriding the base implementation provided by Gtk.Editable which is called by all other <code>Gtk.Entry</code> widgets in your application. By inheriting from Gtk.Editable you override only the <em>'local'</em> copy of the base implementation which only applies to your custom class.</p>
| 2 | 2016-08-08T14:18:36Z | [
"python",
"python-3.x",
"gtk",
"gtk3",
"pygobject"
] |
How to use the return function but avoid repetition of a function? | 38,815,747 | <p>Trying to write this salary calculator script, but the output keeps on calculating taxes twice. It does what it is supposed to do, but I am misusing the concept of return statement, I reckon. I am kinda new to Python and just starting with the DSA. I tried searching for this problem a lot but apart from info for return statement, I couldnt solve this recurring statement problem. I would like your suggestions on the rest of the program as well. </p>
<p>Thanks!</p>
<p>Here is my code: </p>
<pre><code>import math
# Personal Details
name = input("Enter your first name: ")
position= input("Enter your job position: ")
def regPay():
#Computes regular hours weekly pay
hwage= float(input("Enter hourly wage rate: "))
tothours=int(input("Enter total regular hours you worked this week: "))
regular_pay= float(hwage * tothours)
print ("Your regular pay for this week is: ", regular_pay)
return hwage, regular_pay
def overTime(hwage, regular_pay):
#Computes overtime pay and adds the regular to give a total
totot_hours= int(input("Enter total overtime hours this week: "))
ot_rate = float(1.5 * (hwage))
otpay= totot_hours * ot_rate
print("The total overtime pay this week is: " ,otpay )
sum = otpay + regular_pay
print("So total pay due this week is: ", sum)
super_pay = float((9.5/100)*sum)
print ("Your super contribution this week is:",super_pay)
return super_pay
def taxpay():
#Computes the taxes for different income thresholds, for resident Aussies.
x = float(input("Enter the amount of your yearly income: "))
while True:
total = 0
if x < 18200:
print("Congrats! You dont have to pay any tax! :)")
break
elif 18201 < x < 37000:
total = ((x-18200)*0.19)
print ("You have to pay AUD" ,total , "in taxes this year")
return x
break
elif 37001 < x < 80000:
total = 3572 + ((x-37000)*0.32)
print("You have to pay AUD",(((x-37000)*0.32) +3572),"in taxes this year")
return x
break
elif 80001 < x < 180000:
total = 17547+((x-80000)*0.37)
print ("You have to pay AUD" ,total ,"in taxes this year")
return x
break
elif 180001 < x:
total = 54547+((x-180000)*0.45)
print ("You have to pay AUD" , total ,"in taxes this year")
return x
break
else:
print ("Invalid input. Enter again please.")
break
def super(x):
#Computes super over a gross income at a rate of 9.5%
super_rate = float(9.5/100)
super_gross = float((super_rate)*(x))
print ("Your super contribution this year is: ",super_gross)
def main():
#Main function to pass vars from regPay to overTime and call.
hw , r_p = regPay()
overTime(hw, r_p)
taxpay()
y = taxpay()
super(y)
#Call main
main()
</code></pre>
<p>The output I get in powershell:</p>
<pre><code>PS C:\Users\tejas\Desktop\DSA> python salary_calc.py
Enter your first name: tj
Enter your job position: it
Enter hourly wage rate: 23
Enter total regular hours you worked this week: 20
Your regular pay for this week is: 460.0
Enter total overtime hours this week: 20
The total overtime pay this week is: 690.0
So total pay due this week is: 1150.0
Your super contribution this week is: 109.25
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Your super contribution this year is: 1900.0
</code></pre>
| 0 | 2016-08-07T15:37:34Z | 38,815,813 | <p>From your output, I see it asks twice for the yearly income:</p>
<pre><code>Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
</code></pre>
<p>Looks like your problem is here:</p>
<pre><code>def main():
#Main function to pass vars from regPay to overTime and call.
hw , r_p = regPay()
overTime(hw, r_p)
taxpay()
y = taxpay()
super(y)
</code></pre>
<p>You call <code>taxpay()</code>, then set <code>y</code> to another call of <code>taxpay()</code>. Did you mean just to call this once? If so, try this instead:</p>
<pre><code>def main():
#Main function to pass vars from regPay to overTime and call.
hw , r_p = regPay()
overTime(hw, r_p)
y = taxpay()
super(y)
</code></pre>
| 1 | 2016-08-07T15:45:23Z | [
"python",
"return",
"python-3.4"
] |
How to use the return function but avoid repetition of a function? | 38,815,747 | <p>Trying to write this salary calculator script, but the output keeps on calculating taxes twice. It does what it is supposed to do, but I am misusing the concept of return statement, I reckon. I am kinda new to Python and just starting with the DSA. I tried searching for this problem a lot but apart from info for return statement, I couldnt solve this recurring statement problem. I would like your suggestions on the rest of the program as well. </p>
<p>Thanks!</p>
<p>Here is my code: </p>
<pre><code>import math
# Personal Details
name = input("Enter your first name: ")
position= input("Enter your job position: ")
def regPay():
#Computes regular hours weekly pay
hwage= float(input("Enter hourly wage rate: "))
tothours=int(input("Enter total regular hours you worked this week: "))
regular_pay= float(hwage * tothours)
print ("Your regular pay for this week is: ", regular_pay)
return hwage, regular_pay
def overTime(hwage, regular_pay):
#Computes overtime pay and adds the regular to give a total
totot_hours= int(input("Enter total overtime hours this week: "))
ot_rate = float(1.5 * (hwage))
otpay= totot_hours * ot_rate
print("The total overtime pay this week is: " ,otpay )
sum = otpay + regular_pay
print("So total pay due this week is: ", sum)
super_pay = float((9.5/100)*sum)
print ("Your super contribution this week is:",super_pay)
return super_pay
def taxpay():
#Computes the taxes for different income thresholds, for resident Aussies.
x = float(input("Enter the amount of your yearly income: "))
while True:
total = 0
if x < 18200:
print("Congrats! You dont have to pay any tax! :)")
break
elif 18201 < x < 37000:
total = ((x-18200)*0.19)
print ("You have to pay AUD" ,total , "in taxes this year")
return x
break
elif 37001 < x < 80000:
total = 3572 + ((x-37000)*0.32)
print("You have to pay AUD",(((x-37000)*0.32) +3572),"in taxes this year")
return x
break
elif 80001 < x < 180000:
total = 17547+((x-80000)*0.37)
print ("You have to pay AUD" ,total ,"in taxes this year")
return x
break
elif 180001 < x:
total = 54547+((x-180000)*0.45)
print ("You have to pay AUD" , total ,"in taxes this year")
return x
break
else:
print ("Invalid input. Enter again please.")
break
def super(x):
#Computes super over a gross income at a rate of 9.5%
super_rate = float(9.5/100)
super_gross = float((super_rate)*(x))
print ("Your super contribution this year is: ",super_gross)
def main():
#Main function to pass vars from regPay to overTime and call.
hw , r_p = regPay()
overTime(hw, r_p)
taxpay()
y = taxpay()
super(y)
#Call main
main()
</code></pre>
<p>The output I get in powershell:</p>
<pre><code>PS C:\Users\tejas\Desktop\DSA> python salary_calc.py
Enter your first name: tj
Enter your job position: it
Enter hourly wage rate: 23
Enter total regular hours you worked this week: 20
Your regular pay for this week is: 460.0
Enter total overtime hours this week: 20
The total overtime pay this week is: 690.0
So total pay due this week is: 1150.0
Your super contribution this week is: 109.25
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Your super contribution this year is: 1900.0
</code></pre>
| 0 | 2016-08-07T15:37:34Z | 38,815,845 | <p>Simply put, both of the following call / execute the <code>taxpay</code> function, so this will repeat exactly the same output, unless you modify global variables, which doesn't look like you are. </p>
<p>Only the second line will return the value into the <code>y</code> variable. </p>
<pre><code>taxpay()
y = taxpay()
</code></pre>
<p>Along with that point, here you call the function, but never capture its returned output </p>
<pre><code>overTime(hw, r_p)
</code></pre>
<p>And, as an aside, you don't want to break the input loop on invalid input. </p>
<pre><code>print ("Invalid input. Enter again please.")
break # should be 'continue'
</code></pre>
| 0 | 2016-08-07T15:49:08Z | [
"python",
"return",
"python-3.4"
] |
How to sort a numpy 2D array rows descending or ascending using a specific column indices | 38,815,776 | <p>Lets say I have a numpy 2D array like this:</p>
<pre><code>a = np.array([[3,6,7],[1,9,4],[ 3,7,8],[2,5,10]])
a
# array([[ 3, 6, 7],
# [ 1, 9, 4],
# [ 3, 7, 8],
# [ 2, 5, 10]])
</code></pre>
<p>I need to sort the rows descending based on the first column and ascending on the second column to get the below result:</p>
<pre><code>array([[ 3, 6, 7],
[ 3, 7, 8],
[ 2, 5, 10],
[ 1, 9, 4]])
</code></pre>
<p>Doing this in Matlab was simple using sortrows(my_matrix,[-1 2]) where -1 for the first column descending and 2 for the second column ascending.</p>
<p>I wonder if there is a function like that in numpy.</p>
| 1 | 2016-08-07T15:40:40Z | 38,821,758 | <p>If you're willing to use pandas, you can pass a list into the <code>ascending</code> keyword to control the sort order of each field:</p>
<pre><code>>>> pd.DataFrame(a).sort_values([0,1], ascending=[False, True])
0 1 2
0 3 6 7
2 2 5 10
1 1 9 4
</code></pre>
| 1 | 2016-08-08T05:19:30Z | [
"python",
"sorting",
"numpy"
] |
How to sort a numpy 2D array rows descending or ascending using a specific column indices | 38,815,776 | <p>Lets say I have a numpy 2D array like this:</p>
<pre><code>a = np.array([[3,6,7],[1,9,4],[ 3,7,8],[2,5,10]])
a
# array([[ 3, 6, 7],
# [ 1, 9, 4],
# [ 3, 7, 8],
# [ 2, 5, 10]])
</code></pre>
<p>I need to sort the rows descending based on the first column and ascending on the second column to get the below result:</p>
<pre><code>array([[ 3, 6, 7],
[ 3, 7, 8],
[ 2, 5, 10],
[ 1, 9, 4]])
</code></pre>
<p>Doing this in Matlab was simple using sortrows(my_matrix,[-1 2]) where -1 for the first column descending and 2 for the second column ascending.</p>
<p>I wonder if there is a function like that in numpy.</p>
| 1 | 2016-08-07T15:40:40Z | 38,822,358 | <p>Here is how you can do it using the <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package:</p>
<pre><code>import numpy_indexed as npi
print(a[npi.argsort((a[:,1], -a[:,0]))])
</code></pre>
| 1 | 2016-08-08T06:15:22Z | [
"python",
"sorting",
"numpy"
] |
Confusion using path, multiple versions of python on mac osx | 38,815,855 | <p>I'm new to using terminal for python. And I am struggling to understand this environment after installing sublimetext to test and develop codes conveniently.</p>
<p>Below is one question. If I command the following,</p>
<pre><code>echo $PATH
</code></pre>
<p>Returns,
<code>/usr/local/bin:/Library/Frameworks/Python.framework/Versions/3.5/bin:/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</code></p>
<p>It seems like I have python 3.5 and I want to completely remove it since I only want 2.7 on my osx. If I check the version of python using -V, it returns 2.7. Further from the following command,</p>
<pre><code>open ~/.bash_profile
</code></pre>
<p>Returns,</p>
<pre><code>export PATH=/usr/local/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
export PATH=/usr/local/bin:$PATH
export PATH="$HOME/.rbenv/bin:$PATH"
export PATH=/usr/local/bin:$PATH
export PATH
export PATH=/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
</code></pre>
<p>I don't seem to have 3.5 anywhere. I was recommended to check path environment to remove whatever bits left of 3.5 python but I can't. I seem to be missing a lot of something I can't figure on my own. I would appreciate some experts' advise..</p>
<p>Thanks in advance.</p>
| 0 | 2016-08-07T15:50:40Z | 38,817,413 | <p>There is no need to uninstall Python 3; it coexists with Python 2 with no interference.</p>
<p>The last <code>export PATH=...</code> statement compiletely overrides all of the previous ones. You don't need to explicitly export <code>PATH</code> at all from your personal settings anyway, because the system alseady does this. The multiple additions of <code>/usr/local/bin</code> are obviously redundant.</p>
<pre><code>PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
export PATH="$HOME/.rbenv/bin:$PATH"
</code></pre>
<p>would fix the problems and allow the Ruby uninstaller to remove itself at a later time (so I left in the useless <code>export</code> there in case it looks for that when removing itself).</p>
| 0 | 2016-08-07T18:49:19Z | [
"python",
"osx"
] |
groupby+Arithmatic operation on pandas dataframe in python | 38,815,865 | <p>Might be a Stupid question but i am confused in between and a logic of how to apply groupby efficiently in this case will be appreciated.</p>
<p>I have a dataframe like</p>
<pre><code> id NAME TYPE SCORE title
123 DDLJ cat1 1-6 5
123 DDLJ cat1 9-10 25
123 DDLJ cat1 N 5
456 Satya cat2 9-10 1
456 Satya cat2 N 3
222 India cat2 1-6 1
</code></pre>
<p>I need to find out for a groupof (id NAME TYPE) a column named 'cat_score' should be formed with logic "for that group [title for SCORE(9-10) - title for SCORE(1-6)] / [sum of title of that group] "</p>
<pre><code>#ex for group 123, DDLJ cat1
cat score = (title at SCORE "9-10" - title at SCORE "1-6") / (Sum of title of that group)
= (25 - 5) / (35)
= 0.58
</code></pre>
<p>Note::There are 3 types of SCORE ["9-10", "1-6", "N"]. So if for any group any of the score category not found that should be treated as 0 or can be ignored.</p>
<p>My final dataframe should look like </p>
<pre><code> id NAME TYPE SCORE title Cat_Score
123 DDLJ cat1 1-6 5 0.58
123 DDLJ cat1 9-10 25 0.58
123 DDLJ cat1 N 5 0.58
456 Satya cat2 9-10 1 0.34
456 Satya cat2 N 3 0.34
222 India cat2 1-6 1 -1
</code></pre>
<p>Please Suggest.</p>
<h1>I have tried by taking one group</h1>
<pre><code>s = round((int(df[(df['id']=='123') & (df['NAME'] == 'DDLJ') & (df['TYPE']=='cat1') & (df['SCORE']=='9-10')]['title'].values[0]) - int(df[(df['id']=='123') & (df['NAME'] == 'DDLJ') & (df['TYPE']=='cat1') & (df['SCORE']=='1-6')]['title'].values[0])) / (int(df['title'].sum())),2)
s = 0.58
</code></pre>
<p>But for all groups, i am confused how to replicate.</p>
| 0 | 2016-08-07T15:52:38Z | 38,816,405 | <p>I think it would be easier if you first reshape your DataFrame:</p>
<pre><code>df2 = df.set_index(['id', 'NAME', 'TYPE']).pivot(columns='SCORE').fillna(0)
df2.columns = df.columns.droplevel(0)
df2
Out:
SCORE 1-6 9-10 N
id NAME TYPE
123 DDLJ cat1 5.0 25.0 5.0
222 India cat2 1.0 0.0 0.0
456 Satya cat2 0.0 1.0 3.0
</code></pre>
<p>Now you can do those operations more easily:</p>
<pre><code>(df['9-10'] - df['1-6']) / df.sum(axis=1)
Out:
id NAME TYPE
123 DDLJ cat1 0.571429
222 India cat2 -1.000000
456 Satya cat2 0.250000
</code></pre>
<p>In order to use these in merge, I will reset the index:</p>
<pre><code>res = ((df['9-10'] - df['1-6']) / df.sum(axis=1)).reset_index()
res
Out:
id NAME TYPE 0
0 123 DDLJ cat1 0.571429
1 222 India cat2 -1.000000
2 456 Satya cat2 0.250000
</code></pre>
<p>And finally merge with the original DataFrame:</p>
<pre><code>df.merge(res)
Out:
id NAME TYPE SCORE title 0
0 123 DDLJ cat1 1-6 5 0.571429
1 123 DDLJ cat1 9-10 25 0.571429
2 123 DDLJ cat1 N 5 0.571429
3 456 Satya cat2 9-10 1 0.250000
4 456 Satya cat2 N 3 0.250000
5 222 India cat2 1-6 1 -1.000000
</code></pre>
| 2 | 2016-08-07T16:51:03Z | [
"python",
"pandas",
"group-by"
] |
groupby+Arithmatic operation on pandas dataframe in python | 38,815,865 | <p>Might be a Stupid question but i am confused in between and a logic of how to apply groupby efficiently in this case will be appreciated.</p>
<p>I have a dataframe like</p>
<pre><code> id NAME TYPE SCORE title
123 DDLJ cat1 1-6 5
123 DDLJ cat1 9-10 25
123 DDLJ cat1 N 5
456 Satya cat2 9-10 1
456 Satya cat2 N 3
222 India cat2 1-6 1
</code></pre>
<p>I need to find out for a groupof (id NAME TYPE) a column named 'cat_score' should be formed with logic "for that group [title for SCORE(9-10) - title for SCORE(1-6)] / [sum of title of that group] "</p>
<pre><code>#ex for group 123, DDLJ cat1
cat score = (title at SCORE "9-10" - title at SCORE "1-6") / (Sum of title of that group)
= (25 - 5) / (35)
= 0.58
</code></pre>
<p>Note::There are 3 types of SCORE ["9-10", "1-6", "N"]. So if for any group any of the score category not found that should be treated as 0 or can be ignored.</p>
<p>My final dataframe should look like </p>
<pre><code> id NAME TYPE SCORE title Cat_Score
123 DDLJ cat1 1-6 5 0.58
123 DDLJ cat1 9-10 25 0.58
123 DDLJ cat1 N 5 0.58
456 Satya cat2 9-10 1 0.34
456 Satya cat2 N 3 0.34
222 India cat2 1-6 1 -1
</code></pre>
<p>Please Suggest.</p>
<h1>I have tried by taking one group</h1>
<pre><code>s = round((int(df[(df['id']=='123') & (df['NAME'] == 'DDLJ') & (df['TYPE']=='cat1') & (df['SCORE']=='9-10')]['title'].values[0]) - int(df[(df['id']=='123') & (df['NAME'] == 'DDLJ') & (df['TYPE']=='cat1') & (df['SCORE']=='1-6')]['title'].values[0])) / (int(df['title'].sum())),2)
s = 0.58
</code></pre>
<p>But for all groups, i am confused how to replicate.</p>
| 0 | 2016-08-07T15:52:38Z | 38,817,656 | <p>Try this to answer your question how to apply groupby: </p>
<pre><code>def getScore(gb):
x = gb[gb['SCORE'] == '9-10']['title'].values.sum()
y = gb[gb['SCORE'] == '1-6']['title'].values.sum()
z = float(gb['title'].sum())
return pd.Series((x-y)/z)
gb = df2.groupby(["NAME"])['SCORE', 'title'].apply(getScore).reset_index()
gbdict = dict(gb.values)
gbdict
{'DDLJ': 0.5714285714285714, 'India': -1.0, 'Satya': 0.25}
df2['cat_score'] = df2['NAME'].map(dict(gb.values))
id NAME TYPE SCORE title cat_score
0 123 DDLJ cat1 1-6 5 0.571429
1 123 DDLJ cat1 9-10 25 0.571429
2 123 DDLJ cat1 N 5 0.571429
3 456 Satya cat2 9-10 1 0.250000
4 456 Satya cat2 N 3 0.250000
5 222 India cat2 1-6 1 -1.000000
</code></pre>
| 1 | 2016-08-07T19:18:53Z | [
"python",
"pandas",
"group-by"
] |
Using a custom metric with sklearn.neighbors.BallTree gives wrong input? | 38,816,012 | <p>I'm trying to use a custom metric with sklearn.neighbors.BallTree, but when it calls my metric the inputs do not look correct. If I use scipy.spatial.distance.pdist with the same custom metric, it works as expected. However, if I try to instantiate a BallTree, an exception is raised when I try to reshape the input. If I look at the actual inputs, the shape and values do not look correct.</p>
<pre><code>import numpy as np
import scipy.spatial.distance as spdist
import sklearn.neighbors.ball_tree as ball_tree
# custom metric
def minimum_average_direct_flip(x, y):
x = np.reshape(x, (-1, 3))
y = np.reshape(y, (-1, 3))
direct = np.mean(np.sqrt(np.sum(np.square(x - y), axis=1)))
flipped = np.mean(np.sqrt(np.sum(np.square(np.flipud(x) - y), axis=1)))
return min(direct, flipped)
# create an X to test
X = np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9], [11, 12, 13, 14, 15, 16, 17, 18, 19], [21, 22, 23, 24, 25, 26, 27, 28, 29]])
# works as expected
distances = spdist.pdist(X, metric=minimum_average_direct_flip)
# outputs: [ 17.32050808 34.64101615 17.32050808]
print distances
# raises exception, inputs to minimum_average_direct_flip look wrong
# Traceback (most recent call last):
# File ".../test_script.py", line 23, in <module>
# ball_tree.BallTree(X, metric=minimum_average_direct_flip)
# File "sklearn/neighbors/binary_tree.pxi", line 1059, in sklearn.neighbors.ball_tree.BinaryTree.__init__ (sklearn\neighbors\ball_tree.c:8381)
# File "sklearn/neighbors/dist_metrics.pyx", line 262, in sklearn.neighbors.dist_metrics.DistanceMetric.get_metric (sklearn\neighbors\dist_metrics.c:4032)
# File "sklearn/neighbors/dist_metrics.pyx", line 1091, in sklearn.neighbors.dist_metrics.PyFuncDistance.__init__ (sklearn\neighbors\dist_metrics.c:10586)
# File "C:/Users/danrs/Documents/neuro_atlas/test_script.py", line 8, in minimum_average_direct_flip
# x = np.reshape(x, (-1, 3))
# File "C:\Anaconda2\lib\site-packages\numpy\core\fromnumeric.py", line 225, in reshape
# return reshape(newshape, order=order)
# ValueError: total size of new array must be unchanged
ball_tree.BallTree(X, metric=minimum_average_direct_flip)
</code></pre>
<p>In the first call to minimum_average_direct_flip from the BallTree code, the inputs are:</p>
<pre><code>x = [ 0.4238394 0.55205233 0.04699435 0.19542642 0.20331665 0.44594837 0.35634537 0.8200018 0.28598294 0.34236847]
y = [ 0.4238394 0.55205233 0.04699435 0.19542642 0.20331665 0.44594837 0.35634537 0.8200018 0.28598294 0.34236847]
</code></pre>
<p>These look completely incorrect. Am I doing something wrong in the way I am calling this or is this a bug in sklearn?</p>
| 0 | 2016-08-07T16:07:38Z | 38,816,145 | <p>It seems that this is a known issue:
<a href="https://github.com/scikit-learn/scikit-learn/issues/6287" rel="nofollow">https://github.com/scikit-learn/scikit-learn/issues/6287</a></p>
<p>They do some kind of validation step that is problematic. As a workaround I guess I can add a check on the input size, but as the issue notes this is undesirable because I can't do actual validation checks myself.</p>
| 0 | 2016-08-07T16:21:39Z | [
"python",
"scikit-learn",
"nearest-neighbor",
"metric"
] |
How to list alphabetically in this way? | 38,816,017 | <p>I have to sort the user inputted names without using the list sort method. this is what i have so far but am having issues with defining 'one' 'two' and 'three'. i need the program to go through each letter to make sure it is truly alphabetical. can anyone help?</p>
<pre><code>name1=str(input("Enter name #1: "))
name2=str(input("Enter name #2: "))
name3=str(input("Enter name #3: "))
one = name1[0].upper() + name1[1].upper() + name1[2].upper()
two = name2[0].upper() + name2[1].upper() + name2[2].upper()
three = name3[0].upper() + name3[1].upper() + name3[2].upper()
if one < two and two < three:
print("These names in alphabetical order are: ", name1, name2, name3)
elif one < two and three < two:
print("These names in alphabetical order are: ", name1, name3, name2)
elif two < three and three < one:
print("These names in alphabetical order are: ", name2, name3, name1)
elif two < one and one < three:
print("These names in alphabetical order are: ", name2, name1, name3)
elif three < two and two < one:
print("These names in alphabetical order are: ", name3, name2, name1)
else:
print("These names in alphabetical order are: ", name3, name1, name2)
</code></pre>
<p>thanks in advance!
<em>edit</em> my issue is in defining 'one' 'two' and 'three' it needs to run through all of the letters in the input. right now it runs through the first three letters but if i add the next letter and only a three letter name is given it errors. and if i use the len function it tells me its an integer </p>
| 0 | 2016-08-07T16:08:18Z | 38,816,194 | <blockquote>
<p>i need the program to go through each letter to make sure it is truly alphabetical.</p>
</blockquote>
<p>That's what string comparison does anyway. The problem with your code is that you restrict <code>one</code>, <code>two</code> and <code>three</code> to the first three letters of the input strings. Instead, you should just uppercase the <em>entire</em> name and compare those.</p>
<pre><code>name1 = input("Enter name #1: ") # no need for str(...)
... # same for name2, name3
one = name1.upper() # uppercase whole nam, not just first three letters
... # same for two, three
answer = "These names in alphabetical order are: " # don't repeat this X times
if one < two < three: # comparison chaining
print(answer, name1, name2, name3)
elif one < three < two:
print(answer, name1, name3, name2)
elif ...:
# a whole bunch more
else:
print(answer, name3, name2, name1)
</code></pre>
| 0 | 2016-08-07T16:25:23Z | [
"python",
"alphabetical",
"names"
] |
How to list alphabetically in this way? | 38,816,017 | <p>I have to sort the user inputted names without using the list sort method. this is what i have so far but am having issues with defining 'one' 'two' and 'three'. i need the program to go through each letter to make sure it is truly alphabetical. can anyone help?</p>
<pre><code>name1=str(input("Enter name #1: "))
name2=str(input("Enter name #2: "))
name3=str(input("Enter name #3: "))
one = name1[0].upper() + name1[1].upper() + name1[2].upper()
two = name2[0].upper() + name2[1].upper() + name2[2].upper()
three = name3[0].upper() + name3[1].upper() + name3[2].upper()
if one < two and two < three:
print("These names in alphabetical order are: ", name1, name2, name3)
elif one < two and three < two:
print("These names in alphabetical order are: ", name1, name3, name2)
elif two < three and three < one:
print("These names in alphabetical order are: ", name2, name3, name1)
elif two < one and one < three:
print("These names in alphabetical order are: ", name2, name1, name3)
elif three < two and two < one:
print("These names in alphabetical order are: ", name3, name2, name1)
else:
print("These names in alphabetical order are: ", name3, name1, name2)
</code></pre>
<p>thanks in advance!
<em>edit</em> my issue is in defining 'one' 'two' and 'three' it needs to run through all of the letters in the input. right now it runs through the first three letters but if i add the next letter and only a three letter name is given it errors. and if i use the len function it tells me its an integer </p>
| 0 | 2016-08-07T16:08:18Z | 38,816,240 | <p>You can use the good old sorting algorithm</p>
<pre><code>letters = [name1.upper(),name2.upper(),name3.upper()]
for i in range(len(letters)):
for j in range(i,len(letters)):
if letters[i] > letters[j]:
letters[i],letters[j] = letters[j],letters[i]
</code></pre>
| 0 | 2016-08-07T16:30:39Z | [
"python",
"alphabetical",
"names"
] |
what does urllib.request.urlopen() do? | 38,816,032 | <p>In python 3 does urlopen function from urllib.request module retrieve the target of the URL or just open a connection to the URL as a file handle or have i completely lost it ? I would like to understand how it works.</p>
<p>Basically i want to find the time taken to download a file from a URL. how do i go about it ?</p>
<p>Here is my code:</p>
<p><em>VERSION 1</em></p>
<pre><code>import urllib
import time
start = time.time()
with urllib.request.urlopen('http://mirror.hactar.bz/lastsync') as f:
lastsync = f.read() #Do i need this line if i dont care about the data
end = time.time()
duration = end - start
</code></pre>
<p><em>VERSION 2</em></p>
<pre><code>import urllib
import time
with urllib.request.urlopen('http://mirror.hactar.bz/lastsync') as f:
start = time.time()
lastsync = f.read() #Does this line do the actual data retrieval ?
end = time.time()
duration = end - start
</code></pre>
| 0 | 2016-08-07T16:10:14Z | 38,816,113 | <p>From the <a href="https://docs.python.org/2/library/urllib2.html#urllib2.urlopen" rel="nofollow">docs</a>:</p>
<blockquote>
<p>Open the URL url, which can be either a string or a Request object.</p>
<p>...</p>
<p>This function returns a file-like object with three additional methods:</p>
<ul>
<li>geturl() â return the URL of the resource retrieved, commonly used to determine if a redirect was followed</li>
<li>info() â return the meta-information of the page, such as headers, in the form of an mimetools.Message instance (see Quick Reference to HTTP Headers)</li>
<li>getcode() â return the HTTP status code of the response.</li>
</ul>
</blockquote>
<p>Also note that as of Python 3.0, <code>urllib.request.urlopen()</code> and <code>urllib.urlopen()</code> are equivalent.</p>
<p><strong>EDIT</strong> So, to <code>time</code> it:</p>
<pre><code># urllib.request for < python 3.0
import urllib
import time
start = time.time()
# urllib.request.urlopen() for < python 3.0
response = urllib.urlopen('http://example.com/')
data = response.read() # a `bytes` object
end = time.time()
duration = end - start
</code></pre>
| 0 | 2016-08-07T16:18:33Z | [
"python",
"urllib"
] |
Zoom in an Image using python-numpy | 38,816,088 | <p>I'm trying to zoom in an image.</p>
<pre><code> import numpy as np
from scipy.ndimage.interpolation import zoom
import Image
zoom_factor = 0.05 # 5% of the original image
img = Image.open(filename)
image_array = misc.fromimage(img)
zoomed_img = clipped_zoom(image_array, zoom_factor)
misc.imsave('output.png', zoomed_img)
</code></pre>
<p>Clipped Zoom Reference:<br>
<a href="http://stackoverflow.com/questions/37119071/scipy-rotate-and-zoom-an-image-without-changing-its-dimensions">Scipy rotate and zoom an image without changing its dimensions</a></p>
<p>This doesn't works and throws this error:
<code>ValueError: could not broadcast input array from shape</code></p>
<p>Any Help or Suggestions on this
Is there a way to zoom an image given a zoom factor. And what's the problem ?</p>
<p>Traceback:</p>
<pre><code>Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/tornado/web.py", line 1443, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "title_apis_proxy.py", line 798, in get
image, msg = resize_image(image_local_file, aspect_ratio, image_url, scheme, radius, sigma)
File "title_apis_proxy.py", line 722, in resize_image
z = clipped_zoom(face, 0.5, order=0)
File "title_apis_proxy.py", line 745, in clipped_zoom
out[top:top+zh, left:left+zw] = zoom(img, zoom_factor, **kwargs)
ValueError: could not broadcast input array from shape (963,1291,2) into shape (963,1291,3)
</code></pre>
| 0 | 2016-08-07T16:15:56Z | 38,818,441 | <p>The <code>clipped_zoom</code> function you're using from my <a href="http://stackoverflow.com/a/37121993/1461210">previous answer</a> was written for single-channel images only.</p>
<p>At the moment it's applying the same zoom factor to the "color" dimension as well as the width and height dimensions of your input array. The <code>ValueError</code> occurs because the the <code>out</code> array is initialized to the same number of channels as the input, but the result of <code>zoom</code> has fewer channels because of the zoom factor.</p>
<p>To make it work for multichannel images you could either pass each color channel separately to <code>clipped_zoom</code> and concatenate the results, or you could pass a tuple rather than a scalar as the <code>zoom_factor</code> argument to <code>scipy.ndimage.zoom</code>.</p>
<p>I've updated my previous answer using the latter approach, so that it will now work for multichannel images as well as monochrome.</p>
| 2 | 2016-08-07T20:51:41Z | [
"python",
"numpy",
"scipy",
"image-manipulation"
] |
How to filter and print entire row via index in pandas | 38,816,138 | <p>I"m having some issues in trying to print out just the rows based on the <code>index values</code></p>
<pre><code>>>>in: print(df) # My table when I print df
>>>out:
Item Column1 Column2 Column3 Column4 Column5
Fooooo 64.318 7.574 0.471 0.364 -
Yooooo 56.839 7.252 (1.914) (1.945) (0.015)
Zaaaaa 45.275 7.186 (7.109) (1.611) (0.016)
Zorrrr 0.381 0.063 (5.305) (1.6) (0.017)
Kaarrr 1.325 0.26 (5.514) (2.563) (0.019)
</code></pre>
<p><strong>Desired results</strong> </p>
<p>How do I separate the <code>df</code> via <code>index</code> such that it produces the results below?</p>
<pre><code>>>>in: print(df index['Fooooo']) # For example
>>>out:
Item Column1 Column2 Column3 Column4 Column5
Fooooo 64.318 7.574 0.471 0.364 -
>>>in: print(df index['Yooooo']) # For example
>>>out:
Item Column1 Column2 Column3 Column4 Column5
Yooooo 56.839 7.252 (1.914) (1.945) (0.015)
>>>in: print(df index['Zaaaaa']) # For example
>>>out:
Item Column1 Column2 Column3 Column4 Column5
Zaaaaa 45.275 7.186 (7.109) (1.611) (0.016)
</code></pre>
<p><strong>I have tried</strong></p>
<p><code>print(df.index[0])</code> - This just gives me the <code>Item</code>. Does not come along with the rest of the <code>Columns</code></p>
| 0 | 2016-08-07T16:20:51Z | 38,816,287 | <p>you can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow">ix</a>:</p>
<pre><code>In[31]:df.ix['Fooooo']
Out[31]:
Column1 64.318
Column2 7.574
Column3 0.471
Column4 0.364
Column5 -
</code></pre>
| 2 | 2016-08-07T16:36:10Z | [
"python",
"pandas"
] |
How to filter and print entire row via index in pandas | 38,816,138 | <p>I"m having some issues in trying to print out just the rows based on the <code>index values</code></p>
<pre><code>>>>in: print(df) # My table when I print df
>>>out:
Item Column1 Column2 Column3 Column4 Column5
Fooooo 64.318 7.574 0.471 0.364 -
Yooooo 56.839 7.252 (1.914) (1.945) (0.015)
Zaaaaa 45.275 7.186 (7.109) (1.611) (0.016)
Zorrrr 0.381 0.063 (5.305) (1.6) (0.017)
Kaarrr 1.325 0.26 (5.514) (2.563) (0.019)
</code></pre>
<p><strong>Desired results</strong> </p>
<p>How do I separate the <code>df</code> via <code>index</code> such that it produces the results below?</p>
<pre><code>>>>in: print(df index['Fooooo']) # For example
>>>out:
Item Column1 Column2 Column3 Column4 Column5
Fooooo 64.318 7.574 0.471 0.364 -
>>>in: print(df index['Yooooo']) # For example
>>>out:
Item Column1 Column2 Column3 Column4 Column5
Yooooo 56.839 7.252 (1.914) (1.945) (0.015)
>>>in: print(df index['Zaaaaa']) # For example
>>>out:
Item Column1 Column2 Column3 Column4 Column5
Zaaaaa 45.275 7.186 (7.109) (1.611) (0.016)
</code></pre>
<p><strong>I have tried</strong></p>
<p><code>print(df.index[0])</code> - This just gives me the <code>Item</code>. Does not come along with the rest of the <code>Columns</code></p>
| 0 | 2016-08-07T16:20:51Z | 38,816,762 | <p>Try filtering method:</p>
<pre><code>df[df.index == 'Fooooo']
Column1 Column2 Column3 Column4 Column5
Item
Fooooo 64.318 7.574 0.471 0.364 -
</code></pre>
| 1 | 2016-08-07T17:31:42Z | [
"python",
"pandas"
] |
Obtaining Polynomial Regression Stats in Numpy | 38,816,154 | <p>I am looking to obtain the coefficients and intercept using a polynomial regression (polyfit) in Numpy, but am not sure how to write the script to get a polynomial function. </p>
<p>I have made code the code for a linear regression, which I have attached below: </p>
<pre><code>import matplotlib.pyplot as plt
import sys
from numpy import *
import numpy as np
import numpy.polynomial.polynomial as poly
import pylab
from scipy import stats
from scipy.interpolate import *
from datetime import datetime, timedelta
#Open dataset1,dataset2 data
data1 = np.loadtxt('/home/script/2_columns', delimiter=',', skiprows=0)
data2 = np.loadtxt('/home/script/2_columns_a', delimiter=',', skiprows=0)
#Define first column as dataset1
#Define second column as dataset2
x = data1[:,0]
y = data1[:,1]
#The stuff...
slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
</code></pre>
| 0 | 2016-08-07T16:22:07Z | 38,816,662 | <p>Do you need the stats? If not, and you just need the coefficients, it's really quite simple using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html" rel="nofollow"><code>numpy.polyfit</code></a>:</p>
<pre><code>import numpy as np
# from your code
data1 = np.loadtxt('/home/script/2_columns', delimiter=',', skiprows=0)
x = data1[:,0]
y = data1[:,1]
degree = 3
coeffs = np.polyfit(x, y, degree)
# now, coeffs is an array which contains the polynomial coefficients
# in ascending order, i.e. x^0, x^1, x^2
intercept, linear, quadratic, cubic = coeffs
</code></pre>
<p>If you do need the other values, please specify what you need, since for example the <code>r_value</code> is the correlation coefficient between <code>x</code> and <code>y</code>, which isn't very useful when you don't expect the data to be linear.</p>
| 0 | 2016-08-07T17:20:07Z | [
"python",
"numpy",
"scipy",
"polynomials"
] |
Store email locally (imaplib, libpst) | 38,816,164 | <p>I'm using <code>imaplib</code> to fetch emails for several accounts (Gmail, Yahoo..).
What is the best way to store emails locally (including attachments).</p>
<p>Is there any way to <code>pickle</code> and store emails as file?
Is it possible to store emails as bytes and retrieve them
later as mail object?</p>
<p>I'll try to save mail in separate folder with each field in JSON file
and attachment as separate files, but I was wondering if there is a
<code>native</code> way of doing it.</p>
| 0 | 2016-08-07T16:22:55Z | 38,816,253 | <p>There are already several established ways to store mailboxes (i.e. a list of emails). Popular examples are <a href="https://en.wikipedia.org/wiki/Maildir" rel="nofollow">Maildir</a> and <a href="https://en.wikipedia.org/wiki/Mbox" rel="nofollow">mbox</a>.</p>
<p>Python includes the <a href="https://docs.python.org/3/library/mailbox.html" rel="nofollow"><code>mailbox</code></a> module which can handle them:</p>
<blockquote>
<p>Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.</p>
</blockquote>
<p>You can of course roll your own solution, pickle them or dump them as JSON to a file, but if you use one of the common formats, you gain compatibility with other programs (<a href="https://addons.mozilla.org/de/thunderbird/addon/importexporttools/" rel="nofollow">importing them into Thunderbird</a>, for example).</p>
| 0 | 2016-08-07T16:31:51Z | [
"python",
"email",
"imap",
"pop",
"imaplib"
] |
The fastest way of checking the closest distance between points | 38,816,217 | <p>I have 2 dictionaries. Both have key value pairs of an index and a world space location.</p>
<p>Something like:</p>
<pre><code>{
"vertices" :
{
1: "(0.004700, 130.417480, -13.546420)",
2: "(0.1, 152.4, 13.521)",
3: "(58.21, 998.412, -78.0051)"
}
}
</code></pre>
<p>Dictionary 1 will always have about 20 - 100 entries, dictionary 2 will always have around 10,000 entries. </p>
<p>For every point in dictionary 1, I want to find the point in dictionary 2 that's closest to it. What is the fastest way of doing that? For each entry in dictionary 1, loop through <strong>all entries</strong> in dictionary 2 and return the one that's closest by.</p>
<p>Some untested pseudo code:</p>
<pre><code>for point, distance in dict_1.iteritems():
closest_point = get_closest_point(dict_1.get(point))
def get_closest_point(self, start_point)
furthest_distance = 2000000
closest_point = 0
for index, end_point in dict_1.iteritems():
distance = get_distance(self, start_point, end_point)
if distance < furthest_distance:
furthest_distance = distance
closest_point = closest_point
return closest_point
</code></pre>
<p>I think something like this will work. The <em>"problem"</em> is that if I have 100 entries in dictionary 1, it will be 100 x 10,000 = 1,000,000 iterations. That just doesn't seem very fast or elegant to me. </p>
<p><strong>Is there a better way of doing this in Maya/Python?</strong> </p>
<p>EDIT:
Just want to comment that I've used a closestPointOnMesh node before, which works just fine and is a lot easier if the points you're checking against are actually part of a mesh. You could do something like this:</p>
<pre><code>selected_object = pm.PyNode(pm.selected()[0])
cpom = pm.createNode("closestPointOnMesh", name="cpom")
for vertex, distance in dict_1.iteritems():
selected_object.worldMesh >> cpom.inMesh
cpom.inPosition.set(dict_1.get(vertex))
print "closest vertex is %s " % cpom.closestVertexIndex.get()
</code></pre>
<p>Instant reply from the node and all is dandy. However, if the list of point you're checking against are not part of a mesh you can't use this. Would it actually be possible/quicker to:</p>
<ul>
<li>Construct a mesh out of the points in dictionary 2</li>
<li>Use mesh with closestPointOnMesh node</li>
<li>Delete mesh</li>
</ul>
| 0 | 2016-08-07T16:28:38Z | 38,816,981 | <p>You need what is called a KD Tree. Build a KD Tree with points in your second dictionary and query for the closest point to each point in first dictionary.</p>
<p>I am not familiar with maya, if you can use scipy, you can use <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.KDTree.html" rel="nofollow">this</a>.</p>
<p>PS: There seems to be an implementation in C++ <a href="http://download.autodesk.com/us/maya/2008help/RefGuide/node147.html" rel="nofollow">here</a>.</p>
| 0 | 2016-08-07T17:57:48Z | [
"python",
"distance",
"maya",
"points"
] |
The fastest way of checking the closest distance between points | 38,816,217 | <p>I have 2 dictionaries. Both have key value pairs of an index and a world space location.</p>
<p>Something like:</p>
<pre><code>{
"vertices" :
{
1: "(0.004700, 130.417480, -13.546420)",
2: "(0.1, 152.4, 13.521)",
3: "(58.21, 998.412, -78.0051)"
}
}
</code></pre>
<p>Dictionary 1 will always have about 20 - 100 entries, dictionary 2 will always have around 10,000 entries. </p>
<p>For every point in dictionary 1, I want to find the point in dictionary 2 that's closest to it. What is the fastest way of doing that? For each entry in dictionary 1, loop through <strong>all entries</strong> in dictionary 2 and return the one that's closest by.</p>
<p>Some untested pseudo code:</p>
<pre><code>for point, distance in dict_1.iteritems():
closest_point = get_closest_point(dict_1.get(point))
def get_closest_point(self, start_point)
furthest_distance = 2000000
closest_point = 0
for index, end_point in dict_1.iteritems():
distance = get_distance(self, start_point, end_point)
if distance < furthest_distance:
furthest_distance = distance
closest_point = closest_point
return closest_point
</code></pre>
<p>I think something like this will work. The <em>"problem"</em> is that if I have 100 entries in dictionary 1, it will be 100 x 10,000 = 1,000,000 iterations. That just doesn't seem very fast or elegant to me. </p>
<p><strong>Is there a better way of doing this in Maya/Python?</strong> </p>
<p>EDIT:
Just want to comment that I've used a closestPointOnMesh node before, which works just fine and is a lot easier if the points you're checking against are actually part of a mesh. You could do something like this:</p>
<pre><code>selected_object = pm.PyNode(pm.selected()[0])
cpom = pm.createNode("closestPointOnMesh", name="cpom")
for vertex, distance in dict_1.iteritems():
selected_object.worldMesh >> cpom.inMesh
cpom.inPosition.set(dict_1.get(vertex))
print "closest vertex is %s " % cpom.closestVertexIndex.get()
</code></pre>
<p>Instant reply from the node and all is dandy. However, if the list of point you're checking against are not part of a mesh you can't use this. Would it actually be possible/quicker to:</p>
<ul>
<li>Construct a mesh out of the points in dictionary 2</li>
<li>Use mesh with closestPointOnMesh node</li>
<li>Delete mesh</li>
</ul>
| 0 | 2016-08-07T16:28:38Z | 38,862,331 | <p>You definitely need an acceleration structure for non-trivial amounts of points. A KD tree or an octree is what you want -- KD trees are more performant on search but slower to build and can be harder to code. Also since Octrees are spatial rather than binary they may make it easier to do trivial tests.</p>
<p>You can get a python octree here: <a href="http://code.activestate.com/recipes/498121-python-octree-implementation/" rel="nofollow">http://code.activestate.com/recipes/498121-python-octree-implementation/</a></p>
<p>if you're doing a lot of distance checks you'll definitely want to use Maya API vector classes to do the actual math compares -- that will be much, much faster than the equivalent python although. You can get these from <code>pymel.datatypes</code> if you don't know the API well, although using the newer API2 versions is pretty painless.</p>
| 1 | 2016-08-10T00:11:23Z | [
"python",
"distance",
"maya",
"points"
] |
How to kill old threads in python | 38,816,224 | <p>My multi-threading script raising this error:</p>
<pre><code>thread.error : can't start new thread
</code></pre>
<p>when it reached 460 threads:</p>
<pre><code>threading.active_count() = 460
</code></pre>
<p>I assume the old threads keeps stack up, since the script didn't kill them. This my code:</p>
<pre><code>import threading
import Queue
import time
import os
import csv
def main(worker):
#Do Work
print worker
return
def threader():
while True:
worker = q.get()
main(worker)
q.task_done()
def main_threader(workers):
global q
global city
q = Queue.Queue()
for x in range(20):
t = threading.Thread(target=threader)
t.daemon = True
print "\n\nthreading.active_count() = " + str(threading.active_count()) + "\n\n"
t.start()
for worker in workers:
q.put(worker)
q.join()
</code></pre>
<p>How do I kill the old threads when their job is done? (Is the function returning not enough?)</p>
| 0 | 2016-08-07T16:29:10Z | 38,816,270 | <p>Python <code>threading</code> API doesn't have any function to kill a thread (nothing like <code>threading.kill(PID)</code>). </p>
<p>That said, you should code some thread-stopping algorithm yourself. For example, your thread should somehow decide that is should terminate (e.g. check some global variable or check whether some signal has been sent) and simply <code>return</code>.</p>
<hr>
<p>For example:</p>
<pre><code>import threading
nthreads = 7
you_should_stop = [0 for _ in range(nthreads)]
def Athread(number):
while True:
if you_should_stop[number]:
print "Thread {} stopping...".format(number)
return
print "Running..."
for x in range(nthreads):
threading.Thread(target = Athread, args = (x, )).start()
for x in range(nthreads):
you_should_stop[x] = 1
print "\nStopped all threads!"
</code></pre>
| 1 | 2016-08-07T16:34:34Z | [
"python",
"multithreading"
] |
How to populate a matrix of indices with array of values? | 38,816,251 | <p>Given an array <strong>v</strong> and a matrix (or ndarray) <strong>m</strong> containing indices of that array - what is the most efficient and/or concise way to populate the matrix with the associated array values using python+numpy?</p>
<p>Similar to <a href="http://stackoverflow.com/questions/26026682/how-to-populate-matrix-of-indices-with-vector-of-values">this R question</a> but for python+numpy.</p>
| 0 | 2016-08-07T16:31:44Z | 38,816,304 | <pre><code>v[m]
</code></pre>
<p>Example:</p>
<pre><code>import numpy as np
v = np.random.rand((100))
m = np.array([[0, 99], [1, 0]])
print(v[m])
</code></pre>
<p>Prints out (this will vary, because it's using random numbers):</p>
<pre><code>[[ 0.21711542, 0.07093873],
[ 0.83393247, 0.2751812 ]]
</code></pre>
| 1 | 2016-08-07T16:38:34Z | [
"python",
"arrays",
"numpy",
"matrix",
"scipy"
] |
libreoffice python: how to set text wrap properties of images | 38,816,262 | <p>From stackoverflow I learned how to set image properties in LibreOffice Writer with pyhton macros, via com.sun.star.text.WrapTextMode. Now I use that to set the text wrap to THOUGHT. Now I would like to set the image to background, like a watermark. </p>
<p>In LibreOffice Writer interactively I select an image, right-click on it and the context menu contains the "Wrap" commands, one is "Wrap Through" and the other one is "In Background".</p>
<p>In the python macro I have the following code (from <a href="http://stackoverflow.com/questions/31449712/insert-several-images-at-once-using-macro-scripting-in-libreoffice">Insert several images at once using macro scripting in LibreOffice</a> and from the often quoted Andrew Pitonyak):</p>
<pre><code>from com.sun.star.text.WrapTextMode import THROUGHT
</code></pre>
<p>and then to insert the image:</p>
<pre><code>img = doc.createInstance('com.sun.star.text.TextGraphicObject')
element_url = 'file://' + file_name
img.GraphicURL = element_url
img.Surround = THROUGHT
text.insertTextContent(cursor, img, False)
</code></pre>
<p>So what is the code to put it "In Background"?</p>
| 0 | 2016-08-07T16:33:42Z | 39,060,368 | <p><a href="http://extensions.services.openoffice.org/en/project/mri-uno-object-inspection-tool" rel="nofollow">MRI</a> shows that setting "In Background" causes the <a href="https://www.openoffice.org/api/docs/common/ref/com/sun/star/text/BaseFrameProperties.html#Opaque" rel="nofollow">Opaque</a> attribute to be false. So add this to the code:</p>
<pre><code>img.Opaque = False
</code></pre>
<p>By the way, <a href="https://www.openoffice.org/api/docs/common/ref/com/sun/star/text/BaseFrameProperties.html#Surround" rel="nofollow">Surround</a> is deprecated. Try setting <a href="https://www.openoffice.org/api/docs/common/ref/com/sun/star/text/TextContent.html#TextWrap" rel="nofollow">TextWrap</a> to <code>THROUGHT</code> instead.</p>
| 0 | 2016-08-21T02:33:30Z | [
"python",
"libreoffice",
"watermark"
] |
python lirc keyup function? | 38,816,306 | <p>I a using <a href="https://github.com/tompreston/python-lirc" rel="nofollow">lirc for python</a>. This is working pretty good, but I miss one function: In my tests only a code was sent, when a button was pressed. Now, I want to print a code, while the key is pressed. In other words, a function should be started by "key down" and stopped by "key up". Using just the <code>lirc.nextcode()</code> is not working, because only the "key down" event is captured.</p>
<p>So, is there any trick to detect a "key up" with python?</p>
| 0 | 2016-08-07T16:38:39Z | 38,816,625 | <p>There is no such feature in lirc. Think about it like this: a infrared signal from a remote is either received or not, there is no such thing as a keyup event, not even a keydown event.</p>
<p>You will have to code your own key up and key down events.
Have a look at the way you can make configuration files, specifically the part about delay: <a href="http://www.lirc.org/html/configure.html" rel="nofollow">http://www.lirc.org/html/configure.html</a>
Configure in such a way that many events are sent per second.</p>
<p>Then, put lirc in non-blocking mode (see <a href="https://github.com/tompreston/python-lirc" rel="nofollow">https://github.com/tompreston/python-lirc</a>). You can then loop over lirc.nextcode() and if it returns no event or returns an event for a different key, you have your key up event.</p>
| 0 | 2016-08-07T17:17:07Z | [
"python",
"lirc"
] |
Why does pandas multi-index dataframe slicing seem inconsistent? | 38,816,428 | <p>Why is it that when slicing a multi-index dataframe, you can get away with simpler syntax as long as you are slicing the level-0 index? Here is an example dataframe:</p>
<pre><code> hi
a b c
1 foo baz 0
can 1
bar baz 2
can 3
2 foo baz 4
can 5
bar baz 6
can 7
3 foo baz 8
can 9
bar baz 10
can 11
</code></pre>
<p>These work:</p>
<pre><code>df.loc[1, 'foo', :]
df.loc[1, :, 'can']
</code></pre>
<p>While this doesn't:</p>
<pre><code>df.loc[:, 'foo', 'can']
</code></pre>
<p>Forcing me to use one of these instead:</p>
<pre><code>df.loc[(slice(None), 'foo', 'can'), :]
df.loc[pd.IndexSlice[:, 'foo', 'can'], :]
</code></pre>
<p>Below are the same examples but with more detail:</p>
<pre><code>In [1]: import pandas as pd
import numpy as np
ix = pd.MultiIndex.from_product([[1, 2, 3], ['foo', 'bar'], ['baz', 'can']], names=['a', 'b', 'c'])
data = np.arange(len(ix))
df = pd.DataFrame(data, index=ix, columns=['hi'])
print df
hi
a b c
1 foo baz 0
can 1
bar baz 2
can 3
2 foo baz 4
can 5
bar baz 6
can 7
3 foo baz 8
can 9
bar baz 10
can 11
In [2]: df.sort_index(inplace=True)
print df.loc[1, 'foo', :]
hi
a b c
1 foo baz 0
can 1
In [3]: print df.loc[1, :, 'can']
hi
a b c
1 bar can 3
foo can 1
In [4]: print df.loc[:, 'foo', 'can']
KeyError: 'the label [foo] is not in the [columns]'
In [5]: print df.loc[(slice(None), 'foo', 'can'), :]
hi
a b c
1 foo can 1
2 foo can 5
3 foo can 9
In [6]: print df.loc[pd.IndexSlice[:, 'foo', 'can'], :]
hi
a b c
1 foo can 1
2 foo can 5
3 foo can 9
</code></pre>
| 0 | 2016-08-07T16:54:15Z | 38,816,944 | <p>All three examples are technically ambiguous, it's just in the first two, <code>pandas</code> guesses your intent correctly. Since slicing rows, selecting columns (i.e., <code>df.loc[:, columns]</code> is a common idiom, the inference seems to pick that interpretation. </p>
<p>The inference is kind of messy, so I think it's much better to be explicit. It's not that much extra typing if you alias <code>IndexSlice</code></p>
<pre><code>idx = pd.IndexSlice
df.loc[idx[1, 'foo'], :]
df.loc[idx[1, :, 'can'], :]
df.loc[idx[:, 'foo', 'can'], :]
</code></pre>
| 0 | 2016-08-07T17:52:38Z | [
"python",
"pandas",
"numpy",
"dataframe",
"multi-index"
] |
How can I set my username and password for html login page in Django? | 38,816,487 | <p>HTML template</p>
<pre><code>{% load staticfiles %}
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en"> <!--<![endif]-->
<head>
<title>S.P.M School</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link rel="stylesheet" href="css/style.css">
<!--[if lt IE 9]><script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<style>
table, th, td {
border: 0px solid black;
}
</style>
<script>
function validateForm() {
var mail = document.forms["myForm"]["email"].value;
var psd = document.forms["myForm"]["password"].value;
var atpos = mail.indexOf("@");
var dotpos = mail.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=mail.length) {
alert("Not a valid e-mail address");
return false;
}
if (psd == null || psd == "") {
alert("Not a valid Password");
return false;
}
}
</script>
</head>
<body>
<div id="page">
<div id="header">
<div id="section">
{% if user.is_authenticated %}
<a href="{% url 'post_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a>
{% endif %}
<div class="headline">
<font size="10": color="white"><center>S.P.M.L.P School</center></font>
</div>
<span>303nishanth@gmail.com <br />
<br />
+91 9961685892</span> </div>
<ul>
<li class="#"><a href="/">Home</a></li>
<li><a href="{% url 'about' %}">About Us</a></li>
<li><a href="{% url 'event' %}">Event</a></li>
<li><a href="{% url 'calendar' %}">School Calendar</a></li>
<li><a href="{% url 'contact' %}">Contact us</a></li>
</ul>
<br><br>
<section class="container">
<div class="login">
<div id="section"><br><br>
<h1><center>Login As<font color="red"> Admin</font></center></h1><br>
</div>
<form name="myForm" action="{% url 'class_info' %}" onsubmit="return validateForm();" method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='wu5eSIDElr8EsVDgXmHmFNCCmSLdhyK5' />
{%csrf_token%}
<div class="text">
<p><center><input type="text" name="email" placeholder="Username or Email"></p></center>
<p><center><input type="password" name="password" placeholder="Password"></p></center>
<p class="remember_me">
</p>
<center><p class="submit"><input type="submit" name="commit" value="Login"></p></center>
</form>
</div>
</section>
</body>
</html>
</code></pre>
<p>views.py</p>
<pre><code>def login_submit(request):
context = {}
email = request.POST.get('email','')
psd = request.POST.get('password', '')
user = authenticate(username=email, password=psd)
if user is not None:
# the password verified for the user
if user.is_active:
context['message'] = "User is valid, active and authenticated"
return render (request,'class_info.html',context)
else:
context['message']= "The password is valid, but the account has been disabled!"
else:
# the authentication system was unable to verify the username and password
context['message']= "The username and password were incorrect."
return render (request,'login.html',context)
</code></pre>
<p>When I'm using this template and view, I can able to login with any email address and password.But I want to login with my email address and password(I mean only login with a single email address). Is it possible for me?</p>
| 1 | 2016-08-07T17:01:19Z | 38,816,784 | <p>You can write your strict conditions using your custom authenticate. Like:</p>
<pre><code>user = your_custom_authenticate(username=username, password=psd)
</code></pre>
<p>You can return a user object when username is your email in method <code>your_custom_authenticate</code></p>
<p>There are some ways to do what you want to. The <code>view</code> is all controlled by yourself. You can just simply set the <code>context</code> then <code>render</code> to another path if the <code>email</code> is your email. Certainly, if your next page needs some <code>session</code> things, you should save some user info in <code>session</code>, it's all up to you.</p>
| 1 | 2016-08-07T17:34:36Z | [
"python",
"html",
"django"
] |
How can I set my username and password for html login page in Django? | 38,816,487 | <p>HTML template</p>
<pre><code>{% load staticfiles %}
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en"> <!--<![endif]-->
<head>
<title>S.P.M School</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link rel="stylesheet" href="css/style.css">
<!--[if lt IE 9]><script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<style>
table, th, td {
border: 0px solid black;
}
</style>
<script>
function validateForm() {
var mail = document.forms["myForm"]["email"].value;
var psd = document.forms["myForm"]["password"].value;
var atpos = mail.indexOf("@");
var dotpos = mail.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=mail.length) {
alert("Not a valid e-mail address");
return false;
}
if (psd == null || psd == "") {
alert("Not a valid Password");
return false;
}
}
</script>
</head>
<body>
<div id="page">
<div id="header">
<div id="section">
{% if user.is_authenticated %}
<a href="{% url 'post_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a>
{% endif %}
<div class="headline">
<font size="10": color="white"><center>S.P.M.L.P School</center></font>
</div>
<span>303nishanth@gmail.com <br />
<br />
+91 9961685892</span> </div>
<ul>
<li class="#"><a href="/">Home</a></li>
<li><a href="{% url 'about' %}">About Us</a></li>
<li><a href="{% url 'event' %}">Event</a></li>
<li><a href="{% url 'calendar' %}">School Calendar</a></li>
<li><a href="{% url 'contact' %}">Contact us</a></li>
</ul>
<br><br>
<section class="container">
<div class="login">
<div id="section"><br><br>
<h1><center>Login As<font color="red"> Admin</font></center></h1><br>
</div>
<form name="myForm" action="{% url 'class_info' %}" onsubmit="return validateForm();" method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='wu5eSIDElr8EsVDgXmHmFNCCmSLdhyK5' />
{%csrf_token%}
<div class="text">
<p><center><input type="text" name="email" placeholder="Username or Email"></p></center>
<p><center><input type="password" name="password" placeholder="Password"></p></center>
<p class="remember_me">
</p>
<center><p class="submit"><input type="submit" name="commit" value="Login"></p></center>
</form>
</div>
</section>
</body>
</html>
</code></pre>
<p>views.py</p>
<pre><code>def login_submit(request):
context = {}
email = request.POST.get('email','')
psd = request.POST.get('password', '')
user = authenticate(username=email, password=psd)
if user is not None:
# the password verified for the user
if user.is_active:
context['message'] = "User is valid, active and authenticated"
return render (request,'class_info.html',context)
else:
context['message']= "The password is valid, but the account has been disabled!"
else:
# the authentication system was unable to verify the username and password
context['message']= "The username and password were incorrect."
return render (request,'login.html',context)
</code></pre>
<p>When I'm using this template and view, I can able to login with any email address and password.But I want to login with my email address and password(I mean only login with a single email address). Is it possible for me?</p>
| 1 | 2016-08-07T17:01:19Z | 38,817,178 | <p>You could wrap the default <code>authenticate</code> with a function that checks if the current <code>username</code> is your <em>username</em>, like so:</p>
<pre><code>def custom_auth(username=None, password=None):
user = None
if username == 'my_personal@email.com': # only this email is allowed
user = authenticate(username=email, password=psd)
return user
def login_submit(request):
context = {}
email = request.POST.get('email','')
psd = request.POST.get('password', '')
user = custom_auth(username=email, password=psd)
if user is not None:
...
else:
...
return render (request,'login.html',context)
</code></pre>
| 0 | 2016-08-07T18:21:44Z | [
"python",
"html",
"django"
] |
How do I plot trajectory from points whose coordinates are known to me at several time instants? | 38,816,548 | <p>I have the coordinates of say 10 points at different time levels and I wish to join those coordinates to make it look like a trajectory?</p>
<pre><code>def euler_method(points, x_dot, y_dot, x1, x2, time_step, n_steps):
n_points = len(points[:, 0])
point_trajectory = np.zeros((n_points, 2, n_steps))
for i in range(0, n_steps):
point_trajectory[:, :, i] = points
f1 = sp.lambdify((x1, x2), x_dot, "numpy")
f2 = sp.lambdify((x1, x2), y_dot, "numpy")
u = f1(points[:, [0]], points[:, [1]])
v = f2(points[:, [0]], points[:, [1]])
points_new_x = points[:, [0]] + u*time_step
points_new_y = points[:, [1]] + v*time_step
points = np.hstack((points_new_x, points_new_y))
return point_trajectory
</code></pre>
<p><strong>def plot_trajectory(points_at_diff_time)</strong> - <em>Is what I want to create</em></p>
<p>I am not able to think how to represent it. Please suggest how to do it, preferably in matplotlib.</p>
<p>EDIT: Something like this - moving points with different coordinates at different times.</p>
<p><a href="http://i.stack.imgur.com/fuKyM.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/fuKyM.jpg" alt="enter image description here"></a></p>
| 0 | 2016-08-07T17:07:31Z | 38,816,893 | <pre><code>import numpy as np
import matplotlib.pyplot as plt
# make fake data to test with
pt = np.zeros((6, 2, 3)) # 6 points, (x,y), 3 timesteps
pt[:,0] = [-2,-1,1] # x=time, same for all
# set y values
pt[0,1] = [3,4,4.5]
pt[1,1] = [2,2.9,3.4]
pt[2,1] = [1,1.9,2.4]
pt[3,1] = [0,0.6,1.0]
pt[4,1] = [-1.5,-1.6,-1.6]
pt[5,1] = [-2.8,-3.7,-3.8]
# now plot: x and y are 2D
x = pt[:,0].T
y = pt[:,1].T
plt.plot(x, y)
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/ZuXix.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZuXix.png" alt="resulting plot"></a></p>
<p>If you want to smooth the lines, see here: <a href="http://stackoverflow.com/a/5284038/4323">http://stackoverflow.com/a/5284038/4323</a></p>
| 1 | 2016-08-07T17:46:53Z | [
"python",
"numpy"
] |
PDFMiner conditional extraction of text | 38,816,583 | <p>So I've just played around with PDFMiner and can now extract text from a PDF and throw it into an html or textfile.</p>
<pre><code>pdf2txt.py -o outputfile.txt -t txt inputfile.pdf
</code></pre>
<p>I have then written a simple script to extract all certain strings:</p>
<pre><code>with open('output.txt', 'r') as searchfile:
for line in searchfile:
if 'HELLO' in line:
print(line)
</code></pre>
<p>And now I can use all these strings containing the word HELLO to add to my databse if that is what I wanted.</p>
<p>My questions is: </p>
<p><strong>Is the only way or can PDFinder grab conditional stuff before even spitting it out to the txt, html or even straight into the database?</strong></p>
| 0 | 2016-08-07T17:10:00Z | 38,817,072 | <p>Well, yes, you can: PDFMiner has <a href="http://www.unixuser.org/~euske/python/pdfminer/programming.html" rel="nofollow">API</a>.</p>
<p>The basic example sais</p>
<pre><code>from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfpage import PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice
# Open a PDF file.
fp = open('mypdf.pdf', 'rb')
# Create a PDF parser object associated with the file object.
parser = PDFParser(fp)
# Create a PDF document object that stores the document structure.
# Supply the password for initialization.
document = PDFDocument(parser, password)
# Check if the document allows text extraction. If not, abort.
if not document.is_extractable:
raise PDFTextExtractionNotAllowed
# Create a PDF resource manager object that stores shared resources.
rsrcmgr = PDFResourceManager()
# Create a PDF device object.
device = PDFDevice(rsrcmgr)
# Create a PDF interpreter object.
interpreter = PDFPageInterpreter(rsrcmgr, device)
# Process each page contained in the document.
for page in PDFPage.create_pages(document):
interpreter.process_page(page)
# do stuff with the page here
</code></pre>
<p>and in the loop you should go with</p>
<pre><code> # receive the LTPage object for the page.
layout = device.get_result()
</code></pre>
<p>and then use <code>LTTextBox</code> object. You have to analyse that. There's no full example in the docs, but you may check out <a href="https://github.com/euske/pdfminer/blob/master/tools/pdf2txt.py" rel="nofollow">the pdf2txt.py source</a> which will help you to find missing pieces (although it does much more since it parses options and applies them).</p>
<p>And once you have the code that extracts the text, you can do what you want before saving a file. Including searching for certain parts of text.</p>
<p>PS looks like this was, in a way, asked before: <a href="http://stackoverflow.com/questions/5725278/how-do-i-use-pdfminer-as-a-library">How do I use pdfminer as a library</a> which should be helpful, too.</p>
| 0 | 2016-08-07T18:09:20Z | [
"python",
"python-2.7",
"python-3.x"
] |
Python: Write all combinations of a pd.Series in a text file | 38,816,646 | <p>I have several Pandas Series of unique strings:</p>
<pre><code> First Series
P0A8V2
P36683
P15254
Second Series
P09831
P0AFG8
</code></pre>
<p>I want to write a textfile that looks like this (tab seperator):</p>
<pre><code>P0A8V2 P36683
P0A8V2 P15254
P36683 P15254
P09831 P0AFG8
</code></pre>
<p>So in a Series, every object is combined with every other exactly once. The order doesn´t matter. Then the next Series starts right away.</p>
<p>Is there a easy way to do this?</p>
<p>UPDATE:</p>
<p>The Strings are in the index of a DataFrame. I access them with df.index.values. The DataFrames are in df_list.</p>
<pre><code>def Cluster_Network(df_list):
combi_list = []
for cluster in df_list:
combi_list.append(tuple(itertools.combinations(cluster.index.values, 2)))
return combi_list
</code></pre>
<p>I get a list of tuples with the pairs in it.</p>
<pre><code> [('P77717', 'P10378'),
('P18393', 'P77444'),
('P18393', 'P0AD44'),
('P18393', 'P10378'),
('P77444', 'P0AD44'),
('P77444', 'P10378'),
('P0AD44', 'P10378')),
(('P77562', 'P41039'),)]
</code></pre>
<p>How can I write the textfile out of that list?</p>
| 1 | 2016-08-07T17:18:30Z | 38,817,112 | <p>Looks like you are almost there.</p>
<pre><code>combi_list = []
for cluster in df_list:
combi_list.append(pd.DataFrame(list(itertools.combinations(cluster.index, 2))))
result_df = pd.concat(combi_list, ignore_index=True)
result_df.to_csv(filename, sep='\t', index=False, header=False)
</code></pre>
<p>This would generate a file like this:</p>
<pre><code>P0A8V2 P36683
P0A8V2 P15254
P36683 P15254
P09831 P0AFG8
</code></pre>
| 3 | 2016-08-07T18:14:05Z | [
"python",
"pandas",
"combinations"
] |
Python: Write all combinations of a pd.Series in a text file | 38,816,646 | <p>I have several Pandas Series of unique strings:</p>
<pre><code> First Series
P0A8V2
P36683
P15254
Second Series
P09831
P0AFG8
</code></pre>
<p>I want to write a textfile that looks like this (tab seperator):</p>
<pre><code>P0A8V2 P36683
P0A8V2 P15254
P36683 P15254
P09831 P0AFG8
</code></pre>
<p>So in a Series, every object is combined with every other exactly once. The order doesn´t matter. Then the next Series starts right away.</p>
<p>Is there a easy way to do this?</p>
<p>UPDATE:</p>
<p>The Strings are in the index of a DataFrame. I access them with df.index.values. The DataFrames are in df_list.</p>
<pre><code>def Cluster_Network(df_list):
combi_list = []
for cluster in df_list:
combi_list.append(tuple(itertools.combinations(cluster.index.values, 2)))
return combi_list
</code></pre>
<p>I get a list of tuples with the pairs in it.</p>
<pre><code> [('P77717', 'P10378'),
('P18393', 'P77444'),
('P18393', 'P0AD44'),
('P18393', 'P10378'),
('P77444', 'P0AD44'),
('P77444', 'P10378'),
('P0AD44', 'P10378')),
(('P77562', 'P41039'),)]
</code></pre>
<p>How can I write the textfile out of that list?</p>
| 1 | 2016-08-07T17:18:30Z | 38,817,133 | <p>Another way to do this would be to use convert the Series to list and then use itertools.combinations to get the desired results... like so,</p>
<pre><code>import pandas as pd
s1 = pd.Series(['a', 'b', 'c'])
s2 = pd.Series(['d', 'e'])
import itertools
s= s1.tolist()
s.extend(s2.tolist())
open('test.txt','w').writelines(["%s\t%s\n" % (item[0], item[1]) for item in list(itertools.combinations(s,2))])
</code></pre>
| 1 | 2016-08-07T18:16:49Z | [
"python",
"pandas",
"combinations"
] |
Change python version vim uses | 38,816,659 | <p>I have "YouCompleteMe" plugin in vim, when I activate my virtualenv and enter vim, YouCompleteMe complains about python3. </p>
<p>When I run:</p>
<pre><code>vim --version
</code></pre>
<p><a href="http://i.stack.imgur.com/CrtXe.png" rel="nofollow"><img src="http://i.stack.imgur.com/CrtXe.png" alt="enter image description here"></a></p>
<p>The "+" icon is beside python3, I need to make it use "python". What is the command to switch this or whats involved?</p>
| 2 | 2016-08-07T17:19:35Z | 38,817,665 | <p>Make sure to run the install.py script with python3 when compiling YCM.
You may have your default python env set to use python2. </p>
<p><code>python3 install.py</code> </p>
| -1 | 2016-08-07T19:19:31Z | [
"python",
"vim",
"youcompleteme"
] |
python: facebook GraphAPI request function | 38,816,699 | <p>I saw some code look like this:</p>
<pre><code>graph = facebook.GraphAPI(User_Access_Token)
graph.request("search", {'q' : 'social web', 'type' : 'page'})
</code></pre>
<p>This seems fetch all the data containing the key word 'social web'. But I don't understand why we can do such request.
I read the document of help(graph.request), which says</p>
<p>request(self, path, args=None, post_args=None, files=None, method=None) method of facebook.GraphAPI instance
Fetches the given path in the Graph API.</p>
<p>It doesn't mention "search" at all.</p>
| 1 | 2016-08-07T17:24:30Z | 39,789,175 | <p>I have the same question and I assume you installed <code>pip install facebook-sdk</code> as well and I assume again that your source is <code>Mining the Social Web: Analyzing Data from Facebook, Twitter, LinkedIn, and Other Social Media Sites - Feb 11, 2011 by Matthew A. Russell</code>. The facebook-sdk version is facebook_sdk-2.0.0 . I am not sure the versioning system is the same with Facebook's GraphAPI, but if it is, the API documentation for that is <a href="https://developers.facebook.com/docs/apps/changelog" rel="nofollow">not supported anymore</a>. I downloaded the library from <a href="https://pypi.python.org/pypi/facebook-sdk" rel="nofollow">here</a> and in <code>/facebook-sdk-2.0.0/facebook/__init__.py</code> you will be able to see this block of code.</p>
<pre><code>def request(
self, path, args=None, post_args=None, files=None, method=None):
"""Fetches the given path in the Graph API.
We translate args to a valid query string. If post_args is
given, we send a POST request to the given path with the given
arguments.
"""
args = args or {}
if post_args is not None:
method = "POST"
# Add `access_token` to post_args or args if it has not already been
# included.
if self.access_token:
# If post_args exists, we assume that args either does not exists
# or it does not need `access_token`.
if post_args and "access_token" not in post_args:
post_args["access_token"] = self.access_token
elif "access_token" not in args:
args["access_token"] = self.access_token
try:
response = requests.request(method or "GET",
FACEBOOK_GRAPH_URL + path,
timeout=self.timeout,
params=args,
data=post_args,
proxies=self.proxies,
files=files)
except requests.HTTPError as e:
response = json.loads(e.read())
raise GraphAPIError(response)
headers = response.headers
if 'json' in headers['content-type']:
result = response.json()
elif 'image/' in headers['content-type']:
mimetype = headers['content-type']
result = {"data": response.content,
"mime-type": mimetype,
"url": response.url}
elif "access_token" in parse_qs(response.text):
query_str = parse_qs(response.text)
if "access_token" in query_str:
result = {"access_token": query_str["access_token"][0]}
if "expires" in query_str:
result["expires"] = query_str["expires"][0]
else:
raise GraphAPIError(response.json())
else:
raise GraphAPIError('Maintype was not text, image, or querystring')
if result and isinstance(result, dict) and result.get("error"):
raise GraphAPIError(result)
return result
</code></pre>
<p>I hope it helps.</p>
| 0 | 2016-09-30T10:18:27Z | [
"python",
"facebook"
] |
Adding specific column from csv file to new csv file | 38,816,764 | <p>I am trying to copy few columns from a csv file to a new CSV file. I have written below code to fulfill my requirements. But it is not giving me the expected output. Can someone please help me to get the required results.. </p>
<pre><code>import csv
f = csv.reader(open("C:/Users/...../file.csv","rb"))
f2= csv.writer(open("C:/Users/.../test123.csv","wb"))
for row in f:
for column in row:
f2.writerow((column[1],column[2],column[3],column[7]))
f.close()
f2.close()
</code></pre>
| 0 | 2016-08-07T17:32:03Z | 38,816,840 | <p>The second iteration over each row is not necessary. Just access the columns in that row with the column index.</p>
<p>Also, I don't think there's a <code>close</code> method in csv reader and writer.</p>
<pre><code>import csv
f = csv.reader(open("file.csv","rb"))
f2= csv.writer(open("test123.csv","wb"))
for row in f:
f2.writerow((row[1],row[2],row[3],row[7]))
</code></pre>
| 0 | 2016-08-07T17:41:23Z | [
"python",
"python-2.7"
] |
Why use iter() to make a list an iterable? | 38,816,822 | <pre><code>class Node:
def __init__(self, value):
self._value = value
self._children = []
def __repr__(self):
return 'Node({!r})'.format(self._value)
def add_child(self, node):
self._children.append(node)
def __iter__(self):
return iter(self._children)
def depth_first(self):
yield self
for c in self:
yield from c.depth_first()
if __name__ == '__main__':
root = Node(0)
child1 = Node(1)
child2 = Node(2)
root.add_child(child1)
root.add_child(child2)
child1.add_child(Node(3))
child1.add_child(Node(4))
child2.add_child(Node(5))
for a in root.depth_first():
print(a)
# Outputs Node(0), Node(1), Node(3), Node(4), Node(2), Node(5)
</code></pre>
<p>I thought that a list is an object that we can iterate over it so why use <code>iter()</code> ? I am new in python so this look to me so weird.</p>
| 0 | 2016-08-07T17:38:54Z | 38,817,402 | <p>Because returning <code>self._children</code> returns a <code>list</code> object, which doesn't work as an iterator, remember, <em>iterators</em> implement the <code>__next__</code> method in order to supply items during iteration:</p>
<pre><code>>>> next(list()) # doesn't implement a __next__ method
TypeError: 'list' object is not an iterator
</code></pre>
<p><code>list</code>s are <em>iterable</em>, they can be iterated through because calling <code>iter</code> on the will return an <em>iterator</em>, but, <code>list</code>s themselves are not iterators -- a good breakdown of these can be found in the top answer of <a href="http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python/237028#237028">this Question</a>.</p>
<p>A lists <code>__iter__</code> method returns a custom new <code>list_iterator</code> object each time <code>__iter__</code> is called: </p>
<pre><code>list().__iter__()
Out[93]: <list_iterator at 0x7efe7802d748>
</code></pre>
<p>and, by doing that, supports iteration multiple times, the <code>list_iterator</code> object implements the <code>__next__</code> method that's required.
Calling and returning <code>iter</code> on it will just do that, return the lists iterator and save you the trouble of having to implement <code>__next__</code>.</p>
<hr>
<p>Addressing your comment as for why <code>for c in self._children</code> works, well, because it is essentially doing the same thing. What basically happens with the for loop is:</p>
<pre><code>it = iter(self._children) # returns the list iterator
while True:
try:
i = next(it)
<loop body>
except StopIteration:
break
</code></pre>
<p>meaning, <code>iter</code> is called again on the list object and is used by the <code>for</code> loop for <code>next</code> calls.</p>
| 1 | 2016-08-07T18:48:17Z | [
"python",
"list",
"python-3.x",
"iterator"
] |
Why use iter() to make a list an iterable? | 38,816,822 | <pre><code>class Node:
def __init__(self, value):
self._value = value
self._children = []
def __repr__(self):
return 'Node({!r})'.format(self._value)
def add_child(self, node):
self._children.append(node)
def __iter__(self):
return iter(self._children)
def depth_first(self):
yield self
for c in self:
yield from c.depth_first()
if __name__ == '__main__':
root = Node(0)
child1 = Node(1)
child2 = Node(2)
root.add_child(child1)
root.add_child(child2)
child1.add_child(Node(3))
child1.add_child(Node(4))
child2.add_child(Node(5))
for a in root.depth_first():
print(a)
# Outputs Node(0), Node(1), Node(3), Node(4), Node(2), Node(5)
</code></pre>
<p>I thought that a list is an object that we can iterate over it so why use <code>iter()</code> ? I am new in python so this look to me so weird.</p>
| 0 | 2016-08-07T17:38:54Z | 38,830,770 | <p>Every iterable object implements an <strong>iter</strong>() function that returns itself.
the iter(obj) calls the obj.<strong>iter</strong>(), which is same as returning the list object in your example.</p>
| 0 | 2016-08-08T13:40:38Z | [
"python",
"list",
"python-3.x",
"iterator"
] |
How can I capture a key press (key logging) in Linux? | 38,816,861 | <p>How can I capture a key press (key logging) in Linux?</p>
<p>For Windows exist pyHook library but I dont know how to do it in Linux.</p>
| 3 | 2016-08-07T17:44:09Z | 38,816,959 | <p>You can use pyxhook:</p>
<pre><code>#!/usr/bin/env python
import pyxhook
def OnKeyPress(event):
print (event.Key)
if event.Ascii == 32:
exit(0)
hm = pyxhook.HookManager()
hm.KeyDown = OnKeyPress
hm.HookKeyboard()
hm.start()
</code></pre>
<p>sudo apt-get install python-xlib
<a href="https://github.com/JeffHoogland/pyxhook" rel="nofollow">https://github.com/JeffHoogland/pyxhook</a></p>
| 2 | 2016-08-07T17:55:18Z | [
"python",
"linux"
] |
How can I capture a key press (key logging) in Linux? | 38,816,861 | <p>How can I capture a key press (key logging) in Linux?</p>
<p>For Windows exist pyHook library but I dont know how to do it in Linux.</p>
| 3 | 2016-08-07T17:44:09Z | 38,817,295 | <pre><code>#!/usr/bin/env python
import pyxhook
import time
#This function is called every time a key is presssed
def kbevent( event ):
#print key info
print event
#If the ascii value matches spacebar, terminate the while loop
if event.Ascii == 32:
global running
running = False
#Create hookmanager
hookman = pyxhook.HookManager()
#Define our callback to fire when a key is pressed down
hookman.KeyDown = kbevent
#Hook the keyboard
hookman.HookKeyboard()
#Start our listener
hookman.start()
#Create a loop to keep the application running
running = True
while running:
time.sleep(0.1)
#Close the listener when we are done
hookman.cancel()
</code></pre>
| 2 | 2016-08-07T18:34:44Z | [
"python",
"linux"
] |
Web scraping with BS4: unable to find tag | 38,816,915 | <p>There is a site that provides football (soccer) related statistics, I find the in-house option of querying the data to be limiting and want to perform my own analysis, but to do so I must scrape the data - I am using Beautiful Soup 4. </p>
<p>Documentation is found <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-the-tree" rel="nofollow">here</a>.</p>
<p>According to Beautiful Soup documentation I can search for a particular tag using find_all(), however when I try to use it it turns up for a blank. </p>
<p>from urllib.request import urlopen
from bs4 import BeautifulSoup
import csv as csv </p>
<pre><code>html = urlopen("http://members.fantasyfootballscout.co.uk/player-stats/goalkeepers/")
bsObj = BeautifulSoup(html.read(), "lxml")
</code></pre>
<p>Presumably, being behind a pay wall you will not be able to access it. With this in mind I will post code snippet. </p>
<pre><code> <tbody>
<tr>
<td><input type="checkbox" name="players[]" value="61302"></td>
<td class="first">
<a href="/player-profiles/ryan-allsopp/" class="enhanced-title" title="Ryan Allsopp"> Allsopp </a>
<div class="profile-title">
<img src="/images/players/small/default.png" alt="" width="42" height="64">
<br>Ryan Allsopp <br> (Bournemouth, Goalkeeper)
</div>
</td>
<td class="nowrap">
<span class="team-disc bou-light"></span>
<a href="/player-stats/goalkeepers/fantasy-index/bournemouth/" title="Bournemouth"> BOU</a>
</td>
<td title="Starts: 0">0</td>
<td title="Time Played: 54"> 54</td>
<td title="Subbed On: 1">1</td>
<td title="Subbed Off: 0"> 0</td>
<td title="Goals: 0"> 0 </td>
<td title="Assists: 0"> 0 </td>
<td title="Clean Sheets: 0">0 </td>
<td title="Goals Conceded: 1"> 1 </td>
<td title="Own Goals: 0"> 0 </td>
<td title="Saves: 0"> 0 </td>
<td title="Premier League Yellow Cards: 0"> 0</td>
<td title="Premier League Total Red Cards: 0"> 0 </td>
</tr>
<tr>
<td><input type="checkbox" name="players[]" value="57187"></td>
</code></pre>
<p>To start with I want to pull all the table data, but I am having trouble identify even one td in BS. </p>
<pre><code>bsObj.td # returns empty set
bsobj.find_all('td') # returns empty set
</code></pre>
<p>Where am I going wrong?</p>
| 0 | 2016-08-07T17:49:37Z | 38,829,588 | <p>Comments above were helpful, I have persisted session cookies as suggested though that failed to solve the issue. </p>
<p>The solution relates to asynchronous HTTP calls made by the javascript portion of the site. I have installed selenium (documentation <a href="http://selenium-python.readthedocs.io" rel="nofollow">here</a>), which I will use to execute javascript, to give me access to the data that I want. </p>
| 0 | 2016-08-08T12:44:21Z | [
"python",
"beautifulsoup"
] |
Why does YoutubeDL extract only the first index of a playlist? | 38,816,938 | <p>I'm doing a project that's related to playlists and I made a class which inherits from YoutubeDL.</p>
<pre><code>class Playlist(youtube_dl.YoutubeDL):
info = {}
"""
Base class for any playlist. Inherits from youtube_dl.YoutubeDL and overrides some methods to make sure that the
link is an actual playlist and implements some cool stuff to make playlist loading easier.
:var info: the stored information from the extract_info() method
:type info: dict
"""
def extract_info(self, url, download=False, ie_key=None, extra_info=None, process=True, force_generic_extractor=False):
"""
Loads the playlist info and make sures the link is a playlist
:param url: the link with the info to be loaded
:param download: will it download?
:param ie_key: see youtube_dl's doc
:param extra_info: see youtube_dl's doc
:param process: see youtube_dl's doc
:param force_generic_extractor: see youtube_dl's doc
:return: extract_info(...)["entries"] = self.info
:rtype: list
"""
info = super(Playlist, self).extract_info(url, download, ie_key, extra_info, process, force_generic_extractor)
if "_type" not in info:
raise BaseException("\"_type\" not in \"info\"!\n" + info.__str__())
if info["_type"] != "playlist":
raise NotPlaylistError("The url %s does not appear to be a playlist" % url)
self.info = info["entries"]
return self.info
def download(self, url_list=list()):
"""
The inherited download method - now can be used without parameters. If no url_list specified, uses self.info
:param url_list: the url list to be downloaded
:return: nothing
:rtype: None
"""
super(Playlist, self).download(url_list if url_list else self.info)
</code></pre>
<p>So I've simply added a playlist with <code>Playlist().extract_info(my_url)</code>. But it raised a <code>KeyError</code> which was caused by a <code>"_type"</code> key. Thus I played with the code a bit and I found out the code was downloading only the first index of the entire playlist (the actual code posted here is already handling that by raising a <code>BaseError</code>). Why is this happening?</p>
| 3 | 2016-08-07T17:52:06Z | 38,818,104 | <p>First of all, you should probably review <a href="https://github.com/rg3/youtube-dl/blob/master/youtube_dl/extractor/common.py#L74" rel="nofollow">the specification of the info</a> you're looking at. For instance, a missing <code>_type</code> is equivalent to the _type <code>'video'</code>. Thus, a proper check for info to be a playlist is simply</p>
<pre><code>if info.get('_type', 'video') != 'playlist': ..
</code></pre>
<p>Your program will also break or do random stuff when someone calls <code>download</code> without arguments. <code>YoutubeDL.download</code> expects a list of URLs for its first parameter (named <code>url_list</code>).</p>
<p>If <code>extract_info</code> has not been called before, <code>YoutubeDL.download({})</code> will be called. This works currently, but <code>{}</code> is no list, and thus conceptually the wrong format. But luckily, this will just do nothing.</p>
<p>However, if <code>extract_info</code> has been called before, and you have advised youtube-dl to <strong>not</strong> extract detailed information (for example you activated the <code>listformats</code> option to your instance of YoutubeDL), then <code>self.info</code> will be a list of infos, not a list of URLs.</p>
<p>If <code>extract_info</code> has been called before with default options, youtube-dl will <strong>recursively</strong> call extract_info on every element of the playlist. On each invocation, you overwrite <code>self.info</code> with the entries (luckily, as far as I understand, the playlist will win out, but that's incredible brittle code). However, <a href="https://github.com/rg3/youtube-dl/blob/37768f92422c2cf61a961dbaf54d61dabd364506/youtube_dl/extractor/common.py#L266" rel="nofollow">as documented</a>, each item will be a dictionary, not a URL. Likely, you've picked up one of the intermediately set values.</p>
<p>Subclassing may be needlessly complicated as well, especially for a Python beginner. It is likely <a href="https://en.wikipedia.org/wiki/Composition_over_inheritance" rel="nofollow">easier and more flexible</a> to use <a href="https://en.wikipedia.org/wiki/Object_composition" rel="nofollow">composition</a>.</p>
<p>Finally, beware that at its current description, you may be victim of an <a href="http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem">XY problem</a>. Fundamentally, youtube-dl handles a playlist of one item and a single video very similarly, so it doesn't make a lot of sense to distinguish the two.</p>
| 0 | 2016-08-07T20:10:58Z | [
"python",
"youtube-dl"
] |
Determine subsets among members of a powerset efficiently in Python | 38,816,950 | <p>So I've indexed the members of the powerset of the alphabet in the following way:</p>
<pre><code>def bytecode_index(some_subset):
mask = 0
for index in bytearray(some_subset):
mask |= (1<<(index-97))
return mask
</code></pre>
<p>This might be a bit nonstandard, and improvements with respect to improving it are very much welcome, but the crux of my question is actually as follows:</p>
<p>How can I take two such masks and determine if one is a subset of the other efficiently and pythonically? One such way for determining if <code>index1</code> is a subset of <code>index2</code> is to compare their binary strings. if <code>index1</code> has a 1 where <code>index2</code> has a 0, the set corresponding to <code>index1</code>is not a subset of the set corresponding to <code>index2</code>.</p>
<p>I've written something that looks like this for that:</p>
<pre><code>def compare_binary_strings(index1,index2):
return not any(x == "1" and y == "0" for x,y in zip(bin(index1), bin(index2)))
</code></pre>
<p>This seems inefficient, as it involves converting the indices to strings and then comparing them componentwise. Any and all help is much appreciated.</p>
<p>Is there a more simple operation available to quickly compare the two indices?</p>
| 2 | 2016-08-07T17:53:50Z | 38,818,495 | <p>Well I don't know about Pythonically, but generically the way to check if one bitmask is a subset of the other is:</p>
<pre><code>(x & y) == x
</code></pre>
<p>Iff true, <code>x</code> is a subset of <code>y</code>.</p>
<p>This just the bitmath equivalent of the familiar</p>
<p>A â B â A â© B = A</p>
| 2 | 2016-08-07T20:58:11Z | [
"python",
"performance",
"optimization",
"bin",
"powerset"
] |
Index out of range error , Can someone please tell me where Its going wrong | 38,816,963 | <p>This is my function so far:</p>
<pre><code>def fizzbuzz(intList):
strList = list[]
for i in range(0,len(intList)):
if intList[i] % 3== 0 and intList[i] % 5==0:
strList[i] = "FizzBuzz"
elif intList[i] % 3 == 0:
strList[i] = "Fizz"
elif intList[i] % 5 == 0:
strList[i] = "Buzz"
else:
strList[i] = str(intList[i])
return strList
</code></pre>
<p>This is what i'm basically supposed to do:</p>
<ol>
<li><p>For numbers that are multiples of three replace the integer with the string "Fizz".</p></li>
<li><p>For numbers that are multiples of five replace the integer with the string "Buzz".</p></li>
<li><p>For numbers that are multiples of both three AND five replace the integer
with the string <code>"FizzBuzz"</code></p></li>
</ol>
<p>Your function should take in a list of integers as input.
Your function should not modify the input list.
Your function should return an updated list with integers and strings.</p>
| 0 | 2016-08-07T17:55:53Z | 38,816,997 | <p>You're creating (most likely, that is) an <em>empty list</em> with <code>strList = list()</code> and then accessing it <code>strList[i]</code> at an index that does not exist -- the <code>strList</code> is empty, <em>any indexing operation on it</em> will raise an <code>IndexError</code>.</p>
<p>You should be <em>copying</em> the original list instead with <code>[:]</code> (or <code>list(intList)</code>, or <code>[*intList]</code> if on Python 3.5):</p>
<pre><code>strList = intList[:]
</code></pre>
<p>Now, when you index <code>strList</code> you'll use the index that corresponds to the current number in <code>intList</code> you're iterating through.</p>
| 0 | 2016-08-07T18:00:07Z | [
"python",
"indexing"
] |
Index out of range error , Can someone please tell me where Its going wrong | 38,816,963 | <p>This is my function so far:</p>
<pre><code>def fizzbuzz(intList):
strList = list[]
for i in range(0,len(intList)):
if intList[i] % 3== 0 and intList[i] % 5==0:
strList[i] = "FizzBuzz"
elif intList[i] % 3 == 0:
strList[i] = "Fizz"
elif intList[i] % 5 == 0:
strList[i] = "Buzz"
else:
strList[i] = str(intList[i])
return strList
</code></pre>
<p>This is what i'm basically supposed to do:</p>
<ol>
<li><p>For numbers that are multiples of three replace the integer with the string "Fizz".</p></li>
<li><p>For numbers that are multiples of five replace the integer with the string "Buzz".</p></li>
<li><p>For numbers that are multiples of both three AND five replace the integer
with the string <code>"FizzBuzz"</code></p></li>
</ol>
<p>Your function should take in a list of integers as input.
Your function should not modify the input list.
Your function should return an updated list with integers and strings.</p>
| 0 | 2016-08-07T17:55:53Z | 38,817,504 | <p>You are indexing <code>strList</code> based on the length of <code>intList</code>. This will only work if strList and intList are the same length.</p>
<p>To create a list you must also use correct syntax <code>list()</code> as opposed to <code>list[]</code></p>
<p>In addition, you have created <code>strList</code> to be an empty string meaning you do not have to use <code>strList[i]</code> to assign values to each index (seemingly impossible).</p>
<p>A solution to this problem is to use <code>.append(value)</code>. I've created a solution as seen below:</p>
<pre><code>def fizzbuzz(intList):
strList = list()
for i in range(0,len(intList)):
if intList[i] % 3== 0 and intList[i] % 5==0:
strList.append("FizzBuzz")
elif intList[i] % 3 == 0:
strList.append("Fizz")
elif intList[i] % 5 == 0:
strList.append("Buzz")
else:
strList.append(str(intList[i]))
return strList
</code></pre>
<p>Here the function will create the strList, iterate through each value in the given intList. Depending on the value the function will append your desired value to the list. Finally, returning a new list build on words and numbers.</p>
| 0 | 2016-08-07T19:00:14Z | [
"python",
"indexing"
] |
Why do I keep getting this error when checking a variable within an "if" condition? | 38,817,006 | <p>When I run this code:</p>
<pre><code>#!/usr/bin/python
from time import strftime
#welcome
state = input("Morning? [y/n] ")
if state == y:
print("Good morning sir! Welcome to our system!")
pass
else:
print("Good afternoon sir! Welcome to our system!")
pass
user = input("What is your name? ")
print("Hello World.")
print("{} is using this computer right now".format(user))
print(strftime("%Y-%m-%d %H:%M:%S"))
</code></pre>
<p>I get this error:</p>
<pre><code>Morning? [y/n] y
Traceback (most recent call last):
File "C:/Users/toshiba/py/hello/hello_world.py", line 7, in <module>
if state == y:
NameError: name 'y' is not defined
</code></pre>
<p>This code is intended to display a custom print message depending on the input of the user as seen in the first input method. I code in python 3 and I can't figure out the issue.</p>
| -2 | 2016-08-07T18:01:23Z | 38,817,011 | <p>Your if statement should be:</p>
<pre><code>if state == 'y':
</code></pre>
<p>The type of <code>state</code> is a string.</p>
<p>Also, your if statement will currently fail if the user enters <code>Y</code> or <code>yes</code>. It's not excruciatingly important now, but you could always handle that like this: </p>
<pre><code>if state in ('y', 'Y', 'yes'):
</code></pre>
<p>It's just something good to know for the future.</p>
| 4 | 2016-08-07T18:02:00Z | [
"python"
] |
Equal strings doesn't return to true | 38,817,168 | <p>I have started learning Python and I have started with the book Violent Python. In it the first chapter describes a script to crack *nix based password hashes with the help of <code>crypt</code> class. Here is the code:</p>
<pre><code>import crypt
def testPass(cryptPass):
salt = cryptPass[0:2]
dictFile = open('dictionary.txt','r')
for word in dictFile.readlines():
word = word.strip('\n')
cryptWord = crypt.crypt(word,salt)
print cryptPass+":"cryptWord
if(cryptPass == cryptWord):
print "[+] Password found : "+word
return
print "[-] Password Not Found.\n"
return
def main():
passFile = open('passwords.txt')
for line in passFile.readlines():
if ":" in line:
user = line.split(':')[0]
cryptPass = line.split(':')[1].strip(' ')
print "[*] Cracking Password For: "+user
testPass(cryptPass)
if __name__ == "__main__":
main()
</code></pre>
<p>I have a passwords.txt file which contains the username:password(password hash) strings, and another file named dictionary.txt which contains the dictionary words.These are the contents of passwords.txt file : </p>
<pre><code>apple:HXJintBqUVCEY
mango:HXInAjNhZF7YA
banana:HXKfazJbFHORc
grapes:HXtZSWbomS0xQ
</code></pre>
<p>and the dictionary.txt : </p>
<pre><code>apple
abcd
efgh
ijkl
mnop
</code></pre>
<p>The password hash computed from testpass() method and the password hash from passwords.txt for username apple are equal , when I print both of them. But the output here for all 4 usernames is "[-] Password not found". Why the == test fails here?</p>
| 1 | 2016-08-07T18:20:29Z | 38,817,228 | <p>Perhaps you have a trailing <code>\n</code> at the end of the line. Try change:</p>
<pre><code> cryptPass = line.split(':')[1].strip(' ')
</code></pre>
<p>to:</p>
<pre><code> cryptPass = line.split(':')[1].strip('\n').strip(' ')
</code></pre>
<p>or even simpler (as suggested in comments):</p>
<pre><code> cryptPass = line.split(':')[1].strip()
</code></pre>
| 1 | 2016-08-07T18:27:17Z | [
"python",
"dictionary",
"hash"
] |
django cannot find image | 38,817,221 | <p>I have a site with the following file structure:</p>
<pre><code>MyProject
+--- media
+--- user_1
+--- my_image
+--- profiles
+--- templates
+--- profiles
+--- create.html
+--- login.html
+--- profile.html
+--- urls.py
+--- models.py
+--- views.py
+--- MyProject
+--- settings.py
</code></pre>
<p>In <code>settings.py</code> I have my <code>MEDIA_ROOT = os.path.join(BASE_DIR, 'media')</code> and <code>MEDIA_URL = '/'</code> set like so and I have <code>'django.template.context_processors.media'</code> added to <code>context_processors</code>. In my <code>urls.py</code> I have the following:</p>
<pre><code>urlpatterns = [
url(r'^profile/(?P<profile_id>[0-9]+)/$', views.Details, name = "account"),
url(r'^update/', views.Update_Profile, name = "update"),
] + static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) +\
static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
</code></pre>
<p>The template <code>profile.html</code> looks like:</p>
<pre><code>{% extends "base.html" %}
{% load profiles_extras %}
{% block content %}
{% load staticfiles %}
<div class="container-fluid">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<!-- Store Information -->
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
<h2>Store Information</h2>
</div>
<div class="center-block">
<!-- Change picture form -->
<form method="post" action="{% url 'update' %}" class="hidden form-inline" id="picture-change-form" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<input type="file" class="form-control" name="picture" accept="image/*">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
{% if profile.logo %}
<img src="{{ profile.logo.url }}" class="img-responsive" id="logo" alt="Store Logo">
{% else %}
<img src="{% static 'no-image.png' %}" class="img-responsive" id="logo" alt="Store Logo">
{% endif %}
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
</code></pre>
<p>When a profile image is uploaded, this function in <code>profiles.views.py</code> is called.</p>
<pre><code>@login_required
def Update_Profile(request):
update_profile = Profile.objects.get(user = request.user)
has_updated = False
if ('picture' in request.FILES):
update_profile.update_logo( request.FILES['picture'] )
return redirect('profiles.views.Details', profile_id = update_profile.id)
</code></pre>
<p>This function in turn calls <code>update_logo</code> in <code>profiles.models.py</code>:</p>
<pre><code>def update_logo(self, value):
self.logo = value
self.save()
</code></pre>
<p>However, when I upload a photo, <code>my_image.png</code> it comes up as <code>user_1/my_image.png</code> and the server returns a 404 because the file wasn't found. What am I doing wrong here?</p>
| 1 | 2016-08-07T18:26:24Z | 38,817,916 | <p>Django have defined urls for <code>/profile/</code>, <code>/update/</code>, <code>/static/</code> and <code>/</code>.</p>
<p>Url <code>/user_1/</code> is not defined.</p>
<p>Try to change <code>MEDIA_URL</code> to <code>/media/</code>.</p>
| 1 | 2016-08-07T19:50:00Z | [
"python",
"django"
] |
How to pass a matrix as a list of vectors in a cartesian product in python | 38,817,250 | <p>I'm trying to create a combinatorics matrix from a series of vectors. If I wanted all vectors to be included in the combination I would use:</p>
<pre><code>CombinatoricsMatrix = list(itertools.product(vector1, vector2, ...)
</code></pre>
<p>or</p>
<pre><code>CombinatoricsMatrix = cartesian((vector1, vector2))
</code></pre>
<p>such that if </p>
<pre><code>vector1 = [a]
vector2 = [1,2]
CombinatoricsMatrix = cartesian((vector1, vector2))
CombinatoricsMatrix = [a,1; a,2]
</code></pre>
<p>However, there are some matrices that I want to pass as 'a list of vectors' so that the elements of those vectors are not included in the combination. </p>
<p>For example if </p>
<pre><code>matrix3 = [w,x; y,z]
</code></pre>
<p>the desired output is</p>
<pre><code>CombinatoricsMatrix = cartesian((vector1, vector2, matrix3 ))
CombinatoricsMatrix = [a,1,[w,x]; a,1,[y,z]; a,2,[w,x]; a,2,[y,z]]
</code></pre>
<p>Any ideas? Note that the length and amount of vectors were kept short for the example.</p>
| 0 | 2016-08-07T18:30:10Z | 38,817,280 | <p>There are likely more pythonic ways to do this but one solution is to zip the matrices such that </p>
<pre><code>CombinatoricsMatrix = list(itertools.product(vector1, vector2, zip(matrix3))
</code></pre>
| 0 | 2016-08-07T18:33:10Z | [
"python",
"python-3.x",
"combinatorics"
] |
Python SSH server (socket + paramiko) "Address already in use" | 38,817,286 | <p>So I decided to read more about networks in Python, and in the book I'm reading, there's this piece of code that creates a SSH server using paramiko (a third party SSH module) and socket.</p>
<p>The problem I'm having is that whenever I input a server address, it says "Address already in use". In addition, I'm already using <code>sock.setsockopt(sock.SOL_SOCKET, sock.SO_REUSEADDR, 1)</code> so the address can be reused, but the problem still persists.</p>
<p>Here's the full code:</p>
<pre><code>import socket
import paramiko
import threading
import sys
import traceback
# using the key from the Paramiko demo files
host_key = paramiko.RSAKey(filename='test_rsa.key')
class Server (paramiko.ServerInterface):
def __init__(self):
self.event = threading.Event()
def check_channel_request(self, kind, chanid):
if kind=='session':
return paramiko.OPEN_SUCCEEDED
return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
def check_auth_password(self,user, password):
if (usernae == 'matheus') and (password == 'password'):
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
server = sys.argv[1]
ssh_port = int(sys.argv[2])
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((server, ssh_port))
sock.listen(100) # Wow so many connections
print ("[+] Listening for connection ...")
client, addr = sock.accept()
except Exception, e:
print("[-] Listen failed: " + str(e))
traceback.print_stack()
sys.exit(1)
print("[+] Got a connection!") # runs as except exits
try:
bhSession = paramiko.Transport(client)
bhSession.add_server_key(host_key)
server = Server()
try:
bhSession.start_server(server=server)
except paramiko.SSHException, x:
print("[-] SSH negotiation failed.")
chan = bhSession.accept(20)
print("[+] Authenticated!")
print(chan.recv(1024))
chan.send("Welcome to bh_ssh")
while True:
try:
command = raw_input("Enter command: ").strip('\n')
if command != 'exit':
chan.send(command)
print(chan.recv(1024)+'\n')
else:
chan.send('exit')
print("exiting")
bhSession.close()
raise Exception("exit")
except KeyboardInterrupt:
bhSession.close()
except Exception, e:
print("[-] Caught exception: " + str(e))
try:
bhSession.close()
except:
pass
sys.exit(1)
</code></pre>
<p>The addresses I've tried are:</p>
<pre><code>192.168.1.107 (current device address)
0.0.0.0
0.0.0.1
127.0.0.1 (localhost)
</code></pre>
<p>The port was always 22.</p>
<p>Peace!</p>
| 0 | 2016-08-07T18:33:25Z | 38,817,337 | <p>Try using the <code>SO_REUSEADDR</code> socket option before binding the socket.</p>
<pre><code>sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
</code></pre>
| 0 | 2016-08-07T18:38:23Z | [
"python",
"sockets",
"ssh"
] |
Python SSH server (socket + paramiko) "Address already in use" | 38,817,286 | <p>So I decided to read more about networks in Python, and in the book I'm reading, there's this piece of code that creates a SSH server using paramiko (a third party SSH module) and socket.</p>
<p>The problem I'm having is that whenever I input a server address, it says "Address already in use". In addition, I'm already using <code>sock.setsockopt(sock.SOL_SOCKET, sock.SO_REUSEADDR, 1)</code> so the address can be reused, but the problem still persists.</p>
<p>Here's the full code:</p>
<pre><code>import socket
import paramiko
import threading
import sys
import traceback
# using the key from the Paramiko demo files
host_key = paramiko.RSAKey(filename='test_rsa.key')
class Server (paramiko.ServerInterface):
def __init__(self):
self.event = threading.Event()
def check_channel_request(self, kind, chanid):
if kind=='session':
return paramiko.OPEN_SUCCEEDED
return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
def check_auth_password(self,user, password):
if (usernae == 'matheus') and (password == 'password'):
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
server = sys.argv[1]
ssh_port = int(sys.argv[2])
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((server, ssh_port))
sock.listen(100) # Wow so many connections
print ("[+] Listening for connection ...")
client, addr = sock.accept()
except Exception, e:
print("[-] Listen failed: " + str(e))
traceback.print_stack()
sys.exit(1)
print("[+] Got a connection!") # runs as except exits
try:
bhSession = paramiko.Transport(client)
bhSession.add_server_key(host_key)
server = Server()
try:
bhSession.start_server(server=server)
except paramiko.SSHException, x:
print("[-] SSH negotiation failed.")
chan = bhSession.accept(20)
print("[+] Authenticated!")
print(chan.recv(1024))
chan.send("Welcome to bh_ssh")
while True:
try:
command = raw_input("Enter command: ").strip('\n')
if command != 'exit':
chan.send(command)
print(chan.recv(1024)+'\n')
else:
chan.send('exit')
print("exiting")
bhSession.close()
raise Exception("exit")
except KeyboardInterrupt:
bhSession.close()
except Exception, e:
print("[-] Caught exception: " + str(e))
try:
bhSession.close()
except:
pass
sys.exit(1)
</code></pre>
<p>The addresses I've tried are:</p>
<pre><code>192.168.1.107 (current device address)
0.0.0.0
0.0.0.1
127.0.0.1 (localhost)
</code></pre>
<p>The port was always 22.</p>
<p>Peace!</p>
| 0 | 2016-08-07T18:33:25Z | 38,828,991 | <p><code>SO_REUSEPORT</code> is what most people would expect <code>SO_REUSEADDR</code> to be.</p>
<p>Basically, <code>SO_REUSEPORT</code> allows you to bind an arbitrary number of sockets to exactly the same source address and port as long as all prior bound sockets also had <code>SO_REUSEPORT</code> set before they were bound.</p>
| 0 | 2016-08-08T12:15:29Z | [
"python",
"sockets",
"ssh"
] |
Beautifulsoup: findAll recursive doesn't work | 38,817,300 | <p>I'm trying to get articles from wired.com.
Generally their articles' content look like this:</p>
<pre><code><article itemprop="articleBody">
<p>Some text</p>
<p>Next text</p>
<p>...</p>
<p>...</p>
</article>
</code></pre>
<p>or like this:</p>
<pre><code><article itemprop="articleBody">
<div class="listicle-captions marg-t...">
<p></p>
</div>
</article>
</code></pre>
<p>So I want if the page is of type 1, the <code><p></code> and <code><h></code> are extracted, while if the page is of type 2 - do something else. So, if the <code><p></code> and <code><h></code> are direct descendants of <code><article></code>, then it's type 1.
I tried the following code, it looks for <code><p></code> and <code><h></code> and prints out the tag names. The thing is, the <code>recursive="False"</code> doesn't seem to help because when tested on type 2 page, it finds the tags, while it shouldn't (I espected to get a <code>NonType</code> object).</p>
<pre><code>import urllib.request
from bs4 import BeautifulSoup
import datetime
import html
import sys
articleUrl="https://www.wired.com/2016/07/greatest-feats-inventions-100-years-boeing/"
soupArticle=BeautifulSoup(urllib.request.urlopen(articleUrl), "html.parser")
articleBody=soupArticle.find("article", {"itemprop":"articleBody"})
articleContentTags=articleBody.findAll(["h1", "h2","h3", "p"], recursive="False")
for tag in articleContentTags:
print(tag.name)
print(tag.parent.encode("utf-8"))
</code></pre>
<p>Why doesn't it work?</p>
<p>PS Also, is there a difference between using <code>findAll</code> and <code>findChildren</code> in general and in this particular case? These two look the same to me..</p>
| 1 | 2016-08-07T18:34:54Z | 38,818,601 | <p>The string literal <code>"False"</code> is not the same as use the <em>boolean</em> <code>False</code>, you need to actually pass <code>recursive=False</code>:</p>
<pre><code>articleBody.find_all(["h1", "h2","h3", "p"], recursive=False)
</code></pre>
<p>Any non empty string is going to be considered a truthy value , the only string you could pass that would work would be an empty string i.e <code>recursive=""</code>.</p>
<pre><code>In [17]: bool("False")
Out[17]: True
In [18]: bool("foo")
Out[18]: True
In [19]: bool("")
Out[19]: False
</code></pre>
<p>But stick to using the actual <em>boolean</em> <code>False</code>, also you will get an empty <em>list/ResultSet</em> returned with <code>recursive=False</code>, not None as you are calling <em>find_all</em> not <em>find</em>.</p>
| 1 | 2016-08-07T21:11:59Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Randomly select item from list of lists gives ValueError | 38,817,357 | <p>I have a function that sometimes gives me a list of lists where the nested lists sometimes only have one item, such as this one:</p>
<pre><code>a = [['1'], ['3'], ['w']]
</code></pre>
<p>And want to randomly select one item from that main list <code>a</code>. If I try to use <code>np.random.choice</code> on this list, I get a <code>ValueError: a must be 1-dimensional</code>.</p>
<p>But if the list were instead:</p>
<pre><code>b = [['1'], ['3'], ['w', 'w']]
</code></pre>
<p>Then using <code>np.random.choice</code> works perfectly fine. Why is this? And how can I make it so that I can randomly select from both types of lists?</p>
| 4 | 2016-08-07T18:41:18Z | 38,817,508 | <p>I think <code>choice</code> is first turning your list into an array.</p>
<p>In the second case, this array is a 1d array with dtype object:</p>
<pre><code>In [125]: np.array([['1'], ['3'], ['w', 'w']])
Out[125]: array([['1'], ['3'], ['w', 'w']], dtype=object)
In [126]: _.shape
Out[126]: (3,)
</code></pre>
<p>In the second, it makes a 2d array of strings:</p>
<pre><code>In [127]: np.array([['1'], ['3'], ['w']])
Out[127]:
array([['1'],
['3'],
['w']],
dtype='<U1')
In [128]: _.shape
Out[128]: (3, 1)
</code></pre>
<p>This is an issue that comes up periodically. <code>np.array</code> tries to create as a high a dimensional array as the input allows. </p>
<p><a href="http://stackoverflow.com/questions/38774922/prevent-numpy-from-creating-a-multidimensional-array">Prevent numpy from creating a multidimensional array</a></p>
| 3 | 2016-08-07T19:01:03Z | [
"python",
"python-2.7",
"numpy",
"nested-lists"
] |
Randomly select item from list of lists gives ValueError | 38,817,357 | <p>I have a function that sometimes gives me a list of lists where the nested lists sometimes only have one item, such as this one:</p>
<pre><code>a = [['1'], ['3'], ['w']]
</code></pre>
<p>And want to randomly select one item from that main list <code>a</code>. If I try to use <code>np.random.choice</code> on this list, I get a <code>ValueError: a must be 1-dimensional</code>.</p>
<p>But if the list were instead:</p>
<pre><code>b = [['1'], ['3'], ['w', 'w']]
</code></pre>
<p>Then using <code>np.random.choice</code> works perfectly fine. Why is this? And how can I make it so that I can randomly select from both types of lists?</p>
| 4 | 2016-08-07T18:41:18Z | 38,818,187 | <p>To answer the "how to make it work" part you can use:</p>
<pre><code>np.random.choice(np.squeeze(a))
</code></pre>
<p>Note that this will eliminate the square brackets for <code>a</code>, but not for <code>b</code>. But might still be useful.</p>
| 0 | 2016-08-07T20:21:28Z | [
"python",
"python-2.7",
"numpy",
"nested-lists"
] |
Python. Find user folder to appdata | 38,817,364 | <p>How can I find a path to appdata folder if C:\Users*username folder*\AppData this folder isn't same as username?</p>
<p>Thanks in advance.</p>
| -1 | 2016-08-07T18:42:13Z | 38,817,523 | <pre><code>import os
print os.getenv('APPDATA')
</code></pre>
| 0 | 2016-08-07T19:02:32Z | [
"python"
] |
Invalid token from split or input method | 38,817,377 | <p>I'm currently constructing a little python script and for some reason, I'm receiving an invalid token after I input my value.</p>
<p>Code:</p>
<pre><code>#!/usr/bin/python
def main():
frankOceanRelease()
def frankOceanRelease():
info = str(input('Enter the date in which Frank will drop his album (MM/DD/YYYY):')).split("/")
if info[1] == "13" and info[0] == "11":
return('Let\'s hope he doesn\'t flake')
elif info[2] == "3005":
return('This might happen, but no guarantee')
else:
return('Nah man, this album ain\'t out yet!')
if __name__ == "__main__":
main()
</code></pre>
<p>Error:</p>
<pre><code>File "./frankOceanRelease.py", line 16, in <module>
main()
File "./frankOceanRelease.py", line 4, in main
frankOceanRelease()
File "./frankOceanRelease.py", line 7, in frankOceanRelease
info = input('Enter the date in which Frank will drop his album (MM DD YYYY):').split()
File "<string>", line 1
08 07 2016
^
SyntaxError: invalid token
</code></pre>
| 1 | 2016-08-07T18:45:08Z | 38,817,463 | <p>If you're on Python 2, then entering the items with <code>input</code> separated by <code>/</code> (i.e. <code>'MM/DD/YYYY)'</code>) will perform multiple integer divisions. You will almost always get a <code>0</code> since the year will be far larger than the two others.</p>
<p>On the other hand, entering without the separator will raise the error you see since that input cannot be evaluated.</p>
<p>What you want is <code>raw_input</code>:</p>
<pre><code>>>> info = raw_input('Enter the date in which Frank will drop his album (MM/DD/YYYY):').split("/")
Enter the date in which Frank will drop his album (MM/DD/YYYY):11/06/2016
>>> info
['11', '06', '2016']
</code></pre>
| 1 | 2016-08-07T18:54:37Z | [
"python"
] |
TCP client server not receiving any data from each other | 38,817,477 | <p>I have written the following TCP client and server using python socket module. However, after I run them, no output is being given. It seems that
the program is not able to come out of the while loop in the recv_all method
Server:</p>
<pre><code>import socket
def recv_all(sock):
data = []
while True:
dat = sock.recv(18)
if not dat:
break
data.append(dat)
return "".join(data)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = '127.0.0.1'
PORT = 45678
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((HOST, PORT))
sock.listen(1)
print "listening at", sock.getsockname()
while True:
s, addr = sock.accept()
print "receiving from", addr
final = recv_all(s)
print "the client sent", final
s.sendall("hello client")
s.close()
</code></pre>
<p>Client :</p>
<pre><code>import socket
def recv_all(sock):
data=[]
while True:
dat=sock.recv(18)
if not dat:
break
data.append(dat)
return "".join(data)
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
PORT=45678
HOST='127.0.0.1'
sock.connect((HOST,PORT))
sock.sendall("hi server")
final=recv_all(sock)
print "the server sent",final
</code></pre>
| 0 | 2016-08-07T18:56:40Z | 38,828,853 | <p>Because in server file you use an endless loop in another. I suggest you to edit <code>recv_all</code> method in both files this way:</p>
<pre><code>def recv_all(sock):
data = []
dat = sock.recv(18)
data.append(dat)
return "".join(data)
</code></pre>
<p>But after edit like this your server stays on until <code>KeyInterrupt</code>, while you should run client file everytime you want to send data. If you want an automatically <code>send/receive</code> between server and client, I offer you try <code>threading</code>.</p>
| 0 | 2016-08-08T12:09:26Z | [
"python",
"sockets",
"tcp",
"python-sockets"
] |
Replace a column in Pandas dataframe with another that has same index but in a different order | 38,817,484 | <p>I'm trying to re-insert back into a pandas dataframe a column that I extracted and of which I changed the order by sorting it.</p>
<p>Very simply, I have extracted a column from a pandas df:</p>
<pre><code>col1 = df.col1
</code></pre>
<p>This column contains integers and I used the .sort() method to order it from smallest to largest. And did some operation on the data.</p>
<pre><code>col1.sort()
#do stuff that changes the values of col1.
</code></pre>
<p>Now the indexes of col1 are the same as the indexes of the overall df, but in a different order.</p>
<p>I was wondering how I can insert the column back into the original dataframe (replacing the col1 that is there at the moment) </p>
<p>I have tried both of the following methods:</p>
<p>1)</p>
<pre><code>df.col1 = col1
</code></pre>
<p>2)</p>
<pre><code>df.insert(column_index_of_col1, "col1", col1)
</code></pre>
<p>but both methods give me the following error:</p>
<pre><code>ValueError: cannot reindex from a duplicate axis
</code></pre>
<p>Any help will be greatly appreciated.
Thank you.</p>
| 2 | 2016-08-07T18:57:23Z | 38,817,691 | <p>Consider this DataFrame:</p>
<pre><code>df = pd.DataFrame({'A': [1, 2, 3], 'B': [6, 5, 4]}, index=[0, 0, 1])
df
Out:
A B
0 1 6
0 2 5
1 3 4
</code></pre>
<p>Assign the second column to <code>b</code> and sort it and take the square, for example:</p>
<pre><code>b = df['B']
b = b.sort_values()
b = b**2
</code></pre>
<p>Now <code>b</code> is:</p>
<pre><code>b
Out:
1 16
0 25
0 36
Name: B, dtype: int64
</code></pre>
<p>Without knowing the exact operation you've done on the column, there is no way to know whether 25 corresponds to the first row in the original DataFrame or the second one. You can take the inverse of the operation (take the square root and match, for example) but that would be unnecessary I think. If you start with an index that has unique elements (<code>df = df.reset_index()</code>) it would be much easier. In that case,</p>
<pre><code>df['B'] = b
</code></pre>
<p>should work just fine.</p>
| 0 | 2016-08-07T19:22:38Z | [
"python",
"pandas"
] |
Regex for checking the same word in different cases | 38,817,514 | <p>I am looking to get some code written for a (hopefully) simple project. What I have is a plain text document. Lets say it contains two sentences:</p>
<blockquote>
<p>Coding is fun. I enjoy coding.</p>
</blockquote>
<p>What I want is a way to read the file and look at he words <code>Coding</code> and <code>coding</code> as being the same. So, basically read the words and say there are two instances of the word <code>coding</code> regardless of the case used. Is this possible?
All I know is Regex from my python days but I am learning MEAN stack so anything Javascript/NodeJS would be great. </p>
<p>I'm not asking someone to write the code, I just need some guidance in what to look for or if there are better ways to do this in JavaScript.</p>
<p>The return value in the example I give would ideally be 2. I just need it to count the instances.</p>
| -1 | 2016-08-07T19:01:15Z | 38,817,545 | <p>You can do this in plain JavaScript with a regular expression checking for the word <code>counting</code>. You can see the <code>i</code> and <code>g</code> at the end of the pattern. <code>i</code> stands for <code>ignore-case</code> and <code>g</code> stands for <code>global</code>, which means, it doesn't stop looking, if it found one instance, but returns all of the found instances.</p>
<p>If the sentence does not match the pattern, the script will result in an error, because of the <code>null</code> return value of an unmatched pattern. The <code>|| []</code> checks, if the previous expression is <code>null</code> and is only executed if it is so. This way, it won't throw an error in an unmatched situation but rather return 0.</p>
<p><strong>EDIT</strong>: As mentioned in the comments, <code>coding</code> can be part of another word like <code>decoding</code>. To prevent a false match, you can also match the word boundaries (<code>\b</code>). I added those to the code.</p>
<pre><code>var sentence = "Coding is fun. I enjoy coding.";
var count = (sentence.match(/\bcoding\b/ig) || []).length;
console.log(count);
</code></pre>
<p>Credit goes to: <a href="http://stackoverflow.com/a/4009768/3233827">http://stackoverflow.com/a/4009768/3233827</a></p>
| 1 | 2016-08-07T19:04:53Z | [
"python",
"regex",
"node.js"
] |
Regex for checking the same word in different cases | 38,817,514 | <p>I am looking to get some code written for a (hopefully) simple project. What I have is a plain text document. Lets say it contains two sentences:</p>
<blockquote>
<p>Coding is fun. I enjoy coding.</p>
</blockquote>
<p>What I want is a way to read the file and look at he words <code>Coding</code> and <code>coding</code> as being the same. So, basically read the words and say there are two instances of the word <code>coding</code> regardless of the case used. Is this possible?
All I know is Regex from my python days but I am learning MEAN stack so anything Javascript/NodeJS would be great. </p>
<p>I'm not asking someone to write the code, I just need some guidance in what to look for or if there are better ways to do this in JavaScript.</p>
<p>The return value in the example I give would ideally be 2. I just need it to count the instances.</p>
| -1 | 2016-08-07T19:01:15Z | 38,818,523 | <p>Here's a <code>Python</code> solution:</p>
<pre><code>import re
string = """
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
"""
words = {}
rx = re.compile(r'\b\w+\b')
for match in rx.finditer(string):
word = match.group(0).lower()
if word not in words.keys():
words[word] = 1
else:
words[word] += 1
print(words)
</code></pre>
<p><hr>
A "word" is defined as <code>\b\w+\b</code>, that is word characters surrounded by word boundaries. It outputs a dict with the counted words, see <a href="http://ideone.com/QQCaCV" rel="nofollow"><strong>a demo on ideone.com</strong></a>.</p>
| 0 | 2016-08-07T21:02:35Z | [
"python",
"regex",
"node.js"
] |
Flask-SQLAlchemy adds unnecessary row in parents table (relational tables) | 38,817,517 | <p>I'm recently trying to build a little web-app with Flask. For the database 'stuff' I use Flask-SQLAlchemy and now I'm trying to get a relationship between two objects going.<br>
I have a 'project' table and a 'file' table and it should be a one-to-many relation, so x files can be associated with one project (actually there are more relations coming in the future when I've figured the current problem out).<br>
I've made a input-mask template so a user can upload a file and link it to a project via a dropdown which is populated with the existing projects stored in its table. Thats the corresponding view: </p>
<pre><code>@app.route('/admin/upload/', methods=('GET', 'POST'))
def upload():
form = forms.UploadForm()
if not os.path.isdir(app.config['UPLOAD_FOLDER']):
os.mkdir(app.config['UPLOAD_FOLDER'])
print('Folder created')
form.projectId.choices = []
for g in models.Project.query.order_by('name'):
form.projectId.choices.append((g.id, g.name))
if form.validate_on_submit():
filename = secure_filename(form.fileUpload.data.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
assocProject = models.Project(name=models.Project.query.filter_by(id=form.projectId.data).first().name)
form.fileUpload.data.save(filepath)
prepedFile = models.File(path=filepath, project=assocProject)
print(prepedFile)
print(form.projectId.data)
db.session.add(prepedFile)
db.session.commit()
return 'success'
else:
filename = None
return render_template('upload.html', form=form, filename=filename)
</code></pre>
<p>The prepared file should be an instance of the File-Class which has the linked Project-instance as an attribute, therefore the commit should work. </p>
<pre><code> class Project(db.Model):
__tablename__ = 'project'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
file = db.relationship('File', backref="projects")
post = db.relationship('Post', backref="projects")
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Project %r>' % self.name
class File(db.Model):
__tablename__ = 'file'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
path = db.Column(db.String(64))
type = db.Column(db.String(6))
projectId = db.Column(db.Integer, db.ForeignKey('project.id'))
project = db.relationship('Project', backref='files')
def __init__(self, path, project):
self.path = path
self.project = project
fullName = re.search('[a-zA-Z0-9]*\.[a-zA-Z]{2,}', path)
splitName = fullName.group(0).split('.')
self.name = splitName[0]
self.type = splitName[1]
def __repr__(self):
return '<File %r %r %r %r>' % (self.name, self.type, self.path, self.project)
</code></pre>
<p>And now the problem: When I try to upload a file it works and the file information are stored in the file table but it creates a new entry in the project table and link its id to the file entry. E.g., if the project entry looks like: name = TestProj1, id=1 and I try to link the uploaded to the project it will create a second project: name = TestProj1, id=2.<br>
Thats my struggle and I cant figure out whats wrong. Maybe some of you now. I appreciate any help! </p>
<p>P.S. Maybe it is relevant, here the form I wrote:</p>
<pre><code>class UploadForm(Form):
fileUpload = FileField(label='Deine Datei')
projectId = SelectField(u'Projekte', coerce=int)
</code></pre>
| 0 | 2016-08-07T19:01:30Z | 38,818,544 | <p>You create a new <code>Project</code> each time. </p>
<pre><code>assocProject = models.Project(name=models.Project.query.filter_by(id=form.projectId.data).first().name)
</code></pre>
<p>This does two things. First, it finds the first project with the specified id. Second, it passes that project's name to <code>Project()</code>, creating a new instance using that same name. </p>
<p>What you really want is</p>
<pre><code>assocProject = models.Project.query.get(form.projectId.data)
</code></pre>
| 1 | 2016-08-07T21:05:47Z | [
"python",
"mysql",
"flask",
"flask-sqlalchemy"
] |
Dependencies error in Matplotlib and numpy | 38,817,525 | <p>These versions of softwares are installed :</p>
<ol>
<li>python-2.5</li>
<li>numpy-1.0.1.win32-py2.5</li>
<li>scipy-0.5.2.win32-py2.5</li>
<li>matplotlib-0.87.7.win32-py2.5</li>
</ol>
<p>[installed in same order]</p>
<p>While running my program, I am getting this error message :</p>
<pre class="lang-none prettyprint-override"><code>*The import of the numpy version of the _transforms module,
_ns_transforms, failed. This is is either because numpy was
unavailable when matplotlib was compiled, because a dependency of
_ns_transforms could not be satisfied, or because the build flag for
this module was turned off in setup.py. If it appears that
_ns_transforms was not built, make sure you have a working copy of
numpy and then re-install matplotlib. Otherwise, the following
traceback gives more details:
Traceback (most recent call last):
File "C:\Python25\Scripts\_pictsim.py", line 16, in <module>
from pylab import plot, legend, savefig, gca, vlines, figure, title, xlabel, ylabel, semilogy,\
File "C:\Python25\Lib\site-packages\pylab.py", line 1, in <module>
>from matplotlib.pylab import *
File "C:\Python25\Lib\site-packages\matplotlib\pylab.py", line 201, in <module>
>from axes import Axes, PolarAxes
File "C:\Python25\Lib\site-packages\matplotlib\axes.py", line 14, in <module>
>from artist import Artist, setp
File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 4, in <module>
>from transforms import identity_transform
File "C:\Python25\Lib\site-packages\matplotlib\transforms.py", line 223, in <module>
>from _transforms import Value, Point, Interval, Bbox, Affine
File "C:\Python25\Lib\site-packages\matplotlib\_transforms.py", line 17, in <module>
>from matplotlib._ns_transforms import *
ImportError: DLL load failed: The specified module could not be found.*
</code></pre>
<p>There are some dependency errors, how can I resolve them</p>
<p>While installing numpy, scipy, and matplotlib it says : could not create key and set key value</p>
| 0 | 2016-08-07T19:02:37Z | 38,817,641 | <p>The issue was resolved by downloading 2 dll files and copying in system32 and syswow64</p>
<p>Got this answer from another similar stackoverflow question </p>
<p><a href="http://stackoverflow.com/questions/20201868/importerror-dll-load-failed-the-specified-module-could-not-be-found">ImportError: DLL load failed: The specified module could not be found</a></p>
| 0 | 2016-08-07T19:16:46Z | [
"python",
"numpy",
"matplotlib"
] |
Pass an argument to a class which becomes a keyword for a function | 38,817,558 | <p>Using WTForms with Flask and SQLAlchemy. Taking data from a username and email field and making sure it's not already in the database. Here's what I have to do right now.</p>
<pre><code>class IsUnique(object):
def __init__(self, db_field=None):
self.db_field = db_field
def __call__(self, form, field):
data = field.data
if self.db_field=='name':
if User.query.filter_by(name=data).first() != None:
raise ValidationError('Sorry, that username is taken.')
if self.db_field=='email':
if User.query.filter_by(email=data).first() != None:
raise ValidationError(
'Sorry, that email address has already been registered.'
)
</code></pre>
<p>What I would like to do is to pass the db_field argument to the class instance as a string and pass it into <code>User.query.filter_by(db_field=data</code>. Unfortunately all I know how to do is use an if statement, which works, but is kinda cumbersome. There's gotta be a way to do this right, but I don't know how.</p>
| 0 | 2016-08-07T19:06:58Z | 38,817,585 | <p>You can pass <a href="http://stackoverflow.com/questions/334655/passing-a-dictionary-to-a-function-in-python-as-keyword-parameters">keyword arguments as a dict</a>, like this:</p>
<pre><code>def __call__(self, form, field):
key = self.db_field # 'name' or 'email'
params = { key: field.data }
if User.query.filter_by(**params).first() != None:
raise ValidationError('Sorry, that {} is taken.'.format(key))
</code></pre>
| 2 | 2016-08-07T19:09:33Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy",
"wtforms",
"flask-wtforms"
] |
Merge two photos into a single photo in python | 38,817,688 | <p>I'm attempting to create new photos, each with 2 side by side photos taken from a list of 24 photos. I eventually want every possible pair combination (276 total) on a new photo. For the time being, however, I'm just trying to get the program to paste two photos onto a new photo and I'm getting an error. The code and error are listed below:</p>
<pre><code>from PIL import Image
import os
import itertools
plist = os.listdir('image_resize')
for p in plist[:]:
if not(p.endswith('.png')):
plist.remove(p)
print(plist)
os.chdir('C:\Python35-32\Scripts\image_resize')
def get_pics(x,y):
w = os.getcwd()
op = plist[x]
op2 = plist[y]
pic = Image.open(os.path.join(w,op))
pic2 = Image.open(os.path.join(w,op2))
pic.copy()
pic2.copy()
new_image = Image.new("RGB", (1280,400))
new_image.save('conjoined_pics', format='PNG')
pic.paste(Image.open('new_image'), (20,400,620,0))
pic2.paste(Image.open('new_image'), (660,400,1260,0))
get_pics(0,1)
#def get_permutations():
#newlist = list(itertools.permutations(plist, 2))
#print (newlist)
</code></pre>
<p>Here is the error message: </p>
<pre><code>File not found error: [Errno 2] No such file or directory:
'os.path.join(w,op)'
</code></pre>
| -2 | 2016-08-07T19:22:20Z | 38,817,813 | <p>The error message states exactly what is wrong: the image file you are trying to open does not exist. I would try printing the value of <code>os.path.join(w, op)</code> the line before it is used and see if it makes sense.</p>
<p>Also, I would suggest that you change your function so it is provided either two filenames or two image objects instead of passing index values and requiring the use of global variables and requiring the environment to be in a certain directory.</p>
<p><strong>Edit:</strong> I don't think this has to do with working with images specifically. This is probably some simple bug that you just aren't noticing. Try something like this in your function:</p>
<pre><code>fn = os.path.join(w, op)
print(fn, os.path.exists(fn))
pic = Image.open(fn)
</code></pre>
<p>I'm looking at the error message again and it seems like you must be putting quotes around your <code>"os.path.join(...)"</code> part of the code. Is the code in your question exactly what you are running?</p>
<p><strong>Edit: Suggested Edits</strong></p>
<pre><code>plist = [fn for fn in os.path.join("image_resize") if fn.endswith(".png")]
# or better, don't require the cwd or chdir by including the path
base_dir = "C:\Python35-32\Scripts\image_resize"
plist = [os.path.join(base_dir, fn) for fn in os.listdir(base_dir) if fn.endswith(".png")]
# Or even better (this gives full paths)
from glob import glob
base_dir = "C:\Python35-32\Scripts\image_resize"
plist = glob(os.path.join(base_dir, "*.png"))
# for the function
def get_pics(fn_in1, fn_in2):
... make your code work ...
get_pics(plist[0], plist[1])
# Or so that you don't have to reopen the input images *every* time they are used
def get_pics(input_image1, input_image2):
pass
img1 = Image.open(plist[0])
img2 = Image.open(plist[1])
get_pics(img1, img2)
</code></pre>
| 0 | 2016-08-07T19:37:12Z | [
"python",
"image"
] |
Merge two photos into a single photo in python | 38,817,688 | <p>I'm attempting to create new photos, each with 2 side by side photos taken from a list of 24 photos. I eventually want every possible pair combination (276 total) on a new photo. For the time being, however, I'm just trying to get the program to paste two photos onto a new photo and I'm getting an error. The code and error are listed below:</p>
<pre><code>from PIL import Image
import os
import itertools
plist = os.listdir('image_resize')
for p in plist[:]:
if not(p.endswith('.png')):
plist.remove(p)
print(plist)
os.chdir('C:\Python35-32\Scripts\image_resize')
def get_pics(x,y):
w = os.getcwd()
op = plist[x]
op2 = plist[y]
pic = Image.open(os.path.join(w,op))
pic2 = Image.open(os.path.join(w,op2))
pic.copy()
pic2.copy()
new_image = Image.new("RGB", (1280,400))
new_image.save('conjoined_pics', format='PNG')
pic.paste(Image.open('new_image'), (20,400,620,0))
pic2.paste(Image.open('new_image'), (660,400,1260,0))
get_pics(0,1)
#def get_permutations():
#newlist = list(itertools.permutations(plist, 2))
#print (newlist)
</code></pre>
<p>Here is the error message: </p>
<pre><code>File not found error: [Errno 2] No such file or directory:
'os.path.join(w,op)'
</code></pre>
| -2 | 2016-08-07T19:22:20Z | 38,818,694 | <p>Just for fun, and maybe for testing your Python, you can make all the images <em>in parallel</em>, in a <em>one-liner</em> using <strong>GNU Parallel</strong> and <strong>ImageMagick</strong> like this from the command-line in Terminal - assuming your 24 images are named "image????.png"</p>
<pre><code>parallel '[ "{1}" != "{2}" ] && convert {1} {2} +append result{#}.png' ::: image* ::: image*
</code></pre>
<p>If you want to see how it works, add in <code>--dry-run</code> after <code>parallel</code> on the command-line and it will show you what it would do:</p>
<pre><code>...
...
[ "image1.png" != "image1.png" ] && convert image1.png image1.png +append result26.png
[ "image1.png" != "image10.png" ] && convert image1.png image10.png +append result27.png
[ "image1.png" != "image11.png" ] && convert image1.png image11.png +append result28.png
[ "image1.png" != "image12.png" ] && convert image1.png image12.png +append result29.png
[ "image1.png" != "image13.png" ] && convert image1.png image13.png +append result30.png
[ "image1.png" != "image14.png" ] && convert image1.png image14.png +append result31.png
[ "image1.png" != "image15.png" ] && convert image1.png image15.png +append result32.png
[ "image1.png" != "image16.png" ] && convert image1.png image16.png +append result33.png
[ "image1.png" != "image17.png" ] && convert image1.png image17.png +append result34.png
[ "image1.png" != "image18.png" ] && convert image1.png image18.png +append result35.png
[ "image1.png" != "image19.png" ] && convert image1.png image19.png +append result36.png
[ "image1.png" != "image2.png" ] && convert image1.png image2.png +append result37.png
[ "image1.png" != "image20.png" ] && convert image1.png image20.png +append result38.png
[ "image1.png" != "image21.png" ] && convert image1.png image21.png +append result39.png
[ "image1.png" != "image22.png" ] && convert image1.png image22.png +append result40.png
[ "image1.png" != "image23.png" ] && convert image1.png image23.png +append result41.png
...
...
</code></pre>
| 0 | 2016-08-07T21:22:18Z | [
"python",
"image"
] |
Socket - Simple Server/Client - socket.error: [Errno 10060] | 38,817,768 | <p>I have a very simple Socket Server code running on port 9999. When I fire up my server and client, with netstat I can see that the server is running and the client is on the ephemeral port of 7180. </p>
<pre><code>TCP 192.168.1.117:9999 0.0.0.0:0 LISTENING 7180
</code></pre>
<p>However, the output of client shows this error:</p>
<pre><code>Traceback (most recent call last):
File "client.py", line 6, in <module>
clisock.connect((host, 9999))
File "C:\Python27\lib\socket.py", line 222, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
</code></pre>
<p>My server code:</p>
<pre><code>import socket
import sys
import time
srvsock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
print 'Server Socket is Created'
host = socket.gethostname()
try:
srvsock.bind( (host, 9999) )
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
srvsock.listen(5)
print 'Socket is now listening'
while True:
clisock, (remhost, remport) = srvsock.accept()
print 'Connected with ' + remhost + ':' + str(remport)
currentTime = time.ctime(time.time()) + "\r\n"
print currentTime
clisock.send(currentTime)
clisock.close()
srvsock.close()
</code></pre>
<p>And my Socket client program is as follow:</p>
<pre><code>import socket
clisock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
print host
clisock.connect((host, 9999))
tm = clisock.recv(1024)
clisock.close()
print tm
</code></pre>
<p>What is the issue? Could it be a Firewall or something which cause the connection to drop?</p>
| 0 | 2016-08-07T19:32:28Z | 38,817,847 | <p>There is no guarantee that <code>socket.gethostname()</code> will return a FQDN. Try to bind the server to <code>''</code> (empty string is a symbolic name meaning all available interface), then connect your client to <code>localhost</code> or <code>127.0.0.1</code>.</p>
<p>Python documentation includes a very useful example for creating a simple TCP server-client application using low-level socket API [1].</p>
<p>[1] <a href="https://docs.python.org/2/library/socket.html#example" rel="nofollow">https://docs.python.org/2/library/socket.html#example</a></p>
| 1 | 2016-08-07T19:41:36Z | [
"python",
"sockets"
] |
Django UserManager create_user failing with 'NoneType' object not callable | 38,817,805 | <p>I followed the code in this custom Django user model <a href="https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#specifying-a-custom-user-model" rel="nofollow">example</a> almost verbatim, and when I try to create a user it fails on the last parameter of <code>self.model</code> with the error</p>
<pre><code>TypeError: 'NoneType' object is not callable
</code></pre>
<p>The relevant code snippet is below:</p>
<pre><code>class MyUserManager(BaseUserManager):
def create_user(self, email, password=None,
first_name=None,
last_name=None
):
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email,
first_name=first_name,
last_name=last_name
)
user.set_password(password)
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), max_length=254, unique=True)
first_name = models.CharField(_('first name'), max_length=30, blank=False)
last_name = models.CharField(_('last name'), max_length=30, blank=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
</code></pre>
<p>It looks like <code>self.model</code> is <code>None</code>, but I thought having the line <code>objects = MyUserManager()</code> in <code>MyUser</code> is what associated the two.</p>
<p>The traceback:</p>
<pre><code>Traceback (most recent call last):
File "api/tests/test_location.py", line 24, in setUp
first_name=first_name, last_name=last_name)
File "api/models.py", line 99, in create_user
last_name=last_name
TypeError: 'NoneType' object is not callable
</code></pre>
<p>I call it like so:</p>
<pre><code>MyUserManager().create_user(email=email, password=password, first_name=first_name,
last_name=last_name)
</code></pre>
| 0 | 2016-08-07T19:36:23Z | 38,817,910 | <p>There will be no model instance attached to that instance of <code>MyUserManager</code> if you instantiate it directly and call the <code>create_user</code> method like so. You should instead make the call from your <code>MyUser</code> model:</p>
<pre><code>my_user = MyUser.objects.create_user(email=email,
password=password,
first_name=first_name,
last_name=last_name)
</code></pre>
| 2 | 2016-08-07T19:49:01Z | [
"python",
"django",
"authentication",
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.