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 |
|---|---|---|---|---|---|---|---|---|---|
UnboundLocalError from If statement | 38,549,500 | <p>I keep receiving the error:</p>
<pre><code>UnboundLocalError: local variable 'var' referenced before assignment
</code></pre>
<p>When i try running</p>
<pre><code>def func1():
var = True
def func2():
if something_random and var == True:
do stuff
</code></pre>
| 0 | 2016-07-24T06:51:29Z | 38,549,698 | <p>This is because <code>var</code> is defined within the scope of <code>func1</code>, and not in the scope of <code>func2</code>. <a href="http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html" rel="nofollow">See this</a> for an explaination of variable scoping in python.</p>
| 0 | 2016-07-24T07:24:43Z | [
"python"
] |
UnboundLocalError from If statement | 38,549,500 | <p>I keep receiving the error:</p>
<pre><code>UnboundLocalError: local variable 'var' referenced before assignment
</code></pre>
<p>When i try running</p>
<pre><code>def func1():
var = True
def func2():
if something_random and var == True:
do stuff
</code></pre>
| 0 | 2016-07-24T06:51:29Z | 38,549,842 | <p>When you assign to a variable in a python function, that variable is local to the function by default. You <em>could</em> make it global:</p>
<pre><code>var = False # What if func2 was called before func1?
def func1():
global var
var = True
def func2():
global var #... | 0 | 2016-07-24T07:46:19Z | [
"python"
] |
Python not responding in loop | 38,549,507 | <p>Here is my code:</p>
<pre><code>from random import randint
doorNum = randint(1, 3)
doorInp = input("Please Enter A Door Number Between 1 and 3: ")
x = 1
while (x == 1) :
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
exit()
</code></pre>
<p>now, that works fine, if I happ... | 0 | 2016-07-24T06:51:54Z | 38,549,585 | <p>In python3, the <code>input</code> function returns a <em>string</em>. You're comparing this <em>string</em> value to a random <em>int</em> value. This will always evaluate to <code>False</code>. Since you only ask for user input <strong>once</strong>, before the loop, the user never gets a chance to choose a new nu... | -1 | 2016-07-24T07:07:17Z | [
"python",
"shell"
] |
Python not responding in loop | 38,549,507 | <p>Here is my code:</p>
<pre><code>from random import randint
doorNum = randint(1, 3)
doorInp = input("Please Enter A Door Number Between 1 and 3: ")
x = 1
while (x == 1) :
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
exit()
</code></pre>
<p>now, that works fine, if I happ... | 0 | 2016-07-24T06:51:54Z | 38,549,615 | <p>If you are using python3, then <code>input</code> returns a string and comparing a string to an int is always false, thus your <code>exit()</code> function can never run.</p>
| 0 | 2016-07-24T07:11:53Z | [
"python",
"shell"
] |
Python not responding in loop | 38,549,507 | <p>Here is my code:</p>
<pre><code>from random import randint
doorNum = randint(1, 3)
doorInp = input("Please Enter A Door Number Between 1 and 3: ")
x = 1
while (x == 1) :
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
exit()
</code></pre>
<p>now, that works fine, if I happ... | 0 | 2016-07-24T06:51:54Z | 38,549,721 | <p>Your doorInp variable is a string type, which is causing the issue because you are comparing it to an integer in the if statement. You can easily check by adding something like <code>print(type(doorInp))</code> after your input line.
To fix it, just enclose the input statement inside int() like:<code>doorInp = int(i... | 0 | 2016-07-24T07:28:40Z | [
"python",
"shell"
] |
UnicodeEncodeError: Script runs on Spyder and IDLE, yet not on cmd prompt | 38,549,695 | <p>I have a working script at hand, while it runs on the Spyder IDE and python shell, when I just run it by double clicking, it closes right away. To understand the problem, I ran it through the cmd prompt and encountered the following:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Cheese\Desktop\de... | 1 | 2016-07-24T07:24:29Z | 38,550,107 | <p>Okay, found the solution, wonder how I missed this one (considering I tried to figure this one out for 2-3 hours).</p>
<p>To run the program with a non ASCII strings, you can change the code page for the command prompt. To do that:
Open Windows Control Panel
Select Region and Language
Click on the Administrative ta... | 0 | 2016-07-24T08:27:34Z | [
"python",
"unicode"
] |
UnicodeEncodeError: Script runs on Spyder and IDLE, yet not on cmd prompt | 38,549,695 | <p>I have a working script at hand, while it runs on the Spyder IDE and python shell, when I just run it by double clicking, it closes right away. To understand the problem, I ran it through the cmd prompt and encountered the following:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Cheese\Desktop\de... | 1 | 2016-07-24T07:24:29Z | 38,550,595 | <p><code>input</code> with a string argument does a <code>print</code>, and, notoriously, <a href="https://wiki.python.org/moin/PrintFails" rel="nofollow">PrintFails</a>.</p>
<p>The Windows command prompt is hopelessly broken at Unicode. You can change the code page it uses to one that includes the characters you want... | 0 | 2016-07-24T09:34:27Z | [
"python",
"unicode"
] |
How can I do ordinal regression using the mord module in python? | 38,549,756 | <p>I am trying to predict a label based on some features and I have some training data. </p>
<p>Searching for ordinal regression in python, I found <a href="http://pythonhosted.org/mord/" rel="nofollow">http://pythonhosted.org/mord/</a> but I could not figure out how to use it. </p>
<p>It would be great if someone ha... | 0 | 2016-07-24T07:34:24Z | 38,549,926 | <p>I believe it follows the API of Scikit-learn. So here is an example:</p>
<pre><code>import numpy as np
import mord as m
c = m.LogisticIT() #Default parameters: alpha=1.0, verbose=0, maxiter=10000
c.fit(np.array([[0,0,0,1],[0,1,0,0],[1,0,0,0]]), np.array([1,2,3]))
c.predict(np.array([0,0,0,1]))
c.predict(np.array([0... | 1 | 2016-07-24T07:59:13Z | [
"python",
"machine-learning",
"regression",
"logistic-regression",
"non-linear-regression"
] |
How to know file size after reading it as an object in python? | 38,549,793 | <p>I have a functionality for testing out the file size in python server. But after converting file it into Request object (i.e file converted to python object) size mismatched. File size is somewhat smaller than python object. Files are attached from a form in post request.</p>
<p>Is there a way to know correct file ... | 0 | 2016-07-24T07:40:08Z | 38,551,259 | <p>Already answered <a href="http://stackoverflow.com/a/19079887/6631262">here</a></p>
<pre><code># f is a file-like object.
old_file_position = f.tell()
f.seek(0, os.SEEK_END)
size = f.tell()
f.seek(old_file_position, os.SEEK_SET)
</code></pre>
| 1 | 2016-07-24T10:54:18Z | [
"python",
"file",
"object",
"size",
"tornado"
] |
Using seek() to create a mean pixel value comparing software in .tiff format? | 38,549,807 | <p>How does PIL handle seek() function to operate within multiframe .tiff files? I'm trying to extract a piece of information (greyscale pixel values) of various frames in the file, but no matter what I set the seek for, EOFE error is raised.
Example code:</p>
<pre><code>from PIL import Image
im = Image.open('example_... | 0 | 2016-07-24T07:42:10Z | 38,608,994 | <p>Was caused by PIL getting to end of the file: can be fixed like this;</p>
<pre><code>class ImageSequence:
def __init__(self, im):
self.im = im
def __getitem__(self, ix):
try:
if ix:
self.im.seek(ix)
return self.im
except EOFError:
raise IndexError # this is the end of... | 1 | 2016-07-27T09:29:05Z | [
"python",
"image",
"tiff",
"seek"
] |
Python sqlite loop thought all tables in database | 38,549,815 | <p>I have 700 tables in a <code>test.db</code> file, and was wondering how do I loop through all these tables and return the table name if <code>columnA</code> value is <code>-</code>?</p>
<pre><code>connection.execute('SELECT * FROM "all_tables" WHERE "columnA" = "-"')
</code></pre>
<p>How do I put all 700 tables in... | 0 | 2016-07-24T07:43:25Z | 38,549,944 | <p>You could query the <a href="http://www.sqlite.org/faq.html#q7" rel="nofollow">sqlite_master</a> to get all the table names within your database: <code>SELECT name FROM sqlite_master WHERE type = 'table'</code></p>
<p><code>sqlite_master</code> can be thought of as a table that contains information about <em>your</... | 1 | 2016-07-24T08:01:28Z | [
"python",
"sqlite",
"sqlalchemy"
] |
Python sqlite loop thought all tables in database | 38,549,815 | <p>I have 700 tables in a <code>test.db</code> file, and was wondering how do I loop through all these tables and return the table name if <code>columnA</code> value is <code>-</code>?</p>
<pre><code>connection.execute('SELECT * FROM "all_tables" WHERE "columnA" = "-"')
</code></pre>
<p>How do I put all 700 tables in... | 0 | 2016-07-24T07:43:25Z | 38,550,029 | <p>SQLite</p>
<p>get all tables name:</p>
<pre><code>SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;
</code></pre>
<p>Cycle</p>
<pre><code>for table in tables:
...
connection.execute('SELECT * FROM "table1" WHERE "columnA" = "-"')
</code></pre>
<p>or one SQL request UNION</p>
<pre><code>sql =... | 1 | 2016-07-24T08:14:11Z | [
"python",
"sqlite",
"sqlalchemy"
] |
Python sqlite loop thought all tables in database | 38,549,815 | <p>I have 700 tables in a <code>test.db</code> file, and was wondering how do I loop through all these tables and return the table name if <code>columnA</code> value is <code>-</code>?</p>
<pre><code>connection.execute('SELECT * FROM "all_tables" WHERE "columnA" = "-"')
</code></pre>
<p>How do I put all 700 tables in... | 0 | 2016-07-24T07:43:25Z | 38,550,222 | <p>To continue on a theme:</p>
<pre><code>import sqlite3
try:
conn = sqlite3.connect('/home/rolf/my.db')
except sqlite3.Error as e:
print('Db Not found', str(e))
db_list = []
mycursor = conn.cursor()
for db_name in mycursor.execute("SELECT name FROM sqlite_master WHERE type = 'table'"):
db_list.append(db_n... | 0 | 2016-07-24T08:45:30Z | [
"python",
"sqlite",
"sqlalchemy"
] |
code passes all the tests but fails in other tests.. please follow the link | 38,549,822 | <p>Return the sum of the numbers in the array, ignoring sections of numbers between 6 and 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.</p>
<pre><code>sum67([1, 2, 2]) â 5
sum67([1, 2, 2, 6, 99, 99, 7]) â 5
sum67([1, 1, 6, 7, 2]) â 4
</code></pre>
<p>my code: </p>
<pre><code>def ... | 0 | 2016-07-24T07:43:56Z | 38,549,906 | <p>The problem arises if there's a <code>6</code> directly after a <code>7</code>.</p>
<p>Your code detects the first <code>6</code> and skips forward past the next <code>7</code>. But if the next number is another <code>6</code>, it won't be skipped.</p>
<p>It'll work if you change <code>if nums[n]==6:</code> to <co... | 0 | 2016-07-24T07:55:52Z | [
"python"
] |
code passes all the tests but fails in other tests.. please follow the link | 38,549,822 | <p>Return the sum of the numbers in the array, ignoring sections of numbers between 6 and 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.</p>
<pre><code>sum67([1, 2, 2]) â 5
sum67([1, 2, 2, 6, 99, 99, 7]) â 5
sum67([1, 1, 6, 7, 2]) â 4
</code></pre>
<p>my code: </p>
<pre><code>def ... | 0 | 2016-07-24T07:43:56Z | 38,549,939 | <p>@Rawing got this debugged properly. Here's another simple fix if you prefer:</p>
<pre><code>def sum67(nums):
total = 0
n = 0
while n < len(nums):
if nums[n] == 6:
# Skip forward until we find a 7 (or the end of the list).
while n < len(nums) and nums[n] != 7:
... | 0 | 2016-07-24T08:00:41Z | [
"python"
] |
code passes all the tests but fails in other tests.. please follow the link | 38,549,822 | <p>Return the sum of the numbers in the array, ignoring sections of numbers between 6 and 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.</p>
<pre><code>sum67([1, 2, 2]) â 5
sum67([1, 2, 2, 6, 99, 99, 7]) â 5
sum67([1, 1, 6, 7, 2]) â 4
</code></pre>
<p>my code: </p>
<pre><code>def ... | 0 | 2016-07-24T07:43:56Z | 38,549,959 | <p>As @Rawing pointed out your code doesn't cover the scenario where <code>6</code> follows immediately after <code>7</code>. Instead of having multiple loops and updating loop counter yourself you could just iterate over the numbers on the list and have extra variable telling if you need to skip them or not:</p>
<pre... | 0 | 2016-07-24T08:03:49Z | [
"python"
] |
Merging data frame columns of strings into one single column in Pandas | 38,549,915 | <p>I have columns in a dataframe (imported from a CSV) containing text like this.</p>
<pre><code>"New york", "Atlanta", "Mumbai"
"Beijing", "Paris", "Budapest"
"Brussels", "Oslo", "Singapore"
</code></pre>
<p>I want to collapse/merge all the columns into one single column, like this</p>
<pre><code>New york Atlanta
B... | 4 | 2016-07-24T07:57:26Z | 38,550,047 | <p>Suppose you have a <code>DataFrame</code> like so:</p>
<pre><code>>>> df
0 1 2
0 New york Atlanta Mumbai
1 Beijing Paris Budapest
2 Brussels Oslo Singapore
</code></pre>
<p>Then, a simple use of the <code>pd.DataFrame.apply</code> method will work nicely:</p>
... | 4 | 2016-07-24T08:17:11Z | [
"python",
"pandas"
] |
Merging data frame columns of strings into one single column in Pandas | 38,549,915 | <p>I have columns in a dataframe (imported from a CSV) containing text like this.</p>
<pre><code>"New york", "Atlanta", "Mumbai"
"Beijing", "Paris", "Budapest"
"Brussels", "Oslo", "Singapore"
</code></pre>
<p>I want to collapse/merge all the columns into one single column, like this</p>
<pre><code>New york Atlanta
B... | 4 | 2016-07-24T07:57:26Z | 38,550,190 | <p>A faster (but uglier) version is with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.cat.html" rel="nofollow"><code>.cat</code></a>:</p>
<pre><code>df[0].str.cat(df.ix[:, 1:].T.values, sep=' ')
0 New york Atlanta Mumbai
1 Beijing Paris Budapest
2 Brussels Oslo Singapore
... | 4 | 2016-07-24T08:39:45Z | [
"python",
"pandas"
] |
Merging data frame columns of strings into one single column in Pandas | 38,549,915 | <p>I have columns in a dataframe (imported from a CSV) containing text like this.</p>
<pre><code>"New york", "Atlanta", "Mumbai"
"Beijing", "Paris", "Budapest"
"Brussels", "Oslo", "Singapore"
</code></pre>
<p>I want to collapse/merge all the columns into one single column, like this</p>
<pre><code>New york Atlanta
B... | 4 | 2016-07-24T07:57:26Z | 38,550,724 | <p>Here are a couple more ways:</p>
<pre><code>def pir(df):
df = df.copy()
df.insert(2, 's', ' ', 1)
df.insert(1, 's', ' ', 1)
return df.sum(1)
def pir2(df):
df = df.copy()
return pd.MultiIndex.from_arrays(df.values.T).to_series().str.join(' ').reset_index(drop=True)
def pir3(df):
a = df.... | 5 | 2016-07-24T09:48:49Z | [
"python",
"pandas"
] |
Merging data frame columns of strings into one single column in Pandas | 38,549,915 | <p>I have columns in a dataframe (imported from a CSV) containing text like this.</p>
<pre><code>"New york", "Atlanta", "Mumbai"
"Beijing", "Paris", "Budapest"
"Brussels", "Oslo", "Singapore"
</code></pre>
<p>I want to collapse/merge all the columns into one single column, like this</p>
<pre><code>New york Atlanta
B... | 4 | 2016-07-24T07:57:26Z | 38,551,192 | <p>for the sake of completeness:</p>
<pre><code>In [160]: df1.add([' '] * (df1.columns.size - 1) + ['']).sum(axis=1)
Out[160]:
0 New york Atlanta Mumbai
1 Beijing Paris Budapest
2 Brussels Oslo Singapore
dtype: object
</code></pre>
<p>Explanation:</p>
<pre><code>In [162]: [' '] * (df.columns.size - 1) + ['... | 1 | 2016-07-24T10:46:38Z | [
"python",
"pandas"
] |
Merging data frame columns of strings into one single column in Pandas | 38,549,915 | <p>I have columns in a dataframe (imported from a CSV) containing text like this.</p>
<pre><code>"New york", "Atlanta", "Mumbai"
"Beijing", "Paris", "Budapest"
"Brussels", "Oslo", "Singapore"
</code></pre>
<p>I want to collapse/merge all the columns into one single column, like this</p>
<pre><code>New york Atlanta
B... | 4 | 2016-07-24T07:57:26Z | 38,551,387 | <p>If you prefer something more explicit...</p>
<p>Starting with a dataframe df that looks like this:</p>
<pre><code>>>> df
A B C
0 New york Beijing Brussels
1 Atlanta Paris Oslo
2 Mumbai Budapest Singapore
</code></pre>
<p>You can create a new column like th... | 1 | 2016-07-24T11:10:46Z | [
"python",
"pandas"
] |
Shifting grid with matplotlib | 38,550,017 | <p>I'm plotting data which is formatted between 0 and 360 degrees. I'm trying to plot this on cyl or merc projection, but it is only showing data from 0 onwards (I want to plot the data with the GMT in the center, so need the data on a lon grid of -180 to 180). If I shift the grid (lon = lon -180) then all data shows, ... | 2 | 2016-07-24T08:12:56Z | 38,551,520 | <p>I have a solution (albeit an ugly one). By reordering the data.</p>
<pre><code>temp = np.zeros((721,1440))
temp[:,0:720] = Plot[:,720:1440]
temp[:,720:1440] = Plot[:,0:720]
Plot[:]=temp[:]
</code></pre>
| 1 | 2016-07-24T11:26:29Z | [
"python",
"matplotlib",
"matplotlib-basemap"
] |
Shifting grid with matplotlib | 38,550,017 | <p>I'm plotting data which is formatted between 0 and 360 degrees. I'm trying to plot this on cyl or merc projection, but it is only showing data from 0 onwards (I want to plot the data with the GMT in the center, so need the data on a lon grid of -180 to 180). If I shift the grid (lon = lon -180) then all data shows, ... | 2 | 2016-07-24T08:12:56Z | 39,277,671 | <p>Please Try:</p>
<pre><code>import numpy as np
from mpl_toolkits.basemap import shiftgrid
from mpl_toolkits.basemap import Basemap
lat = np.linspace(-90, 90, 721)
lon = np.linspace(0, 360, 1440)
Plot, lon = shiftgrid(180., Plot, lon, start=False) # shiftgrid
m = Basemap(projection='cyl', llcrnrlat=-90, urcrnrlat=9... | 0 | 2016-09-01T17:33:16Z | [
"python",
"matplotlib",
"matplotlib-basemap"
] |
No Resolution to Pygame Error | 38,550,055 | <p>I am using anaconda [python 2.7] on ubuntu machine [15.04].</p>
<p>I need opencv, pygame, python 2.7 for my code to run.</p>
<p>I get the error on running my code:</p>
<pre><code>Traceback (most recent call last):
File "deep_q_network.py", line 8, in <module>
import wrapped_flappy_bird as game
File ... | 1 | 2016-07-24T08:18:26Z | 38,550,068 | <p>Read the error: <code>File is not a Windows BMP file</code>. The image you're trying to load seems to be a .png: <code>assets/sprites/0.png</code>. To fix, save the image as a .bmp. Your pygame is missing support for other formats. <a href="http://www.pygame.org/docs/ref/image.html" rel="nofollow">Documentation quot... | 0 | 2016-07-24T08:20:35Z | [
"python",
"python-2.7",
"opencv"
] |
Parsing text file (Python) | 38,550,071 | <p>I have a text file with a bunch of lines which contains:</p>
<pre><code>"blah0","blah1","blah2","blah3","blah4"
"blah5","blah6","blah7","blah8","blah9"
"blah10","blah11","blah12","blah13","blah14"
</code></pre>
<p>I have around 50 of these little guys, and I want the script to get rid of the stuff I don't need, al... | -5 | 2016-07-24T08:21:07Z | 38,550,420 | <p>I cant tell how what information you really need, but using a spreadsheet editor is probably best. All you would need to do is remove the Quote marks, then your file is in csv format and can be opened in excel or most spreadsheet editors (rename to .csv).</p>
<p>To remove the quotes there are many options, like Fin... | -1 | 2016-07-24T09:12:01Z | [
"python",
"parsing"
] |
boost python C++ function calling another function error | 38,550,098 | <p>I have written a function in C++ and built successfully.</p>
<p>However, if I just calling it from another function in C++, then the built failed.</p>
<pre><code>double getlistvalue(boost::python::list l, int index)
{
if (index = -1)
return 0;
else
return boost::python::extract<double>... | 0 | 2016-07-24T08:26:15Z | 38,550,192 | <p>You are passing the lists by value, which requires a copy constructor. The error message is telling you that no copy constructor has been provided for list. The solution therefore is to pass the list by reference:</p>
<pre><code>double getlistvalue(const boost::python::list &l, int index)
</code></pre>
<p>(and... | 1 | 2016-07-24T08:40:11Z | [
"python",
"c++",
"boost"
] |
Sum for Multiple Ranges on GroupBy Aggregations in Elasticsearch | 38,550,149 | <p>The following mapping is aggregated on multiple levels on a field grouping documents using another field.</p>
<p>Mapping:</p>
<pre><code> {
'predictions': {
'properties': {
'Company':{'type':'string'},
'TxnsId':{'type':'string'},
'Emp':{'type':'string'},
... | 0 | 2016-07-24T08:32:45Z | 38,560,944 | <p>Something like this should do the job:</p>
<pre><code>{
"size": 0,
"aggs": {
"by_emp": {
"terms": {
"field": "Emp"
},
"aggs": {
"cash_online": {
"filters": {
"filters": {
"cashed": {
"term": {
"Cash/onlin... | 0 | 2016-07-25T06:24:22Z | [
"python",
"elasticsearch",
"dsl",
"elasticsearch-query"
] |
Matrix terminology | 38,550,207 | <p>I've found three useful operations when dealing with lists of lists.</p>
<pre><code>mat=[list('abc'),list('pqr'),list('xyz')]
</code></pre>
<p>1.<code>mat=[x for sl in mat for x in sl]</code> ("flatten")</p>
<ol start="2">
<li><p><code>mat=list(zip(*mat))</code> (transposing)</p></li>
<li><p><code>mat=mat[::-1]</... | 0 | 2016-07-24T08:42:16Z | 38,552,849 | <ol>
<li>In my corner of the world, this is often called ârasterizingâ a matrix (though we might be appropriating the term from image processing). Numpy calls it <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html" rel="nofollow"><code>ravel()</code></a>. Matlab calls it âvectorizeâ an... | 0 | 2016-07-24T14:02:00Z | [
"python",
"arrays",
"list",
"matrix",
"linear-algebra"
] |
(flask) python - mysql - using where clause in a select query with variable from URL | 38,550,263 | <pre><code>@app.route('/select/<username>')
def select(username):
db = MySQLdb.connect("localhost","myusername","mypassword","mydbname" )
cursor = db.cursor()
cursor.execute("SELECT * FROM p_shahr")
data = cursor.fetchall()
db.close()
return render_template('select.html', data=data)
... | 0 | 2016-07-24T08:50:30Z | 38,550,328 | <p>Use string formatting to prepare the query.</p>
<pre><code>@app.route('/select/<username>')
def select(username):
db = MySQLdb.connect("localhost","myusername","mypassword","mydbname" )
cursor = db.cursor()
query_string = "SELECT * FROM p_shahr WHERE os = '{username}'".format(username=username)... | 0 | 2016-07-24T08:57:40Z | [
"python",
"mysql",
"select",
"flask"
] |
pandas.apply() returns NaN from difference between two columns | 38,550,304 | <p>I want to calculate the absolute differences of two pandas columns <code>I</code> and <code>Imean</code> with the following code</p>
<pre><code> def diff(row):
""" calculate absolute difference of this row """
return np.abs(row['I'] - row['Imean'])
spectrum['diff'] = spectrum.apply(diff, axi... | 2 | 2016-07-24T08:55:03Z | 38,550,487 | <p>IIUC you can do it this way:</p>
<pre><code>In [6]: df = pd.DataFrame(np.random.randint(0, 20, (10,2)), columns=['I', 'Imean'])
In [7]: df['diff'] = (df['I'] - df['Imean']).abs()
In [8]: df
Out[8]:
I Imean diff
0 2 9 7
1 9 1 8
2 18 11 7
3 6 19 13
4 5 12 7
5 ... | 1 | 2016-07-24T09:20:34Z | [
"python",
"numpy",
"pandas"
] |
How to TCP server serves forever? | 38,550,322 | <p><br></p>
<p>Hello everyone!</p>
<p>I'm new to python networking programming.</p>
<p>My development environments are as below.</p>
<ul>
<li>Windows 7</li>
<li>Python 3.4</li>
</ul>
<p>I am studying with "Python Network Programming Cookbook". In this book, there's an example of <strong>ThreadingMixIn</strong> soc... | -1 | 2016-07-24T08:57:19Z | 38,550,380 | <p>You will have to run on an infinite loop and on each loop wait for some data to come from client. This way the connection will be kept alive.</p>
<p>Same infinite loop for the server to accept more clients.</p>
<p>However, you will have to somehow detect when a client closes the connection with the server because ... | 0 | 2016-07-24T09:06:09Z | [
"python",
"network-programming"
] |
How to TCP server serves forever? | 38,550,322 | <p><br></p>
<p>Hello everyone!</p>
<p>I'm new to python networking programming.</p>
<p>My development environments are as below.</p>
<ul>
<li>Windows 7</li>
<li>Python 3.4</li>
</ul>
<p>I am studying with "Python Network Programming Cookbook". In this book, there's an example of <strong>ThreadingMixIn</strong> soc... | -1 | 2016-07-24T08:57:19Z | 38,550,548 | <p>Your program exits because your server thread is a daemon:</p>
<pre><code># Exit the server thread when the main thread exits
server_thread.daemon = True
</code></pre>
<p>You can either remove that line or add <code>server_thread.join()</code> at the bottom of the code to prevent the main thread from exiting early... | 1 | 2016-07-24T09:28:54Z | [
"python",
"network-programming"
] |
Random number generation with seeds | 38,550,345 | <p>So in games where you can create "random" worlds there is an option for seeds. The thing i don't understand is: how can you get the same outcome if you fill in the same seed? I would say you have to store every outcome but thats very hard to achieve. I've read something about PRNG(Pseudo random number generator). Ev... | -3 | 2016-07-24T09:01:09Z | 38,550,384 | <p>Just use <code>random.seed</code>:</p>
<pre><code>import random
random.seed(42)
random.random() # 0.6394267984578837
</code></pre>
<p>This program will always return that value as the first generated random number, because the seed is always the same.</p>
| 1 | 2016-07-24T09:06:38Z | [
"python"
] |
Random number generation with seeds | 38,550,345 | <p>So in games where you can create "random" worlds there is an option for seeds. The thing i don't understand is: how can you get the same outcome if you fill in the same seed? I would say you have to store every outcome but thats very hard to achieve. I've read something about PRNG(Pseudo random number generator). Ev... | -3 | 2016-07-24T09:01:09Z | 38,550,390 | <p>It's quite easy actually, firstly you have to import random library and then you juste have to set the seed manually using your game's seed value :</p>
<pre><code>import random
your_seed = 1234
random.seed(seed)
random.randint(1, 10)
</code></pre>
| 0 | 2016-07-24T09:07:41Z | [
"python"
] |
Random number generation with seeds | 38,550,345 | <p>So in games where you can create "random" worlds there is an option for seeds. The thing i don't understand is: how can you get the same outcome if you fill in the same seed? I would say you have to store every outcome but thats very hard to achieve. I've read something about PRNG(Pseudo random number generator). Ev... | -3 | 2016-07-24T09:01:09Z | 38,550,408 | <p>A PRNG does not create "random" number but always produces the same numbers when the same seed is used. Thus if you do something in dependence on these numbers you will always do the same when you enter the same seed.</p>
<p>In python the <code>random</code> module will take a seed, see <a href="https://docs.python... | 0 | 2016-07-24T09:10:28Z | [
"python"
] |
Random number generation with seeds | 38,550,345 | <p>So in games where you can create "random" worlds there is an option for seeds. The thing i don't understand is: how can you get the same outcome if you fill in the same seed? I would say you have to store every outcome but thats very hard to achieve. I've read something about PRNG(Pseudo random number generator). Ev... | -3 | 2016-07-24T09:01:09Z | 38,550,480 | <h2>How does a RNG end up generating the same sequence given the same seed?</h2>
<p>Let's take a trivial RNG implementation:</p>
<pre><code>class SillyRand:
"""Don't try this at home!"""
def __init__(self, seed):
self.current = self.calc(seed)
def get(self):
current_ = self.current
... | 1 | 2016-07-24T09:19:33Z | [
"python"
] |
Python - on windows, how to make all the files as zip? | 38,550,392 | <p>I have a folder <code>(C:\\Python27\\security_camera_snapshot\\)</code> where <code>image1.png 2.png 3.png .... 100.png</code> is stored. I need to make them in one.zip file and upload it to a NAS server.</p>
<p>But how can i do the compression of all those files in zip?</p>
| -2 | 2016-07-24T09:08:05Z | 38,550,416 | <p>Just use the zipfile library as in this example adapted for your usage : </p>
<pre><code>#!/usr/bin/env python
import os
import zipfile
def zipdir(path, ziph):
# ziph is zipfile handle
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file))
if... | 1 | 2016-07-24T09:11:38Z | [
"python",
"windows"
] |
web.py multiple parameters query not working | 38,550,400 | <p>I have created a web.py service.</p>
<p>Here is thet code:</p>
<pre><code>urls = ('/', 'index')
class index:
def GET(self):
user_data = web.input(url=[])
print (user_data)
</code></pre>
<p>This is the url that i try to open:</p>
<pre><code>http://webpy_server/?url=http://www.phonebook.com.pk... | 0 | 2016-07-24T09:09:11Z | 38,550,436 | <p>You need to escape the URL properly. It should be </p>
<pre><code>http://webpy_server/?url=http%3A//www.phonebook.com.pk/dynamic/search.aspx%3Fsearchtype%3Dcat%26class_id%3D4520%26page%3D1
</code></pre>
<p>The multiple question-marks are messing things up.</p>
<p>(Assuming that cat and the others are meant as pa... | 1 | 2016-07-24T09:13:59Z | [
"python",
"web.py"
] |
python selenium: element not visible in [weird] dropdown to be clicked | 38,550,477 | <p>There are two dropdown element code: one is standard option-select and the other is made of div, ul, li elements.</p>
<p>And somehow both are used to select a dropdown element via javascript...</p>
<p>Problem is selenium is not able to click the element and throws not visible exception.....</p>
<p>See the dropdow... | 0 | 2016-07-24T09:19:23Z | 38,550,773 | <p>It would be nice if you'd post your code, so we can see a bit clearer what's happening.
Also admitted, I did not check all of your links to see everything that doesn't work. However my guess is this:</p>
<p><em>If you get an <code>ElementNotVisible</code> exception, then you should probably make your element visib... | 0 | 2016-07-24T09:56:00Z | [
"python",
"selenium"
] |
How to bounce turtle off the canvas | 38,550,483 | <p>I am currently, learning Charles Dierbach's book, Introduction to Computer Science using Python.</p>
<p>I am trying to make my turtle bounce off the canvas but it does not work. I have tried different variations but have not being able to fix it</p>
<p>Here is my code:</p>
<pre><code> #Drunkard walk PYTHON
f... | 0 | 2016-07-24T09:20:07Z | 38,558,123 | <p>I've extracted a minimum example from your code and got it bouncing about the screen. The key changes are:</p>
<p>1) your routine that decides if the turtle should bounce off a wall shouldn't do anything if the turtle hasn't actually reached a wall -- but you return a new heading regardless</p>
<p>2) you shouldn'... | 0 | 2016-07-25T00:15:03Z | [
"python",
"function",
"graphics",
"turtle-graphics",
"bounce"
] |
CRC16-CCITT for binary file using python | 38,550,489 | <p>What is the maximum size of file that CRC16-CCITT calculates?</p>
<p>If I split the binary file on blocks of 256*1024, can I add the crc result of each block to determine the CRC of the whole file?</p>
<p>what is the criterias to choose CRC-16CCITT and CRC-32CCITT?</p>
| -1 | 2016-07-24T09:20:40Z | 38,551,761 | <p>CRC imposes no limit on file size. However your library should support feeding data in chunks to calculate crc. Simply adding CRC values of chunks won't work - you have to use CRC of preceding chunk as the starting value for next chunk CRC calculation and that needs to be support by your library.</p>
<p>E.g. <a hre... | 2 | 2016-07-24T11:59:48Z | [
"python",
"crc"
] |
Command completions are invisible in ipython 5.0 | 38,550,608 | <p>In ipython 5.0, the autocompletion function seems to be replaced by a new one.</p>
<p>Now "os.[tab]" does not display a list of possible commands, but seems to cycle through the module members. But while it does, it seems to display below the current line a list of possible members, but all but the currently select... | 4 | 2016-07-24T09:35:48Z | 38,554,161 | <p>On my terminal (Ubuntu linux) the completion list appears as black text on a gray background. Up/down keys scroll through this, with the current selection appearing on the <code>IN</code> line as well as highlighted with white text on dark gray. </p>
<p>Repeated tab also steps through the list (column by column).... | 1 | 2016-07-24T16:20:27Z | [
"python",
"terminal",
"ipython"
] |
Command completions are invisible in ipython 5.0 | 38,550,608 | <p>In ipython 5.0, the autocompletion function seems to be replaced by a new one.</p>
<p>Now "os.[tab]" does not display a list of possible commands, but seems to cycle through the module members. But while it does, it seems to display below the current line a list of possible members, but all but the currently select... | 4 | 2016-07-24T09:35:48Z | 38,575,512 | <p>Debian has a separate package <code>rxvt-unicode-256color</code> for the version with full color support. Using this version, the ipython colors are correct.</p>
| 1 | 2016-07-25T18:58:13Z | [
"python",
"terminal",
"ipython"
] |
Calling a function within a class instead of function using multiprocessing in Python | 38,550,733 | <p>In the Python <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">documentation on multiprocessing</a> there are numerous examples of parallelizing the work of a function. I assumed it would also be possible to do this of a function contained in a class. However the following example does... | 0 | 2016-07-24T09:50:05Z | 38,550,887 | <p>The serialization provided by the <code>Process</code> class is only one-way. It will serialize the <code>target</code> and <code>args</code> you give it, but it doesn't bring anything back automatically.</p>
<p>So when you create your <code>Process</code>es, the <code>multiprocessing</code> module pickles the <cod... | 1 | 2016-07-24T10:10:12Z | [
"python",
"multiprocessing"
] |
unable to stop thread from a module | 38,550,828 | <p>I need to be able to call a stop funtion of a running thread. I tried several ways to achieve this but so far no luck. I think I need a thread id but have no idea how this is done.</p>
<p>relevant code:
model:</p>
<pre><code>import MODULE
class do_it():
def __init__(self):
self.on_pushButton_start_clic... | 0 | 2016-07-24T10:02:35Z | 38,551,293 | <p>Regarding the <code>thread</code> module, this is what the docs say:</p>
<blockquote>
<p>This module provides low-level primitives for working with multiple
threads [â¦] The <code>threading</code> module provides an easier to use and
higher-level threading API built on top of this module.</p>
</blockquote>
... | 0 | 2016-07-24T10:58:14Z | [
"python",
"multithreading",
"class",
"web2py",
"python-module"
] |
Python pip2 fails - ImportError: No module named moves | 38,550,925 | <p>I can't run pip2, which is installed from its Arch Linux package:</p>
<pre><code>$ pip2
Traceback (most recent call last):
File "/usr/bin/pip2", line 5, in <module>
from pkg_resources import load_entry_point
File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 47, in <module>
... | 0 | 2016-07-24T10:15:32Z | 38,550,926 | <p>While I don't understand the issue, it is possible to reset it by removing locally (<code>--user</code>) installed packages:</p>
<p>Move all packages installed as the user:</p>
<pre><code>mv ~/.local/lib/python2.7/site-packages ~/site-packages-bak
</code></pre>
<p>or try to pinpoint the problematic files. In my c... | 0 | 2016-07-24T10:15:32Z | [
"python",
"pip"
] |
Dynamically generated field in SqlAlchemy model with Postgres | 38,550,984 | <p>I want to create a table with a column for each hour of the day of Float type.
How do I get rid of this verbose syntax:</p>
<pre><code>from app import db
class HourlySchedule(db.Model):
id = db.Column(
db.Integer,
primary_key=True
)
h0 = db.Column(db.Float, nullable=True)
h1 = db.... | 0 | 2016-07-24T10:22:21Z | 38,553,323 | <p>You may need to play around with the order of calling <code>super().__init__(*args, **kwargs)</code>, but this should theoretically work.</p>
<p>As for validation, the good thing about the <code>validates</code> decorator is that it takes multiple column names, so we can achieve dynamic field creation and validatio... | -1 | 2016-07-24T14:49:16Z | [
"python",
"flask",
"sqlalchemy",
"data-modeling"
] |
Dynamically generated field in SqlAlchemy model with Postgres | 38,550,984 | <p>I want to create a table with a column for each hour of the day of Float type.
How do I get rid of this verbose syntax:</p>
<pre><code>from app import db
class HourlySchedule(db.Model):
id = db.Column(
db.Integer,
primary_key=True
)
h0 = db.Column(db.Float, nullable=True)
h1 = db.... | 0 | 2016-07-24T10:22:21Z | 38,575,915 | <p>The key here is to realize that a <code>class</code> block is just a block of code, so you can put loops in there:</p>
<pre><code>class HourlySchedule(db.Model):
id = db.Column(db.Integer, primary_key=True)
for i in range(24):
locals()["h{}".format(i)] = db.Column(db.Float)
@validates(*("h{}".... | 0 | 2016-07-25T19:26:02Z | [
"python",
"flask",
"sqlalchemy",
"data-modeling"
] |
Strange behaviour: Same code, different errors | 38,551,016 | <p>I have to use packages tensorflow and pygame.</p>
<p>In my machine [Ubuntu 15.04][Anaconda, Python=2.7] I installed
pygame and tensorflow in the same environment.</p>
<p>Now, when I import tensorflow in the Python interpreter:</p>
<pre class="lang-none prettyprint-override"><code>>>> import tensorflow
</... | 0 | 2016-07-24T10:25:30Z | 38,551,099 | <p>Have you installed Anaconda in the correct way?</p>
<pre><code>$ conda install virtualenv
$ conda create --name=tensorflow_env python=2.7
$ source activate tensorflow_env
$ pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.5.0-cp27-none-linux_x86_64.whl
</code></pre>
<p>Maybe, ... | 0 | 2016-07-24T10:36:45Z | [
"python",
"python-2.7",
"pygame",
"tensorflow",
"development-environment"
] |
Strange behaviour: Same code, different errors | 38,551,016 | <p>I have to use packages tensorflow and pygame.</p>
<p>In my machine [Ubuntu 15.04][Anaconda, Python=2.7] I installed
pygame and tensorflow in the same environment.</p>
<p>Now, when I import tensorflow in the Python interpreter:</p>
<pre class="lang-none prettyprint-override"><code>>>> import tensorflow
</... | 0 | 2016-07-24T10:25:30Z | 38,634,839 | <p>try <code>$ sudo pip install tensorflow</code></p>
| 0 | 2016-07-28T11:18:36Z | [
"python",
"python-2.7",
"pygame",
"tensorflow",
"development-environment"
] |
Radio Button in Pygame? | 38,551,168 | <p>I want to know if there's a radio button in pygame or a module of it.
I'm making a questions game which requires radio buttons.</p>
| -1 | 2016-07-24T10:43:04Z | 38,625,795 | <p>I know how you feel man, I needed some radio buttons to. I have, however, been working on a checkbox in pygame. I'll post the code below if you want to use it:</p>
<pre><code>import pygame as pg
pg.init()
class Checkbox:
def __init__(self, surface, x, y, color=(230, 230, 230), caption="", outline_color=(0, 0,... | 0 | 2016-07-28T01:38:06Z | [
"python",
"python-2.7",
"pygame"
] |
Django Signal on relation update | 38,551,253 | <p>I have similar models:</p>
<pre><code>class Basket(model.Models):
pass
class Item(models.Model):
basket = models.ForeignKey(Basket, related_name='items')
</code></pre>
<p>I want to catch <code>Basket.items</code> update with Django Signal, but from Basket side, due to call signal once when multiple items... | 0 | 2016-07-24T10:53:51Z | 38,552,001 | <p>You can easily get the item object in your basket using <code>post_signal</code></p>
<pre><code>class Basket(model.Models):
pass
@classmethod
def item_added(self, **kargs):
print karts['instance']
class Item(models.Model):
basket = models.ForeignKey(Basket, related_name='items')
post_sav... | 0 | 2016-07-24T12:25:39Z | [
"python",
"django",
"django-signals"
] |
import my local module in python3 so it can i installed in the system via pip | 38,551,276 | <p>I have a directory structure as:</p>
<pre><code> tree
.
âââ bin
â  âââ mkbib.py
âââ LICENSE
âââ mkbib
â  âââ __init__.py #empty file
â  âââ menubar.ui #a xml file. where should I place it?
â  âââ menu.py... | 0 | 2016-07-24T10:56:30Z | 38,551,927 | <p>This is one of Python's quirks: setting up paths to modules and packages. In your case, after you install the <code>mkbib</code> package <code>bin/mkbib.py</code> should simply have:</p>
<pre><code>import mkbib
</code></pre>
<p>without any changes to <code>PYTHONPATH</code>. This is because <code>bin/mkbib.py</cod... | 0 | 2016-07-24T12:17:11Z | [
"python",
"python-3.x",
"setuptools",
"setup.py"
] |
Returning value from thread in python without blocking main thread | 38,551,298 | <p>I have got an XMLRPC server and client runs some functions on server and gets returned value. If the function executes quickly then everything is fine but I have got a function that reads from file and returns some value to user. Reading takes about minute(there is some complicated stuff) and when one client runs th... | 0 | 2016-07-24T10:58:55Z | 38,553,796 | <p>Yes, using the <code>threading</code> module you can spawn new threads. See the <a href="https://docs.python.org/2/library/threading.html" rel="nofollow">documentation</a>. An example would be this:</p>
<pre><code>import threading
import time
def main():
print("main: 1")
thread = threading.Thread(target=th... | -1 | 2016-07-24T15:40:18Z | [
"python",
"multithreading",
"server",
"xml-rpc"
] |
Running Python code from an IDLE editor window | 38,551,393 | <p>I've programmed a bit in Python for the last few days and everything has worked fine up until yesterday. Whenever I try to run a script now the shell only responds with the message RESTART and a path to where my script is stored. Here's an image:</p>
<p><a href="http://i.stack.imgur.com/H4t9U.png" rel="nofollow"><i... | 1 | 2016-07-24T11:11:19Z | 38,551,658 | <p>That's because your <code>testprog.py</code> doesn't actually output anything. Try changing it to <code>print(5 + 5)</code> or something similar, currently it only computes <code>5+5</code> and then it exits.</p>
| -1 | 2016-07-24T11:47:07Z | [
"python",
"python-idle"
] |
Running Python code from an IDLE editor window | 38,551,393 | <p>I've programmed a bit in Python for the last few days and everything has worked fine up until yesterday. Whenever I try to run a script now the shell only responds with the message RESTART and a path to where my script is stored. Here's an image:</p>
<p><a href="http://i.stack.imgur.com/H4t9U.png" rel="nofollow"><i... | 1 | 2016-07-24T11:11:19Z | 38,555,821 | <p>Except for the RESTART line, the behavior you see has nothing to do with IDLE. Run any program (without IDLE) that does not print anything with the '-i' option and you will see the same thing -- a '>>> ' prompt.</p>
<pre><code>C:\Users\Terry>type testprog.py
5+5
C:\Users\Terry>python -i testprog.py
>>... | 0 | 2016-07-24T19:17:59Z | [
"python",
"python-idle"
] |
Selenium Python Script throws no element error exception even though the x path is right? | 38,551,400 | <pre><code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
driver=webdriver.Chrome()
driver.get("https://paytm.com/")
driver... | 2 | 2016-07-24T11:12:07Z | 38,551,604 | <p>You should try using <code>WebDriverWait</code> to wait until <code>input</code> element visible on the page as below :-</p>
<pre><code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdr... | 0 | 2016-07-24T11:39:12Z | [
"python",
"python-2.7",
"selenium",
"selenium-webdriver",
"selenium-chromedriver"
] |
Selenium Python Script throws no element error exception even though the x path is right? | 38,551,400 | <pre><code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
driver=webdriver.Chrome()
driver.get("https://paytm.com/")
driver... | 2 | 2016-07-24T11:12:07Z | 38,551,909 | <p>In selenium each frame is treated individually. Since the login is in a separate <code>iframe</code> element, you need to switch to it first using:</p>
<pre><code>iframe = driver.find_elements_by_tag_name('iframe')[0]
driver.switch_to_frame(iframe)
</code></pre>
<p><strong>Before</strong> trying to interact with ... | 3 | 2016-07-24T12:15:38Z | [
"python",
"python-2.7",
"selenium",
"selenium-webdriver",
"selenium-chromedriver"
] |
Can a user access data from a context_dict? | 38,551,432 | <p>My <code>models.py</code>:</p>
<pre><code>class Mymodel(models.Model):
title = models.CharField(max_length=32)
other_useful_field = models.CharField(max_length=32)
...
secret_field = models.CharField(max_length=32)
</code></pre>
<p>My <code>views.py</code>:</p>
<pre><code>def myview(request):
... | 0 | 2016-07-24T11:15:48Z | 38,551,806 | <p>The template is rendered on the server and output as HTML for the user to see. The user never sees the raw template. As long as your server is secure you have nothing to worry about.</p>
| 1 | 2016-07-24T12:04:58Z | [
"python",
"django-templates"
] |
i can not get the body element of html page in web scrapping by python | 38,551,466 | <p>I would like to parse a website with urllib python library. I wrote this:</p>
<pre><code>from bs4 import BeautifulSoup
from urllib.request import HTTPCookieProcessor, build_opener
from http.cookiejar import FileCookieJar
def makeSoup(url):
jar = FileCookieJar("cookies")
opener = build_opener(HTTPCookiePro... | 0 | 2016-07-24T11:19:43Z | 38,551,530 | <p>The page is using JavaScript to check the cookie and to generate the content. However, <code>urllib</code> does not process JavaScript and thus the page shows nothing. </p>
<p>You'll either need to use something like <a href="http://selenium-python.readthedocs.io" rel="nofollow">Selenium</a> that acts as a browser ... | 0 | 2016-07-24T11:28:02Z | [
"python",
"cookies",
"web"
] |
Error with pip install MySQLdb library | 38,551,513 | <p>In python 2.7.10, Windows OS.
Could not find a version that satisfies the requirement mysqldb(from version)
no matching distribution found for mysqldb</p>
<p><strong>pip install MySQL-python also failed:</strong> Unable to find vcvarsall.bat and many other errors if I am patching solution for this one. </p>
| 1 | 2016-07-24T11:25:20Z | 38,551,703 | <p>Building Python libraries on Windows can be challenging.</p>
<p>This message <a href="https://stackoverflow.com/questions/2817869/error-unable-to-find-vcvarsall-bat">indicates that the Visual C++ compiler cannot be found</a>:</p>
<blockquote>
<p>Unable to find vcvarsall.bat</p>
</blockquote>
<p>You could instal... | 1 | 2016-07-24T11:52:47Z | [
"python",
"python-2.7",
"mysql-python"
] |
Seperate RSS feed link/s | 38,551,570 | <p>I am using the feedparser module to create a news feed in my program.</p>
<p>The Yahoo! Finance API link element actually has two links: the Yahoo link, and the actual article link (external site/source). The two are separated by an asterisks, with the following being an example:</p>
<p>'<a href="http://us.rd.yaho... | 0 | 2016-07-24T11:34:23Z | 38,551,640 | <p>You can split this the following way:</p>
<pre><code>link = 'http://us.rd.yahoo.com/finance/external/investors/rss/SIG=12shc077a/*http://www.investors.com/news/technology/click/pokemon-go-hurting-facebook-snapchat-usage/'
rss_link, article_link = link.split('*')
</code></pre>
<p>Keep in mind that this requires th... | 0 | 2016-07-24T11:44:10Z | [
"python",
"python-3.x",
"rss",
"feedparser"
] |
How to avoid repeating "from . import class_name" when "." is actually referring to an invalid identifier? | 38,551,694 | <p>Say I have the very simple folder architecture below when working with a PyCharm project:</p>
<pre class="lang-none prettyprint-override"><code>- 1 - Something
- scripta.py
- scriptb.py
- dummyclass.py
</code></pre>
<p>Since <code>1 - Something</code> is an invalid identifier I have to use something like ... | 0 | 2016-07-24T11:51:15Z | 38,551,829 | <p>I'm not sure why the directory can't be renamed - if it's someone else's codebase it's just as invalid for them as it is for you. But assuming you can't, one solution is to put that directory directly on the Python path; either from outside Python by adding it to the PYTHONPATH environment variable, or from inside b... | 1 | 2016-07-24T12:07:43Z | [
"python",
"python-3.x",
"module",
"package"
] |
How to do time diff in each group on Pandas in Python | 38,551,749 | <p>Here's the phony data:</p>
<pre><code>df = pd.DataFrame({'email': ['u1','u1','u1','u2','u2','u2'],
'timestamp': [3, 1, 5, 11, 15, 9]})
</code></pre>
<p>What I intend to retrieve is the time diff in each group of email. Thus, after sorting by timestamp in each group, the data should be:</p>
<pre><cod... | 0 | 2016-07-24T11:58:28Z | 38,551,811 | <pre><code>df = pd.DataFrame({'email': ['u1','u1','u1','u2','u2','u2'],
'timestamp': [3, 1, 5, 11, 15, 9]})
(df.sort_values(['email', 'timestamp'], ascending=[True, False])
.groupby('email')['timestamp']
.diff(-1)
.dropna())
Out:
2 2.0
0 2.0
4 4.0
3 2.0
Name: timestamp, dtype: float6... | 3 | 2016-07-24T12:05:21Z | [
"python",
"pandas",
"group-by"
] |
How to access 1 cell in a DataFrame that has a Float64 as index? (Python3) | 38,551,769 | <p>Newbie here, I have csv file with rows that I want to index by a UNIQUE float</p>
<pre><code>"GOOGL @ 759.28"
"August 19 2016 Calls","","","","","","","","","","August 19 2016 Puts"
,"IV","Delta","Open Int","Vol","Change","Last","Bid","Ask","Strike","Bid","Ask","Last","Change","Vol","Open Int","Delta","IV"
,"85.67"... | 0 | 2016-07-24T12:01:03Z | 38,553,319 | <p>Try this:</p>
<pre><code>import numpy as np
import pandas as pd
def read_csv_file(pathToFile="options.csv"):
return pd.read_csv(pathToFile, header=2,
dtype={"Strike":np.float}, index_col="Strike",
usecols=["Strike","Bid","Ask","Bid.1","Ask.1"],
... | 0 | 2016-07-24T14:49:02Z | [
"python",
"pandas",
"dataframe"
] |
How to access 1 cell in a DataFrame that has a Float64 as index? (Python3) | 38,551,769 | <p>Newbie here, I have csv file with rows that I want to index by a UNIQUE float</p>
<pre><code>"GOOGL @ 759.28"
"August 19 2016 Calls","","","","","","","","","","August 19 2016 Puts"
,"IV","Delta","Open Int","Vol","Change","Last","Bid","Ask","Strike","Bid","Ask","Last","Change","Vol","Open Int","Delta","IV"
,"85.67"... | 0 | 2016-07-24T12:01:03Z | 38,556,643 | <p>Ok, I "RTFM" (<a href="http://pandas.pydata.org/pandas-docs/stable/10min.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/10min.html</a>) and noticed that I had to explicitly say that I want to compare the value in the Column 'Strike' and that will give me the series.</p>
<p>Here is my new code:</p>... | 0 | 2016-07-24T20:50:07Z | [
"python",
"pandas",
"dataframe"
] |
How do I put variable in a list slicing operation? | 38,551,817 | <p>I have a list in a function, and I want to sometimes use the whole thing, sometimes just a section depending on an offset variable. Sometimes I want to apply the offset to the start, sometimes the end.</p>
<p>I know </p>
<pre><code>my_list = my_list[:]
</code></pre>
<p>will give me just the same list, and </p>
... | 3 | 2016-07-24T12:06:19Z | 38,551,874 | <p>Python supports negative offsets to specify distance from the end of the list (-1 is the last character), so if you have something like:</p>
<pre><code>s = "Hello world!"
print(s[:-6])
</code></pre>
<p>It will print <code>Hello</code>.</p>
<p>You can also do:</p>
<pre><code>s = "Hello world!"
print(s[-5:])
</cod... | 0 | 2016-07-24T12:12:16Z | [
"python",
"list",
"slice"
] |
How do I put variable in a list slicing operation? | 38,551,817 | <p>I have a list in a function, and I want to sometimes use the whole thing, sometimes just a section depending on an offset variable. Sometimes I want to apply the offset to the start, sometimes the end.</p>
<p>I know </p>
<pre><code>my_list = my_list[:]
</code></pre>
<p>will give me just the same list, and </p>
... | 3 | 2016-07-24T12:06:19Z | 38,551,884 | <p>You can't sum None.
However, you can sum to other numbers like 0 (start) and <code>len(my_list)</code> (End)</p>
<pre><code>my_list = [1,2,3,4,5,7,8,9,10]
print(my_list)
my_list = my_list[:]
print(my_list)
start1 = None
end1 = None
my_list = my_list[start1:end1]
print(my_list)
##################################... | 1 | 2016-07-24T12:13:07Z | [
"python",
"list",
"slice"
] |
Big data methods: Iterative (chunk-wise) computation of data moments | 38,551,864 | <p>I'm having data in the terabytes. Therefore, standard <code>pandas</code> and <code>numpy</code> procedures (<code>group-by</code>, <code>mean</code>, <code>histogram</code> etc.) will not work when I can't load in all the data at the same time. </p>
<p>My data will come from <a href="http://pandas.pydata.org/panda... | 1 | 2016-07-24T12:11:10Z | 38,551,929 | <p>for the average (<code>mean</code>) it can be done like this:</p>
<pre><code>i, cumsum = 0
for chunk in store.select('key', chunksize=N):
cumsum += chunk['variable'].sum()
i += len(chunk)
my_mean = cumsum / i
</code></pre>
<p>As a <em>general</em> approach i would go for an Apache Spark on Hadoop Cluster ... | 0 | 2016-07-24T12:17:23Z | [
"python",
"numpy",
"pandas",
"scipy",
"hdf5"
] |
Why is function not changing global variable even after specifying global | 38,551,905 | <p>I have recently started programming. Everything is working fine but this piece of code intriguing me from a long time. </p>
<p>Here is my code.</p>
<pre><code>addon = 20
startup = 50 + addon
def click():
global addon, startup
addon *= 2
print addon, startup
click()
click()
click()
click()
click()
cl... | -2 | 2016-07-24T12:15:10Z | 38,552,112 | <p><code>startup</code> does not store an <em>expression</em>, it stores the <em>result</em> of an expression, <strong>once</strong>.</p>
<p>In other words, the variable <code>startup</code> references the <em>result</em> of <code>50 + addon</code>, which at the time is the integer <code>70</code>.</p>
<p>That <code>... | 1 | 2016-07-24T12:39:03Z | [
"python",
"python-2.7",
"global-variables"
] |
Get country name from Country code in python? | 38,551,958 | <p>I have worked with 2 python libraries: <a href="https://pypi.python.org/pypi/phonenumbers" rel="nofollow">phonenumbers</a>, <a href="https://pypi.python.org/pypi/pycountry" rel="nofollow">pycountry</a>. I actually could not find a way to give just country code and get its corresponding country name.</p>
<p>In <code... | 1 | 2016-07-24T12:20:39Z | 38,552,310 | <p>The <code>phonenumbers</code> library is rather under-documented; instead they advice you to look a the original Google project for unittests to learn about functionality.</p>
<p>The <a href="https://github.com/googlei18n/libphonenumber/blob/master/java/libphonenumber/test/com/google/i18n/phonenumbers/PhoneNumberUt... | 4 | 2016-07-24T12:59:08Z | [
"python",
"phone-number"
] |
Django - Registration form can't upload image | 38,552,028 | <p>I am a beginner with Django. I have a problem when I am filling the registration form. I can't upload any image.
If the ImageField is set to required=true, it's never validated, impossible to submit.
If required=false, it's possible to submit it but the image is never saved in destination folder (model).
However, ... | 0 | 2016-07-24T12:28:51Z | 38,552,790 | <p>You have to add request.FILES in form class</p>
<pre><code>form = UserRegistrationForm(request.POST)
</code></pre>
<p>And also <code>form.post = request.FILES['photo']</code></p>
| 0 | 2016-07-24T13:55:36Z | [
"python",
"django",
"forms"
] |
How to scan a panda dataframe for all values greater than something and returns row and column number corresponding to that value? | 38,552,055 | <p>I have a problem where I have huge data set like below (Correl Coeef matrix)</p>
<pre><code> A B C D E
A 1, 0.413454352,0.615350574,0.479720098,0.34261232
B 0.413454352,1, 0.568124328,0.316543449,0.361164436
C 0.615350574,0.568124328,1, 0.633182519... | 3 | 2016-07-24T12:31:18Z | 38,552,230 | <p><strong>UPDATE:</strong> using <a href="http://stackoverflow.com/a/38552281/5741205">@Divakar's solution</a> and <a href="http://stackoverflow.com/questions/38552055/how-to-scan-a-panda-dataframe-for-all-values-greater-than-something-and-returns/38552230?noredirect=1#comment64505165_38552230">his hints</a>:</p>
<pr... | 1 | 2016-07-24T12:51:34Z | [
"python",
"pandas",
"dataframe"
] |
How to scan a panda dataframe for all values greater than something and returns row and column number corresponding to that value? | 38,552,055 | <p>I have a problem where I have huge data set like below (Correl Coeef matrix)</p>
<pre><code> A B C D E
A 1, 0.413454352,0.615350574,0.479720098,0.34261232
B 0.413454352,1, 0.568124328,0.316543449,0.361164436
C 0.615350574,0.568124328,1, 0.633182519... | 3 | 2016-07-24T12:31:18Z | 38,552,281 | <p>Here's a NumPy based approach -</p>
<pre><code># Extract values and row, column names
arr = df.values
index_names = df.index
col_names = df.columns
# Get indices where such threshold is crossed; avoid diagonal elems
R,C = np.where(np.triu(arr,1)>0.6)
# Arrange those in columns and put out as a dataframe
out_a... | 3 | 2016-07-24T12:56:30Z | [
"python",
"pandas",
"dataframe"
] |
How can I periodically change a tkinter image? | 38,552,086 | <p>I have an image that is saved in a file <code>test.bmp</code> and this file is overwritten 2 times per second<br>
(I want to show 2 images per second).</p>
<p>Here is what I have so far:</p>
<pre><code>import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
img_path = 'test.bmp'
img = ImageTk.PhotoImag... | 1 | 2016-07-24T12:35:33Z | 38,555,487 | <p>Gee, the code in your question looks very <a href="http://stackoverflow.com/a/38527334/355230">familiar</a>...</p>
<p>Coming up with an answer comprised of tested code was complicated by the need to have the image file be updated by some mysterious unspecified process. This is done in the code below by creating a s... | 1 | 2016-07-24T18:39:35Z | [
"python",
"image",
"python-3.x",
"tkinter"
] |
how to know which environment running unit tests in django works on | 38,552,131 | <h1>Question</h1>
<p>I want to separate my prod settings from my local settings. I found this library <a href="https://github.com/sobolevn/django-split-settings" rel="nofollow">django-split-settings</a>, which worked nicely. </p>
<p>However somewhere in my code I have something like this:</p>
<pre><code>if settings.... | 1 | 2016-07-24T12:41:34Z | 38,552,177 | <p><code>--settings</code> is <code>The Python path to a settings module</code>. So <code>bx</code> is your root project folder and settings.py file is there then </p>
<blockquote>
<p>./run ./manage.py test --settings="bx"</p>
</blockquote>
| 0 | 2016-07-24T12:46:25Z | [
"python",
"django",
"unit-testing"
] |
how to know which environment running unit tests in django works on | 38,552,131 | <h1>Question</h1>
<p>I want to separate my prod settings from my local settings. I found this library <a href="https://github.com/sobolevn/django-split-settings" rel="nofollow">django-split-settings</a>, which worked nicely. </p>
<p>However somewhere in my code I have something like this:</p>
<pre><code>if settings.... | 1 | 2016-07-24T12:41:34Z | 38,553,153 | <p>Django test, by default, set DEBUG = False</p>
<p><a href="https://docs.djangoproject.com/en/1.9/topics/testing/overview/#other-test-conditions" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/testing/overview/#other-test-conditions</a></p>
| 0 | 2016-07-24T14:31:01Z | [
"python",
"django",
"unit-testing"
] |
Variable changing by itself inside loop | 38,552,163 | <p>I have a python <code>for</code> loop that seems to have a variable changing of its own accord inside the loop. My variables are defined as:</p>
<pre><code>yhat = np.empty((1,len(prices)))
yhat[:] = nan
yhat = yhat.astype('float')
e = Q = yhat
P = R = np.matrix(np.zeros((2,2)))
B = np.empty((2,len(prices)))
B[:] =... | 0 | 2016-07-24T12:44:42Z | 38,552,187 | <p><code>e = Q = yhat</code> won't create copies. They are instead additional <em>references to the same object</em>. Altering that object through either the <code>e</code> or <code>Q</code> names will reflect in those changes being visible through the <code>yhat</code> reference too.</p>
<p>So</p>
<pre><code>yhat[0,... | 3 | 2016-07-24T12:47:03Z | [
"python",
"loops",
"variables",
"matrix"
] |
How to pass echo y to plink.exe for first connection | 38,552,236 | <p>I would like to pass <code>echo y</code> to plink.exe, so that plink execute a command.
How it can be achieved?</p>
<pre><code>os.system(' c:/netapp/python/plink.exe admin@192.168.1.1 -pw xxx uptime > c:/netapp/python/12.txt')
</code></pre>
<blockquote>
<p>The server's host key is not cached in the registry.... | 0 | 2016-07-24T12:52:18Z | 38,552,455 | <p>Confirming a server's SSH key fingerprint is an important step. This is how you know you've connected to the correct machine, and should always be done with care.</p>
<p>The Plink documentation <a href="http://the.earth.li/~sgtatham/putty/0.67/htmldoc/Chapter7.html#plink-usage-batch" rel="nofollow">makes the follow... | 0 | 2016-07-24T13:17:43Z | [
"python",
"plink"
] |
How to pass echo y to plink.exe for first connection | 38,552,236 | <p>I would like to pass <code>echo y</code> to plink.exe, so that plink execute a command.
How it can be achieved?</p>
<pre><code>os.system(' c:/netapp/python/plink.exe admin@192.168.1.1 -pw xxx uptime > c:/netapp/python/12.txt')
</code></pre>
<blockquote>
<p>The server's host key is not cached in the registry.... | 0 | 2016-07-24T12:52:18Z | 38,572,722 | <p><strong>Do not!</strong></p>
<p>Verifying host key fingerprint is an integral part of securing your connection. Blindly accepting any host key will make you vulnerable to the <a href="https://en.wikipedia.org/wiki/Man-in-the-middle_attack" rel="nofollow">man-in-the-middle attacks</a>.</p>
<hr>
<p>Instead, use the... | 2 | 2016-07-25T16:12:58Z | [
"python",
"plink"
] |
change urlparse.path of a url | 38,552,253 | <p>Here is the python code:</p>
<pre><code>url = http://www.phonebook.com.pk/dynamic/search.aspx
path = urlparse(url)
print (path)
>>>ParseResult(scheme='http', netloc='www.phonebook.com.pk', path='/dynamic/search.aspx', params='', query='searchtype=cat&class_id=4520&page=1', fragment='')
print (pat... | 1 | 2016-07-24T12:53:34Z | 38,552,680 | <p>I've tried to look into <code>urlparse</code> to find any method that could help in your situation, but didn't find, may be overlooked, but anyway, at this level, you probably would have to make your own method or hack:</p>
<pre><code>>>> path.path
'/dynamic/search.aspx'
>>> import re
>>>... | 1 | 2016-07-24T13:44:22Z | [
"python",
"python-3.x",
"urlparse"
] |
instantiate object (codecademy) | 38,552,285 | <p>I typed the following code, printed the answers I was supposed to get (3 and True), but it keeps giving me an error, asking me if I "Created an instance in class Triangle called my_triangle". How can this be, if I in fact did intantiate my_triangle and even got the correct results with it?</p>
<pre><code>class Tria... | -1 | 2016-07-24T12:56:50Z | 38,552,309 | <p>Your indentation is wrong. The last three lines need to be aligned all the way to the left.</p>
| 1 | 2016-07-24T12:59:05Z | [
"python"
] |
Does numpy methods work correctly on numbers too big to fit numpy dtypes? | 38,552,392 | <p>I would like to know if numbers bigger than what int64 or float128 can be correctly processed by numpy functions
EDIT: numpy functions applied to numbers/python objects outside of any numpy array. Like using a np function in a list comprehension that applies to the content of a list of int128?</p>
<p>I can't find ... | 0 | 2016-07-24T13:09:40Z | 38,552,519 | <p>You can have numpy arrays of python objects, which could be a python integer which is too big to fit in np.int64. Some of numpy's functionality will work, but many functions call underlying c code which will not work. Here is an example:</p>
<pre><code>import numpy as np
a = np.array([123456789012345678901234567890... | 1 | 2016-07-24T13:25:35Z | [
"python",
"numpy",
"int",
"precision"
] |
Does numpy methods work correctly on numbers too big to fit numpy dtypes? | 38,552,392 | <p>I would like to know if numbers bigger than what int64 or float128 can be correctly processed by numpy functions
EDIT: numpy functions applied to numbers/python objects outside of any numpy array. Like using a np function in a list comprehension that applies to the content of a list of int128?</p>
<p>I can't find ... | 0 | 2016-07-24T13:09:40Z | 38,552,523 | <p>When storing a number into a numpy array with a dtype not sufficient to store it, you will get truncation or an error</p>
<pre><code>arr = np.empty(1, dtype=np.int64)
arr[0] = 2**65
arr
</code></pre>
<p>Gives <code>OverflowError: Python int too large to convert to C long</code>.</p>
<pre><code>arr = np.empty(1, d... | 1 | 2016-07-24T13:26:17Z | [
"python",
"numpy",
"int",
"precision"
] |
Does numpy methods work correctly on numbers too big to fit numpy dtypes? | 38,552,392 | <p>I would like to know if numbers bigger than what int64 or float128 can be correctly processed by numpy functions
EDIT: numpy functions applied to numbers/python objects outside of any numpy array. Like using a np function in a list comprehension that applies to the content of a list of int128?</p>
<p>I can't find ... | 0 | 2016-07-24T13:09:40Z | 38,552,699 | <p>See the Extended Precision heading in the Numpy documentation <a href="http://docs.scipy.org/doc/numpy/user/basics.types.html" rel="nofollow">here</a>. For very large numbers, you can also create an array with <code>dtype</code> set to <code>'object'</code>, which will allow you essentially to use the Numpy framewor... | 1 | 2016-07-24T13:46:04Z | [
"python",
"numpy",
"int",
"precision"
] |
How can I load a text file as array that can be loaded element by element? | 38,552,418 | <p>I have a text file with the following information:</p>
<pre><code>SHRO
BJRD
ZNJK
GRMI
</code></pre>
<p>I want to save them in a way that I can load them line by line. I mean, suppose its name is "name", and I want the 4th column like below:</p>
<pre><code>name[3] = "GRMI"
</code></pre>
<p>How can I do this? </p>... | 0 | 2016-07-24T13:13:00Z | 38,552,561 | <p>You could do something like this:</p>
<pre><code>with open('filename.txt') as f:
name = f.read().split()
</code></pre>
<p>EDIT<br>
According to that answer you've posted, I understand that you simply need to print the name in a line and so, the modified code will be this:</p>
<pre><code>with open('filename.tx... | 3 | 2016-07-24T13:30:49Z | [
"python"
] |
How can I load a text file as array that can be loaded element by element? | 38,552,418 | <p>I have a text file with the following information:</p>
<pre><code>SHRO
BJRD
ZNJK
GRMI
</code></pre>
<p>I want to save them in a way that I can load them line by line. I mean, suppose its name is "name", and I want the 4th column like below:</p>
<pre><code>name[3] = "GRMI"
</code></pre>
<p>How can I do this? </p>... | 0 | 2016-07-24T13:13:00Z | 38,553,041 | <p>You probably want something like</p>
<pre><code>with open('stationlist', 'r') as f:
station_names = [line.split()[0] for line in f]
</code></pre>
<p>If all of the station names are four characters, the list comprehension could be replaced by</p>
<pre><code>[line[:4] for line in f]
</code></pre>
| 0 | 2016-07-24T14:21:14Z | [
"python"
] |
Scrapy - input processor | 38,552,506 | <p>items.py:</p>
<pre><code>import scrapy
from scrapy.loader.processors import MapCompose
def filter_spaces(value):
return value.strip(" ").strip("\n")
class LotItem(scrapy.Item):
num = scrapy.Field(input_processor=MapCompose(filter_spaces))
</code></pre>
<p>spider.py:</p>
<pre><code>def parse_item(self, r... | 1 | 2016-07-24T13:25:11Z | 38,556,992 | <p>You can use response.xpath with a regular expression instead of extract(). Something like this for the number:</p>
<pre><code>response.xpath("//div/span/text()").re(r"(?:'num':\s'\\n)([0-9]*)(?:\s*')")
</code></pre>
<p>or something like this for the city:</p>
<pre><code>.re(r'(?:\\"city\\":\s\"G\\\)(.*)(?:\\")')
... | 1 | 2016-07-24T21:29:15Z | [
"python",
"scrapy"
] |
Python SQLite update error | 38,552,571 | <p>I'm writing some scoring server using python and sqlite, and error occured when using update. </p>
<pre><code>Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from server import *
>... | 0 | 2016-07-24T13:32:16Z | 38,552,769 | <p>You are interpolating column values as <em>SQL object names</em>, with no quoting:</p>
<pre><code>update_score_str = "UPDATE score SET {0} = {1} WHERE USER_ID = {2}".format(songID, score, cardID)
musica_db.execute(update_score_str)
</code></pre>
<p>Don't use string interpolation for SQL <em>values</em>. Use bind p... | 1 | 2016-07-24T13:53:47Z | [
"python",
"python-2.7",
"sqlite3"
] |
How Django authnetication works with SQL Server? | 38,552,624 | <p>Just wanted to understand how exactly Python Django works with databases such as SQL Server or MySql.</p>
<p>For example, in ASP.NET WebForms, you'll have a <code>UserID</code> field from your custom <code>User</code> table that you link with the default <code>aspnet_Users</code> table. That's what connects your da... | 1 | 2016-07-24T13:38:12Z | 38,553,102 | <p>Django is consider a "batteries included" framework. Django has a robust ORM and build in system for user management. In specifics to users and authentication and authorization, Django has an out-of-the-box user model with fields for username, password, first name, last name, and email address; it also has facilitie... | 0 | 2016-07-24T14:26:16Z | [
"python",
"mysql",
"asp.net",
"sql-server",
"django"
] |
Pandas gives an error from str.extractall('#') | 38,552,688 | <p>I am trying to filter all the <code>#</code> keywords from the tweet text. I am using <code>str.extractall()</code> to extract all the keywords with <code>#</code> keywords.
This is the first time I am working on filtering keywords from the tweetText using pandas. Inputs, code, expected output and error are given ... | 2 | 2016-07-24T13:45:14Z | 38,553,194 | <p>The <code>extractall</code> function requires a regex pattern <strong>with capturing groups</strong> as the first argument, for which you have provided <code>#</code>.</p>
<p>A possible argument could be <code>(#\S+)</code>. The braces indicate a capture group, in other words what the <code>extractall</code> functi... | 2 | 2016-07-24T14:35:02Z | [
"python",
"pandas"
] |
Pandas gives an error from str.extractall('#') | 38,552,688 | <p>I am trying to filter all the <code>#</code> keywords from the tweet text. I am using <code>str.extractall()</code> to extract all the keywords with <code>#</code> keywords.
This is the first time I am working on filtering keywords from the tweetText using pandas. Inputs, code, expected output and error are given ... | 2 | 2016-07-24T13:45:14Z | 38,553,531 | <p>If you are not too tied to using <code>extractall</code>, you can try the following to get your final output:</p>
<pre><code>from io import StringIO
import pandas as pd
import re
data_text = """userID,tweetText
01, home #sweet home
01, #happy #life
02, #world peace
03, #all are one
"""
data = pd.read_csv(String... | 2 | 2016-07-24T15:12:11Z | [
"python",
"pandas"
] |
Pandas gives an error from str.extractall('#') | 38,552,688 | <p>I am trying to filter all the <code>#</code> keywords from the tweet text. I am using <code>str.extractall()</code> to extract all the keywords with <code>#</code> keywords.
This is the first time I am working on filtering keywords from the tweetText using pandas. Inputs, code, expected output and error are given ... | 2 | 2016-07-24T13:45:14Z | 38,554,554 | <p>Try this: </p>
<p>Since it filters for '#', your NAN should not exist. </p>
<pre><code> data = pd.read_csv(StringIO(data_text),header=0, index_col=0 )
data = data["tweetText"].str.split(' ', expand=True).stack().reset_index().rename(columns = {0:"tweetText"}).drop('level_1', 1)
data = data[data['tweetTe... | 0 | 2016-07-24T17:04:28Z | [
"python",
"pandas"
] |
python BeautifulSoap table scraping | 38,552,722 | <p>my HTML has several tables, the first table is:</p>
<pre><code><table>
<tr>
<td>
<div id="string">
</div>
</td>
</tr>
</table>
</code></pre>
<p>and the rest are of the form:</p>
<pre><code><table class="confluenceTa... | 1 | 2016-07-24T13:49:31Z | 38,552,982 | <p>I suspect you are trying to scrape an <em>Atlassian Confluence</em> page which is usually quite dynamic and makes use of JavaScript intensively to load the page. If you look into the HTML source you download with <code>urllib</code> you would not find <code>table</code> elements with <code>confluenceTable</code> cla... | 2 | 2016-07-24T14:16:02Z | [
"python",
"beautifulsoup"
] |
How to improve the performance of this Python code? | 38,552,736 | <p>Is there any way I can improve the Python code I attached below? It seems too slow for me now.</p>
<pre><code>C_abs = abs(C)
_, n = C_abs.shape
G = np.zeros((n, n))
for i in xrange(n):
for j in xrange(n):
G[i,j] = C_abs[i,j]+C_abs[j,i]
</code></pre>
| 4 | 2016-07-24T13:51:02Z | 38,552,762 | <p>Just add <code>C_abs</code> with its <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html" rel="nofollow"><code>transposed version</code></a> -</p>
<pre><code>G = C_abs + C_abs.T
</code></pre>
<p>To understand, look at the computation part of the code :</p>
<pre><code>G[i,j] = C_abs[i... | 6 | 2016-07-24T13:53:21Z | [
"python",
"performance",
"numpy",
"scipy"
] |
Django: item extendable discount calculation | 38,552,851 | <p>I'm thinhking about e-shop django skeleton.</p>
<pre><code># models.py
class Category(models.Model):
name = models.CharField()
discount = models.DecimalField()
class Product(models.Model):
name = models.CharField()
price = models.DecimalField()
category = models.ForeignKey(Category)
discou... | 0 | 2016-07-24T14:02:11Z | 38,554,249 | <p>You could make a method that checks all of your model's fields for 2 conditions: 1.) that the field is a <code>ForeignKey</code> and 2.) that the model it references has a <code>discount</code> attribute. If both are true, the method adds the value of the <code>reference_model.discount</code> to an array of discount... | 0 | 2016-07-24T16:30:33Z | [
"python",
"django",
"oop",
"e-commerce"
] |
Getting Attribute error while Checking model | 38,553,132 | <p>I am creating my first model in django, I have been following The django book which was predated when compare to the django version I been using,I have created an app Book and written the below model </p>
<pre><code>from django.db import models
#Create your models here.
class Publisher(models.Model):
... | 0 | 2016-07-24T14:28:42Z | 38,553,395 | <p>Your app is named <code>books</code>, so <code>books</code> (and not <code>first.books</code>) should be included as the <code>app_name</code> in your <code>INSTALLED_APPS</code> setting.</p>
| 1 | 2016-07-24T14:57:55Z | [
"python",
"django",
"django-models"
] |
scrapy CSV writing | 38,553,178 | <p>Being new user I managed to make a spider can romper e- commerce site and extract
Title and variations of each product and the output CSV file and a product line but what I will wish
This is a variation by line, please can someone help me move forward in my project.</p>
<p>I'm looking forward to come to the questio... | 1 | 2016-07-24T14:33:31Z | 38,555,015 | <p>Check out <a href="http://doc.scrapy.org/en/latest/faq.html?highlight=csv#simplest-way-to-dump-all-my-scraped-items-into-a-json-csv-xml-file" rel="nofollow">official docummentation here</a> </p>
<p>In short there are two approaches, the simpliest one would be just to use crawl command argument <code>--output</code>... | 0 | 2016-07-24T17:52:59Z | [
"python",
"csv",
"scrapy",
"scrapy-spider"
] |
TypeError: not all arguments converted during string formatting postgres | 38,553,237 | <p>I try to add data to the database (use psycopg2.connect): </p>
<pre><code>cand = Candidate('test', datetime.now(), 'test@test.t', '123123', "21", 'test', 'test', 'test', datetime.now(), "1", "1", 'test', 'M', "18", "2", "2")
db.addCandidate(cand)
</code></pre>
<p>my function add:</p>
<pre><code>def addCandidate(s... | 0 | 2016-07-24T14:40:01Z | 38,553,406 | <p>I can't tell for sure because I don't know the types of your columns but it's plausible that your datetime object is not of the right format. You're sending in the datetime object not a string in the right date format. Try:</p>
<pre><code>candidate.pub_date.isoformat()
</code></pre>
<p>or</p>
<pre><code>candidate... | 0 | 2016-07-24T15:00:02Z | [
"python",
"postgresql",
"psycopg2"
] |
TypeError: not all arguments converted during string formatting postgres | 38,553,237 | <p>I try to add data to the database (use psycopg2.connect): </p>
<pre><code>cand = Candidate('test', datetime.now(), 'test@test.t', '123123', "21", 'test', 'test', 'test', datetime.now(), "1", "1", 'test', 'M', "18", "2", "2")
db.addCandidate(cand)
</code></pre>
<p>my function add:</p>
<pre><code>def addCandidate(s... | 0 | 2016-07-24T14:40:01Z | 38,554,176 | <p>In instead of <code>execute</code> do <code>mogrify</code> to check what exactly is being sent to the server: </p>
<pre><code>print cursor.mogrify ("""
INSERT INTO candidate (
name, pub_date, email, tel, age, proff, href, city,
last_update, called_count, status, comment,
sex, recrut_i... | 0 | 2016-07-24T16:22:46Z | [
"python",
"postgresql",
"psycopg2"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.