title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
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... | 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... | 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>clas... | 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... | 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 var... | 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 . . . "
... | 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)
... | 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.momen... | 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&... | 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(week... | 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://pand... | 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 {} -... | 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... | 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</cod... | 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... | 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 e... | 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... | 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... | 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... | 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 (... | 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... | 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... | 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 cal... | 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 eliminat... | 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>
<... | 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 fo... | 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>
<... | 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 | 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 Reque... | 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', passw... | 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])
pri... | 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.</... | 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 ... | 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(... | 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 ... | 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 ... | 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_c... | 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... | 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 : ................
........ | 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... | 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... | 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_... | 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_... | 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 fu... | 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_... | 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(s... | 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.e... | 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/is... | 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 ... | 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 acce... | 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... | 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 }}
{% end... | 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><... | 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><... | 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 ... | 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... | 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>... | 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... | 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',... | 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).__i... | 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 th... | 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)
... | 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 do... | 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 ret... | 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>
<p... | 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 ret... | 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 = taxp... | 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 t... | 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 t... | 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/Pytho... | 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 d... | 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 ... | 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 ... | 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 ... | 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'].ap... | 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. ... | 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... | 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: "))
na... | 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... | 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: "))
na... | 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... | 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... | 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... | 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 ... | 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 - ... | 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 - ... | 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
impor... | 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_col... | 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... | 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... | 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 ... | 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.h... | 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 ... | 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... | 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... | 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 ... | 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-po... | 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, rig... | 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... | 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 "... | 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, specifi... | 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
ca... | 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... | 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"> &... | 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 wha... | 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"> &... | 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... | 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... | 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]... | 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 s... | 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.pd... | 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... | 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 wou... | 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... | 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').wri... | 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 des... | 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 h... | 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 ... | 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(o... | 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... | 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)
de... | 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
Type... | 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)
de... | 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://g... | 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 hookmanage... | 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/Beautiful... | 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... | 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 pla... | 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 ... | 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 respe... | 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:
... | 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>c... | 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:
... | 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>... | 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? ")
prin... | -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... | 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 = op... | 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... | 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
+--- ... | 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))
</... | 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 alre... | 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 alre... | 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 ... | 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>
... | 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... | 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 l... | 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 ... | 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 l... | 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/Y... | 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 ... | 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:
... | 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>Key... | 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... | 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
<... | 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... | -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 lo... | 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... | -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 gubergre... | 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 (actuall... | 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>Pro... | 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 prettyp... | 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: T... | 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, fiel... | 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.que... | 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... | -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 filen... | 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... | -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 '[ ... | 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, ... | 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 usef... | 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>... | 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,
... | 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.