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 |
|---|---|---|---|---|---|---|---|---|---|
Flask SQLAlchemy: How to extend the base Model class? | 37,515,794 | <p>In Flask/SQLAlchemy, we use the <code>Model</code> class from <code>flask_sqlalchemy</code> instead of from <code>sqlalchemy</code>, like this:</p>
<pre><code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
class Foo(db.Model):
bar = db.Column(db.Stri... | 3 | 2016-05-29T23:06:16Z | 37,515,941 | <p>You can fix the error by setting <code>__abstract__ = True</code>. I modified your example:</p>
<pre><code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
class Foo(db.Model):
__abstract__ = True
bar = db.Column(db.String)
</code></pre>
<p><code... | 6 | 2016-05-29T23:38:08Z | [
"python",
"flask",
"sqlalchemy"
] |
how to add an image to a button in tkinter? | 37,515,847 | <p>How can I add an image to a button in python?</p>
<p>Why when I use this code it does not work</p>
<pre><code>B.config(image=PhotoImage(file="1.png"), compound=RIGHT)
</code></pre>
<p>but this does work?</p>
<pre><code>mi=PhotoImage(file="1.png")
B.config(image=mi, compound=RIGHT)
</code></pre>
| 1 | 2016-05-29T23:16:32Z | 37,515,891 | <p>Your image is getting garbage collected when you try to use it in the first version.</p>
<p>effbot is ancient, but here's good <a href="http://effbot.org/tkinterbook/photoimage.htm" rel="nofollow">snippet</a>:</p>
<blockquote>
<p>You must keep a reference to the image object in your Python program, either by sto... | 2 | 2016-05-29T23:26:37Z | [
"python",
"image",
"tkinter"
] |
Python: How do you make a variable = 1 and it still being that way in a different def block? (For a game) | 37,515,863 | <p>I have a question. How do you get variables to stay defined in even when your in a different def functions? I have a function that serves a purpose of seeing how many <code>AIs a user wants</code> and for example if they choose 'One' for the amount of AIs they wanted <code>AI1 would be equal 1</code>. Here is where ... | 4 | 2016-05-29T23:20:37Z | 37,515,912 | <p>I believe you are facing a <a href="https://en.wikipedia.org/wiki/Scope_(computer_science)" rel="nofollow">scope</a> problem, with the fact that although you are defining it as global, you haven't defined it outside the function to begin with. If you define the three variables outside any of your functions, then yo... | 4 | 2016-05-29T23:30:08Z | [
"python",
"function",
"python-3.x",
"global"
] |
Python: How do you make a variable = 1 and it still being that way in a different def block? (For a game) | 37,515,863 | <p>I have a question. How do you get variables to stay defined in even when your in a different def functions? I have a function that serves a purpose of seeing how many <code>AIs a user wants</code> and for example if they choose 'One' for the amount of AIs they wanted <code>AI1 would be equal 1</code>. Here is where ... | 4 | 2016-05-29T23:20:37Z | 37,515,952 | <p>The problem is that you are not defining the variables AI1, AI2 or AI3 in AISection(). You need to set them to 0 there, else they are not defined.</p>
<pre><code>def AISection():
global AI1, AI2, AI3
AI1 = 0
AI2 = 0
AI3 = 0
print("How many AIs do you want to play with?\nChoices:\n1. One\n2. Two\... | 1 | 2016-05-29T23:39:55Z | [
"python",
"function",
"python-3.x",
"global"
] |
Pandas read_csv dtype specify all columns but one | 37,515,896 | <p>I've a CSV file. Most of it's values I want to read as string, but I want to read a column as bool if the column with the given title exists..</p>
<p>Because the CSV file has a lots of columns, I don't want to specify on each column the datatype directly and give something like this:</p>
<pre><code>data = read_csv... | 1 | 2016-05-29T23:27:14Z | 37,515,924 | <p>You can first filter columns <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow"><code>contains</code></a> value <code>X</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</c... | 1 | 2016-05-29T23:34:07Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
Pandas read_csv dtype specify all columns but one | 37,515,896 | <p>I've a CSV file. Most of it's values I want to read as string, but I want to read a column as bool if the column with the given title exists..</p>
<p>Because the CSV file has a lots of columns, I don't want to specify on each column the datatype directly and give something like this:</p>
<pre><code>data = read_csv... | 1 | 2016-05-29T23:27:14Z | 37,515,946 | <p>why not use <code>bool()</code> data type. <code>bool()</code> evaluates to true if a parameter is passed and the parameter is not False, None, '', or 0</p>
<pre><code>if 'X' in data.columns:
try:
l = bool(data.columns['X'].replace('False', 0))
except:
l = None
data['X'] = data.apply(l, ... | 1 | 2016-05-29T23:38:56Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
Pandas read_csv dtype specify all columns but one | 37,515,896 | <p>I've a CSV file. Most of it's values I want to read as string, but I want to read a column as bool if the column with the given title exists..</p>
<p>Because the CSV file has a lots of columns, I don't want to specify on each column the datatype directly and give something like this:</p>
<pre><code>data = read_csv... | 1 | 2016-05-29T23:27:14Z | 37,516,048 | <p>Actually you don't need any special handling when using read_csv from pandas (tested on version 0.17). Using your example file with X:</p>
<pre><code>import pandas as pd
df = pd.read_csv("file.csv", delimiter=";")
print(df.dtypes)
A object
B object
C object
X bool
dtype: object
</code></pre>
| 1 | 2016-05-29T23:56:41Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
Iterate to regex match then continue to next match | 37,515,943 | <p>I'm building a script to parse out data from switch configuration files and have come to a bit of hiccup (using Python 3.5)</p>
<p>Here's the pseudo code I'm trying to work through:</p>
<pre><code>if re.match(patter0):
continue to match pattern1
if re.match(pattern1):
test if < 10 minutes
... | 2 | 2016-05-29T23:38:32Z | 37,517,229 | <p>I may have found a solution though it's not very dynamic which seems like it could present problems in the future. Like if I came across a switch with more than three vty's the code would need adjusted. Here's what I was able to come up with tonight, thoughts or other answers will be considered too:</p>
<pre><code... | 0 | 2016-05-30T03:31:24Z | [
"python",
"loops",
"python-3.x",
"iteration"
] |
how to put widgets inside a PyQt QMdiSubWindow | 37,515,978 | <p>Sorry, my question may sound very stupid but Frankly i spend a lot of time on internet trying to figure out how to add a widget<strong>s</strong> to QMdiSubWindow, I mean a <strong>Multiple Widgets</strong> not just one Widget(this is very important for me .. I need my Sub window to contain a multiple widget not a s... | 0 | 2016-05-29T23:44:50Z | 37,625,421 | <p>The hierarchy of widgets and layouts should always follow</p>
<pre><code>widget -> layout -> widget -> layout -> widget -> ...
</code></pre>
<p>where each widget can only have one layout, but each layout can contain multiple widgets (note that for simplicity the above only shows one widget per layou... | 1 | 2016-06-04T01:16:14Z | [
"python",
"pyqt4"
] |
Python NetworkX edge lists out of range | 37,516,065 | <p>I'm currently working with NetworkX in Python2 and just faced a weird situation here. I wanted to discover what nodes are connected to each node in a graph, so I wrote this for loop. (I know that each node is only connected to two other nodes, but I need the exact labels) </p>
<pre><code> for i in sorted(graph.n... | 1 | 2016-05-30T00:00:10Z | 37,516,234 | <p>The error implies <code>b</code> is the empty list, <code>[]</code>:</p>
<pre><code>In [143]: b = []
In [147]: b[0]
IndexError: list index out of range
</code></pre>
<p>That could happen if there is a node <code>i</code> for which <code>PedigNetwork.in_edges(i)</code>
returns an empty list. To test this theory, y... | 2 | 2016-05-30T00:30:35Z | [
"python",
"networking",
"graph",
"networkx"
] |
how to recode the categorical variable to ordinal based on the event rate of another variable in python? | 37,516,189 | <p>I have a dataframe in python with many categorical variables and the target variable is binary. I want to convert the categorical variable to ordinal based on the rank of target variable event rate (same to mean of target variable) on each category of the variable. For example, if below is my original dataset</p>
<... | 1 | 2016-05-30T00:23:48Z | 37,516,363 | <p>Just calculate the <code>mean</code> for each <code>grouped</code> category value, <code>rank</code> the result and <code>map</code> to category values. Sample data for illustration:</p>
<pre><code>import string
abc = string.ascii_uppercase
df = pd.DataFrame({'target': np.random.randint(low=0, high=2, size=10), 'co... | 0 | 2016-05-30T00:57:08Z | [
"python",
"pandas",
"data-manipulation",
"categorical-data"
] |
how to recode the categorical variable to ordinal based on the event rate of another variable in python? | 37,516,189 | <p>I have a dataframe in python with many categorical variables and the target variable is binary. I want to convert the categorical variable to ordinal based on the rank of target variable event rate (same to mean of target variable) on each category of the variable. For example, if below is my original dataset</p>
<... | 1 | 2016-05-30T00:23:48Z | 37,516,444 | <p>What you want to do is a <code>transform</code>. Lets look at the following ...</p>
<pre><code>col1 col2 target
0 A D 1
1 A A 0
2 A E 0
3 B A 0
4 A C 0
5 A D 1
6 B E 0
7 A C 0
8 B C 0
9 B B 0
</c... | 0 | 2016-05-30T01:12:26Z | [
"python",
"pandas",
"data-manipulation",
"categorical-data"
] |
How to filter data in mongo collection using pymongo | 37,516,219 | <p>I am using pymongo to query MongoDB and check duplicates in a particular collection. I have identified the duplicates but I want to add one more filter to the script. Please find my script below</p>
<pre><code>from pymongo import MongoClient
client = MongoClient ('localhost')
db = client.test
data = db.devices.a... | 2 | 2016-05-30T00:29:09Z | 37,516,392 | <p>I think this is a near duplicate of <a href="http://stackoverflow.com/questions/20469712/using-and-with-match-in-mongodb">using $and with $match in mongodb</a>.</p>
<p>As in that question, I believe you may simply have a syntax error in your query, you will want something like:</p>
<pre><code>$match: {
$and: [... | 0 | 2016-05-30T01:02:19Z | [
"python",
"mongodb",
"pymongo"
] |
How to filter data in mongo collection using pymongo | 37,516,219 | <p>I am using pymongo to query MongoDB and check duplicates in a particular collection. I have identified the duplicates but I want to add one more filter to the script. Please find my script below</p>
<pre><code>from pymongo import MongoClient
client = MongoClient ('localhost')
db = client.test
data = db.devices.a... | 2 | 2016-05-30T00:29:09Z | 37,527,987 | <p>You can do this efficiently by prepending a <code>$match</code> stage to your pipeline to filter the docs so that you're only grouping on the docs where deviceType = "email":</p>
<pre><code>data = db.devices.aggregate([
{'$match': {'deviceType': 'email'}},
{'$group': {'_id': {'UserId': "$userId", 'DeviceTyp... | 1 | 2016-05-30T14:21:45Z | [
"python",
"mongodb",
"pymongo"
] |
Find next available IP address in python | 37,516,298 | <p>Using python I need to find the next IP address given a range of IP addresses I've already used. So if I have a list of IP address like...</p>
<pre><code>IPs = ['10.220.1.1','10.220.1.2','10.220.1.3','10.220.1.5']
</code></pre>
<p>When I ask for the next IP address I need it to return '10.220.1.4'. The next reques... | -1 | 2016-05-30T00:44:10Z | 37,516,312 | <p>You can use an generator using the <a href="https://pypi.python.org/pypi/ipaddress" rel="nofollow">ipaddress</a> module which is a bultin from python >= 3.3 or you can install with pip for earlier versions:</p>
<pre><code>In [20]: from ipaddress import ip_network
In [21]: IPs = {'10.220.1.1','10.220.1.2','10.220.... | 0 | 2016-05-30T00:46:38Z | [
"python"
] |
Find next available IP address in python | 37,516,298 | <p>Using python I need to find the next IP address given a range of IP addresses I've already used. So if I have a list of IP address like...</p>
<pre><code>IPs = ['10.220.1.1','10.220.1.2','10.220.1.3','10.220.1.5']
</code></pre>
<p>When I ask for the next IP address I need it to return '10.220.1.4'. The next reques... | -1 | 2016-05-30T00:44:10Z | 37,516,362 | <p>If you're using Python 3 you could use <a href="https://docs.python.org/3/library/ipaddress.html" rel="nofollow"><code>ipaddress</code></a> with generator:</p>
<pre><code>import ipaddress
def gen_ip(start, reserved):
start = int(ipaddress.IPv4Address(start))
for i in range(start + 1, int(2 ** 32) + 1):
... | 0 | 2016-05-30T00:57:01Z | [
"python"
] |
Find next available IP address in python | 37,516,298 | <p>Using python I need to find the next IP address given a range of IP addresses I've already used. So if I have a list of IP address like...</p>
<pre><code>IPs = ['10.220.1.1','10.220.1.2','10.220.1.3','10.220.1.5']
</code></pre>
<p>When I ask for the next IP address I need it to return '10.220.1.4'. The next reques... | -1 | 2016-05-30T00:44:10Z | 37,516,383 | <p>Create a basic ip object to hold a record of your current ip and to get the next ip</p>
<pre><code>class IPObj(object):
def __init__(self, list_of_ips):
self.position = 0
self.ips = list_of_ips
self.current_ip = self.ips[self.position]
def next_ip(self, stop_iteration=False):
... | 0 | 2016-05-30T01:00:31Z | [
"python"
] |
Find next available IP address in python | 37,516,298 | <p>Using python I need to find the next IP address given a range of IP addresses I've already used. So if I have a list of IP address like...</p>
<pre><code>IPs = ['10.220.1.1','10.220.1.2','10.220.1.3','10.220.1.5']
</code></pre>
<p>When I ask for the next IP address I need it to return '10.220.1.4'. The next reques... | -1 | 2016-05-30T00:44:10Z | 37,516,402 | <p>Convert your list to a set, for performance:</p>
<pre><code>used_ips = set(IPs)
</code></pre>
<p>Now generate your IP#'s however you would like, and check if they are contained in the set:</p>
<pre><code>for next_ip in generate_ip_numbers():
if next_ip in used_ips:
continue
print("Next ip address... | 0 | 2016-05-30T01:04:23Z | [
"python"
] |
Find next available IP address in python | 37,516,298 | <p>Using python I need to find the next IP address given a range of IP addresses I've already used. So if I have a list of IP address like...</p>
<pre><code>IPs = ['10.220.1.1','10.220.1.2','10.220.1.3','10.220.1.5']
</code></pre>
<p>When I ask for the next IP address I need it to return '10.220.1.4'. The next reques... | -1 | 2016-05-30T00:44:10Z | 37,516,432 | <p>If you're using Python 3.3 (or newer), you can use the <a href="https://docs.python.org/3/library/ipaddress.html" rel="nofollow"><code>ipaddress</code></a> module. Example for all hosts in the subnet <code>10.220.1.0/24</code> except for those in <code>reserved</code>:</p>
<pre><code>from ipaddress import IPv4Netw... | 0 | 2016-05-30T01:09:34Z | [
"python"
] |
Error when indexing numpy array | 37,516,388 | <p>I'm running the following code to sort the rows of a matrix and then pick the corresponding elements from another vector: </p>
<pre><code>import pandas as pd
import numpy as np
# compute ids
coeff = np.dot(matrix1, np.transpose(matrix2))
print coeff.shape, ids.shape
indices = coeff.argsort()[:, ::-1]
print indice... | 0 | 2016-05-30T01:01:30Z | 37,516,430 | <p>NumPy arrays allow <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#integer-array-indexing" rel="nofollow">integer array indexing</a>, but Pandas Series do not:</p>
<pre><code>In [168]: arr = np.arange(5)
In [169]: ser = pd.Series(arr)
In [170]: indices = np.array([[0,1],[4,3],[2,2]])
In [... | 1 | 2016-05-30T01:09:21Z | [
"python",
"numpy",
"pandas",
"linear-algebra"
] |
Can I persist an http connection (or other data) across Flask requests? | 37,516,409 | <p>I'm working on a Flask app which retrieves the user's XML from the myanimelist.net API (<a href="http://myanimelist.net/malappinfo.php?u=doomcat55&status=all&type=anime" rel="nofollow">sample</a>), processes it, and returns some data. The data returned can be different depending on the Flask page being viewe... | 1 | 2016-05-30T01:06:15Z | 37,517,108 | <p>I think you aren't approaching this from the right direction because you place your app too much as a proxy of myanimelist.net.</p>
<p>What happens when you have 2000 users? Your app end up doing tons of requests to myanimelist.net, and a mean user could definitely DoS your app (or use it to DoS myanimelist.net).</... | 0 | 2016-05-30T03:11:39Z | [
"python",
"http",
"flask"
] |
sympy: Using Wild symbols as input for function | 37,516,481 | <p>Consider the following expression in python/sympy:</p>
<pre><code>from sympy.abc import x, y
expression = 3*x**2*y**1 + x**2*y**3
</code></pre>
<p>Now I want to replace <code>x**n*y**m</code> by <code>max(n,m)</code> by using pattern matching:</p>
<pre><code>from sympy import Wild
n = Wild('n')
m = Wild('m')
expr... | 2 | 2016-05-30T01:18:34Z | 37,529,899 | <p>Ok, I have found a solution, it is note very pretty though which might have to do with the fact that I know little about writing functions that interact nicely with sympy.</p>
<p>At first I import everything relevant:</p>
<pre><code>import sympy
from sympy.abc import x, y, a, b,z
from sympy import Wild
from sympy ... | 0 | 2016-05-30T16:08:51Z | [
"python",
"python-3.x",
"sympy"
] |
sympy: Using Wild symbols as input for function | 37,516,481 | <p>Consider the following expression in python/sympy:</p>
<pre><code>from sympy.abc import x, y
expression = 3*x**2*y**1 + x**2*y**3
</code></pre>
<p>Now I want to replace <code>x**n*y**m</code> by <code>max(n,m)</code> by using pattern matching:</p>
<pre><code>from sympy import Wild
n = Wild('n')
m = Wild('m')
expr... | 2 | 2016-05-30T01:18:34Z | 37,800,976 | <p><strike><code>max</code> is the built in Python function, which tries to evaluate immediately, hence the error (it can't determine which of <code>n</code> and <code>m</code> are larger when they are symbolic). You probably want the SymPy <code>Max</code> function, which works symbolically. The <code>my_func</code> y... | 1 | 2016-06-14T00:03:59Z | [
"python",
"python-3.x",
"sympy"
] |
Getting an error when trying to create a virtual env | 37,516,570 | <p>I want to learn django so I tried to create a virtual env and I am getting this error:</p>
<pre><code>mkvirtualenv djngo
Traceback (most recent call last):
File "/usr/local/bin/virtualenv", line 5, in <module>
from pkg_resources import load_entry_point
File "/Library/Python/2.7/site-packages/distribu... | 0 | 2016-05-30T01:33:29Z | 37,516,632 | <p>You're using <code>mkvirtualenv</code> which is a <code>virtualenvwrapper</code> command. You probably do not have <code>virtualenvwrapper</code> installed.</p>
<p>Type <code>virtualenvwrapper</code> in your command line and observe the input. If you get something like <code>command not found</code>, then you shoul... | 0 | 2016-05-30T01:45:54Z | [
"python",
"django",
"virtualenv"
] |
How to delete a single opening or closing tag in an XML using minidom | 37,516,578 | <p>I made <a href="http://stackoverflow.com/questions/37432161/how-would-i-combine-nested-elements-in-an-xml-using-minidom">this</a> thread last week, but haven't got any replies so maybe it was too poorly worded and therefore incomprehensible.</p>
<p>Using python 3.5 and its default minidom, I would like to know if i... | 0 | 2016-05-30T01:34:48Z | 37,519,046 | <p>When XML data is loaded into a DOM representation, the concept of opening/closing tags does not exist. The DOM knows about <em>elements</em> and their contents. The existence of tags (opening and closing) has to do only with the serialized version of the DOM -- i.e. they are a necessary part of the serialized enco... | 0 | 2016-05-30T06:33:24Z | [
"python",
"xml",
"minidom"
] |
Importing user defined modules in python from a directory | 37,516,579 | <p>I'm trying to import a module I wrote in python that just prints out a list containing numbers. The issue I'm having is that I want to be able to import it from a separate directory but the answers I have read so far don't seem to be working for my situation.</p>
<p>For example, given I want to import printnumbers.... | 1 | 2016-05-30T01:35:13Z | 37,516,594 | <p>When the file is <code>printnumbers.py</code>, the module is called <code>printnumbers</code> (without the <code>.py</code>). Therefore use</p>
<pre><code>import printnumbers
</code></pre>
<hr>
<pre><code>import sys
sys.path.append('/home/jake/Documents')
</code></pre>
<p>appends <code>'/home/jake/Documents'</co... | 5 | 2016-05-30T01:37:30Z | [
"python",
"module",
"python-module"
] |
Importing user defined modules in python from a directory | 37,516,579 | <p>I'm trying to import a module I wrote in python that just prints out a list containing numbers. The issue I'm having is that I want to be able to import it from a separate directory but the answers I have read so far don't seem to be working for my situation.</p>
<p>For example, given I want to import printnumbers.... | 1 | 2016-05-30T01:35:13Z | 37,526,052 | <blockquote>
<p>and one more thing, use an empty <strong>__ init __.py</strong> file in you directory
to make it as a python package (only then Python will know that this
directory is a Python package directory other than an ordinary
directory). Thus you can import modules from that package from
different dir... | 1 | 2016-05-30T12:46:14Z | [
"python",
"module",
"python-module"
] |
Making my own python module | 37,516,583 | <p>I have created a python class that i want to be able to use by running <code>import car</code> which i believe is the proper language. Currently the only way i can use anything with my class is by opening the file (<code>/home/pi/Desktop/python/car.py</code>) in the python3 IDE clicking run and then using my class. ... | -1 | 2016-05-30T00:48:33Z | 37,516,666 | <p>First and foremost, <strong>do not</strong> create your local modules in your Python installation directory.</p>
<p>You're not able to import your module because you haven't specified the <code>PYTHONPATH</code>.
You should export the path to that module in your command line.
<code>export PYTHONPATH=/home/pi/Deskto... | 2 | 2016-05-30T01:53:28Z | [
"python"
] |
Making my own python module | 37,516,583 | <p>I have created a python class that i want to be able to use by running <code>import car</code> which i believe is the proper language. Currently the only way i can use anything with my class is by opening the file (<code>/home/pi/Desktop/python/car.py</code>) in the python3 IDE clicking run and then using my class. ... | -1 | 2016-05-30T00:48:33Z | 37,516,678 | <pre><code>import car
my_car = car('n', 'vns', '15', '13')
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
my_car = car('n', 'vns', '15', '13')
TypeError: 'module' object is not callable
</code></pre>
<p>You're making a few mistakes about your general python development, bu... | 2 | 2016-05-30T01:55:57Z | [
"python"
] |
how to create a SQL database from a csv file in Python | 37,516,643 | <p>I need to load in a large dataset (20gb for now but will be 100 gb in the future) from a csv file. I am using the MySQLdb module in python (PyCharm). I also need to only select some certain columns. So far I have tried this:</p>
<pre><code>import csv
import MySQLdb
mydb = MySQLdb.connect(host='localhost',
user... | 2 | 2016-05-30T01:47:40Z | 37,516,717 | <p>To answer your questions</p>
<blockquote>
<ol>
<li>with MySQLdb.connect( host,user,passwd,db etc), what are host, user, password etc? to my understanding, they are credentials for my
account in the computer. so do I need to put in my user account and
password?</li>
</ol>
</blockquote>
<ul>
<li><strong>An... | 0 | 2016-05-30T02:02:16Z | [
"python",
"database",
"csv",
"mysql-python"
] |
how to create a SQL database from a csv file in Python | 37,516,643 | <p>I need to load in a large dataset (20gb for now but will be 100 gb in the future) from a csv file. I am using the MySQLdb module in python (PyCharm). I also need to only select some certain columns. So far I have tried this:</p>
<pre><code>import csv
import MySQLdb
mydb = MySQLdb.connect(host='localhost',
user... | 2 | 2016-05-30T01:47:40Z | 37,517,322 | <p>If you want to create an SQL db with Python just for the sake of playing with both languages, you should try SQLite: </p>
<pre><code>import sqlite3
conn = sqlite3.connect("brand_new_db.db")
</code></pre>
<p>and you are done. </p>
<p>There are many tutorials on the web. <a href="http://www.tutorialspoint.com/sqlit... | 0 | 2016-05-30T03:47:45Z | [
"python",
"database",
"csv",
"mysql-python"
] |
How do I convert a dataframe consisting of a column of sentences and a column of scores into one with a column of words and average scores? | 37,516,660 | <p>I have a Pandas dataframe that resembles this:</p>
<pre><code>sentence score
"This is a sentence." 5
"Another sentence?" 8
</code></pre>
<p>And I want one that resembles this:</p>
<pre><code>word total_score count normalized_score
"sentence" 13 2 6.5
"this" 5 1... | 1 | 2016-05-30T01:52:23Z | 37,516,759 | <p>You could use the <code>iterrows</code> method on the DataFrame to and process each row into a new DataFrame and then concatenate these together. You would then need to handle duplicate words.</p>
<p>The <code>string</code> module (in the standard library) has some collections of characters that can help you filte... | 0 | 2016-05-30T02:08:28Z | [
"python",
"pandas",
"split"
] |
How do I convert a dataframe consisting of a column of sentences and a column of scores into one with a column of words and average scores? | 37,516,660 | <p>I have a Pandas dataframe that resembles this:</p>
<pre><code>sentence score
"This is a sentence." 5
"Another sentence?" 8
</code></pre>
<p>And I want one that resembles this:</p>
<pre><code>word total_score count normalized_score
"sentence" 13 2 6.5
"this" 5 1... | 1 | 2016-05-30T01:52:23Z | 37,516,791 | <p>You could use <code>df.itertuples</code> to iterate through the rows of <code>df</code> and build a
long-format DataFrame of the form:</p>
<pre><code>In [86]: longframe
Out[86]:
score word
0 5 This
1 5 is
2 5 a
3 5 sentence
4 8 Another
5 8 sentence
6 ... | 2 | 2016-05-30T02:15:18Z | [
"python",
"pandas",
"split"
] |
Python not finding kv file | 37,516,904 | <p>I have tried many different solutions but always end up with an empty black screen when my program starts up, here is my Python code:</p>
<pre><code>from kivy.app import App
from kivy.uix.label import Label
class AwesomeApp(App):
def build(self):
return Label()
if __name__ == "__main__":
AwesomeA... | 0 | 2016-05-30T02:37:22Z | 37,523,608 | <p>You can use the <code>Builder</code> class to load the kv file with a specific filename<br>
Here is the example usage: </p>
<pre><code>from kivy.lang import Builder
Builder.load_file("awesome.kv")
</code></pre>
<p><code>Builder</code> also can load the kv instructions from a string, allowing you to have your kv i... | 1 | 2016-05-30T10:38:59Z | [
"python",
"kivy"
] |
Python not finding kv file | 37,516,904 | <p>I have tried many different solutions but always end up with an empty black screen when my program starts up, here is my Python code:</p>
<pre><code>from kivy.app import App
from kivy.uix.label import Label
class AwesomeApp(App):
def build(self):
return Label()
if __name__ == "__main__":
AwesomeA... | 0 | 2016-05-30T02:37:22Z | 37,532,443 | <p>Please don't use widget's name as your own rule because of <a href="https://github.com/kivy/kivy/blob/master/kivy/data/style.kv" rel="nofollow">this</a>. You try to overwrite it and it may have unexpected results. Also, as Leva7 said in his answer + since Kivy 1.really.old a .kv file that is named as class that inhe... | 1 | 2016-05-30T19:22:39Z | [
"python",
"kivy"
] |
How to copy image from one excel to another in openpyxl? | 37,516,984 | <p>I have one excel which contains a logo(logo.png), and I want to read and edit the excel with openpyxl, and save it as another excel, but I found that when I use <code>load_workbook</code>, the image data seems to be lost.</p>
<p>Does openpyxl have any solution to do that?</p>
| 0 | 2016-05-30T02:50:26Z | 37,518,780 | <p>It quite clearly states in the <a href="http://openpyxl.readthedocs.io/en/default/usage.html#read-an-existing-workbook" rel="nofollow">documentation</a> that images are not preserved in existing files.</p>
| 0 | 2016-05-30T06:15:24Z | [
"python",
"openpyxl"
] |
Compare current row based from other rows | 37,517,011 | <p>For example, I have a df</p>
<pre><code>ID Name Value
0 A 10
1 A 11
3 A 15
4 B 7
5 B 11
C X 1
</code></pre>
<p>I want to find, for the current row, count how many other rows has the same name and greater value.
Expected output;</p>
<pre><code>ID Name Value Res
0 ... | -1 | 2016-05-30T02:53:24Z | 37,517,084 | <p>With a bit of tweaking, you could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rank.html" rel="nofollow"><code>Series.rank</code></a> with <code>method='dense'</code>:</p>
<pre><code>>>> grouped = df.groupby("Name")["Value"]
>>> df["Res"] = grouped.rank(method="... | 3 | 2016-05-30T03:08:21Z | [
"python",
"pandas"
] |
Efficiently convert gmpy2.mpz to numpy boolean array | 37,517,022 | <p>I try to convert from gmpy2.mpz to a numpy boolean array, but can't quite get it right. (gmpy2: <a href="https://gmpy2.readthedocs.io" rel="nofollow">https://gmpy2.readthedocs.io</a>)</p>
<pre><code>import gmpy2
import numpy as np
x = gmpy2.mpz(int('1'*1000,2))
print("wrong conversion 1")
y = np.fromstring(gmpy2.... | 1 | 2016-05-30T02:56:14Z | 37,517,357 | <p>This works, but it is slow.</p>
<pre><code>import gmpy2
import numpy as np
x_str = '1'*8+'01'
print(x_str)
x_int = int(x_str,2)
x_mpz = gmpy2.mpz(x_int)
x_01 = bin(int(x_mpz))[2:] # get rid of '0b'
x_bin = x_01.replace('1','\x01').replace('0','\x00')
x_np_bool = np.fromstring(x_bin, dtype = bool)
x_1_index = np.whe... | 0 | 2016-05-30T03:52:08Z | [
"python",
"numpy",
"gmpy"
] |
Efficiently convert gmpy2.mpz to numpy boolean array | 37,517,022 | <p>I try to convert from gmpy2.mpz to a numpy boolean array, but can't quite get it right. (gmpy2: <a href="https://gmpy2.readthedocs.io" rel="nofollow">https://gmpy2.readthedocs.io</a>)</p>
<pre><code>import gmpy2
import numpy as np
x = gmpy2.mpz(int('1'*1000,2))
print("wrong conversion 1")
y = np.fromstring(gmpy2.... | 1 | 2016-05-30T02:56:14Z | 37,517,787 | <p>There are a couple of options. The function <code>gmpy2.bit_scan1(x, n)</code> will return the index of the first bit that is set that has an index >= n.</p>
<pre><code>>>> x = gmpy2.mpz(123456)
>>> bin(x)
'0b11110001001000000'
>>> n = 0
>>> while True:
... n = gmpy2.bit_scan... | 1 | 2016-05-30T04:49:31Z | [
"python",
"numpy",
"gmpy"
] |
Appending back to the file/dictionary after hashing (and anonymizing names) | 37,517,053 | <p>so I have a question as to how to move forward. I have a csv file that goes like
[Name ,Date/Time,Message,Major,Minor,Tone,Crisis,Suicide,Poster,Topics Tags]</p>
<p>I just need to anonymize the Names and I used hash in order to do that. I was able to isolate the Names and hash them but I don't really know how to a... | -1 | 2016-05-30T03:04:07Z | 37,517,093 | <p>Following code should work, it will replace the first item on every row with hashed value and write the result to new file:</p>
<pre><code>import hashlib
with open('example.csv') as fin, open('output.csv', 'w') as fout:
for ex in fin:
items = ex.split(',')
items[0] = hashlib.md5(items[0].encode... | 0 | 2016-05-30T03:09:26Z | [
"python"
] |
Product of tuple | 37,517,085 | <p>As a Python newbie, it might be a silly question, but I can't find a solution.
I'm doing the product of a tuple, and working perfectly, like this: </p>
<pre><code>list = list(itertools.product(["this", "the"],["example", "test"],["is not", "isnt"],[" working", "correct"]))
print(list)
</code></pre>
<p>But if a dec... | 0 | 2016-05-30T03:08:28Z | 37,517,126 | <p>First off, it's bad to use <code>list</code> as a variable name, since this overwrites the default <code>list</code> function.</p>
<p>In your first, working, example, you pass multiple arguments to <code>itertools.product</code>, and it combines each argument to give the output you want. In your nonworking example,... | 2 | 2016-05-30T03:14:34Z | [
"python",
"python-2.7"
] |
Breaking inner loop python | 37,517,165 | <p>I want to exit just the inner loop where I have placed the break. Using continue works, but I thought break was supposed to exit the inner most loop yet it seems to exit the whole program. What's the deal with break?</p>
<pre><code>counter = 0
while counter == 0:
print "You enter a dark room with two doors. ... | -2 | 2016-05-30T03:20:31Z | 37,517,181 | <p>You only have one loop in your code, and break is exiting it, "if" is not a loop, it is a statement...even if you have multiple, they are statements, and break, will "break" from your while loop, not "if" statement.</p>
| 2 | 2016-05-30T03:24:22Z | [
"python",
"python-2.7",
"while-loop",
"break"
] |
Breaking inner loop python | 37,517,165 | <p>I want to exit just the inner loop where I have placed the break. Using continue works, but I thought break was supposed to exit the inner most loop yet it seems to exit the whole program. What's the deal with break?</p>
<pre><code>counter = 0
while counter == 0:
print "You enter a dark room with two doors. ... | -2 | 2016-05-30T03:20:31Z | 37,517,190 | <blockquote>
<p><code>break</code>- Jumps out of the closest enclosing loop (past the entire loop
statement)</p>
</blockquote>
<p>In your case thats exactly what it is doing. <code>if</code> is not a looping statement, its a control statement.</p>
<p>You have only one loop which is a <code>while</code>.</p>
| 1 | 2016-05-30T03:25:54Z | [
"python",
"python-2.7",
"while-loop",
"break"
] |
multiple inputs in python | 37,517,174 | <p>I am trying to input multiple entries but when I run these statements, it does not as expected. Suppose I want to read name and age of person.</p>
<pre><code>num1=raw_input("ENter a number :");
nam1=raw_input("What is your name:");
print num1;
ENter a number :nam1=raw_input("What is your name:")
print nam1;
Traceb... | 0 | 2016-05-30T03:22:42Z | 37,517,199 | <p>You shouldn't use ; to terminate lines using python.</p>
<pre><code>num1=raw_input("ENter a number :"); #<= remove the ; here
nam1=raw_input("What is your name:"); #<= remove the ; here
</code></pre>
<p>clean version :</p>
<pre><code>num1 = raw_input("ENter a number :")
nam1 = raw_input("What is your name:... | 1 | 2016-05-30T03:27:05Z | [
"python"
] |
multiple inputs in python | 37,517,174 | <p>I am trying to input multiple entries but when I run these statements, it does not as expected. Suppose I want to read name and age of person.</p>
<pre><code>num1=raw_input("ENter a number :");
nam1=raw_input("What is your name:");
print num1;
ENter a number :nam1=raw_input("What is your name:")
print nam1;
Traceb... | 0 | 2016-05-30T03:22:42Z | 37,517,274 | <p>If I get you, you must be copying multiple lines in to shell, which isn't what you are supposed to do.</p>
<p>If you want to copy the code into shell, you need to make it a single line:<br>
<code>num1=raw_input("ENter a number :");nam1=raw_input("What is your name:");print num1;print nam1</code> </p>
<p>Notice tha... | 0 | 2016-05-30T03:38:12Z | [
"python"
] |
PyOSC, python. Why oscserver needs IP address for receiving? | 37,517,188 | <p>In PyOSC, you need to both IP and port for the OSCServer to receive information. And this doesn't quite make sense to me. As on Max, you only need to declare the port. Isn't for receiving you always just need the localhost as the ip?</p>
<p>I have an android app which send OSC message to my python program on my com... | 0 | 2016-05-30T03:25:18Z | 37,517,234 | <p>have you tried <code>127.0.0.1</code> ? it should work everywhere.</p>
<p>I believe you are giving the IP the server will use.</p>
<ul>
<li><p><code>127.0.0.1</code> basically means : "listen only for local connections".</p></li>
<li><p><code>192.168.0.3</code> (in your case) means : "listen for connections from t... | 0 | 2016-05-30T03:32:02Z | [
"android",
"python",
"osc"
] |
PyOSC, python. Why oscserver needs IP address for receiving? | 37,517,188 | <p>In PyOSC, you need to both IP and port for the OSCServer to receive information. And this doesn't quite make sense to me. As on Max, you only need to declare the port. Isn't for receiving you always just need the localhost as the ip?</p>
<p>I have an android app which send OSC message to my python program on my com... | 0 | 2016-05-30T03:25:18Z | 37,943,694 | <p>You should indeed use "localhost".</p>
<p>Define the port you want, and then send the messages from the other computer to the one running this code on its ip. I suppose you've already taken care of things such as port opening and you know about the difference of access scope from the outside network to inside your ... | 0 | 2016-06-21T11:52:46Z | [
"android",
"python",
"osc"
] |
(python)how to change the key conparation in dictionary? | 37,517,207 | <p>I want to build a segment dictionary like segment tree.
I mean I want to use sequence (11, 22) as key, if the input value like 11 it should be use the same key.
how to do it.</p>
<p>for example the dictionary is {(11, 22): 35, (44, 45):12}.
I want to write fellows:</p>
<pre><code>for i in dictionary:
blad
... | 0 | 2016-05-30T03:28:22Z | 37,517,233 | <p>When you use tuples are dictionary keys they have to be used fully to reference that value.</p>
<p><strong><em>In your case <code>(11,22)</code> is a key. And you may not use them separately to identify values.</em></strong></p>
<p><strong>Tuples are used as keys when both its elements mean something together.</st... | 0 | 2016-05-30T03:31:59Z | [
"python",
"dictionary",
"key",
"segment"
] |
(python)how to change the key conparation in dictionary? | 37,517,207 | <p>I want to build a segment dictionary like segment tree.
I mean I want to use sequence (11, 22) as key, if the input value like 11 it should be use the same key.
how to do it.</p>
<p>for example the dictionary is {(11, 22): 35, (44, 45):12}.
I want to write fellows:</p>
<pre><code>for i in dictionary:
blad
... | 0 | 2016-05-30T03:28:22Z | 37,517,295 | <p>write your won insert method </p>
<pre><code> def insert(key,value,dict):
for i in dict:
if key in i:
dict[i]=value
</code></pre>
| 0 | 2016-05-30T03:43:36Z | [
"python",
"dictionary",
"key",
"segment"
] |
Trying to guess the encoding of a file using chardet | 37,517,301 | <p>I'm writing a program that works with CSV files. These files can have a specific encoding. I'm trying to incorporate a procedure to try to guess what the encoding of a file the user wants to open using chardet.</p>
<p>I'm trying with the following code:</p>
<pre><code>rawdata = open('file.csv', "r").read()
result ... | 1 | 2016-05-30T03:44:21Z | 37,531,241 | <p>How about reading data as binary in the first place?</p>
<pre><code>rawdata = open('file.csv', "rb").read()
</code></pre>
| 2 | 2016-05-30T17:47:47Z | [
"python",
"python-3.x",
"encoding",
"character-encoding",
"chardet"
] |
Bad Selection Sort in Python | 37,517,314 | <p>I have a problem with a simple sort of a multidimensional array.</p>
<p>The Python code is:</p>
<p><strong>SelectionSort.py</strong></p>
<pre><code>class SelectionSort(object):
@staticmethod
def sort(list):
for i in range(0, len(list)):
min = i;
for j in range (i+1, len(li... | 1 | 2016-05-30T03:46:55Z | 37,517,402 | <p><code>sort</code> method has a small bug in it, it's comparing loop counter <code>j</code> against minimum value. If you make the following change it will fix the issue:</p>
<pre><code>def sort(list):
for i in range(0, len(list)):
min = i;
for j in range (i+1, len(list)):
if list[j] ... | 0 | 2016-05-30T03:58:40Z | [
"python",
"selection-sort"
] |
How can I change the intensity of a colormap in matplotlib? | 37,517,587 | <p>I use <a href="http://matplotlib.org/api/pyplot_api.html?highlight=pcolor#matplotlib.pyplot.pcolor" rel="nofollow">matplotlib.pyplot.pcolor()</a> to plot a heatmap with matplotlib:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
data = np.sort(np.random.rand(8,12))
plt.figu... | 2 | 2016-05-30T04:22:57Z | 37,518,137 | <p>You have to assembly new custom color map based on a standard. </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
np.random.seed(1)
data = np.sort(np.random.rand(8,12))
plt.figure()
cmap = cm.get_cmap('RdBu', len(data)) # set how many colors you want in color map
# modify... | 2 | 2016-05-30T05:26:33Z | [
"python",
"matplotlib",
"colormap"
] |
How can I change the intensity of a colormap in matplotlib? | 37,517,587 | <p>I use <a href="http://matplotlib.org/api/pyplot_api.html?highlight=pcolor#matplotlib.pyplot.pcolor" rel="nofollow">matplotlib.pyplot.pcolor()</a> to plot a heatmap with matplotlib:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
data = np.sort(np.random.rand(8,12))
plt.figu... | 2 | 2016-05-30T04:22:57Z | 37,518,459 | <p>This is quite similar to Stanley R's (edit: now Serenity) answer, without the (in my opinion) unnecessary complexity of loops, appending to lists, et cetera:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
a = 0.5
# Get the colormap colors, multip... | 4 | 2016-05-30T05:52:16Z | [
"python",
"matplotlib",
"colormap"
] |
Python decorator handles default arguments of the decorated function | 37,517,607 | <p>I want to create a 'cache' decorator for class methods, which registers in an internal class property the result of the method for avoiding to compute it several times (and I do not want to use a simple property, computed in the <code>__init__</code>, because I am not sure to compute it even once all the time).</p>
... | 0 | 2016-05-30T04:26:00Z | 37,519,870 | <p>There can be various solutions depending on how complicated will be arguments' structure of function. The solution I prefer is to add inner function into <code>hello</code>. If you don't want to change the name of your cache, give it the same name your outer function have:</p>
<pre><code>class Test:
def hello(s... | 1 | 2016-05-30T07:24:24Z | [
"python",
"decorator",
"python-decorators"
] |
Python decorator handles default arguments of the decorated function | 37,517,607 | <p>I want to create a 'cache' decorator for class methods, which registers in an internal class property the result of the method for avoiding to compute it several times (and I do not want to use a simple property, computed in the <code>__init__</code>, because I am not sure to compute it even once all the time).</p>
... | 0 | 2016-05-30T04:26:00Z | 37,521,335 | <p>If you're using a sufficiently recent version of Python, you can use <a href="https://docs.python.org/3/library/inspect.html#introspecting-callables-with-the-signature-object" rel="nofollow"><code>inspect.signature</code></a> to get a <code>Signature</code> object that fully encapsulates the information about the fu... | 1 | 2016-05-30T08:46:32Z | [
"python",
"decorator",
"python-decorators"
] |
How do I select from drop down menu with changing id on reload of webpage | 37,517,609 | <p>I want to select "802.11n" from drop down menu using selenium webdriver but "sbSelector_xxx" id is changed every time I reload the page.</p>
<pre><code><div id="RADIO_5GHz_adv" style="display: block;">
<table class="block" border="0">
<tbody>
<tr>
<tr id="show_80211Mode_5G">
... | 0 | 2016-05-30T04:26:16Z | 37,521,071 | <p>There is multiple ways you can do this. 1 way is by using the classname of the selector.
</p>
<pre><code>driver.find_element_by_class_name('sbSelector')
</code></pre>
<p>If you don't want to do it by class name or it isn't unique you can still use the ID by checking if it contains sbSelector_ using Xpath.</p>
<pr... | 2 | 2016-05-30T08:31:52Z | [
"python",
"html",
"selenium",
"selenium-webdriver"
] |
Incorporating a function into an ODE integration | 37,517,679 | <p>This question is probably very simple but for the life of me I can't figure it out. Basically, I have a neuron whose voltage I'm modeling, but I have it receiving input spikes from other neurons randomly. So a friend of mine helped to create a function that essentially has some excitatory neurons provide a random Po... | 0 | 2016-05-30T04:34:11Z | 37,517,699 | <p><code>I_syn</code> is just a function so using <code>I_syn[i-1]</code> will throw this error:</p>
<pre><code>'function' object has no attribute '__getitem__'
</code></pre>
<p>If what you are looking for is a return value from the function, then you should first call it and then access what you want.</p>
<pre><cod... | 0 | 2016-05-30T04:37:42Z | [
"python",
"function"
] |
didn't get the right output for creating list of tuples given two lists | 37,517,684 | <p>I am following <a href="https://teamtreehouse.com/library/python-collections/tuples/combo" rel="nofollow">TreeHouse</a> tuple tutorials for Python 3 and I got this error for the following code:
<a href="http://i.stack.imgur.com/b8irI.png" rel="nofollow"><img src="http://i.stack.imgur.com/b8irI.png" alt="enter image ... | 1 | 2016-05-30T04:34:45Z | 37,517,713 | <p>You do not need nested cycles. Try this code:</p>
<pre><code>def combo(iter1, iter2):
ltup = []
for a,b in zip(iter1, iter2):
ltup.append((a, b))
return ltup
print combo([1,2,3],[3,2,1])
</code></pre>
<p>Or another the shortest variant, I guess:
<code>zip(iter1, iter2)</code></p>
<blockq... | 1 | 2016-05-30T04:40:12Z | [
"python",
"list",
"python-3.x",
"tuples"
] |
didn't get the right output for creating list of tuples given two lists | 37,517,684 | <p>I am following <a href="https://teamtreehouse.com/library/python-collections/tuples/combo" rel="nofollow">TreeHouse</a> tuple tutorials for Python 3 and I got this error for the following code:
<a href="http://i.stack.imgur.com/b8irI.png" rel="nofollow"><img src="http://i.stack.imgur.com/b8irI.png" alt="enter image ... | 1 | 2016-05-30T04:34:45Z | 37,517,722 | <p>Youcan use <code>zip</code> to get the answer.</p>
<pre><code>a = [1,2,3]
b = [4,5,6]
ans = zip(a,b)
[(1, 4), (2, 5), (3, 6)]
</code></pre>
| 1 | 2016-05-30T04:41:39Z | [
"python",
"list",
"python-3.x",
"tuples"
] |
didn't get the right output for creating list of tuples given two lists | 37,517,684 | <p>I am following <a href="https://teamtreehouse.com/library/python-collections/tuples/combo" rel="nofollow">TreeHouse</a> tuple tutorials for Python 3 and I got this error for the following code:
<a href="http://i.stack.imgur.com/b8irI.png" rel="nofollow"><img src="http://i.stack.imgur.com/b8irI.png" alt="enter image ... | 1 | 2016-05-30T04:34:45Z | 37,517,732 | <p>You just need to <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip</code></a> those iterables together:</p>
<blockquote>
<p>This function returns a <code>list</code> of tuples, where the <code>i-th tuple</code> contains the <code>i-th</code> element from each of the argument ... | 1 | 2016-05-30T04:42:29Z | [
"python",
"list",
"python-3.x",
"tuples"
] |
didn't get the right output for creating list of tuples given two lists | 37,517,684 | <p>I am following <a href="https://teamtreehouse.com/library/python-collections/tuples/combo" rel="nofollow">TreeHouse</a> tuple tutorials for Python 3 and I got this error for the following code:
<a href="http://i.stack.imgur.com/b8irI.png" rel="nofollow"><img src="http://i.stack.imgur.com/b8irI.png" alt="enter image ... | 1 | 2016-05-30T04:34:45Z | 37,517,898 | <p>The following works too (the other answers were missing to convert it to a list):</p>
<pre><code>def combo(iter1, iter2):
return list(zip(iter1, iter2))
</code></pre>
| 1 | 2016-05-30T05:01:51Z | [
"python",
"list",
"python-3.x",
"tuples"
] |
Fetch d3.js array from a url | 37,517,727 | <p>This is the kind of data that I have </p>
<pre><code>{ "_id" : ObjectId("kdahfa"), "minTime" : ISODate("2016-04-02T00:00:00.000+0000"), "maxTime" : ISODate("2016-04-02T00:11:00.000+0000"), "Time" : 660.0, "Name" : "Sam" }
{ "_id" : ObjectId("aabhk"), "minTime" : ISODate("2016-04-02T01:00:00.000+0000"), "maxTime... | 0 | 2016-05-30T04:42:15Z | 37,523,185 | <pre><code> a = dbcoll.find_one({},{'_id':False})
</code></pre>
<p>In this line, you are only querying for one entry in your database, that is why the result returned is a single object instead of an array (probably you also need to change the first parameter <code>{}</code> to <code>[]</code> or something to denote a... | 0 | 2016-05-30T10:18:19Z | [
"javascript",
"python",
"mongodb",
"d3.js",
"bottle"
] |
Matplotlib scatterplot : Open image corresponding to point which i click | 37,517,936 | <p>I have made a simple matplotlib code where i am generating scatterplot. Now i want to open image corresponding to the point when i click on that point. For example when i click on point one it should open image one, for point two it should open image two. Here is my code,</p>
<pre><code>import matplotlib.image as m... | 0 | 2016-05-30T05:05:40Z | 37,522,715 | <p>If you want this to work while zooming, I would make the distance within which a click has to occur a function of the axis limits:</p>
<pre><code>import matplotlib.image as mpimg
import numpy as np
import matplotlib.pyplot as plt
plt.close('all')
x=[1,2,3,4]
y=[1,4,9,16]
fig = plt.figure()
ax = fig.add_subplot(... | 1 | 2016-05-30T09:56:08Z | [
"python",
"matplotlib"
] |
What's the proper way to make a Python 3 function accept presets? | 37,517,967 | <p>Consider a function that takes three arguments:</p>
<pre><code>def foo(arg1, arg2, arg3):
pass
</code></pre>
<p>and a class that provides presets in a tuple:</p>
<pre><code>class Presets():
preset1 = (1, 2, 3)
preset2 = (3, 2, 1)
</code></pre>
<p>What's the proper way to make the function accept eith... | 2 | 2016-05-30T05:08:59Z | 37,518,012 | <p>One way to do it is by using a decorator.</p>
<pre><code>from functools import wraps
def tupled_arguments(f):
@wraps(f) # keeps name, docstring etc. of f
def accepts_tuple(tup, *args):
if not args: # only one argument given
return f(*tup)
return f(tup, *args)
return accept... | 4 | 2016-05-30T05:12:50Z | [
"python",
"python-3.x"
] |
What's the proper way to make a Python 3 function accept presets? | 37,517,967 | <p>Consider a function that takes three arguments:</p>
<pre><code>def foo(arg1, arg2, arg3):
pass
</code></pre>
<p>and a class that provides presets in a tuple:</p>
<pre><code>class Presets():
preset1 = (1, 2, 3)
preset2 = (3, 2, 1)
</code></pre>
<p>What's the proper way to make the function accept eith... | 2 | 2016-05-30T05:08:59Z | 37,518,196 | <p>The simplest way is to just use an asterisk <code>*</code> to cause the arguments to be flattened when passed to <code>foo</code>:</p>
<pre><code>foo(*Presets.preset2)
</code></pre>
<p>This is equivalent to:</p>
<pre><code>foo(*(3, 2, 1))
</code></pre>
<p>which is equivalent to:</p>
<pre><code>foo(3, 2, 1)
</co... | 3 | 2016-05-30T05:31:21Z | [
"python",
"python-3.x"
] |
OpenCV install opencv_contrib on Windows | 37,517,983 | <p>I am using <strong>OpenCV 3.1.0</strong> , <strong>Python 2.7.11</strong> and <strong>Windows 10.</strong> I want to build the extra modules (<strong>opencv_contrib</strong>) into OpenCV. </p>
<p>I follow the step in this <a href="https://github.com/Itseez/opencv_contrib" rel="nofollow">GitHub</a>.</p>
<pre><code>... | 1 | 2016-05-30T05:10:06Z | 37,518,522 | <p>It seems that you have no compiler installed or it is not found. </p>
<p>I have successfully worked with this guide:</p>
<p><a href="http://docs.opencv.org/3.0-rc1/d5/de5/tutorial_py_setup_in_windows.html" rel="nofollow">http://docs.opencv.org/3.0-rc1/d5/de5/tutorial_py_setup_in_windows.html</a></p>
<p>However, i... | 0 | 2016-05-30T05:57:58Z | [
"python",
"opencv"
] |
OpenCV install opencv_contrib on Windows | 37,517,983 | <p>I am using <strong>OpenCV 3.1.0</strong> , <strong>Python 2.7.11</strong> and <strong>Windows 10.</strong> I want to build the extra modules (<strong>opencv_contrib</strong>) into OpenCV. </p>
<p>I follow the step in this <a href="https://github.com/Itseez/opencv_contrib" rel="nofollow">GitHub</a>.</p>
<pre><code>... | 1 | 2016-05-30T05:10:06Z | 39,248,733 | <p>If you follow the instruction to <a href="http://docs.opencv.org/2.4/doc/tutorials/introduction/windows_install/windows_install.html#installation-by-using-the-pre-built-libraries" rel="nofollow">install the pre-build libraries</a> from here, then you will not need any compiler.</p>
<p>The same page has instructions... | -1 | 2016-08-31T11:43:32Z | [
"python",
"opencv"
] |
OpenCV install opencv_contrib on Windows | 37,517,983 | <p>I am using <strong>OpenCV 3.1.0</strong> , <strong>Python 2.7.11</strong> and <strong>Windows 10.</strong> I want to build the extra modules (<strong>opencv_contrib</strong>) into OpenCV. </p>
<p>I follow the step in this <a href="https://github.com/Itseez/opencv_contrib" rel="nofollow">GitHub</a>.</p>
<pre><code>... | 1 | 2016-05-30T05:10:06Z | 39,361,161 | <p>I have made a tutorial on how to compile and build your own OpenCV 3.1.0-dev from scratch. It is simple and organized and works with me very well. If you have time to recompile OpenCV check out the <a href="https://youtu.be/MXqpHIMdKfU" rel="nofollow">tutorial</a>.</p>
<p>The steps to follow are:</p>
<ol>
<li>Inst... | 2 | 2016-09-07T04:22:56Z | [
"python",
"opencv"
] |
python flask partically update webpage | 37,518,019 | <p>I am trying to use python flask framework to build a webpage. This webpage is a dashboard, which has two divs. The first div is a table, each row of which is the info for a certain stock. The second div is a chart which shows the price curve for one of the stocks in the first table.</p>
<p>I would like to refresh t... | 2 | 2016-05-30T05:13:19Z | 37,518,476 | <p>You can generate URL in flask using url_for(). So maybe your template to generate charts can use url_for('/stock', stock_name='GOOG'). Which will embed the route /stock/GOOG into a link to show a chart for GOOG. </p>
<p>Then you can use a nested template to show the chart div when the above route is called.</p>
<p... | 1 | 2016-05-30T05:53:40Z | [
"python",
"html",
"flask"
] |
python loop function to loop another function over a list | 37,518,097 | <p>I have a function called <code>add_ten</code>. I want to loop this function over a list.
I want to create a <code>looper</code> function and pass the <code>list</code> and the <code>add_ten</code> function to loop over as input </p>
<pre><code>def add_ten(x):
y = x+10
print 'value of x is ' + str(x)
pri... | 0 | 2016-05-30T05:22:31Z | 37,518,120 | <blockquote>
<p><code>TypeError: add_ten() takes exactly 1 argument (0 given)</code></p>
</blockquote>
<p>You are getting this error because you are calling the function <code>add_ten()</code> without an argument.</p>
<hr>
<blockquote>
<p>I want to create a <code>looper</code> function and pass the <code>list</c... | 1 | 2016-05-30T05:25:02Z | [
"python",
"list",
"function",
"loops"
] |
python loop function to loop another function over a list | 37,518,097 | <p>I have a function called <code>add_ten</code>. I want to loop this function over a list.
I want to create a <code>looper</code> function and pass the <code>list</code> and the <code>add_ten</code> function to loop over as input </p>
<pre><code>def add_ten(x):
y = x+10
print 'value of x is ' + str(x)
pri... | 0 | 2016-05-30T05:22:31Z | 37,518,122 | <p>Look closer at the error you get: "add_ten() takes exactly 1 argument (0 given)".<BR><BR>This is because in <code>return func[i]</code> you should do: <code>return func(i)</code> (note different brackets).<BR><BR>
Otherwise the argument to the call to <code>funct()</code> is lacking.</p>
| 0 | 2016-05-30T05:25:28Z | [
"python",
"list",
"function",
"loops"
] |
python loop function to loop another function over a list | 37,518,097 | <p>I have a function called <code>add_ten</code>. I want to loop this function over a list.
I want to create a <code>looper</code> function and pass the <code>list</code> and the <code>add_ten</code> function to loop over as input </p>
<pre><code>def add_ten(x):
y = x+10
print 'value of x is ' + str(x)
pri... | 0 | 2016-05-30T05:22:31Z | 37,518,150 | <ol>
<li>Dont call the function when it's an argument</li>
</ol>
<p><code>looper([1,2], add_ten)</code></p>
<ol start="2">
<li>Use parentheses instead of squaree brackets when calling <code>func(i)</code>.</li>
</ol>
<p>Otherwise,your code looks good.</p>
| 0 | 2016-05-30T05:27:26Z | [
"python",
"list",
"function",
"loops"
] |
python loop function to loop another function over a list | 37,518,097 | <p>I have a function called <code>add_ten</code>. I want to loop this function over a list.
I want to create a <code>looper</code> function and pass the <code>list</code> and the <code>add_ten</code> function to loop over as input </p>
<pre><code>def add_ten(x):
y = x+10
print 'value of x is ' + str(x)
pri... | 0 | 2016-05-30T05:22:31Z | 37,518,237 | <p>With looper([1,2],add_ten()) your're passing the result of the function-call rather than the function itself.</p>
<p>The fixed version looks like this:</p>
<pre><code>def add_ten(x):
y = x+10
print 'value of x is ' + str(x)
print 'value of y is ' + str(y)
def looper(list,func):
for i in list:
... | 0 | 2016-05-30T05:34:42Z | [
"python",
"list",
"function",
"loops"
] |
python loop function to loop another function over a list | 37,518,097 | <p>I have a function called <code>add_ten</code>. I want to loop this function over a list.
I want to create a <code>looper</code> function and pass the <code>list</code> and the <code>add_ten</code> function to loop over as input </p>
<pre><code>def add_ten(x):
y = x+10
print 'value of x is ' + str(x)
pri... | 0 | 2016-05-30T05:22:31Z | 37,518,240 | <p>Trying to understand the question, I arrive at the following working code:</p>
<pre><code>#! /usr/bin/env python
from __future__ import print_function
def add_ten(x):
print('value of x is %s\nvalue of y is %s' % (str(x), str(x + 10)))
def looper(list, func):
for i in list:
func(i)
if __name__ =... | 1 | 2016-05-30T05:34:48Z | [
"python",
"list",
"function",
"loops"
] |
How many DB connections are open when Pyramid handles HTTP requests on top of CherryPy | 37,518,297 | <p>Some background info, I'm building a web application on top of Pyramid Web Framework. In production, I use CherryPy as the WSGI server.</p>
<p>The question is: How is DB Connection is managed provided that I use Postgres + SQLAlchemy for DB access?</p>
| 2 | 2016-05-30T05:40:21Z | 37,616,922 | <p>The default SQLAlchemy setup uses <a href="http://docs.sqlalchemy.org/en/latest/core/pooling.html" rel="nofollow">internal connection pooling</a>.</p>
<ul>
<li><p>Certain number of connections is created on process startup (depending on your setup you can have M processes running N threads)</p></li>
<li><p>The conn... | 0 | 2016-06-03T14:24:09Z | [
"python",
"postgresql",
"sqlalchemy",
"pyramid",
"cherrypy"
] |
Cannot save to grib2 file using python iris module | 37,518,337 | <p>I'm using the python iris module to read in some netCDF data and output specific fields in grib format for further downstream processing. However I generate the following error</p>
<pre><code> .../pythonlib/iris/1.9.1/lib/python2.7/site-packages/Iris-1.9.1-py2.7-linux-x86_64.egg/iris/fileformats/grib/_save_rules.py... | 0 | 2016-05-30T05:43:08Z | 37,825,168 | <p>Thanks to Andrew Dawson on the iris google group for the answer. Dimensions [0] and [1] in grib_save_rules.py strictly refer to spatial dimensions, even if your cube may use time for the zeroth dimension. To quote:</p>
<blockquote>
<p>There is a <em>huge</em> amount of code in between your cube and saving as
gr... | 0 | 2016-06-15T02:34:59Z | [
"python",
"netcdf",
"grib",
"python-iris"
] |
how to get the unique combination of columns and sort by them in python data frame? | 37,518,590 | <p>how to get the unique combination of columns and sort by them in python data frame? I know I can use df.groupby(['col1','col2']).size() to get the unique combination. However, I also want to have the result order by the ascending order of col2, and then ascending order by col1. For example, if my dataframe is like t... | 1 | 2016-05-30T06:02:48Z | 37,518,665 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by <code>col2</code> and <code>col1</code>, but then need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.swaplevel.html" rel="nofollow"><code>swap... | 1 | 2016-05-30T06:07:29Z | [
"python",
"sorting",
"pandas",
"dataframe",
"group-by"
] |
Array List of Lists Python | 37,518,647 | <p>Hi I'm following a tutorial where they use the MNIST database. Now they use the cPickle to unzip the data and get a tuple of list and so on. I want to use my own data but I have it on csv format and I'm not sure how to convert to the MNIST format. I use 48 units for my training data and the last one is my desired re... | 2 | 2016-05-30T06:06:18Z | 37,519,363 | <p>For understanding the data structure you can (initially) ignore the array() and dtype information. Basically you appear to need a two part tuple (lets call them LEFT and RIGHT). LEFT is a (rectangular) list of lists (i.e. a 2dimensional array) and RIGHT is a list (i.e. a 1dimensional array).</p>
<p>For each row in ... | 2 | 2016-05-30T06:54:21Z | [
"python",
"csv",
"pickle",
"mnist"
] |
Showing form within another one | 37,518,811 | <p>I want to show a form within another form.</p>
<p>For example I have these models:</p>
<pre><code>class Measure(models.Model):
length = models.ForeignKey(Statistics, related_name='Length', null=True, blank=True)
surface_area = models.ForeignKey(Statistics, related_name='Surface area+', null=True, blank=Tr... | 0 | 2016-05-30T06:17:51Z | 37,520,808 | <p>Your database scheme and models are incorrectly designed to solve the problem at hand. You are defining a "has many" relationship in the wrong direction. One <code>Measurement</code> is supposed to have several <code>Statistics</code>, however one <code>Statistics</code> is not supposed to have many <code>Measureme... | 2 | 2016-05-30T08:17:39Z | [
"python",
"django"
] |
Python pandas - merging a table with itself | 37,518,901 | <p>I have a dataframe that looks conceptually like this:</p>
<pre><code>ID SUM Stime Etime
3 10.0 18:00:00 18:09:59
2 12.0 18:15:00 18:26:59
3 3.0 18:36:00 18:38:59
4 3.0 18:36:00 18:38:59
5 59.0 18:00:00 18:58:59
12 10.0 17:00:00 17:09:59
12 16.0 18:24:00 18:39:59
7 16.0 18:24:00 1... | 0 | 2016-05-30T06:23:38Z | 37,519,479 | <p>Beni - apologies as I don't have the reputation to comment. I'm pretty sure I have answered your previous question which should avoid the need for a solution here: <a href="http://stackoverflow.com/questions/37467146/python-pandas-combining-2-lines-from-data-frame-with-condition/37514169#37514169">Python Pandas - co... | 0 | 2016-05-30T07:01:17Z | [
"python",
"pandas"
] |
Python pandas - merging a table with itself | 37,518,901 | <p>I have a dataframe that looks conceptually like this:</p>
<pre><code>ID SUM Stime Etime
3 10.0 18:00:00 18:09:59
2 12.0 18:15:00 18:26:59
3 3.0 18:36:00 18:38:59
4 3.0 18:36:00 18:38:59
5 59.0 18:00:00 18:58:59
12 10.0 17:00:00 17:09:59
12 16.0 18:24:00 18:39:59
7 16.0 18:24:00 1... | 0 | 2016-05-30T06:23:38Z | 37,519,672 | <pre><code>d = {'ID' : [1, 2, 3,12, 4,12,5,12],'SUM' : [4, 3, 2, 16,1,19,2,11]}
df =pd.DataFrame(d)
>>> df
ID SUM
0 1 4
1 2 3
2 3 2
3 12 16
4 4 1
5 12 19
6 5 2
7 12 11
df.groupby(['ID']).sum()
SUM
ID
1 4
2 3
3 2
4 1
5 2
12 46
</code></p... | 0 | 2016-05-30T07:13:32Z | [
"python",
"pandas"
] |
SVG (Python) xPath get Elements by Attribute | 37,518,933 | <p>Hello im making a programm to IMPORT a SVG File into my Document. (LXML)</p>
<pre><code> if so.funktion != "0":
if so.funktion=="1":
searchStr = '//svg:g[@svg-creator="popup1"]'
selectStr = template.xpath(searchStr, namespaces=inkex.NSS)
if selectStr != []:
... | 0 | 2016-05-30T06:26:13Z | 37,520,244 | <p>You can use simple XPath to find child element, for example, "button1" from <code>selectStr</code> :</p>
<pre><code>btn1 = selectStr.find('svg:g[@svg-creator="button1"]', inkex.NSS)
</code></pre>
<p>or using <code>xpath()</code> method if you like :</p>
<pre><code>btn1 = selectStr.xpath('svg:g[@svg-creator="butto... | 0 | 2016-05-30T07:45:19Z | [
"python",
"xpath",
"svg",
"lxml"
] |
Python script : Running a script with multiple arguments using subprocess | 37,518,997 | <p>My question is related to this earlier question - <a href="http://stackoverflow.com/questions/17242828/python-subprocess-and-running-a-bash-script-with-multiple-arguments">Python subprocess usage</a></p>
<p>I am trying to run this command using python </p>
<p><strong>nccopy -k 4 "<a href="http://www.esrl.noaa.gov... | 0 | 2016-05-30T06:30:05Z | 37,519,320 | <p>Instead of arg1 = "-k 4", use two arguments instead.</p>
<pre><code>import subprocess
url = 'http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis2/pressure/air.2014.nc?air[408:603][2][20:34][26:40]'
outputFile = 'foo.nc'
arg1 = "-k"
arg2 = "4"
arg3 = url
arg4 = outputFile
subprocess.check_call(... | 2 | 2016-05-30T06:51:58Z | [
"python",
"arguments",
"subprocess"
] |
Python script : Running a script with multiple arguments using subprocess | 37,518,997 | <p>My question is related to this earlier question - <a href="http://stackoverflow.com/questions/17242828/python-subprocess-and-running-a-bash-script-with-multiple-arguments">Python subprocess usage</a></p>
<p>I am trying to run this command using python </p>
<p><strong>nccopy -k 4 "<a href="http://www.esrl.noaa.gov... | 0 | 2016-05-30T06:30:05Z | 37,520,723 | <p>There's two dilemmas here.<br>
One being that subprocess processes your arguments and tries to use <code>4</code> as a separate argument.</p>
<p>The other being that system calls still goes under normal shell rules, meaning that parameters and commands will be parsed for <a href="http://www.tutorialspoint.com/unix/... | 2 | 2016-05-30T08:12:55Z | [
"python",
"arguments",
"subprocess"
] |
Python script : Running a script with multiple arguments using subprocess | 37,518,997 | <p>My question is related to this earlier question - <a href="http://stackoverflow.com/questions/17242828/python-subprocess-and-running-a-bash-script-with-multiple-arguments">Python subprocess usage</a></p>
<p>I am trying to run this command using python </p>
<p><strong>nccopy -k 4 "<a href="http://www.esrl.noaa.gov... | 0 | 2016-05-30T06:30:05Z | 37,544,530 | <p>If you have a working shell command that runs a single program with multiple arguments and you want to parameterized it e.g., to use a variable filename instead of the hardcoded value then you could use <code>shlex.split()</code> to create a list of command-line arguments that you could pass to <code>subprocess</cod... | 1 | 2016-05-31T11:30:58Z | [
"python",
"arguments",
"subprocess"
] |
How do I upload a large SQLite file to Object Storage using OpenStack's Swift (via Python) | 37,519,045 | <p>I have an <a href="https://console.ng.bluemix.net/catalog/services/object-storage/" rel="nofollow">Object Storage</a> instance on IBM's Bluemix, and I'm attempting to upload a ~32GB SQLite file. Here is my Python code which uses the OpenStack Swift API (with the credentials removed):</p>
<pre><code>import swiftcli... | 0 | 2016-05-30T06:33:19Z | 37,537,146 | <p>You'll need to read-up on Swift DLO/SLO support and manifests. Here's a blog <a href="http://blog.ibmjstart.net/2016/04/14/e-pluribus-unum-creating-openstack-manifest-objects-in-ibm-bluemix-object-storage/" rel="nofollow">post</a> that might help with context on what manifests are and the differences between Static... | 1 | 2016-05-31T04:58:14Z | [
"python",
"ibm-bluemix",
"openstack",
"openstack-swift"
] |
Is it possible to loop through Amazon S3 bucket and count the number of lines in its file/key using Python? | 37,519,061 | <p>Is it possible to loop through the file/key in Amazon S3 bucket, read the contents and count the number of lines using Python?</p>
<p>For Example:</p>
<pre><code> 1. My bucket: "my-bucket-name"
2. File/Key : "test.txt"
</code></pre>
<p>I need to loop through the file "test.txt" and count the number of line in... | 1 | 2016-05-30T06:34:52Z | 37,520,526 | <p>Amazon S3 is only a storage service. You must get the file in order to perform actions on it (e.g. reading number of files).</p>
| 0 | 2016-05-30T08:01:23Z | [
"python",
"amazon-web-services",
"amazon-s3",
"boto"
] |
Is it possible to loop through Amazon S3 bucket and count the number of lines in its file/key using Python? | 37,519,061 | <p>Is it possible to loop through the file/key in Amazon S3 bucket, read the contents and count the number of lines using Python?</p>
<p>For Example:</p>
<pre><code> 1. My bucket: "my-bucket-name"
2. File/Key : "test.txt"
</code></pre>
<p>I need to loop through the file "test.txt" and count the number of line in... | 1 | 2016-05-30T06:34:52Z | 37,521,818 | <p>You can loops through a bucket using <a href="http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.list_objects_v2" rel="nofollow">boto3 list_objects_v2</a>. Because list_objects_v2 only list maximum of 1000 keys (even you specify MaxKeys), you must whether <code>NextContinuationToken</code> ex... | 0 | 2016-05-30T09:12:03Z | [
"python",
"amazon-web-services",
"amazon-s3",
"boto"
] |
Is it possible to loop through Amazon S3 bucket and count the number of lines in its file/key using Python? | 37,519,061 | <p>Is it possible to loop through the file/key in Amazon S3 bucket, read the contents and count the number of lines using Python?</p>
<p>For Example:</p>
<pre><code> 1. My bucket: "my-bucket-name"
2. File/Key : "test.txt"
</code></pre>
<p>I need to loop through the file "test.txt" and count the number of line in... | 1 | 2016-05-30T06:34:52Z | 37,533,067 | <p><strong>Using <code>boto3</code> you can do the following:</strong></p>
<pre><code>import boto3
# create the s3 resource
s3 = boto3.resource('s3')
# get the file object
obj = s3.Object('bucket_name', 'key')
# read the file contents in memory
file_contents = obj.get()["Body"].read()
# print the occurrences of th... | 0 | 2016-05-30T20:11:57Z | [
"python",
"amazon-web-services",
"amazon-s3",
"boto"
] |
How to convert list pairs into tuple pairs | 37,519,065 | <p>How do you turn a list that contain pairs into a list that contains tuple pairs by using easy programming e.g for loop? x,y = ...?</p>
<p>My code: </p>
<pre><code>def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
numbers.split(',')
x,y = tuple numbers
retu... | 0 | 2016-05-30T06:35:10Z | 37,519,233 | <pre><code>def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
return [tuple(map(int,pair.split(','))) for pair in numbers]
</code></pre>
| 2 | 2016-05-30T06:46:33Z | [
"python"
] |
How to convert list pairs into tuple pairs | 37,519,065 | <p>How do you turn a list that contain pairs into a list that contains tuple pairs by using easy programming e.g for loop? x,y = ...?</p>
<p>My code: </p>
<pre><code>def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
numbers.split(',')
x,y = tuple numbers
retu... | 0 | 2016-05-30T06:35:10Z | 37,519,296 | <p>Try this by using nested list comprehension:</p>
<pre><code>o = [tuple(int(y) for y in x.split(',')) for x in numbers]
</code></pre>
| 2 | 2016-05-30T06:50:31Z | [
"python"
] |
How to convert list pairs into tuple pairs | 37,519,065 | <p>How do you turn a list that contain pairs into a list that contains tuple pairs by using easy programming e.g for loop? x,y = ...?</p>
<p>My code: </p>
<pre><code>def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
numbers.split(',')
x,y = tuple numbers
retu... | 0 | 2016-05-30T06:35:10Z | 37,519,453 | <p>Just use list comprehension. Read more about it <a href="https://docs.python.org/2.7/tutorial/datastructures.html#list-comprehensions" rel="nofollow">here</a>!</p>
<pre><code># Pass in numbers as an argument so that it will work
# for more than 1 list.
def read_numbers(numbers):
return [tuple(int(y) for y in x.... | 1 | 2016-05-30T07:00:06Z | [
"python"
] |
How to convert list pairs into tuple pairs | 37,519,065 | <p>How do you turn a list that contain pairs into a list that contains tuple pairs by using easy programming e.g for loop? x,y = ...?</p>
<p>My code: </p>
<pre><code>def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
numbers.split(',')
x,y = tuple numbers
retu... | 0 | 2016-05-30T06:35:10Z | 37,521,461 | <p>Try this : </p>
<pre><code>def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
final_list = []
[final_list.append(tuple(int(test_str) for test_str in number.split(','))) for number in numbers]
return final_list
</code></pre>
| 0 | 2016-05-30T08:52:00Z | [
"python"
] |
Why only one result in loop scrapy | 37,519,092 | <p>I'm trying to use <em>scrapy</em> to crawl some page with a lot of links inside, but my existing code so far only show the contents of the first link.</p>
<p>What mistake have I made?</p>
<pre><code>from scrapy.spiders import BaseSpider
from scrapy.spiders import Spider
from scrapy.http.request import Request
from... | 0 | 2016-05-30T06:36:41Z | 37,519,202 | <p>The issue is that you have a <code>return</code> statement within your <code>for</code> loop. In Python, a <code>return</code> will return out of the function, giving you only the first links worth of content. Instead, consider adding <code>req</code> to a list of returned objects.</p>
<pre><code>def parse(self, re... | 1 | 2016-05-30T06:44:45Z | [
"python",
"loops",
"scrapy"
] |
Why only one result in loop scrapy | 37,519,092 | <p>I'm trying to use <em>scrapy</em> to crawl some page with a lot of links inside, but my existing code so far only show the contents of the first link.</p>
<p>What mistake have I made?</p>
<pre><code>from scrapy.spiders import BaseSpider
from scrapy.spiders import Spider
from scrapy.http.request import Request
from... | 0 | 2016-05-30T06:36:41Z | 37,520,371 | <p>according to the scrapy docs, <a href="http://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.spiders.Spider.parse" rel="nofollow"><code>parse</code> needs to return an interable</a> of <code>Request</code>, i.e. a list or a generator. Just change <code>return</code> to <code>yield</code> and it should work as e... | 1 | 2016-05-30T07:52:40Z | [
"python",
"loops",
"scrapy"
] |
working with regex | 37,519,105 | <p>I have a string and I need first element to be captured.</p>
<pre><code>s = extra-root, May 15, 2024, Entry, abcd: efgh
</code></pre>
<p>I am doing it as, </p>
<pre><code>print s.split(",")[0]
</code></pre>
<p>But, is there any way using re to get the first element of string with comma? I want "extra-root".</p>
| 1 | 2016-05-30T06:37:18Z | 37,519,140 | <p>You may use a regular split function with if condition. If you want regex then <code>re.search</code> is the best choice which should return the first match.</p>
<pre><code>>>> s = 'extra-root, May 15, 2024, Entry, abcd: efgh, ds:sd'
>>> [i for i in s.split(',') if ':' in i][0]
' abcd: efgh'
>&... | 3 | 2016-05-30T06:39:27Z | [
"python",
"regex"
] |
Python - Find center of object in an image | 37,519,238 | <p>I have an image file that's has a white background with a non-white object.
I want to find the center of the object using python (Pillow).</p>
<p>I have found a similar question in c++ but no acceptable answer - <a href="http://stackoverflow.com/questions/12394153/how-can-i-find-center-of-object">How can I find cen... | 1 | 2016-05-30T06:46:50Z | 37,519,372 | <p>I would try and find a way to draw a triangle around it, with one point of the triangle at the farthest "points" on the object, and then find the center of that triangle.</p>
| 1 | 2016-05-30T06:55:10Z | [
"python",
"image",
"pillow"
] |
Python - Find center of object in an image | 37,519,238 | <p>I have an image file that's has a white background with a non-white object.
I want to find the center of the object using python (Pillow).</p>
<p>I have found a similar question in c++ but no acceptable answer - <a href="http://stackoverflow.com/questions/12394153/how-can-i-find-center-of-object">How can I find cen... | 1 | 2016-05-30T06:46:50Z | 37,521,603 | <p>If you define center as Center of Mass, then it is not difficult, although the CoM can be outside of your shape. You can interpret your image as a 2D distribution, and you can find its expected value (CoM) using integration (summation).</p>
<p>If you have numpy it is quite simple. First create a numpy array contain... | 0 | 2016-05-30T08:59:26Z | [
"python",
"image",
"pillow"
] |
Exclude/hide a field in Django form rendered with crispy-forms | 37,519,550 | <p>I have two templates with the same form but on one page I do not want display 'photo' field. The problem is that my form described via FormHelper of crispy-forms. How can I hide/exclude/delete 'photo' field and FormActions(Button)? Thanks in advance.</p>
<p>views.py:</p>
<pre><code> def user_data_view(request)... | 0 | 2016-05-30T07:05:45Z | 37,520,532 | <p>not the best desicion, but nevertheless...</p>
<p>in template you want to hide the photo, just insert smth like that:</p>
<pre><code> <script> document.onLoad(function(){document.getElementById('form').getElementsByTagName('img')[0].style = 'display:none';
}) </script>
</code></pre>
| 0 | 2016-05-30T08:01:35Z | [
"python",
"django",
"forms",
"django-crispy-forms"
] |
Creating Multi-hierarchy pivot table in Pandas | 37,519,618 | <h3>1. Background</h3>
<p>The .xls files I have now contain some parameters of multi-pollutant in many aspects for different sites. </p>
<p>I created an simplified dataframe below as an illustration:</p>
<p><a href="http://i.stack.imgur.com/OLu1y.png" rel="nofollow"><img src="http://i.stack.imgur.com/OLu1y.png" al... | 0 | 2016-05-30T07:09:58Z | 37,520,259 | <p>IIUC</p>
<p>You want the same dataframe, but with a better column index.</p>
<p>To create the first level:</p>
<pre><code>level0 = df.columns.str.extract(r'([^\d]*)', expand=False)
</code></pre>
<p>then assign a multiindex to the columns attribute.</p>
<pre><code>df.columns = pd.MultiIndex.from_arrays([level0, ... | 1 | 2016-05-30T07:46:16Z | [
"python",
"excel",
"pandas",
"pivot-table"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.