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 |
|---|---|---|---|---|---|---|---|---|---|
What format should I use to store timestamp in JSON for mongodb queries used in nodejs? | 38,936,739 | <p>I am currently using python to preprocess my data into JSON and insert my data into the collection via nodejs: <code>collection.insert(data, {safe:true}, function(err, result) {});</code> My queries will be executed using nodejs as well.</p>
<p>I previously used python <code>datetime.datetime</code> to format my timestamps, and this is how my JSON is structured:</p>
<pre><code>[{
"timestamp" : "2016-08-02 20:30:02",
"detail" : blah blah blah
},{
"timestamp" : "2016-08-02 20:33:23",
"detail" : blah blah blah
},
...
]
</code></pre>
<p>I was trying to query based on the timestamp, and according to a lot of posts such as this <a href="http://stackoverflow.com/questions/7651064/create-an-isodate-with-pymongo">Create an ISODate with pyMongo</a>, I am supposed to use <code>ISODate</code> for my query. So one of my attempts is:</p>
<pre><code> collection.findOne({ timestamp: new ISODate("2016-08-02T20:33:23.786Z")})
</code></pre>
<p>This one says that ISODate is undefined. So based on this <a href="http://stackoverflow.com/questions/8848314/isodate-is-not-defined">post</a> I changed my query to:</p>
<pre><code> collection.findOne({ timestamp: new Date("2016-08-02T20:33:23.786Z")})
</code></pre>
<p>This one says record not found. How should I store my timestamps into JSON? Is <code>new Date("2016-08-02T20:33:23.786Z")</code> the right way to retrieve my instance? Also, when mongodb query timestamps, will it look at exact hours and minutes as well? I want to find the exact year, month, day, hour, minute and second just like how my timestamp is stored. </p>
| 2 | 2016-08-13T20:31:19Z | 38,937,390 | <p>The following <a href="http://stackoverflow.com/questions/3778428/best-way-to-store-date-time-in-mongodb">answer</a> suggests that the best way is to use the JavaScript <code>Date</code> (constructed also via <code>ISODate</code>), which is native to Mongo. Digging into the <a href="https://docs.mongodb.com/manual/reference/bson-types/#document-bson-type-date" rel="nofollow">BSON documentation</a> it further clarifies the internal values:</p>
<blockquote>
<p>BSON Date is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970). This results in a representable date range of about 290 million years into the past and future.</p>
</blockquote>
<p>So the short answer is: no matter which language you store it from, just store that 64bit integer number of milliseconds, which you will be able to read natively. I would expect that value to be in UTC, both written and read.</p>
<p>The <a href="http://stackoverflow.com/questions/6999726/how-can-i-convert-a-datetime-object-to-milliseconds-since-epoch-unix-time-in-p">following answer</a> also tells you how to convert your python <code>datetime</code> object to milliseconds since epoch.</p>
| 1 | 2016-08-13T22:04:28Z | [
"python",
"json",
"node.js",
"mongodb",
"isodate"
] |
How to find the correlation between two lists when one list consists of date values? | 38,936,752 | <p>I'm trying to calculate the correlation between two lists every 30 days using the <em>pearsonr</em> function from scipy.</p>
<p>One list consists of dates (called <strong>dateValues</strong>), and the other one consists of sales (called <strong>saleNumbers</strong>). I already extracted the dates using datetime.strptime earlier and if I print out <strong>dateValues</strong>, I get a range of dates with an arbitrary length.</p>
<pre><code>datetime.datetime(2016, 8, 12, 0, 0), datetime.datetime(2016, 8, 11, 0, 0), datetime.datetime(2016, 8, 10, 0, 0)...etc
</code></pre>
<p>While here is the sales list:</p>
<pre><code>saleNumbers = [3567,2348,1234,....etc]
</code></pre>
<p>However when I do</p>
<pre><code>pearsonr(dateValues,saleNumbers)
</code></pre>
<p>I get the error</p>
<pre><code>TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'
</code></pre>
<p>After searching endlessly, I found that one can use <em>datetime.date</em> to do arithmetic between dates.</p>
<p>So i did this:</p>
<pre><code>print(datetime.date(dateValues[0]) - datetime.date(dateValues[29]))
</code></pre>
<p>And sure enough that gives me 30 days for the time difference.</p>
<p>So I then tried this:</p>
<p>pearsonr(datetime.date(dateValues[0]) - datetime.date(dateValues[29]),saleNumbers)</p>
<p>But I then get this error</p>
<pre><code>TypeError: len() of unsized object
</code></pre>
<p>Any ideas on how I can move forward with this? Also I don't think <em>datetime.date(dateValues[0]) - datetime.date(dateValues[2])</em> is the correct Pythonic way to handle the dates list when finding the correlation.</p>
<p>PS: In this image, is an Excel spreadsheet showing what I've already done, but trying to replicate here in Python: <a href="http://i.imgur.com/0Fj36Al.jpg" rel="nofollow">http://i.imgur.com/0Fj36Al.jpg</a></p>
| 0 | 2016-08-13T20:32:29Z | 38,936,772 | <p>Convert them to numeric values first:</p>
<pre><code>arbitrary_date = datetime(1970,1,1)
pearsonr([(d - arbitrary_date).total_seconds() for d in dateValues], saleNumbers)
</code></pre>
<p>Perason correlation is unaffected by scaling or translation in either axis (affine transformations)</p>
| 1 | 2016-08-13T20:35:38Z | [
"python",
"numpy",
"scipy",
"data-analysis",
"python-datetime"
] |
How to find the correlation between two lists when one list consists of date values? | 38,936,752 | <p>I'm trying to calculate the correlation between two lists every 30 days using the <em>pearsonr</em> function from scipy.</p>
<p>One list consists of dates (called <strong>dateValues</strong>), and the other one consists of sales (called <strong>saleNumbers</strong>). I already extracted the dates using datetime.strptime earlier and if I print out <strong>dateValues</strong>, I get a range of dates with an arbitrary length.</p>
<pre><code>datetime.datetime(2016, 8, 12, 0, 0), datetime.datetime(2016, 8, 11, 0, 0), datetime.datetime(2016, 8, 10, 0, 0)...etc
</code></pre>
<p>While here is the sales list:</p>
<pre><code>saleNumbers = [3567,2348,1234,....etc]
</code></pre>
<p>However when I do</p>
<pre><code>pearsonr(dateValues,saleNumbers)
</code></pre>
<p>I get the error</p>
<pre><code>TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'
</code></pre>
<p>After searching endlessly, I found that one can use <em>datetime.date</em> to do arithmetic between dates.</p>
<p>So i did this:</p>
<pre><code>print(datetime.date(dateValues[0]) - datetime.date(dateValues[29]))
</code></pre>
<p>And sure enough that gives me 30 days for the time difference.</p>
<p>So I then tried this:</p>
<p>pearsonr(datetime.date(dateValues[0]) - datetime.date(dateValues[29]),saleNumbers)</p>
<p>But I then get this error</p>
<pre><code>TypeError: len() of unsized object
</code></pre>
<p>Any ideas on how I can move forward with this? Also I don't think <em>datetime.date(dateValues[0]) - datetime.date(dateValues[2])</em> is the correct Pythonic way to handle the dates list when finding the correlation.</p>
<p>PS: In this image, is an Excel spreadsheet showing what I've already done, but trying to replicate here in Python: <a href="http://i.imgur.com/0Fj36Al.jpg" rel="nofollow">http://i.imgur.com/0Fj36Al.jpg</a></p>
| 0 | 2016-08-13T20:32:29Z | 38,936,889 | <p>You might try something like this:</p>
<pre><code>import numpy as np
pearsonr(np.array(dateValues, dtype=np.datetime64).astype("int"), np.array(saleNumbers))
</code></pre>
| 1 | 2016-08-13T20:49:28Z | [
"python",
"numpy",
"scipy",
"data-analysis",
"python-datetime"
] |
Categorize Data in a column in dataframe | 38,936,854 | <p>I have a column of numbers in my dataframe, i want to categorize these numbers into e.g high , low, excluded. How do i accomplish that. I am clueless , i have tried looking at the cut function and category datatype.</p>
| -1 | 2016-08-13T20:45:18Z | 38,936,967 | <p>This question is pretty broad, but a good place to start might be this page in the documentation:</p>
<p><a class='doc-link' href="http://stackoverflow.com/documentation/pandas/1751/indexing-and-selecting-data/6784/boolean-indexing#t=201608132054126569217">Boolean indexing</a></p>
<p>Or you could look into numpy.where</p>
<pre><code> import numpy as np
df['is_high'] = np.where(df.['column_of_interest'] > 5 ,1,0)
</code></pre>
| 0 | 2016-08-13T20:59:03Z | [
"python",
"pandas",
"machine-learning",
"data-analysis"
] |
Categorize Data in a column in dataframe | 38,936,854 | <p>I have a column of numbers in my dataframe, i want to categorize these numbers into e.g high , low, excluded. How do i accomplish that. I am clueless , i have tried looking at the cut function and category datatype.</p>
| -1 | 2016-08-13T20:45:18Z | 38,987,747 | <p>A short example with <code>pd.cut</code>.</p>
<p>Let's start with some data frame:</p>
<pre><code>df = pd.DataFrame({'A': [0, 8, 2, 5, 9, 15, 1]})
</code></pre>
<p>and, say, we want to assign the numbers to the following categories: <code>'low'</code> if a number is in the interval <code>[0, 2]</code>, <code>'mid'</code> for <code>(2, 8]</code>, <code>'high'</code> for <code>(8, 10]</code>, and we exclude numbers above 10 (or below 0).</p>
<p>Thus, we have 3 bins with edges: 0, 2, 8, 10. Now, we can use <code>cut</code> as follows:</p>
<pre><code>pd.cut(df['A'], bins=[0, 2, 8, 10], include_lowest=True)
Out[33]:
0 [0, 2]
1 (2, 8]
2 [0, 2]
3 (2, 8]
4 (8, 10]
5 NaN
6 [0, 2]
Name: A, dtype: category
Categories (3, object): [[0, 2] < (2, 8] < (8, 10]]
</code></pre>
<p>The argument <code>include_lowest=True</code> includes the left end of the first interval. (If you want intervals open on the right, then use <code>right=False</code>.)</p>
<p>The intervals are probably not the best names for the categories. So, let's use names: <code>low/mid/high</code>:</p>
<pre><code>pd.cut(df['A'], bins=[0, 2, 8, 10], include_lowest=True, labels=['low', 'mid', 'high'])
Out[34]:
0 low
1 mid
2 low
3 mid
4 high
5 NaN
6 low
Name: A, dtype: category
Categories (3, object): [low < mid < high]
</code></pre>
<p>The excluded number 15 gets a "category" <code>NaN</code>. If you prefer a more meaningful name, probably the simplest solution (there're other ways to deal with NaN's) is to add another bin and a category name, for example:</p>
<pre><code>pd.cut(df['A'], bins=[0, 2, 8, 10, 1000], include_lowest=True, labels=['low', 'mid', 'high', 'excluded'])
Out[35]:
0 low
1 mid
2 low
3 mid
4 high
5 excluded
6 low
Name: A, dtype: category
Categories (4, object): [low < mid < high < excluded]
</code></pre>
| 1 | 2016-08-17T03:41:09Z | [
"python",
"pandas",
"machine-learning",
"data-analysis"
] |
(Python) Passing multiple changes to URL | 38,936,855 | <p>I have a list of several stock tickers:</p>
<pre><code>ticker = (GE,IBM,GM,F,PG,CSCO)
</code></pre>
<p>That I want to pass to the URL in my python program. </p>
<pre><code>url = "https://www.quandl.com/api/v3/datasets/WIKI/FB.json"
</code></pre>
<p>I'm trying to pass a new ticker into the URL on each subsequent pass thru my program. I'm struggling with how to pass each new ticker in the list of ticker into the URL as it loops thru the program. Program needs to grab a new ticker from the list and replace the one in the URL.</p>
<p>Example: After the first pass, program should grab GE from the list and replace FB in the URL and continue looping thru until all tickers have been passed to URL. Not sure how best to deal with the part of the program. Any help would be appreciated. </p>
| -1 | 2016-08-13T20:45:18Z | 38,936,917 | <pre><code>import requests
url_tpl = "https://www.quandl.com/api/v3/datasets/WIKI/{ticker}.json"
# Here your results will be stored
jsons = {}
for ticker in ('FB', 'GE', 'IBM', 'GM', 'F' , 'PG', 'CSCO'):
res = requests.get(url_tpl.format(ticker=ticker))
if res.status_code == 200:
jsons[ticker] = res.json()
else:
print('error while fetching {ticker}, response code: '
'{status}'.format(ticker=ticker, status=res.status_code))
</code></pre>
| 2 | 2016-08-13T20:53:09Z | [
"python"
] |
Concatenate lines of form input into a single line | 38,936,861 | <p>I have a HTML form, user will input here text (with lines), like this : </p>
<pre><code>How are you?
I am fine.
Thank you!
</code></pre>
<p>In the server side, I will get that input by :</p>
<pre><code>input = request.POST['input']
</code></pre>
<p>And then I will to concatenate them into a single line like this : </p>
<pre><code>How are you? I am fine.Thank you!
</code></pre>
<p>I have tried this but it doesn't work : </p>
<pre><code> input = request.POST['input']
input = input.rstrip('\n')
print(input) #print to test the concatenation
</code></pre>
<p>Please help me! Thank you!</p>
| 1 | 2016-08-13T20:46:34Z | 38,936,933 | <p><code>newstring = input.replace('\n', '')</code> should work</p>
| 1 | 2016-08-13T20:55:23Z | [
"python",
"django",
"concatenation"
] |
Concatenate lines of form input into a single line | 38,936,861 | <p>I have a HTML form, user will input here text (with lines), like this : </p>
<pre><code>How are you?
I am fine.
Thank you!
</code></pre>
<p>In the server side, I will get that input by :</p>
<pre><code>input = request.POST['input']
</code></pre>
<p>And then I will to concatenate them into a single line like this : </p>
<pre><code>How are you? I am fine.Thank you!
</code></pre>
<p>I have tried this but it doesn't work : </p>
<pre><code> input = request.POST['input']
input = input.rstrip('\n')
print(input) #print to test the concatenation
</code></pre>
<p>Please help me! Thank you!</p>
| 1 | 2016-08-13T20:46:34Z | 38,937,145 | <p>Use</p>
<pre><code>" ".join(input.split("\n"))
</code></pre>
| 1 | 2016-08-13T21:26:33Z | [
"python",
"django",
"concatenation"
] |
Concatenate lines of form input into a single line | 38,936,861 | <p>I have a HTML form, user will input here text (with lines), like this : </p>
<pre><code>How are you?
I am fine.
Thank you!
</code></pre>
<p>In the server side, I will get that input by :</p>
<pre><code>input = request.POST['input']
</code></pre>
<p>And then I will to concatenate them into a single line like this : </p>
<pre><code>How are you? I am fine.Thank you!
</code></pre>
<p>I have tried this but it doesn't work : </p>
<pre><code> input = request.POST['input']
input = input.rstrip('\n')
print(input) #print to test the concatenation
</code></pre>
<p>Please help me! Thank you!</p>
| 1 | 2016-08-13T20:46:34Z | 38,937,274 | <p>Thank you Harrison and Cychih for your answer, I tried however, they don't work. The solution I found is this : </p>
<pre><code>newstring = input1.replace('\r\n', ' ')
</code></pre>
<p>It's </p>
<pre><code>'\r\n'
</code></pre>
<p>not </p>
<pre><code>'\n'
</code></pre>
<p>When I put in the form 3 lines like this ; </p>
<pre><code>Line 1
Line 2
Line 3
</code></pre>
<p>Here is the output of the request.POST</p>
<pre><code><QueryDict: {'input1': ['Line 1 \r\nLine 2\r\nLine 3\r\n'], 'csrfmiddlewaretoken': ['tvC0ISHPNEkdQzocuVRnhJCp5yadDkgC5wf832blrpYPP0MZVV1iNY5bI2cYXsA4'], 'output1': [' ']}>
</code></pre>
<p>I don't know why new line is set as \r\n but it's the way it is . </p>
<p>Thank you again for your help!</p>
| 0 | 2016-08-13T21:45:52Z | [
"python",
"django",
"concatenation"
] |
Dynamically create methods for an instance in Python | 38,937,123 | <p>I have a class called 'Movable Piece'. Of course, I want every instance of this class to move. For that, I thought another class called 'Movement' would be nice, and reusable in case I need other stuff to move. Besides, I quite like how <code>my_piece.move.up</code> looks in the code. </p>
<p>The problem comes when I realize I need to dynamically try to set methods for the instance of the Movements class instantiated by the Piece, as the functions that move the piece may as well be user-defined. How can I achieve this? I think the code will clarify what I want to do.</p>
<pre><code>class MovablePiece(Piece):
class Movements:
def __init__(self, piece, movement_functions=None):
if movement_functions is None:
self.__default_movements(piece)
else:
self.__set_movements(movement_functions)
def __default_movements(self, piece):
def up(): return piece.move(piece.surroundings[Direction.UP])
def right(): return piece.move(piece.surroundings[Direction.RIGHT])
def down(): return piece.move(piece.surroundings[Direction.DOWN])
def left(): return piece.move(piece.surroundings[Direction.LEFT])
self.__set_movements([up, right, down, left])
def __set_movements(self, movement_functions):
for movement_function in movement_functions:
setattr(self, movement_function.__name__, movement_function)
def __init__(self, letter, name, movements=None, walkable=False):
Piece.__init__(self, letter, name, walkable)
self.move = MovablePiece.Movements()
</code></pre>
<p>This, of course, won't work: setattr is trying to set a function as an attribute, which I don't think makes much sense, but you get the gist of it.</p>
<p>This is the error when I try to do <code>my_piece.move.right</code>:</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 45, in <module>
screen.show()
File "/home/joaquin/Documents/escape/ludema/screen.py", line 12, in show
function()
File "main.py", line 35, in control_bruma
mappings[action]()
File "/home/joaquin/Documents/escape/ludema/pieces.py", line 78, in right
def right(): return piece.move(piece.surroundings[Direction.RIGHT])
TypeError: 'Movements' object is not callable
</code></pre>
<p>Similar problem if I force the methods to be staticmethods (as they don't actually require 'self'):</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 45, in <module>
screen.show()
File "/home/joaquin/Documents/escape/ludema/screen.py", line 12, in show
function()
File "main.py", line 35, in control_bruma
mappings[action]()
TypeError: 'staticmethod' object is not callable
</code></pre>
| -2 | 2016-08-13T21:22:59Z | 38,937,299 | <p>IMHO you should have provided a <a href="http://stackoverflow.com/help/mcve">mvce</a> in the question that way this answer could add some additional tips, in any case, here's a working example guessing the missing bits of your code:</p>
<pre><code>class Piece(object):
def __init__(self, letter, name, walkable):
self.letter = letter
self.name = name
self.walkable = walkable
class Movements:
def __init__(self, piece, movement_functions=None):
if movement_functions is None:
self.__default_movements(piece)
else:
self.__set_movements(movement_functions)
def __default_movements(self, piece):
def up(): print("up")
def right(): print("right")
def down(): print("down")
def left(): print("left")
self.__set_movements([up, right, down, left])
def __set_movements(self, movement_functions):
for movement_function in movement_functions:
setattr(self, movement_function.__name__, movement_function)
class MovablePiece(Piece):
def __init__(self, letter, name, movements=None, walkable=False):
Piece.__init__(self, letter, name, walkable)
self.move = Movements(self)
p = MovablePiece("foo", "foo")
for direction in ["up", "right", "down", "left"]:
getattr(p.move, direction)()
</code></pre>
<p>Another choice would be coding something like this:</p>
<pre><code>class UpMovement(object):
def __init__(self, piece):
self.piece = piece
self.name = "up"
def move(self):
if self.piece.walkable:
print("up")
else:
print("piece not walkable to go up")
class DownMovement(object):
def __init__(self, piece):
self.piece = piece
self.name = "down"
def move(self):
if self.piece.walkable:
print("down")
else:
print("piece not walkable to go down")
class LeftMovement(object):
def __init__(self, piece):
self.piece = piece
self.name = "left"
def move(self):
if self.piece.walkable:
print("left")
else:
print("piece not walkable to go left")
class RightMovement(object):
def __init__(self, piece):
self.piece = piece
self.name = "right"
def move(self):
if self.piece.walkable:
print("right")
else:
print("piece not walkable to go right")
class Piece(object):
def __init__(self, letter, name, walkable):
self.letter = letter
self.name = name
self.walkable = walkable
class Movements(object):
def __init__(self):
pass
class MovablePiece(Piece):
def __init__(self, letter, name):
Piece.__init__(self, letter, name, True)
movements = [
UpMovement(self),
DownMovement(self),
LeftMovement(self),
RightMovement(self)
]
self.move = Movements()
for m in movements:
setattr(self.move, m.name, m.move)
class StaticPiece(Piece):
def __init__(self, letter, name):
Piece.__init__(self, letter, name, False)
movements = [
UpMovement(self),
DownMovement(self),
LeftMovement(self),
RightMovement(self)
]
self.move = Movements()
for m in movements:
setattr(self.move, m.name, m.move)
p1 = MovablePiece("foo1", "foo1")
for name in ["up", "down", "left", "right"]:
getattr(p1.move, name)()
p2 = StaticPiece("foo2", "foo2")
for name in ["up", "down", "left", "right"]:
getattr(p2.move, name)()
</code></pre>
<p>Of course, you could overengineer the thing abstracting classes here and there, making the class design much better and applying SOLID design principles. In any case, the question was basically how to attach dynamically stuff to Pieces, so here's a possible solution :)</p>
| 1 | 2016-08-13T21:50:06Z | [
"python",
"class",
"python-3.x"
] |
Dynamically create methods for an instance in Python | 38,937,123 | <p>I have a class called 'Movable Piece'. Of course, I want every instance of this class to move. For that, I thought another class called 'Movement' would be nice, and reusable in case I need other stuff to move. Besides, I quite like how <code>my_piece.move.up</code> looks in the code. </p>
<p>The problem comes when I realize I need to dynamically try to set methods for the instance of the Movements class instantiated by the Piece, as the functions that move the piece may as well be user-defined. How can I achieve this? I think the code will clarify what I want to do.</p>
<pre><code>class MovablePiece(Piece):
class Movements:
def __init__(self, piece, movement_functions=None):
if movement_functions is None:
self.__default_movements(piece)
else:
self.__set_movements(movement_functions)
def __default_movements(self, piece):
def up(): return piece.move(piece.surroundings[Direction.UP])
def right(): return piece.move(piece.surroundings[Direction.RIGHT])
def down(): return piece.move(piece.surroundings[Direction.DOWN])
def left(): return piece.move(piece.surroundings[Direction.LEFT])
self.__set_movements([up, right, down, left])
def __set_movements(self, movement_functions):
for movement_function in movement_functions:
setattr(self, movement_function.__name__, movement_function)
def __init__(self, letter, name, movements=None, walkable=False):
Piece.__init__(self, letter, name, walkable)
self.move = MovablePiece.Movements()
</code></pre>
<p>This, of course, won't work: setattr is trying to set a function as an attribute, which I don't think makes much sense, but you get the gist of it.</p>
<p>This is the error when I try to do <code>my_piece.move.right</code>:</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 45, in <module>
screen.show()
File "/home/joaquin/Documents/escape/ludema/screen.py", line 12, in show
function()
File "main.py", line 35, in control_bruma
mappings[action]()
File "/home/joaquin/Documents/escape/ludema/pieces.py", line 78, in right
def right(): return piece.move(piece.surroundings[Direction.RIGHT])
TypeError: 'Movements' object is not callable
</code></pre>
<p>Similar problem if I force the methods to be staticmethods (as they don't actually require 'self'):</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 45, in <module>
screen.show()
File "/home/joaquin/Documents/escape/ludema/screen.py", line 12, in show
function()
File "main.py", line 35, in control_bruma
mappings[action]()
TypeError: 'staticmethod' object is not callable
</code></pre>
| -2 | 2016-08-13T21:22:59Z | 38,943,759 | <p>This is how I finally ended up doing it. I'm sorry this example is not reproducible, but there are just too many classes involved in the mix and I think it would just tamper with readability and comprehension for this precise problem. You can nevertheless peep the code at <a href="https://github.com/Mellatrix/escape/tree/master/ludema" rel="nofollow">github</a>.</p>
<p>Notably, I didn't have to force the functions to be static even when they take no parameters. Apparently Python does that for you, somehow. </p>
<pre><code>class MovablePiece(Piece):
class Movements:
"""A simple interface to represent the movements of the MovablePiece.
"""
def __init__(self, piece, movement_functions=None):
if movement_functions is None:
self.__default_movements(piece)
else:
self.__set_movements(movement_functions)
def __default_movements(self, piece):
def up(): return piece.move_to_tile(piece.surroundings[Direction.UP])
def right(): return piece.move_to_tile(piece.surroundings[Direction.RIGHT])
def down(): return piece.move_to_tile(piece.surroundings[Direction.DOWN])
def left(): return piece.move_to_tile(piece.surroundings[Direction.LEFT])
self.__set_movements([up, right, down, left])
def __set_movements(self, movement_functions):
for movement_function in movement_functions:
setattr(self, movement_function.__name__, movement_function)
def __init__(self, letter, name, movements=None, walkable=False):
Piece.__init__(self, letter, name, walkable)
self.move = MovablePiece.Movements(self)
def _unsafe_move_to_tile(self, tile):
"""Move the object in a certain direction, if it can:
That means: unlink the piece from its current tile and link it
to the new tile; unless there's a piece in the destiny tile already.
Return True if could move there, False is possition was already
ocuppied.
Can raise a PieceIsNotOnATileError if the piece hasn't been put on a
map prior to moving or a PieceIsNotOnThisBoardError if the piece
you're trying to move has an associated tile in another board, not
the one where the destinity tile is.
"""
if not self.home_tile:
raise PieceIsNotOnATileError
if self.home_tile.board is not tile.board:
raise PieceIsNotOnThisBoardError
if tile.piece is not None:
tile.piece.on_touch_do(touching_piece=self)
if not tile.piece.walkable:
return False
self.home_tile.piece = None
tile.piece = self
return True
def move_to_tile(self, tile):
if tile:
try:
return self._unsafe_move_to_tile(tile)
except (PieceIsNotOnATileError, PieceIsNotOnThisBoardError):
return False
else:
return False
</code></pre>
| 0 | 2016-08-14T15:34:30Z | [
"python",
"class",
"python-3.x"
] |
python issues with csv | 38,937,187 | <p>I just started leaning python while taking an udacity course for data analytics, and am having problems with my code in pyCharm. To preface this, the code works when used in the udacity shell and the file locations changed to instructed location for the udacity website. Below is the code and the 2 errors I'm getting. I do know C++ and thought python would be a breeze to learn kind of on the fly, but except for the coding itself I tend to get these types of errors I never encountered before. If there are any rules of thumb how to avoid this it would be greatly appreciated.</p>
<pre><code>import csv
daily_engagements = []
project_submissions = []
with open(r'C:\Users\austi\Downloads\daily_engagement.csv', 'rt') as f:
reader = csv.DictReader(f)
daily_engagement = list(reader)
print(project_submissions[5])
with open(r'C:\Users\austi\Downloads\project_submissions.csv', 'rt') as g:
reader1 = csv.DictReader(g)
project_submissions = list(reader)
print(daily_engagement[17])
</code></pre>
<p>ERROR 1</p>
<pre><code> C:\Users\austi\AppData\Local\Programs\Python\Python35-32\python.exe
C:/Users/austi/PycharmProjects/untitled2/p2prac.py
Traceback (most recent call last):
File "C:/Users/austi/PycharmProjects/untitled2/p2prac.py", line 15, in <module>
project_submissions = list(reader)
File "C:\Users\austi\AppData\Local\Programs\Python\Python35- 32\lib\csv.py", line 110, in __next__
row = next(self.reader)
ValueError: I/O operation on closed file.
Process finished with exit code 1
</code></pre>
<p>ERROR 2</p>
<pre><code>C:\Users\austi\AppData\Local\Programs\Python\Python35-32\python.exe
C:/Users/austi/PycharmProjects/untitled2/p2prac.py
Traceback (most recent call last):
File "C:/Users/austi/PycharmProjects/untitled2/p2prac.py", line 10, in <module>
print(project_submissions[5])
IndexError: list index out of range
Process finished with exit code 1
</code></pre>
| -2 | 2016-08-13T21:32:26Z | 38,937,261 | <p>I'll note your errors with inline comments. Basically, you seem to have trouble keeping track of objects and their names.</p>
<pre><code>import csv
daily_engagements = [] # this is never used
project_submissions = [] # you never add anything to this list
with open(r'C:\Users\austi\Downloads\daily_engagement.csv', 'rt') as f:
reader = csv.DictReader(f)
daily_engagement = list(reader)
print(project_submissions[5]) # you've never added to this list, so it has no element 5... did you mean to use daily_engagement?
with open(r'C:\Users\austi\Downloads\project_submissions.csv', 'rt') as g:
reader1 = csv.DictReader(g)
project_submissions = list(reader) # you are using reader, which was closed already, rather than reader1
print(daily_engagement[17])
</code></pre>
<p>Here is a cleaned-up version. I don't have your files and I don't know which data you want to print, but this is probably what you want as far as I can determine:</p>
<pre><code>import csv
with open(r'C:\Users\austi\Downloads\daily_engagement.csv') as f:
reader = csv.DictReader(f)
daily_engagement = list(reader)
print(daily_engagement[5])
with open(r'C:\Users\austi\Downloads\project_submissions.csv') as g:
reader = csv.DictReader(g)
project_submissions = list(reader)
print(project_submissions[17])
</code></pre>
| 1 | 2016-08-13T21:42:40Z | [
"python",
"csv",
"pycharm"
] |
Custom class which is a dict, but initialized without dict copy? | 38,937,227 | <p>For legibility purposes, I would like to have a custom class that behaves exactly like a dict (but carries a meaningful type instead of the more general dict type):</p>
<pre><code>class Derivatives(dict):
"Dictionary that represents the derivatives."
</code></pre>
<p>Now, is there a way of building new objects of this class in a way that does not involve copies? The naive usage</p>
<pre><code>derivs = Derivatives({var: 1}) # var is a Python object
</code></pre>
<p>in fact creates a <em>copy</em> of the dictionary passed as an argument, which I would like to avoid, for efficiency reasons.</p>
<p>I tried to bypass the copy but then the class of the dict cannot be changed, in CPython:</p>
<pre><code>class Derivatives(dict):
def __new__(cls, init_dict):
init_dict.__class__ = cls # Fails with __class__ assignment: only for heap types
return init_dict
</code></pre>
<p>I would like to have both the ability to give an explicit class name to the dictionaries that the program manipulates <em>and</em> an efficient way of building such dictionaries (instead of being forced to copy a Python dict). Is this doable efficiently in Python?</p>
<p>PS: The use case is maybe 100,000 creations of single-key <code>Derivatives</code>, where the key is a variable (not a string, so no keyword initialization). This is actually not slow, so "efficiency reasons" here means more something like "elegance": there is ideally no need to waste time doing a copy when the copy is not needed. So, in this particular case the question is more about the elegance/clarity that Python can bring here than about running speed.</p>
| 2 | 2016-08-13T21:38:02Z | 38,937,654 | <p>TL;DR: There's not general-purpose way to do it unless you do it in C.</p>
<p>Long answer:
The <code>dict</code> class is implemented in C. Thus, there is no way to access it's internal properties - and most importantly, it's internal hash table, unless you use C.</p>
<p>In C, you could simply copy the pointer representing the hash table into your object without having to iterate over the <code>dict</code> (key, value) pairs and insert them into your object. (Of course, it's a bit more complicated than this. Note that I omit memory management details).</p>
<p>Longer answer:</p>
<p>I'm not sure why you are concerned about efficiency.</p>
<p>Python passes arguments as references. It rarely every copies unless you explicitly tell it to.</p>
<p>I read in the comments that you can't use named parameters, as the keys are actual Python objects. That leaves me to understand that you're worried about copying the <code>dict</code> keys (and maybe values). However, even the dictionary keys are not copied, and passed by reference! Consider this code:</p>
<pre><code>class Test:
def __init__(self, x, y):
self.x = x
self.y = y
def __hash__(self):
return self.x
t = Test(1, 2)
print(t.y) # prints 2
d = {t: 1}
print(d[t]) # prints 1
keys = list(d.keys())
keys[0].y = 10
print(t.y) # prints 10! No copying was made when inserting object into dictionary.
</code></pre>
<p>Thus, the only remaining area of concern is iterating through the <code>dict</code> and inserting the values in your <code>Derivatives</code> class. This is unavoidable, unless you can somehow set the internal hash table of your class to the <code>dict</code>'s internal hash table. There is no way to do this in pure python, as the dict class is implemented in C (as mentioned above).</p>
<p>Note that others have suggested using generators. This seems like a good idea too - say if you were reading the derivatives from a file or if you were generating them with a simple formula. It would avoid creating the <code>dict</code> object in the first place. However, there will be no noticable improvements in efficiency if the generators are just wrappers around <code>list</code>s (or any other data structure that can contain an arbritary set of values).</p>
<p>Your best bet is do stick with your original method. Generators are great, but they can't efficiently represent an arbritary set of values (which might be the case in your scenario). It's also not worth it to do it in C.</p>
<p>EDIT: It <em>might</em> be worth it to do it in C, after all!</p>
<p>I'm not too big on the details of the Python C API, but consider defining a class in C, for example,<code>DerivativesBase</code> (deriving from <code>dict</code>). All you do is define an <code>__init__</code> function in C for <code>DerivativesBase</code> that takes a <code>dict</code> as a parameter and copies the hash table pointer from the <code>dict</code> into your <code>DerivativesBase</code> object. Then, in python, your <code>Derivatives</code> class derives from <code>DerivativesBase</code> and implements the bulk of the functionality.</p>
| 0 | 2016-08-13T22:53:06Z | [
"python",
"dictionary",
"inheritance"
] |
Custom class which is a dict, but initialized without dict copy? | 38,937,227 | <p>For legibility purposes, I would like to have a custom class that behaves exactly like a dict (but carries a meaningful type instead of the more general dict type):</p>
<pre><code>class Derivatives(dict):
"Dictionary that represents the derivatives."
</code></pre>
<p>Now, is there a way of building new objects of this class in a way that does not involve copies? The naive usage</p>
<pre><code>derivs = Derivatives({var: 1}) # var is a Python object
</code></pre>
<p>in fact creates a <em>copy</em> of the dictionary passed as an argument, which I would like to avoid, for efficiency reasons.</p>
<p>I tried to bypass the copy but then the class of the dict cannot be changed, in CPython:</p>
<pre><code>class Derivatives(dict):
def __new__(cls, init_dict):
init_dict.__class__ = cls # Fails with __class__ assignment: only for heap types
return init_dict
</code></pre>
<p>I would like to have both the ability to give an explicit class name to the dictionaries that the program manipulates <em>and</em> an efficient way of building such dictionaries (instead of being forced to copy a Python dict). Is this doable efficiently in Python?</p>
<p>PS: The use case is maybe 100,000 creations of single-key <code>Derivatives</code>, where the key is a variable (not a string, so no keyword initialization). This is actually not slow, so "efficiency reasons" here means more something like "elegance": there is ideally no need to waste time doing a copy when the copy is not needed. So, in this particular case the question is more about the elegance/clarity that Python can bring here than about running speed.</p>
| 2 | 2016-08-13T21:38:02Z | 38,937,844 | <p>By inheriting from <code>dict</code> you are given three possibilities for constructor arguments: (baring the <code>{}</code> literal)</p>
<pre><code>class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
</code></pre>
<p>This means that, in order to instantiate your instance you <strong>must</strong> do one of the following:</p>
<ol>
<li>Pass the variables as keywords <code>D(x=1)</code> which are then packed into an intermediate dictionary anyway.</li>
<li><p>Create a plain dictionary and pass it as a <code>mapping</code>.</p></li>
<li><p>Pass an iterable of (key,value) pairs.</p></li>
</ol>
<p>So in all three of these cases you will need to create intermediate objects to satisfy the <code>dict</code> constructor.</p>
<p>The third option for a single pair it would look like <code>D(((var,1),))</code> which I highly recommend against for readability sake.</p>
<p>So if you want your class to inherit from a dictionary, using <code>Derivatives({var: 1})</code> is your most efficient and most readable option. </p>
<p>As a personal note if you will have thousands of single pair dictionaries I'm not sure how the <code>dict</code> setup is the best in the first place, you may just reconsider the basis of your class.</p>
| 0 | 2016-08-13T23:28:50Z | [
"python",
"dictionary",
"inheritance"
] |
Python 3.4: After popen.communicate() program is lost | 38,937,238 | <p>I'll try to connect a button on my RPi to control mplayer, first button press shall start the player, and each later button press shall play another entry in the playlist.
As a minimal example I created following script on Linux Mint 18 and Python3.4.3:</p>
<pre><code>from time import sleep
from subprocess import Popen, PIPE, DEVNULL
cmd = ["mplayer", "-shuffle", "-playlist", "/path/to/playlist.m3u"]
if __name__ == '__main__':
first = False
p = None
i = 0
if first == False: # should simulate first button
print("player starting")
p = Popen(cmd, stdin=PIPE, stdout=DEVNULL)
print("player started")
first = True
while 1:
sleep(1)
i += 1
print(str(i)+ " " +str(first))
if i == 5 and first == True: # should simulate each later button
i = 0
print("sending keystroke to mplayer")
p.communicate(b"\n")[0] # mplayer plays next song, but the program is lost
print("sended keystroke to mplayer - never printed")
</code></pre>
<p>And the output is:</p>
<pre><code>player starting
player started
1 True
2 True
3 True
4 True
5 True
sending keystroke to mplayer
</code></pre>
<p>And now I'm expecting a restart of the loop, but it's missing.
Debugging did not help me.
Do you have any ideas how to solve the problem and how to return into the loop?</p>
<p>Thank you.</p>
| 0 | 2016-08-13T21:39:43Z | 38,942,094 | <p>I solved it with mplayer slave:</p>
<pre><code>from time import sleep
from subprocess import Popen
pathtoControlFile = "/home/immi/mplayer-control"
cmd = ["mplayer", "-slave", "-input", "file="+pathtoControlFile, "-shuffle", "-playlist", "/media/immi/9A005723005705A3/Musik/playlist.m3u"]
if __name__ == '__main__':
first = False
i = 0
if first == False: # initial start
print("player starting")
p = Popen(cmd)
print("player started")
first = True
while 1:
sleep(1)
i += 1
print(str(i)+ " " +str(first))
if i == 5 and first == True: # each later button
i = 0
print("sending keystroke to mplayer")
with open(pathtoControlFile, "wb+", buffering=0) as fileInput:
p = Popen(["echo", "pt_step next"], stdout=fileInput)
</code></pre>
| 0 | 2016-08-14T12:09:18Z | [
"python",
"python-3.x",
"subprocess",
"popen"
] |
two dataframes into one | 38,937,245 | <p>Not sure if this is possible. I have two dataframes df1 and df2 which are presented like this:</p>
<pre><code>df1 df2
id value id value
a 5 a 3
c 9 b 7
d 4 c 6
f 2 d 8
e 2
f 1
</code></pre>
<p>They will have many more entries in reality than presented here. I would like to create a third dataframe df3 based on the values in df1 and df2. Any values in df1 would take precedence over values in df2 when writing to df3 (if the same id is present in both df1 and df2) so in this example I would return:</p>
<pre><code>df3
id value
a 5
b 7
c 9
d 4
e 2
f 2
</code></pre>
<p>I have tried using df2 as the base (df2 will have all of the id's present for the whole universe) and then overwriting the value for id's that are present in df1, but cannot find the merge syntax to do this. Any help would be greatly appreciated.</p>
<p>Thanks</p>
| 0 | 2016-08-13T21:40:39Z | 38,937,284 | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow"><code>combine_first</code></a>, provided that you first make the DataFrame index <code>id</code> (so that the <code>values</code> get aligned by <code>id</code>):</p>
<pre><code>In [80]: df1.set_index('id').combine_first(df2.set_index('id')).reset_index()
Out[80]:
id value
0 a 5.0
1 b 7.0
2 c 9.0
3 d 4.0
4 e 2.0
5 f 2.0
</code></pre>
<hr>
<p>Since you mentioned merging, you might be interested in seeing that
you could merge <code>df1</code> and <code>df2</code> on <code>id</code>, and then use <code>fillna</code> to replace NaNs in <code>df1</code>'s the <code>value</code> column with values from <code>df2</code>'s value column:</p>
<pre><code>df1 = pd.DataFrame({'id': ['a', 'c', 'd', 'f'], 'value': [5, 9, 4, 2]})
df2 = pd.DataFrame({'id': ['a', 'b', 'c', 'd', 'e', 'f'], 'value': [3, 7, 6, 8, 2, 1]})
result = pd.merge(df2, df1, on='id', how='left', suffixes=('_x', ''))
result['value'] = result['value'].fillna(result['value_x'])
result = result[['id', 'value']]
print(result)
</code></pre>
<p>yields the same result, though the first method is simpler.</p>
| 1 | 2016-08-13T21:47:19Z | [
"python",
"pandas"
] |
How to take input in single line in python and storing it into list | 38,937,301 | <p>I am getting <strong>Runtime Error - NZEC</strong> while running this code online. I searched.. it is because of input format. Please help me out.</p>
<pre><code>import math
a=input()
b=int(a)
e=list()
answer=1
for c in range(0,b):
d=input()
e.append(d)
for c in range(0,b):
g=e[c]
answer=math.fmod(float(float(answer) * float(g)),float((10**9)+7))
print(int(answer))
</code></pre>
| 0 | 2016-08-13T21:50:10Z | 38,937,535 | <p>if you want to take the second and following inputs in a single line (I guess separated by spaces), you can do the following:</p>
<pre><code>import math
a=input()
b=int(a)
answer=1
e = raw_input().split(" ")[:b]
for c in range(0,b):
g=e[c]
answer=math.fmod(float(float(answer) * float(g)),float((10**9)+7))
print(int(answer))
</code></pre>
<p>For instance you would type "3[enter]" then "5 66 77[enter]". Is that what you need?</p>
<p>EDIT: I guess this is some kind of programming exercise. But if needed you can even omit the first input, and request just a list of X numbers separated by spaces:</p>
<pre><code>import math
answer=1
for g in raw_input().split(" "):
answer=math.fmod(float(float(answer) * float(g)),float((10**9)+7))
print(int(answer))
</code></pre>
| 0 | 2016-08-13T22:31:24Z | [
"python",
"python-3.x"
] |
Incorrect display of major and minor ticks on matplotlib plot | 38,937,363 | <p>I have the foll. dataframe:</p>
<pre><code>Version A2011 v1.0h
Decade
1510 - 1500 -3.553251 -0.346051
1520 - 1510 -2.797978 -0.356409
1530 - 1520 -2.194027 -0.358922
1540 - 1530 -1.709211 -0.329759
1550 - 1540 -1.354583 -0.308463
1560 - 1550 -1.062436 -0.305522
1570 - 1560 -0.821615 -0.293803
1580 - 1570 -0.620067 -0.279270
1590 - 1580 -0.465902 -0.271717
1600 - 1590 -0.341307 -0.289985
1610 - 1600 -0.365580 -0.491428
1620 - 1610 -0.329492 -0.532413
1630 - 1620 -0.299107 -0.568895
1640 - 1630 -0.283209 -0.591281
1650 - 1640 -0.267895 -0.595867
1660 - 1650 -0.250805 -0.593352
1670 - 1660 -0.240772 -0.539465
1680 - 1670 -0.234985 -0.514080
1690 - 1680 -0.230892 -0.497424
1700 - 1690 -0.229585 -0.484620
1710 - 1700 -0.853362 -0.892739
1720 - 1710 -0.738257 -1.017681
1730 - 1720 -0.660543 -0.966818
1740 - 1730 -1.331018 -1.171711
1750 - 1740 -1.271687 -1.541482
1760 - 1750 -1.023931 -1.559551
1770 - 1760 -1.089076 -1.757628
1780 - 1770 -1.965483 -2.404880
1790 - 1780 -1.579474 -2.167510
1800 - 1790 -1.740528 -2.023357
1810 - 1800 -2.237945 -2.804366
1820 - 1810 -2.744933 -2.379714
1830 - 1820 -3.706726 -3.717356
1840 - 1830 -4.680707 -4.048362
1850 - 1840 -5.836515 -4.660951
1860 - 1850 -7.141815 -4.919932
1870 - 1860 -5.847633 -2.972652
1880 - 1870 -9.280493 -6.146244
1890 - 1880 -8.815674 -6.689340
1900 - 1890 -9.548756 -8.893766
1910 - 1900 -10.596151 -10.115838
1920 - 1910 -12.002151 -10.492217
1930 - 1920 -12.524735 -11.155891
1940 - 1930 -13.945205 -14.295251
1950 - 1940 -13.877164 -13.609756
1960 - 1950 -20.660728 -17.546248
1970 - 1960 -14.495609 -15.537517
1980 - 1970 -14.865093 -13.292412
1990 - 1980 -16.254918 -13.626304
2000 - 1990 -12.212572 -8.392916
</code></pre>
<p>and I plot it so:</p>
<pre><code> import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
ax = df.plot()
# major ticks every 5, minor ticks every 1
ax.xaxis.set_major_locator(MaxNLocator(11))
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)
ax.legend().set_visible(False)
plt.xticks(rotation=75)
plt.tight_layout()
plt.show()
</code></pre>
<p>Resulting figure looks like this:</p>
<p><a href="http://i.stack.imgur.com/AYYE4.png" rel="nofollow"><img src="http://i.stack.imgur.com/AYYE4.png" alt="enter image description here"></a></p>
<p>How do I fix the number of major and minor ticks so that there are at least 10 major ticks, and user-specified number of minor ticks between major ticks?</p>
| 1 | 2016-08-13T21:59:37Z | 38,937,796 | <p>From a bit of looking around it seems that pandas doesn't play well with locators. It seems that the preferred method of setting ticklabels is automatic. The problem seems to be that the implicit coupling of data vs index, used when automatically setting the tick labels, gets mixed up with a different number of tick labels to be set.</p>
<p>It feels like there should be a better aproach (I don't have much experience with pandas), but in the mean time you can roll your own tick labels using a major formatter. My experience anyway is that <code>df.plot()</code> is convenient, but if you want to be sure, you should use matplotlib directly.</p>
<p>The key trick is to set the major formatter of the x axis using a semi-documented <a href="http://matplotlib.org/api/ticker_api.html#tick-formatting" rel="nofollow"><code>IndexFormatter</code></a>, the labels of which come from the <code>index</code> of the dataframe:</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator,IndexFormatter
ax = df.plot()
ax.xaxis.set_major_locator(MaxNLocator(11))
ax.xaxis.set_major_formatter(IndexFormatter(df.index)) # <-- new here
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)
ax.legend().set_visible(False)
plt.xticks(rotation=75)
plt.tight_layout()
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/Y46e2.png" rel="nofollow"><img src="http://i.stack.imgur.com/Y46e2.png" alt="fixed major ticklabels"></a></p>
<p>And the reason your minor ticks are missing is this:</p>
<pre><code>>>> ax.xaxis.get_minor_locator()
<matplotlib.ticker.NullLocator at 0x7faf53d0e1d0>
</code></pre>
<p>The default locator for minor ticks is a <code>NullLocator</code>, which in effect disables minor ticks, which in turn leads to a distinct lack of minor grid lines. You should choose and set an appropriate <code>Locator</code> for the minor ticks, and everything should work then (in other words, I'm not sure if there's an easy way to specify the number of minor grids in terms of the major ones).</p>
| 1 | 2016-08-13T23:20:33Z | [
"python",
"pandas",
"matplotlib"
] |
logged out users are accessing views which logged in users can only access in django | 38,937,380 | <p>I am quite new to Django and came across this error. When ever I input a url directly ( '/accounts/admin2@outlook.com/'), django shows the user the view which only logged in users can see. I am using LoginRequiredMixin but it is not helping. </p>
<p>My view file is : `</p>
<pre><code>from django.shortcuts import render,redirect
from django.views.generic import View
from .forms import UserCreationForm,SignInForm
from django.contrib.auth import login,logout,get_backends,authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.decorators import method_decorator
from .backend import ClientAuthBackend
from .models import MyUser
class UserHomeView(LoginRequiredMixin,View):
def get(self,request,email):
print(request.user.is_authenticated())
return render(request,'user_home_view.html',{'title':'Home','user':MyUser.objects.get(email=email)})
class SignOutView(View):
def get(self,request):
logout(request)
return redirect(to='/accounts/signin/')
class SignInView(View):
def get(self,request):
return render(request,'log_in.html',{'title':'Sign In','form':SignInForm()})
def post(self,request):
form = SignInForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = authenticate(username=email,password=password)
if user is not None:
login(request,user)
return redirect(to='/accounts/' + str(email) + '/')
else:
form.add_error(None,"Couldn't authenticate your credentials !")
return render(request,'log_in.html',{'title':'Sign In','form':form})
else:
return render(request, 'log_in.html', {'title': 'Sign In', 'form': form})
class SignUpView(View):
def get(self,request):
return render(request,'sign_up.html',{'title':'Sign Up','form':UserCreationForm()})
def post(self,request):
form = UserCreationForm(request.POST)
try:
if form.is_valid():
user = MyUser.objects.create_user(email=form.cleaned_data['email'],date_of_birth=
form.cleaned_data['date_of_birth'],first_name=form.cleaned_data['first_name'],last_name=
form.cleaned_data['last_name'],password=form.clean_password2())
return redirect(to='/accounts/signin')
else:
return render(request,'sign_up.html',{'title':'Sign Up','form':form})
except ValueError:
form.add_error(None,"Passwords don't match !!!")
return render(request, 'sign_up.html', {'title': 'Sign Up', 'form': form})
</code></pre>
<p>`</p>
<p>And that print statement in userhomeview also returns True each time a not logged in user accesses the url directly.
My url file is : `</p>
<pre><code>from django.conf.urls import url,include
from django.contrib import admin
from .views import SignUpView,SignInView,SignOutView,UserHomeView
urlpatterns = [
url(r'^signup/$',SignUpView.as_view()),
url(r'^signin/$',SignInView.as_view()),
url(r'^signout/$',SignOutView.as_view()),
url(r'^(?P<email>[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)/',UserHomeView.as_view()),
]
</code></pre>
<p>`</p>
<p>My settings file is : `</p>
<pre><code>"""
Django settings for django_3 project.
Generated by 'django-admin startproject' using Django 1.9.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ac=6)v&jf(90%!op*$ttf29+qw_51n+(5#(jas&f&*(!=q310u'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
STATIC_URL = '/static/'
STATIC_ROOT = '/Users/waqarahmed/Desktop/Python Projects/learning_django/django_3/assets'
STATICFILES_DIRS = (
os.path.join(
BASE_DIR,'static',
),
)
AUTH_USER_MODEL = 'users.MyUser'
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend','users.backend.ClientAuthBackend')
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'django_3.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'django_3.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
</code></pre>
<p><code>
My custom backend file is :</code></p>
<pre><code>from .models import MyUser
from django.contrib.auth.backends import ModelBackend
class ClientAuthBackend(ModelBackend):
def authenticate(self,username=None,password=None):
try:
user = MyUser.objects.get(email=username)
if user.check_password(password):
return user
else:
return None
except MyUser.DoesNotExist:
return None
def get_user(self,email):
try:
user = MyUser.objects.get(email=email)
return user
except MyUser.DoesNotExist:
return None
</code></pre>
<p>`</p>
<p>And my model file is : `</p>
<pre><code>from django.db import models
from django.contrib.auth.models import (
BaseUserManager,AbstractBaseUser
)
import time
from django.utils.dateparse import parse_date
class MyUserManager(BaseUserManager):
def create_user(self, email, date_of_birth, first_name, last_name, password=None):
if not email:
raise ValueError('User must have an email id !')
email = str(email).lower()
date_of_birth = str(date_of_birth)
user = self.model(
email = self.normalize_email(email=email),
date_of_birth = parse_date(date_of_birth),
first_name = first_name,
last_name = last_name,
join_date = time.strftime('%Y-%m-%d'),
)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, date_of_birth, first_name, last_name, password=None):
if not email:
raise ValueError('User must have an email id !')
user = self.model(
email = self.normalize_email(email=email),
date_of_birth = date_of_birth,
first_name = first_name,
last_name = last_name,
join_date = time.strftime('%Y-%m-%d'),
)
user.is_admin = True
user.set_password(password)
user.save()
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(verbose_name='email address',max_length=255,unique=True)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
join_date = models.DateField(auto_now_add=True)
date_of_birth = models.DateField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name','last_name','date_of_birth']
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
@property
def is_staff(self):
return self.is_admin
</code></pre>
<p>`</p>
| 0 | 2016-08-13T22:02:11Z | 38,945,227 | <p>Please correct following things first.</p>
<ul>
<li>Whenever you are using class based view you must use request object via <code>self</code>.</li>
<li>Check auth use with the following<code>self.request.user.is_authenticated()</code>(It will return the what request does have)</li>
<li>If you want to use an automated way to check if a request is from an authenticated user you must use following middelwares <code>django.contrib.auth.middleware.AuthenticationMiddleware</code> <code>django.contrib.auth.middleware.RemoteUserMiddleware</code>(add thes two in settings installed_apps) with following decorator <code>from django.contrib.auth.decorators import login_required</code>. Add <code>@login_required</code> above the view. </li>
</ul>
| 0 | 2016-08-14T18:20:35Z | [
"python",
"django",
"authentication"
] |
regarding understanding a python function using logical operators | 38,937,461 | <p>I once read the following python function,</p>
<pre><code>def f1(i, num_digits):
return np.array([i >> d & 1 for d in range(num_digits)])
</code></pre>
<p>I am not very clear on how does the part of <code>i >> d & 1</code> work. Running <code>f1(2,5)</code> will return <code>[0,1,0,0,0]</code></p>
| 0 | 2016-08-13T22:16:33Z | 38,937,586 | <p>This function creates a list containing the last bit of <code>i</code> after it got shifted <code>index</code> times to the right.</p>
<p>Sounds cryptic? It is.</p>
<p>Here is what happens:</p>
<p>The list comprehension creates a list of size <code>num_digits-1</code>, using the values of the range expression (which are 0 to <code>num_digits-1</code>) to calculate the value of the item that is supposed to be at that index of the list. To calculate the value of the list item, the integer <code>i</code> is taken and the bits of it are shifted to the right by <code>d</code> places, where <code>d</code> is the current value of the range we are iterating over to construct our list. The <code>>></code> (bitshift-right) operator has higher precedence than the <code>&</code> operator, so this calculation is done first. The last step to calculating the list value is performing a logical <code>&</code> of the bitshifted value and the value <code>1</code>. This step requires some thinking, but what it does is it returns the last bit of our bitshifted value.</p>
<p>This is easier if you actually do the steps on a piece of paper. See, how the only time the last bit of our computation is 1 is if we shift the bit value of 2 to the right by one place (hence the list entry at index 1 is a 1 and the rest are 0's):</p>
<pre><code>Index 0: 2 (dec) = 10 (bin) -> >> 0 -> 10 (bin) -> 10 & 01 = 00 (bin) = 0 (dec)
Index 1: 2 (dec) = 10 (bin) -> >> 1 -> 01 (bin) -> 01 & 01 = 01 (bin) = 1 (dec)
Index 2: 2 (dec) = 10 (bin) -> >> 2 -> 00 (bin) -> 00 & 01 = 00 (bin) = 0 (dec)
# From here on it will be the same as index 2, because we are only shifting 0's
</code></pre>
<p>I hope this helps you understanding what is going on.</p>
| 0 | 2016-08-13T22:40:58Z | [
"python",
"numpy",
"scipy"
] |
regarding understanding a python function using logical operators | 38,937,461 | <p>I once read the following python function,</p>
<pre><code>def f1(i, num_digits):
return np.array([i >> d & 1 for d in range(num_digits)])
</code></pre>
<p>I am not very clear on how does the part of <code>i >> d & 1</code> work. Running <code>f1(2,5)</code> will return <code>[0,1,0,0,0]</code></p>
| 0 | 2016-08-13T22:16:33Z | 38,937,783 | <p><code>numpy</code> lets us demonstrate this action in a nice table:</p>
<pre><code>In [1633]: np.arange(10)[:,None]>>np.arange(5)
Out[1633]:
array([[0, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[2, 1, 0, 0, 0],
[3, 1, 0, 0, 0],
[4, 2, 1, 0, 0],
[5, 2, 1, 0, 0],
[6, 3, 1, 0, 0],
[7, 3, 1, 0, 0],
[8, 4, 2, 1, 0],
[9, 4, 2, 1, 0]], dtype=int32)
</code></pre>
<p>Looks like <code>& 1</code> turns this into a binary digit representation:</p>
<pre><code>In [1634]: np.arange(10)[:,None]>>np.arange(5) & 1
Out[1634]:
array([[0, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[1, 0, 1, 0, 0],
[0, 1, 1, 0, 0],
[1, 1, 1, 0, 0],
[0, 0, 0, 1, 0],
[1, 0, 0, 1, 0]], dtype=int32)
</code></pre>
<p>The bit shift is effectively a divide by powers of 2</p>
<pre><code>In [1641]: np.arange(10)[:,None]//(2**np.arange(5))
Out[1641]:
array([[0, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[2, 1, 0, 0, 0],
[3, 1, 0, 0, 0],
[4, 2, 1, 0, 0],
[5, 2, 1, 0, 0],
[6, 3, 1, 0, 0],
[7, 3, 1, 0, 0],
[8, 4, 2, 1, 0],
[9, 4, 2, 1, 0]], dtype=int32)
</code></pre>
<p>and a modulus 2 remainder:</p>
<pre><code>In [1642]: np.arange(10)[:,None]//(2**np.arange(5)) % 2
Out[1642]:
array([[0, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[1, 0, 1, 0, 0],
[0, 1, 1, 0, 0],
[1, 1, 1, 0, 0],
[0, 0, 0, 1, 0],
[1, 0, 0, 1, 0]], dtype=int32)
</code></pre>
| 0 | 2016-08-13T23:18:48Z | [
"python",
"numpy",
"scipy"
] |
MultiValueDictKeyError on Django View with GET | 38,937,506 | <p>Trying to build a facebook bot with Django. I get a <code>MultiValueDictKeyError</code> when I do <code>except ValueError:</code>. I am using ngrok to hook Django up to facebook.</p>
<p>Here is the code:</p>
<pre><code>class PPBChatBotView(generic.View):
def get(self, request, *args, **kwargs):
try:
if self.request.GET['hub.verify_token'] == '10101100':
return HttpResponse(self.request.GET['hub.challenge'])
else:
return HttpResponse('Error, invalid token supplied')
except ValueError:
pass
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return generic.View.dispatch(self, request, *args, **kwargs)
#POST function to handle Facebook messages
def post(self, request, *args, **kwargs):
#Convert the text payload into a python dictionary
incoming_message = json.loads(self.request.body.decode('utf-8'))
for entry in incoming_message['entry']:
for message in entry['messaging']:
if 'message' in message:
#Print the message to the terminal
pprint(message)
return HttpResponse()
</code></pre>
<p>This is what is printed in the terminal (with response code 500) after I try loading the URL in my browser:</p>
<pre><code> raise MultiValueDictKeyError(repr(key))
django.utils.datastructures.MultiValueDictKeyError: "'hub.verify_token'"
[13/Aug/2016 22:13:44] "GET /ppbchatbot/c7ca5ddafdcde1b9a3d9c6a8cdf3bf6e45fe7b41f2c0bd078f HTTP/1.1" 500 105527
</code></pre>
<p>When I use <code>.GET.get()</code>, I get a positive response in the terminal (response code 200) but it says the token is invalid even though it is vlid on both ends (localhost and Facebook):</p>
<pre><code>[13/Aug/2016 22:20:11] "GET /ppbchatbot/c7ca5ddafdcde1b9a3d9c6a8cdf3bf6e45fe7b41f2c0bd078f HTTP/1.1" 200 29
</code></pre>
<p>What am I doing wrong?</p>
| 0 | 2016-08-13T22:25:25Z | 39,446,429 | <p>Try <code>if request.GET.get('hub.verify_token') == '10101100':</code></p>
| 0 | 2016-09-12T08:46:01Z | [
"python",
"facebook",
"python-3.x",
"hash",
"django-views"
] |
Parsing Successfully Until IndexError? | 38,937,518 | <p>I have a script that's parsing for the first upper-case words in this file:</p>
<pre><code>IMPORT fs
IF fs.exists("fs.pyra") THEN
PRINT "fs.pyra Exists!"
END
</code></pre>
<p>The script looks like this:</p>
<pre><code>file = open(sys.argv[1], "r")
file = file.read().split("\n")
while '' in file:
findIt = file.index('')
file.pop(findIt)
for line in file:
func = ""
index = 0
while line[index] == " ":
index = index + 1
while not line[index] == " " or "=" and line[index].isupper():
func = func + line[index]
index = index + 1
print func
</code></pre>
<p>All used modules are already imported.<br>
I passed the file that's being parsed's path in the arguments, and I'm getting this output:</p>
<pre><code>IMPORT
IF
PRINT
Traceback (most recent call last):
File "src/source.py", line 20, in <module>
while not line[index] == " " or "=" and line[index].isupper():
IndexError: string index out of range
</code></pre>
<p>Which means it's parsing successfully until the last argument in the list, and then it's not parsing it at all. How do I fix this?</p>
| 0 | 2016-08-13T22:28:24Z | 38,937,583 | <p>You don't need to increment the index on spaces - <code>line.strip()</code> will remove leading and trailing spaces. </p>
<p>You could <code>split()</code> the line on spaces to get words. </p>
<p>Then you can iterate over those strings and use <code>isupper()</code> to check whole words, rather than individual characters </p>
<hr>
<p>Alternatively, run the whole file through a pattern matcher for <code>[A-Z]+</code></p>
<hr>
<p>Anyways, your error... </p>
<pre><code>while not line[index] == " " or "="
</code></pre>
<p>The <code>or "="</code> is always True, so your index is going out of bounds </p>
| 0 | 2016-08-13T22:40:33Z | [
"python"
] |
Parsing Successfully Until IndexError? | 38,937,518 | <p>I have a script that's parsing for the first upper-case words in this file:</p>
<pre><code>IMPORT fs
IF fs.exists("fs.pyra") THEN
PRINT "fs.pyra Exists!"
END
</code></pre>
<p>The script looks like this:</p>
<pre><code>file = open(sys.argv[1], "r")
file = file.read().split("\n")
while '' in file:
findIt = file.index('')
file.pop(findIt)
for line in file:
func = ""
index = 0
while line[index] == " ":
index = index + 1
while not line[index] == " " or "=" and line[index].isupper():
func = func + line[index]
index = index + 1
print func
</code></pre>
<p>All used modules are already imported.<br>
I passed the file that's being parsed's path in the arguments, and I'm getting this output:</p>
<pre><code>IMPORT
IF
PRINT
Traceback (most recent call last):
File "src/source.py", line 20, in <module>
while not line[index] == " " or "=" and line[index].isupper():
IndexError: string index out of range
</code></pre>
<p>Which means it's parsing successfully until the last argument in the list, and then it's not parsing it at all. How do I fix this?</p>
| 0 | 2016-08-13T22:28:24Z | 38,937,645 | <p>If the file you're trying to process is compatible with Python's built in tokenizer, you can use that so it'll also handle stuff within quotes, then take the very first name token it finds in capitals from each line, eg:</p>
<pre><code>import sys
from itertools import groupby
from tokenize import generate_tokens, NAME
with open(sys.argv[1]) as fin:
# Tokenize and group by each line
grouped = groupby(tokenize.generate_tokens(fin.readline), lambda L: L[4])
# Go over the lines
for k, g in grouped:
try:
# Get the first capitalised name
print next(t[1] for t in g if t[0] == NAME and t[1].isupper())
except StopIteration:
# Couldn't find one - so no panic - move on
pass
</code></pre>
<p>This gives you:</p>
<pre><code>IMPORT
IF
PRINT
END
</code></pre>
| 0 | 2016-08-13T22:51:40Z | [
"python"
] |
How do I fix an error in my python code where it is complaining about a string being wanted? | 38,937,545 | <p>I was actually using code from a course at Udacity.com on Data Wrangling. The code file is very short so I was able to copy what they did and I still get an error. They use python 2.7.x. The course is about a year old, so maybe something about the functions or modules in the 2.7 branch has changed. I mean the code used by the instructors works.</p>
<p>I know that using the csv module or function would solve the issue but they want to demonstrate the use of a custom parse function. In addition, they are using the enumerate function. Here is the <a href="https://gist.github.com/BruceMWhealton/f8181a2d003eaf14024c78b7ca53266f" rel="nofollow">link to the gist</a>.</p>
<p>This should be very simple and basic and that is why it is frustrating me. I know they are reading the file, which is a csv file, as binary, with the "rb" parameter to the line </p>
<pre><code>with open("file.csv", "rb") as f:
</code></pre>
| 0 | 2016-08-13T22:33:20Z | 38,946,383 | <p>You don't have matching characters in your csv file and the dictionaries in your test function. In particular, in your csv file you are using an <em>em dash</em> (U+2014) and in your <code>firstline</code> and <code>tenthline</code> dictionaries you are using a <em>hyphen-minus</em> (U+002D).</p>
<pre><code>hex(ord(d[0]['US Chart Position'].decode('utf-8')))
'0x2014' # output: code point for the em dash character in csv file
hex(ord(firstline['US Chart Position']))
'0x2d' # output: code point for hyphen-minus
</code></pre>
<p>To fix it, just copy and paste the <code>â</code> character from the csv in your gist into the dictionaries in your source code to replace the <code>-</code> characters.</p>
<p>Make sure to include this comment at the top of your file:</p>
<pre><code># -*- coding: utf-8 -*-
</code></pre>
<p>This will ensure that Python knows to expect non-ascii characters in the source code.</p>
<p>Alternatively, you could replace all the <code>â</code> (em dash) characters in the csv file with hyphens:</p>
<pre><code>sed 's/â/-/g' beatles-diskography.csv > beatles-diskography2.csv
</code></pre>
<p>Then, remember to use the new file name in your source code.</p>
| 1 | 2016-08-14T20:35:47Z | [
"python",
"python-2.7",
"csv"
] |
list index out of range error while using if statement in for loop | 38,937,621 | <p>I'm new to python; I've been coding in javascript so I'm not used to all the errors I'm getting.</p>
<p>I'm trying to add properties to an empty object with a for loop, but I get an error saying list index out of range. The error seems to be happening when I add an if statement inside my for loop. I'm not using an index to loop through the seats_info array though. Please help me understand why this is happening, thank you!</p>
<pre><code> seats_info = ['\n1,133,0,A', '\n1,133,2,C', '\n1,133,1,B', '\n1,133,4,E', '\n1,133,3,D', '\n2,132,0,24', '\n2,132,1,25', '\n2,132,2,26']
def read_manifest(self, manifest):
file = manifest_dir + '/' + manifest
data = open(file, 'r')
seats_info = data.read().split('\r')[1:]
data.close()
self.seat_information = {}
for seat_info in seats_info:
one_seat = seat_info.split(',')
section_id = one_seat[0][1:]
one_seat.remove(one_seat[0])
one_seat.insert(0, section_id)
if one_seat[1] not in self.seat_information:
self.seat_information[one_seat[1]] = [one_seat]
else:
self.seat_information[one_seat[1]].append(one_seat)
Error Message that I received
Traceback (most recent call last):
File "path/normalizer.py", line 75, in <module>
normalizer.read_manifest(citifield)
File "path/normalizer.py", line 36, in read_manifest
if one_seat[1] not in self.seat_information:
IndexError: list index out of range
</code></pre>
| 0 | 2016-08-13T22:46:49Z | 38,962,564 | <p>Insert a blank line in the data file to reproduce the error.</p>
<pre><code>section_id = one_seat[0][1:]
one_seat[0] = section_id
</code></pre>
<p>At this point, one_seat = [''], so there is no one_seat[1]</p>
<pre><code>if one_seat[1] ...
</code></pre>
<p>Thus list index out of range is correctly raised.</p>
<p>Instead, when you use hard-coded indexes, you may want to verify that your assumptions hold. Here is a sample re-write:</p>
<pre><code>def execute():
seats_info = ['\n', '\n1,133,0,A', '\n1,133,2,C', '\n1,133,1,B', '\n1,133,4,E', '\n1,133,3,D', '\n2,132,0,24', '\n2,132,1,25', '\n2,132,2,26']
for seat_info in seats_info:
one_seat = seat_info.split(',')
if len(one_seat):
section_id = one_seat[0][1:]
one_seat[0] = section_id
# maybe check for a legal section_id here?
if len(one_seat) > 1:
row_id = one_seat[1]
if row_id not in seat_information:
seat_information[row_id] = [one_seat]
else:
seat_information[row_id].append(one_seat)
seat_information = {}
execute()
for row, seats in seat_information.items():
print "row", row
for seat in seats:
print "seat:", seat
</code></pre>
| 0 | 2016-08-15T20:29:11Z | [
"python",
"python-2.7"
] |
list index out of range error while using if statement in for loop | 38,937,621 | <p>I'm new to python; I've been coding in javascript so I'm not used to all the errors I'm getting.</p>
<p>I'm trying to add properties to an empty object with a for loop, but I get an error saying list index out of range. The error seems to be happening when I add an if statement inside my for loop. I'm not using an index to loop through the seats_info array though. Please help me understand why this is happening, thank you!</p>
<pre><code> seats_info = ['\n1,133,0,A', '\n1,133,2,C', '\n1,133,1,B', '\n1,133,4,E', '\n1,133,3,D', '\n2,132,0,24', '\n2,132,1,25', '\n2,132,2,26']
def read_manifest(self, manifest):
file = manifest_dir + '/' + manifest
data = open(file, 'r')
seats_info = data.read().split('\r')[1:]
data.close()
self.seat_information = {}
for seat_info in seats_info:
one_seat = seat_info.split(',')
section_id = one_seat[0][1:]
one_seat.remove(one_seat[0])
one_seat.insert(0, section_id)
if one_seat[1] not in self.seat_information:
self.seat_information[one_seat[1]] = [one_seat]
else:
self.seat_information[one_seat[1]].append(one_seat)
Error Message that I received
Traceback (most recent call last):
File "path/normalizer.py", line 75, in <module>
normalizer.read_manifest(citifield)
File "path/normalizer.py", line 36, in read_manifest
if one_seat[1] not in self.seat_information:
IndexError: list index out of range
</code></pre>
| 0 | 2016-08-13T22:46:49Z | 38,963,069 | <p>Although the solution by Kenny Ostrom is well, I would actually suggest pre-processing the data file after reading it in. This way, you don't have to constantly check assumptions and it simplifies the code. Specifically, I had the following in mind:</p>
<pre><code>seats_info = ['\n', '\n1,133,0,A', '\n1,133,2,C', '\n1,133,1,B', '\n1,133,4,E', '\n1,133,3,D', '\n2,132,0,24', '\n2,132,1,25', '\n2,132,2,26']
#remove new line and other markup characters
seats_info = [str.strip(s) for s in seats_info]
#remove elements that have no content:
seats_info = [s for s in seats_info if len(s)>0]
</code></pre>
<p>so now, <code>seats_info</code> is cleaner and won't throw errors at you:</p>
<pre><code>In [21]: seats_info
Out[21]:
['1,133,0,A',
'1,133,2,C',
'1,133,1,B',
'1,133,4,E',
'1,133,3,D',
'2,132,0,24',
'2,132,1,25',
'2,132,2,26']
</code></pre>
<p>Since currently you're indexing out the <code>\n</code> but now you don't have to, you'll have to simplify your data extraction loop to:</p>
<pre><code>for seat_info in seats_info:
one_seat = seat_info.split(',')
section_id = one_seat[0]
if one_seat[1] not in seat_information:
self.seat_information[one_seat[1]] = [one_seat]
else:
self.seat_information[one_seat[1]].append(one_seat)
</code></pre>
<p>Finally, I HIGHLY encourage you to use the <code>with</code> statement to read in your data as that is easier on the eyes and, I'd say, more Pythonic. Specifically, consider the following definition for your <code>read_manifest</code> function:</p>
<pre><code>def read_manifest(self, manifest):
file = manifest_dir + '/' + manifest
#read in the file:
with open(file, 'r') as f:
#because we later use str.strip, you don't need to do [1:] to get rid of \r
seats_info = f.read().split('\r')
#pre-process:
seats_info = [str.strip(s) for s in seats_info]
seats_info = [s for s in seats_info if len(s)>0]
</code></pre>
| -1 | 2016-08-15T21:06:33Z | [
"python",
"python-2.7"
] |
Pandas rank by column value with conditions | 38,937,652 | <p>I have the following dataset <strong>(non-unique id)</strong> :</p>
<pre><code>id data country
1 8 B
2 15 A
3 14 D
3 19 D
3 8 C
3 20 A
</code></pre>
<p>For rows with <strong>country ANYTHING BUT "A"</strong>, I want to add a "rank" column.</p>
<p>For rows with <strong>country "A"</strong>, I want to leave "rank" value empty (or 0).</p>
<p>Expected output :</p>
<pre><code>id data country rank
1 8 B 1
2 15 A 0
3 14 D 3
3 19 D 4
3 8 C 2
3 20 A 0
</code></pre>
<p>This post <a href="http://stackoverflow.com/questions/30425796/pandas-rank-by-column-value">Pandas rank by column value</a> gives great insight.</p>
<p>I can try :</p>
<pre><code>df['rank'] = df['data'].rank(ascending=True)
</code></pre>
<p>but I don't know how to take "country" into account ?</p>
| 1 | 2016-08-13T22:52:49Z | 38,937,838 | <p><strong>EDIT: Written before an edit to the question so doesn't do exactly what the OP wants.</strong></p>
<pre><code>df['rank_A'] = df.data[df['country']=='A'].rank(ascending=True)
</code></pre>
<p>Tested on this </p>
<pre><code> import pandas as pd
from pandas import DataFrame
import numpy as np
df2 = DataFrame(np.random.randn(5, 2))
df2.columns = ['A','B']
df2['rank'] = df2.A[df2['B']>0].rank(ascending=True)
df2
</code></pre>
<p>which gives the ranking according to A for rows in which B is greater than zero.</p>
| 2 | 2016-08-13T23:27:20Z | [
"python",
"sorting",
"pandas"
] |
python loops without index | 38,937,663 | <p>I'm learning python and I love that you can loop through iterable objects without constantly creating index variables. </p>
<p>But I keep finding myself creating index variables anyway so I can reference them in calls from parallel objects. Like when I'm comparing two lists, or a list and a dictionary. </p>
<p>As requested: some examples </p>
<pre><code>`s= "GAGCCTACTAACGGGAT"# the strings we are evaluating
t= "CATCGTAATGACGGCCT"
c = 0# c = position of interest within the strings
m = 0 # m = number of mutations found so far.
for i in s: # cycling through all nucleotides listed in s
if(i == t[c]): #compare s[c] to t[c]
c +=1 # if equal, increase position counter
else:
c+=1 # if not equal, increase both position and
m+=1 #mutation counters.`
</code></pre>
<p>AND </p>
<pre><code>def allPossibleSubStr(s): #takes a dict of strings, finds the shortest, and produces a list of all possible substrings, thus a list of possible common substrings to all elements of the original dict
ks = s.keys()
c=0 #counter
j=0 # ks place holder for shortest string
subSTR = []
for i in ks: #finds the shortest entry in stringDict
if(s[i] < s[ks[(c+1)%len(s)]]):
j=c
c +=1
c=s[ks[j]] #c is now a string, the shortest...
j=ks[j] # j is now a key string, the shortest...
n = (len(c)*(len(c)+1))/2 # number of subsets of c
#producing a list of possible substrings
for i in range(len(c)):
for k in range(len(c)-i):
subSTR.append(c[i:i+k+1])
#print("i =" +str(i)+ " and k=" + str(k))
#is there a list function with eleminates duplicate entries.
subSTR=list(set(subSTR))# a set does not have any duplicate entires
subSTR.sort(key=len) # sorts substring from shortest to longest string
subSTR.reverse()
return subSTR
</code></pre>
<p>Is there a way around this? </p>
| -1 | 2016-08-13T22:54:54Z | 38,937,674 | <p>Use enumerate...</p>
<pre><code>for i, item in enumerate(myList):
foo = parallelList[i]
</code></pre>
<p>or zip...</p>
<pre><code>for item, foo in zip(myList, parallelList):
...
</code></pre>
| 1 | 2016-08-13T22:57:14Z | [
"python",
"loops",
"indexing"
] |
python loops without index | 38,937,663 | <p>I'm learning python and I love that you can loop through iterable objects without constantly creating index variables. </p>
<p>But I keep finding myself creating index variables anyway so I can reference them in calls from parallel objects. Like when I'm comparing two lists, or a list and a dictionary. </p>
<p>As requested: some examples </p>
<pre><code>`s= "GAGCCTACTAACGGGAT"# the strings we are evaluating
t= "CATCGTAATGACGGCCT"
c = 0# c = position of interest within the strings
m = 0 # m = number of mutations found so far.
for i in s: # cycling through all nucleotides listed in s
if(i == t[c]): #compare s[c] to t[c]
c +=1 # if equal, increase position counter
else:
c+=1 # if not equal, increase both position and
m+=1 #mutation counters.`
</code></pre>
<p>AND </p>
<pre><code>def allPossibleSubStr(s): #takes a dict of strings, finds the shortest, and produces a list of all possible substrings, thus a list of possible common substrings to all elements of the original dict
ks = s.keys()
c=0 #counter
j=0 # ks place holder for shortest string
subSTR = []
for i in ks: #finds the shortest entry in stringDict
if(s[i] < s[ks[(c+1)%len(s)]]):
j=c
c +=1
c=s[ks[j]] #c is now a string, the shortest...
j=ks[j] # j is now a key string, the shortest...
n = (len(c)*(len(c)+1))/2 # number of subsets of c
#producing a list of possible substrings
for i in range(len(c)):
for k in range(len(c)-i):
subSTR.append(c[i:i+k+1])
#print("i =" +str(i)+ " and k=" + str(k))
#is there a list function with eleminates duplicate entries.
subSTR=list(set(subSTR))# a set does not have any duplicate entires
subSTR.sort(key=len) # sorts substring from shortest to longest string
subSTR.reverse()
return subSTR
</code></pre>
<p>Is there a way around this? </p>
| -1 | 2016-08-13T22:54:54Z | 38,938,653 | <p>It sounds like you write code like this:</p>
<pre><code>for i, item in enumerate(list1):
if item == list2[i]:
...
</code></pre>
<p>You still don't need an explicit index, because you can zip the two lists and iterate over a list of tuples.</p>
<pre><code>for item1, item2 in zip(list1, list2):
if item1 == item2:
</code></pre>
<p>You can do the same thing with two dicts, although since they are unordered, you probably want to zip their keys after sorting:</p>
<pre><code>for key1, key2 in zip(sorted(dict1), sorted(dict2)):
</code></pre>
| 1 | 2016-08-14T02:34:09Z | [
"python",
"loops",
"indexing"
] |
I need help in understanding the function of the number "1" and the word 'sum' in the code below | 38,937,685 | <p>This is the solution to counting upper and lower case letters in a sentence that my friend gave to me without explaining the use of 1 in the statements.</p>
<pre><code>x = raw_input('Enter the word')
print ("Capital Letters: ", sum(1 for d in x if d.isupper()))
print ("Small letters:" , sum(1 for d in x if d.islower()))
</code></pre>
<p>Could anyone help me explain why 1 is used ? also why is sum used instead of len?
Thanks </p>
| 0 | 2016-08-13T22:59:59Z | 38,937,717 | <p>He's filtering all the capital letters in a string and building a list of 1's for each item in the remaining list. Then he's summing that list. Since the list comprehension is building a generator and not a list, <code>len</code> cannot be used.</p>
<p>(Edited. Previous version said <code>len</code> could be used equivalently)</p>
| 0 | 2016-08-13T23:04:57Z | [
"python"
] |
I need help in understanding the function of the number "1" and the word 'sum' in the code below | 38,937,685 | <p>This is the solution to counting upper and lower case letters in a sentence that my friend gave to me without explaining the use of 1 in the statements.</p>
<pre><code>x = raw_input('Enter the word')
print ("Capital Letters: ", sum(1 for d in x if d.isupper()))
print ("Small letters:" , sum(1 for d in x if d.islower()))
</code></pre>
<p>Could anyone help me explain why 1 is used ? also why is sum used instead of len?
Thanks </p>
| 0 | 2016-08-13T22:59:59Z | 38,937,756 | <p>The <code>sum</code> function takes in a container as its arguments and returns the sum of its elements.</p>
<p>This line, <code>sum(1 for d in x if d.isupper())</code>, feeds a generator expression to the <code>sum</code> function, consisting of ones, which in effect counts the number of upper case words in the string. </p>
<p>For example if your string was <code>HeLLo</code>, it would essentially look like <code>sum((1,1,1))</code>, which is equal to 3.</p>
| 1 | 2016-08-13T23:13:40Z | [
"python"
] |
global frame vs. stack frame | 38,937,721 | <p><em>Everything below is from the main page of <a href="http://www.pythontutor.com" rel="nofollow">www.pythontutor.com</a> (a fantastic tool and website by the way).</em></p>
<p>Here's some code (image file):</p>
<p><a href="http://i.stack.imgur.com/cfGvY.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/cfGvY.jpg" alt="Here's some code:"></a></p>
<p>Here's what the author describes as the "global frame" and the "stack frames" at the current point of execution for the above code:</p>
<p><a href="http://i.stack.imgur.com/ilR0f.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/ilR0f.jpg" alt="Here's what the author describes as the "global frame" and the "stack frames" at the current point of execution for the above code"></a> </p>
<p><strong>My question:</strong> What's the difference between "global frame" and the "stack frame"? Is this terminology even correct (I googled around and got all kinds of different answers)?</p>
| 1 | 2016-08-13T23:05:24Z | 38,938,014 | <p><a href="https://docs.python.org/2/library/inspect.html#inspect.currentframe" rel="nofollow"><code>frames</code></a> are actual python objects that you can interact with:</p>
<pre><code>import inspect
my_frame = inspect.currentframe()
print(my_frame) #<frame object at MEMORY_LOCATION>
print(my_frame.f_lineno) #this is line 7 so it prints 7
print(my_frame.f_lineno) #this is line 8 so it prints 8
print(my_frame.f_lineno) #this is line 9 so it prints 9
</code></pre>
<p>You seem to think that there is something special about a global frame vs a local frame but they are just frames in the <a href="https://docs.python.org/2/library/inspect.html#inspect.stack" rel="nofollow"><code>stack</code></a> of execution:</p>
<pre><code>Python 3.6.0a1 (v3.6.0a1:5896da372fb0, May 16 2016, 15:20:48)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import inspect
>>> import pprint
>>> def test():
... pprint.pprint(inspect.stack())
...
>>> test() #shows the frame in test() and global frame
[FrameInfo(frame=<frame object at 0x1003a3be0>, filename='<stdin>', lineno=2, function='test', code_context=None, index=None),
FrameInfo(frame=<frame object at 0x101574048>, filename='<stdin>', lineno=1, function='<module>', code_context=None, index=None)]
>>> pprint.pprint(inspect.stack()) #only shows global frame
[FrameInfo(frame=<frame object at 0x1004296a8>, filename='<stdin>', lineno=1, function='<module>', code_context=None, index=None)]
</code></pre>
<p>When ever you call a function (defined with python source code) it will add a frame local to that function call to the stack, when ever a module is loaded then the global frame for that module is added to the stack. This means that the first module loaded is always the bottom frame in the stack.</p>
<p>The only real difference between global and "function" frames is that with global frames there is no distinction between global and local variables:</p>
<pre><code>>>> my_frame.f_globals is my_frame.f_locals
True
</code></pre>
<p>The <code>global</code> keyword indicates variables that - when assigned - should be set in <code>.f_globals</code> instead of <code>.f_locals</code>. This is why adding the <code>global</code> keyword in the global scope does nothing, because <code>f_locals</code> and <code>f_globals</code> point to the same namespace.</p>
<p>In your case the term "global frame" is just the name given to that frame because usually frames are identified by the function they are in, since global frames are not within a function they are just called "global" in your tutorial, python instead refers to them as being <code><module></code> as can be seen in above example (<code>function='<module>'</code>) or in errors:</p>
<pre><code>>>> raise TypeError
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
raise TypeError
TypeError
# ^ up there
</code></pre>
| 1 | 2016-08-14T00:00:52Z | [
"python",
"python-2.7",
"stack",
"global",
"stack-trace"
] |
First Digits of a number | 38,937,776 | <p>I want the first 9 digits and last 9 digits of a fibonocci series for an infinite loop. Running the tests individually, I get better result for the last 9 digits using modulo operator no where comparable to the first 9 digits. I ran different tests like <code>int(str(b)[::-1])%10**9, b/(10**(len(str(b))-9))</code> but still the same result. I think this happens because of number to string conversion of higher digits. Is there any other way of printing the first 9 digits without converting into a string or an efficient way with/without strings?</p>
<pre><code>def fibby():
a,b = 1,1
yield [a,a]
yield [b,b]
while True:
a,b = b,a+b
yield [str(b)[:9], b%10**9]
</code></pre>
| 2 | 2016-08-13T23:16:22Z | 38,938,240 | <p>Here are a few versions and timings for getting the first 30000 prefixes. I left out the first two yields and the last digits for simplicity.</p>
<ul>
<li><code>fibby1</code> is the original way just using <code>str(b)[:9]</code>.</li>
<li><code>fibby2</code> keeps track of the appropriate power of 10 to divide by.</li>
<li><code>fibby3</code> keeps the first 9 digits in <code>a</code> and <code>b</code> and the remaining digits in <code>A</code> and <code>B</code>. Compared to <code>fibby2</code>, this avoids dividing a large <code>b</code> by a large power of 10. Large numbers are only added/subtracted/compared, or multiplied with a tiny number.</li>
<li><code>fibby4</code> uses <code>math.log10</code> suggested by @therefromhere.</li>
<li><code>fibby5</code> uses the <a href="https://docs.python.org/3/library/decimal.html" rel="nofollow"><code>decimal</code></a> module.</li>
</ul>
<p>The output:</p>
<pre><code>All agree? True
fibby1: 24.835 seconds
fibby2: 0.289 seconds
fibby3: 0.201 seconds
fibby4: 2.802 seconds
fibby5: 0.216 seconds
</code></pre>
<p>Just for comparison I also tried <code>str(b % 10**9)</code>, i.e., the last nine digits, and that took 0.506 seconds. Which is <strong>slower</strong> than my fast solutions for the first nine digits.</p>
<p>The code:</p>
<pre><code>def fibby1():
a, b = 1, 1
while True:
yield str(b)[:9]
a, b = b, a+b
def fibby2():
a, b = 1, 1
div = 1
while True:
while True:
front = b // div
if front < 10**9:
break
div *= 10
yield str(front)
a, b = b, a+b
def fibby3():
a,b = 1,1
A,B,C = 0,0,1
while True:
yield str(b)
a, b = b, a+b
A, B = B, A+B
if B >= C:
B -= C
b += 1
if b >= 10**9:
A += a%10 * C
B += b%10 * C
a //= 10
b //= 10
C *= 10
def fibby4():
from math import log10
a, b = 1, 1
while True:
yield str(b // 10**max(0, int(log10(b) - 8)))
a, b = b, a+b
def fibby5():
from decimal import Decimal, getcontext
getcontext().prec = 7000 # enough for n = 30000
a, b = Decimal(1), Decimal(1)
while True:
yield str(b)[:9]
a, b = b, a+b
from timeit import timeit
from itertools import islice
from time import time
n = 30000
t0 = time()
list1 = list(islice(fibby1(), n))
t1 = time()
list2 = list(islice(fibby2(), n))
t2 = time()
list3 = list(islice(fibby3(), n))
t3 = time()
list4 = list(islice(fibby4(), n))
t4 = time()
list5 = list(islice(fibby5(), n))
t5 = time()
print('All agree?', list1 == list2 == list3 == list4 == list5)
print('fibby1: %6.3f seconds' % (t1 - t0))
print('fibby2: %6.3f seconds' % (t2 - t1))
print('fibby3: %6.3f seconds' % (t3 - t2))
print('fibby4: %6.3f seconds' % (t4 - t3))
print('fibby5: %6.3f seconds' % (t5 - t4))
</code></pre>
| 1 | 2016-08-14T00:48:38Z | [
"python"
] |
python write to file does not write | 38,937,777 | <p>I have found similar questions, and tried the solutions proposed within, and none seem to solve my problem. What I am attempting to do is in essence copy the data from one file to another, and even though it does not error our and I have verified the 'line' variable is a string and contains the correct data, it simply does not write to the file. I am currently using python 2.7. </p>
<p>I have attempted to add .flush() as some other solutions have suggested with no success. I have verified that if I write a static string before the first for loop, it does in fact write to the file. My suspicion is it has something to do with having both files open and iterating through one of them, but I am unsure on the validity of this. </p>
<pre><code>with open("data/data.csv", 'w+') as data_file, open("data/raw/" + data_point + ".csv", 'r') as raw_file:
for line in raw_file:
line = line.split(',')
temp_date = datetime(int(line[0]), int(line[1]), int(line[2]))
if newest_date == datetime(1,1,1):
newest_date = temp_date
if temp_date < oldest_date:
oldest_date = temp_date
sorted_raw = [[float(line[4]), float(line[5])]] + sorted_raw
raw_file.seek(0) # reset read pointer
for line in raw_file:
data_file.write(line)
</code></pre>
<p>EDIT: I now realize my idiocies. I had a second uncompleted function that was basicly a modified copy paste of this, but with no writes. the "w+" method of opening the file cleared it every time and since this second function was always called right after this block of code finished I was never able to catch the written file. I apologize for the noise</p>
| 0 | 2016-08-13T23:16:38Z | 38,937,798 | <p>You could just write to the data file in your first loop.</p>
<pre><code>with open("data/data.csv", 'w+') as data_file, open("data/raw/" + data_point + ".csv", 'r') as raw_file:
for line in raw_file:
line = line.split(',')
temp_date = datetime(int(line[0]), int(line[1]), int(line[2]))
if newest_date == datetime(1,1,1):
newest_date = temp_date
if temp_date < oldest_date:
oldest_date = temp_date
sorted_raw = [[float(line[4]), float(line[5])]] + sorted_raw
data_file.write(line)
</code></pre>
| 1 | 2016-08-13T23:20:51Z | [
"python"
] |
Word Search on Python 2.7.4 | 38,937,814 | <p><a href="http://i.stack.imgur.com/YlYzp.png" rel="nofollow">The image shows the output. You can clearly see how the letters are not perfectly aligned. </a>We are trying to make a game for a school project and chose Word Search. We researched and have found a piece of coding that helps us make the grid as well as place our word into the grid. But the problem we are facing now is that the grid is not properly aligned. (ie. the 3rd letter from first row is not exactly above the third letter in second row.). This makes it difficult to find the word.But unfortunately we have not studied how to use <code>random.choice</code> and cant seem to understand how to align the letters properly. All thoughts and opinions are appreciated.</p>
<pre><code>import string
import random
print '''Welcome to WORD SEARCH. This game has five stages. You will have a crossword in each stage with one element hidden in each puzzle.
However, do remember that the game is over once you make a mistake. So, think carefully and play.
Good luck!!!!'''
width = 12
height = 12
def put_word(word,grid):
word = random.choice([word,word[::-1]])
d = random.choice([[1,0],[0,1],[1,1]])
xsize = width if d[0] == 0 else width - len(word)
ysize = height if d[1] == 0 else height - len(word)
x = random.randrange(0,xsize)
y = random.randrange(0,ysize)
for i in range(0,len(word)):
grid[y + d[1]*i][x + d[0]*i] = word[i]
return grid
</code></pre>
<p>Thank You</p>
| 0 | 2016-08-13T23:23:13Z | 38,937,932 | <p>Seems to be printing fine to me... Maybe you should use a Monospaced font in your terminal / wherever you are printing out the grid. </p>
<pre><code>grid = [['_' for _ in range(width)] for _ in range(height)]
def print_grid():
global grid
for row in grid:
print " ".join(row)
put_word("hello", grid)
put_word("world", grid)
print_grid()
</code></pre>
<p>You may want to fix the algorithm, though, because words are overlapping and you see I added <code>"hello"</code>, but <code>"herlo"</code> is there instead... </p>
<p>Sample Output</p>
<pre><code>_ _ _ h _ _ _ _ _ _ _ _
_ _ _ _ e _ _ _ _ _ _ _
_ _ _ d l r o w _ _ _ _
_ _ _ _ _ _ l _ _ _ _ _
_ _ _ _ _ _ _ o _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _
</code></pre>
| 2 | 2016-08-13T23:43:33Z | [
"python",
"python-2.7"
] |
Auto creating instances of class | 38,937,891 | <p>I'm trying to create instances of a class by loading a textfile and using some strings from that as input.</p>
<p>This is supposed to spit out all the scene headers from a film manuscript and create an instance of a Scene class for every time it reads a scene header that is characterized by starting with either INT or EXT.</p>
<p>While it does find all the scenes correctly, I am having trouble creating the actual instances. </p>
<p><strong>How do I make instances of Class in the create function, and then print them out ?</strong></p>
<pre><code>class Scene(object):
def __init__(self, name, isint, isday):
self.name = name
self.isint = bool(isint)
self.isday = bool(isday)
def create(self):
with open('output.txt', 'r') as searchfile:
for line in searchfile:
if 'INT' in line or 'EXT' in line:
return Scene()
if line.startswith(INT):
Scene.isint == True
if line.endswith('NAT\n'):
Scene.isday == False
def __repr__(self):
print(self)
</code></pre>
| 0 | 2016-08-13T23:35:51Z | 38,937,962 | <p>Your function shouldn't be a method of <code>Scene</code>, since it doesn't actually do anything but create a bunch of objects. You can use generators to emit your <code>Scene</code> instances as you parse the file:</p>
<pre><code>def read_scenes(filename):
with open(filename, 'r') as handle:
scene = Scene(None, None, None)
for line in handle:
if line.startswith('INT'):
scene.isint = True
if line.endswith('NAT\n'):
scene.isday = False
if 'INT' in line or 'EXT' in line:
# Spit out the current scene
yield scene
# Create a new one
scene = Scene(None, None, None)
for scene in read_scenes('output.txt'):
print(scene)
</code></pre>
<hr>
<p><strong>Original answer</strong></p>
<p>Your <code>create</code> function is an instance method, so it requires you create an instance of your class <em>first</em> and then call the <code>create</code> method. This is kind of backwards if you think about it, since your <code>create</code> method should not require an instance of a class, since it should be the one creating the instance.</p>
<p>The solution is to make your <code>create</code> method a <a href="https://docs.python.org/3/library/functions.html#classmethod" rel="nofollow">class method</a>. Instance methods take in an <em>instance</em> of your class as their first argument, while class methods take in the <em>class itself</em>, letting you create instance of your class using different functions.</p>
<pre><code>class Scene(object):
def __init__(self, name, isint, isday):
self.name = name
self.isint = bool(isint)
self.isday = bool(isday)
@classmethod
def from_file(cls, filename, name):
isint = None
isday = None
with open(filename, 'r') as searchfile:
for line in searchfile:
if 'INT' in line or 'EXT' in line:
return cls(name, isint, isday)
if line.startswith(INT):
isint = True
if line.endswith('NAT\n'):
isday = False
</code></pre>
<p>Since the function is a class method, you don't need an instance of your <code>Scene</code> class to call it:</p>
<pre><code>scene = Scene.from_file('output.txt', 'The Name')
</code></pre>
<p>It's equivalent to doing something like:</p>
<pre><code>name, isint, isday = parse_scene_file('output.txt')
scene = Scene(name, isint, isday)
</code></pre>
| 0 | 2016-08-13T23:49:26Z | [
"python"
] |
pySerial: how to check the current baud rate | 38,937,903 | <p>I have a device (<a href="http://www.robotshop.com/media/files/pdf/datasheet-sen-11792.pdf" rel="nofollow">GT511C3 fingerprint scanner</a>) that I am connecting to Raspberry Pi and programming it using <a href="http://pyserial.readthedocs.io/en/stable/index.html" rel="nofollow">Python Serial module</a>. The GT511 device has a default baud rate of 9600, and there is capability of changing the it. Once you change the GT511 baudrate, it keeps this setting until next restart.</p>
<p>The question is if there is a way for me to check the current baud rate of the connected device (in case the device was already programmed, and connected by a different host). I know it is possible to do it using <code>stty</code>:</p>
<pre><code>$> stty < /dev/ttyAMA0
speed 57600 bud; line = 0
...
</code></pre>
<p>Is there a way to do it using Python serial or any other module, or do I have to write an iterative checking procedure to find it out?</p>
<p><strong>UPDATE 1:</strong>
Current solution I use to find the accepted baud rate:</p>
<pre><code>ser = serial.Serial('/dev/ttyAMA0')
ser.timeout = 0.5
for baudrate in ser.BAUDRATES:
if 9600 <= baudrate <= 115200:
ser.baudrate = baudrate
ser.write(packet)
resp = ser.read()
if resp != '':
break
if ser.baudrate > 115200:
raise RuntimeError("Couldn't find appropriate baud rate!")
</code></pre>
<p><strong>UPDATE 2:</strong>
Please, stop suggesting <code>serial.baudrate</code> - this is <strong>NOT</strong> what I am asking.</p>
| 0 | 2016-08-13T23:38:08Z | 38,941,001 | <p>Maybe you shoul use <code>stty</code> until you find a better alternative.
You can call it from Python code and parse the result to obtain what you need.
Here is a basic example (not tested):</p>
<pre><code>import subprocess
import shlex
def get_baudrate(device):
command = 'stty < {0}'.format(device)
proc_retval = subprocess.check_output(shlex.split(command))
baudrate = int(proc_retval.split()[1])
return baudrate
</code></pre>
| 0 | 2016-08-14T09:45:43Z | [
"python",
"serial-port",
"pyserial"
] |
Python thread in socket chat application won't start | 38,937,917 | <p>I'm new to python, and I'm trying to write a simple chat application, featuring a server which runs a thread that accepts from and transmits messages to connected clients, and a client which runs two threads that send messages to and accept messages from the server respectively. Here's the code</p>
<p>Server:</p>
<pre><code>import socket
import sys
import thread
def receiveAndDeliverMessage(conn):
while True:
data = conn.recv(1040)
if not data: break
print(data)
conn.send(data)
conn.close
HOST = '' # Localhost
PORT = 8888 # Arbitrary non-privileged port
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create a TCP/IP socket
print 'Socket created'
#Bind socket to local host and port
try:
sock.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
sock.listen(10)
print 'Socket now listening'
# Create threads for receiving a connection from client and receiving data from client
while True:
connection, address = sock.accept() #Accept method returns a tupule containing a new connection and the address of the connected client
print 'Connected with ' + address[0] + ':' + str(address[1])
try:
thread.start_new_thread(receiveAndDeliverMessage, (connection))
except:
print ("Error: unable to start thread")
sock.close()
</code></pre>
<p>Client:</p>
<pre><code>#Socket client example in python
import socket #for sockets
import sys #for exit
import thread
def sendMessage():
count = 0
while (count < 3):
message = raw_input('Write message to send to server: ');
count = count + 1
print 'message '+str(count)+': '+(message)
try :
#Send the whole string
sock.sendall(message)
except socket.error:
#Send failed
print 'Send failed'
sys.exit()
print 'Message sent successfully to server'
def receiveMessage():
reply = sock.recv(1024)
print reply#Print the message received from server
#create an INET, STREAMing socket
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print 'Failed to create socket'
sys.exit()
print 'Socket Created'
serverHost = 'localhost'
serverPort = 8888
try:
remote_ip = socket.gethostbyname(serverHost)
except socket.gaierror:
#could not resolve
print 'Hostname could not be resolved. Exiting'
sys.exit()
#Connect to remote server
sock.connect((remote_ip , serverPort))
print 'Socket Connected to ' + serverHost + ' on ip ' + remote_ip
try:
thread.start_new_thread(receiveMessage, ())
except:
print ("Error: unable to start receive message thread")
try:
thread.start_new_thread(sendMessage, ())
except:
print ("Error: unable to start send message thread")
sock.close()#Close socket to send eof to server
</code></pre>
<p>Now every time a client is opened, instead of the thread which runs receiveAndDelivermessage function running on the server, the exception gets thrown. So I get the "Error: unable to start thread". I don't understand why the exception gets thrown. Maybe I haven't yet quite grasped how threads work. Any help greatly appreciated. Also each time a client is opened, it gets terminated immediately, after the connection to server is established.</p>
| -1 | 2016-08-13T23:40:25Z | 38,938,091 | <p>You swallow the original exception and print out a custom message so it's hard to determine what's causing the issue. So I am going to provide some tips around debugging the issue. </p>
<pre><code> try:
thread.start_new_thread(receiveAndDeliverMessage, (connection))
except:
print ("Error: unable to start thread")
</code></pre>
<p>You are catching all types of exception in one <code>except</code> block which is quite bad. Even if you do so, try to find the message - </p>
<pre><code>except Exception as ex:
print(ex)
</code></pre>
<p>Or you can also get the full traceback instead of just printing the exception: </p>
<pre><code>import traceback
tb = traceback.format_ex(ex)
</code></pre>
| 1 | 2016-08-14T00:18:34Z | [
"python",
"multithreading",
"sockets",
"networking",
"chat"
] |
distributed tensorflow on localhosts failed by "socket error, connection refused" | 38,937,984 | <p>I am experimenting distributed tensorflow using a slight modification of an <a href="https://www.tensorflow.org/versions/r0.10/how_tos/distributed/index.html" rel="nofollow">official example</a>.</p>
<p>My experiment code is (you can skip this for now and scroll down to the problem),</p>
<pre><code>import tensorflow as tf
import numpy as np
# Flags for defining the tf.train.ClusterSpec
tf.app.flags.DEFINE_string("ps_hosts", "",
"Comma-separated list of hostname:port pairs")
tf.app.flags.DEFINE_string("worker_hosts", "",
"Comma-separated list of hostname:port pairs")
# Flags for defining the tf.train.Server
tf.app.flags.DEFINE_string("job_name", "", "One of 'ps', 'worker'")
tf.app.flags.DEFINE_integer("task_index", 0, "Index of task within the job")
FLAGS = tf.app.flags.FLAGS
def main(_):
ps_hosts = FLAGS.ps_hosts.split(",")
worker_hosts = FLAGS.worker_hosts.split(",")
# Create a cluster from the parameter server and worker hosts.
cluster = tf.train.ClusterSpec({"ps": ps_hosts, "worker": worker_hosts})
# Create and start a server for the local task.
server = tf.train.Server(cluster,
job_name=FLAGS.job_name,
task_index=FLAGS.task_index)
if FLAGS.job_name == "ps":
server.join()
elif FLAGS.job_name == "worker":
# Assigns ops to the local worker by default.
with tf.device(tf.train.replica_device_setter(
worker_device="/job:worker/task:%d" % FLAGS.task_index,
cluster=cluster)):
# Build model...
x = tf.placeholder("float", [10, 10], name="x")
y = tf.placeholder("float", [10, 1], name="y")
initial_w = np.zeros((10, 1))
w = tf.Variable(initial_w, name="w", dtype="float32")
loss = tf.pow(tf.add(y,-tf.matmul(x,w)),2,name="loss")
global_step = tf.Variable(0)
saver = tf.train.Saver()
summary_op = tf.merge_all_summaries()
init_op = tf.initialize_all_variables()
# Create a "supervisor", which oversees the training process.
sv = tf.train.Supervisor(is_chief=(FLAGS.task_index == 0),
logdir="/tmp/train_logs",
init_op=init_op,
summary_op=summary_op,
saver=saver,
global_step=global_step,
save_model_secs=600)
# The supervisor takes care of session initialization, restoring from
# a checkpoint, and closing when done or an error occurs.
with sv.managed_session(server.target) as sess:
# Loop until the supervisor shuts down or 1000000 steps have completed.
step = 0
while not sv.should_stop() and step < 1000000:
# Run a training step asynchronously.
# See `tf.train.SyncReplicasOptimizer` for additional details on how to
# perform *synchronous* training.
_, step = sess.run([loss, global_step])
print("job_name: %s; task_index: %s; step: %d" % (FLAGS.job_name,FLAGS.task_index,step))
# Ask for all the services to stop.
sv.stop()
if __name__ == "__main__":
tf.app.run()
</code></pre>
<p>Then I run the following commands as instructed by the official document (the script is named hello_distributed.py),</p>
<pre><code>sudo python3 hello_distributed.py --ps_hosts=localhost:2222,localhost:2223 --worker_hosts=localhost:2777,localhost:2778 --job_name=ps --task_index=0
sudo python3 hello_distributed.py --ps_hosts=localhost:2222,localhost:2223 --worker_hosts=localhost:2777,localhost:2778 --job_name=ps --task_index=1
sudo python3 hello_distributed.py --ps_hosts=localhost:2222,localhost:2223 --worker_hosts=localhost:2777,localhost:2778 --job_name=worker --task_index=0
sudo python3 hello_distributed.py --ps_hosts=localhost:2222,localhost:2223 --worker_hosts=localhost:2777,localhost:2778 --job_name=worker --task_index=1
</code></pre>
<p>The first two lines for running "ps" are good. The last two lines get the following "connection refused" error. </p>
<p><a href="http://i.stack.imgur.com/zkGPi.png" rel="nofollow"><img src="http://i.stack.imgur.com/zkGPi.png" alt="enter image description here"></a></p>
<p>Thank you!</p>
| 0 | 2016-08-13T23:54:44Z | 39,805,195 | <p>The error message tells you where the problem is ---- the worker1 can't connect to worker2. The reason for this problem is you <strong>didn't</strong> start the worker2 server.</p>
<p>So execute the fourth command even if there are connection failure messages after executing the third one. Then you will find everything works well.</p>
| 0 | 2016-10-01T09:51:51Z | [
"python",
"tensorflow"
] |
Performing Power Operations in Dictionaries | 38,938,001 | <pre><code> dict1 = {'A': 2,'B': 4,'C': 6}
</code></pre>
<p>I want a new dictionary to be the values of dict1 squared.</p>
<pre><code> dict2 = {'A': 4,'B': 16,'C': 36}
</code></pre>
<p>A tried using </p>
<pre><code>for k in dict1.keys():
value = dict[k]
for k1 in value.keys():
value[k1] = value**2 # also tried pow(value,2.)
</code></pre>
<p>The error I get is AttributeError: 'float' object has no attribute 'keys'. Any ideas what I am doing wrong?</p>
| 2 | 2016-08-13T23:58:40Z | 38,938,036 | <p>You first need to create <code>dict2</code>:</p>
<pre><code>dict2 = {}
</code></pre>
<p>Then, you can populate it using the keys and values of <code>dict1</code>:</p>
<pre><code>for key in dict1.keys():
dict2[key] = dict1[key] ** 2
</code></pre>
<p>Or in one line:</p>
<pre><code>dict2 = {key: value ** 2 for key, value in dict1.items()}
</code></pre>
| 3 | 2016-08-14T00:06:36Z | [
"python",
"dictionary"
] |
Performing Power Operations in Dictionaries | 38,938,001 | <pre><code> dict1 = {'A': 2,'B': 4,'C': 6}
</code></pre>
<p>I want a new dictionary to be the values of dict1 squared.</p>
<pre><code> dict2 = {'A': 4,'B': 16,'C': 36}
</code></pre>
<p>A tried using </p>
<pre><code>for k in dict1.keys():
value = dict[k]
for k1 in value.keys():
value[k1] = value**2 # also tried pow(value,2.)
</code></pre>
<p>The error I get is AttributeError: 'float' object has no attribute 'keys'. Any ideas what I am doing wrong?</p>
| 2 | 2016-08-13T23:58:40Z | 38,938,041 | <p>You can just iterate through your old dictionary using a dictionary comprehension like so (python 2):</p>
<pre><code>>>> dict1 = {'A': 2,'B': 4,'C': 6}
>>> dict2 = {k:v**2 for k,v in dict1.iteritems()}
>>> dict2
{'A': 4, 'C': 36, 'B': 16}
</code></pre>
<p>Note that for python 3:</p>
<pre><code>>>> dict2 = {k:v**2 for k,v in dict1.iteritems()}
</code></pre>
<p>becomes</p>
<pre><code>>>> dict2 = {k:v**2 for k,v in dict1.items()}
</code></pre>
| 3 | 2016-08-14T00:07:28Z | [
"python",
"dictionary"
] |
I want get the sum of integers? | 38,938,048 | <p>I am a beginner and I wrote this code, but how can I make it output the sum of the integers?</p>
<pre><code>a=100
b=200
for a in range (b):
if a%2==1:
print a
</code></pre>
| -5 | 2016-08-14T00:09:04Z | 38,938,067 | <p>If you mean the sum of all the numbers <code>a < x < b</code>, then this will do it.</p>
<pre><code>a = 100
b = 200
total = 0
for i in range(a,b+1):
total += i
print total
</code></pre>
<p>In this case it will print <code>15150</code>.</p>
<p>As per your question, if you want just odd numbers:</p>
<pre><code>for i in range(a, b+1):
if i % 2 != 0:
total += 1
</code></pre>
<p>I know this isn't a 1 liner approach to the solution, but I wrote it out in this manner so that you could understand it better and more clearly. Also because it looks like you were taking an approach like this, and I wanted you to see how it would be done the way that you were trying to do it.</p>
| -3 | 2016-08-14T00:13:15Z | [
"python"
] |
libxml2-dev not installing on raspbian/debian | 38,938,055 | <p>When I <code>sudo apt-get install libxml2-dev</code> I receive the error
<code>libxml2-dev : Depends: libxml2 (= 2.9.4+dfsg1-1+b1) but 2.9.4+dfsg1-1 is to be installed
E: Unable to correct problems, you have held broken packages.</code></p>
<p>I tried to follow this guide: <a href="https://www.raspberrypi.org/forums/viewtopic.php?f=28&t=105859" rel="nofollow">https://www.raspberrypi.org/forums/viewtopic.php?f=28&t=105859</a></p>
<p>but when I get to <code>cd ~/libxml2-2.9.1</code> the directory does not exist. Here is my actual output:</p>
<pre><code>pi@rpi:~ $ sudo apt-get install python-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
libglew1.10 liborcus-0.8-0 libpython3.4 libpython3.4-dev libpython3.4-minimal libpython3.4-stdlib
libwps-0.3-3 python3.4 python3.4-dev python3.4-minimal
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
libpython-dev libpython-stdlib libpython2.7 libpython2.7-dev libpython2.7-minimal libpython2.7-stdlib
python python-minimal python2.7 python2.7-dev python2.7-minimal
Suggested packages:
python-doc python-tk python2.7-doc
The following NEW packages will be installed:
libpython-dev libpython2.7-dev python-dev python2.7-dev
The following packages will be upgraded:
libpython-stdlib libpython2.7 libpython2.7-minimal libpython2.7-stdlib python python-minimal python2.7
python2.7-minimal
8 upgraded, 4 newly installed, 0 to remove and 784 not upgraded.
Need to get 32.6 MB of archives.
After this operation, 37.6 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://archive.raspbian.org/raspbian stretch/main armhf python2.7 armhf 2.7.12-2 [277 kB]
Get:2 http://archive.raspbian.org/raspbian stretch/main armhf libpython2.7 armhf 2.7.12-2 [913 kB]
Get:3 http://archive.raspbian.org/raspbian stretch/main armhf libpython2.7-stdlib armhf 2.7.12-2 [1,843 kB]
Get:4 http://archive.raspbian.org/raspbian stretch/main armhf python2.7-minimal armhf 2.7.12-2 [1,173 kB]
Get:5 http://archive.raspbian.org/raspbian stretch/main armhf libpython2.7-minimal armhf 2.7.12-2 [388 kB]
Get:6 http://archive.raspbian.org/raspbian stretch/main armhf python-minimal armhf 2.7.11-2 [40.3 kB]
Get:7 http://archive.raspbian.org/raspbian stretch/main armhf python armhf 2.7.11-2 [153 kB]
Get:8 http://archive.raspbian.org/raspbian stretch/main armhf libpython-stdlib armhf 2.7.11-2 [19.8 kB]
Get:9 http://archive.raspbian.org/raspbian stretch/main armhf libpython2.7-dev armhf 2.7.12-2 [27.5 MB]
Get:10 http://archive.raspbian.org/raspbian stretch/main armhf libpython-dev armhf 2.7.11-2 [19.8 kB]
Get:11 http://archive.raspbian.org/raspbian stretch/main armhf python2.7-dev armhf 2.7.12-2 [278 kB]
Get:12 http://archive.raspbian.org/raspbian stretch/main armhf python-dev armhf 2.7.11-2 [1,132 B]
Fetched 32.6 MB in 25s (1,284 kB/s)
Reading changelogs... Done
(Reading database ... 130446 files and directories currently installed.)
Preparing to unpack .../python2.7_2.7.12-2_armhf.deb ...
Unpacking python2.7 (2.7.12-2) over (2.7.9-2) ...
Preparing to unpack .../libpython2.7_2.7.12-2_armhf.deb ...
Unpacking libpython2.7:armhf (2.7.12-2) over (2.7.9-2) ...
Preparing to unpack .../libpython2.7-stdlib_2.7.12-2_armhf.deb ...
Unpacking libpython2.7-stdlib:armhf (2.7.12-2) over (2.7.9-2) ...
Preparing to unpack .../python2.7-minimal_2.7.12-2_armhf.deb ...
Unpacking python2.7-minimal (2.7.12-2) over (2.7.9-2) ...
Preparing to unpack .../libpython2.7-minimal_2.7.12-2_armhf.deb ...
Unpacking libpython2.7-minimal:armhf (2.7.12-2) over (2.7.9-2) ...
Preparing to unpack .../python-minimal_2.7.11-2_armhf.deb ...
Unpacking python-minimal (2.7.11-2) over (2.7.9-1) ...
Processing triggers for gnome-menus (3.13.3-6) ...
Processing triggers for desktop-file-utils (0.22-1) ...
Processing triggers for mime-support (3.58) ...
Processing triggers for man-db (2.7.0.2-5) ...
Processing triggers for libc-bin (2.23-4) ...
Setting up libpython2.7-minimal:armhf (2.7.12-2) ...
Setting up python2.7-minimal (2.7.12-2) ...
Setting up python-minimal (2.7.11-2) ...
(Reading database ... 130445 files and directories currently installed.)
Preparing to unpack .../python_2.7.11-2_armhf.deb ...
Unpacking python (2.7.11-2) over (2.7.9-1) ...
Preparing to unpack .../libpython-stdlib_2.7.11-2_armhf.deb ...
Unpacking libpython-stdlib:armhf (2.7.11-2) over (2.7.9-1) ...
Selecting previously unselected package libpython2.7-dev:armhf.
Preparing to unpack .../libpython2.7-dev_2.7.12-2_armhf.deb ...
Unpacking libpython2.7-dev:armhf (2.7.12-2) ...
Selecting previously unselected package libpython-dev:armhf.
Preparing to unpack .../libpython-dev_2.7.11-2_armhf.deb ...
Unpacking libpython-dev:armhf (2.7.11-2) ...
Selecting previously unselected package python2.7-dev.
Preparing to unpack .../python2.7-dev_2.7.12-2_armhf.deb ...
Unpacking python2.7-dev (2.7.12-2) ...
Selecting previously unselected package python-dev.
Preparing to unpack .../python-dev_2.7.11-2_armhf.deb ...
Unpacking python-dev (2.7.11-2) ...
Processing triggers for man-db (2.7.0.2-5) ...
Setting up libpython2.7-stdlib:armhf (2.7.12-2) ...
Setting up python2.7 (2.7.12-2) ...
Setting up libpython-stdlib:armhf (2.7.11-2) ...
Setting up libpython2.7:armhf (2.7.12-2) ...
Setting up libpython2.7-dev:armhf (2.7.12-2) ...
Setting up python2.7-dev (2.7.12-2) ...
Setting up python (2.7.11-2) ...
Setting up libpython-dev:armhf (2.7.11-2) ...
Setting up python-dev (2.7.11-2) ...
Processing triggers for libc-bin (2.23-4) ...
pi@rpi:~ $ sudo apt-get install python-lxml
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
libglew1.10 liborcus-0.8-0 libpython3.4 libpython3.4-dev libpython3.4-minimal libpython3.4-stdlib
libwps-0.3-3 python3.4 python3.4-dev python3.4-minimal
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
python-bs4
Suggested packages:
python-lxml-dbg python-lxml-doc
The following NEW packages will be installed:
python-bs4 python-lxml
0 upgraded, 2 newly installed, 0 to remove and 784 not upgraded.
Need to get 761 kB of archives.
After this operation, 2,991 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://archive.raspbian.org/raspbian stretch/main armhf python-bs4 all 4.5.0-1 [85.5 kB]
Get:2 http://archive.raspbian.org/raspbian stretch/main armhf python-lxml armhf 3.6.0-1 [675 kB]
Fetched 761 kB in 2s (301 kB/s)
Selecting previously unselected package python-bs4.
(Reading database ... 130580 files and directories currently installed.)
Preparing to unpack .../python-bs4_4.5.0-1_all.deb ...
Unpacking python-bs4 (4.5.0-1) ...
Selecting previously unselected package python-lxml.
Preparing to unpack .../python-lxml_3.6.0-1_armhf.deb ...
Unpacking python-lxml (3.6.0-1) ...
Setting up python-bs4 (4.5.0-1) ...
Setting up python-lxml (3.6.0-1) ...
pi@rpi:~ $ sudo dpkg -l |grep libxml2
ii libxml2:armhf 2.9.1+dfsg1-5+deb8u2 armhf GNOME XML library
ii python-lxml 3.6.0-1 armhf pythonic binding for the libxml2 and libxslt libraries
</code></pre>
<p>Any ideas?</p>
| 0 | 2016-08-14T00:10:59Z | 38,949,270 | <p>Ended up downloading from source: <a href="https://packages.debian.org/search?keywords=libxml2" rel="nofollow">https://packages.debian.org/search?keywords=libxml2</a></p>
<p>And then installing manually via <code>sudo dpkg -i /path/to/deb/file</code></p>
| 0 | 2016-08-15T04:19:58Z | [
"python",
"raspberry-pi",
"debian",
"raspbian",
"libxml2"
] |
libxml2-dev not installing on raspbian/debian | 38,938,055 | <p>When I <code>sudo apt-get install libxml2-dev</code> I receive the error
<code>libxml2-dev : Depends: libxml2 (= 2.9.4+dfsg1-1+b1) but 2.9.4+dfsg1-1 is to be installed
E: Unable to correct problems, you have held broken packages.</code></p>
<p>I tried to follow this guide: <a href="https://www.raspberrypi.org/forums/viewtopic.php?f=28&t=105859" rel="nofollow">https://www.raspberrypi.org/forums/viewtopic.php?f=28&t=105859</a></p>
<p>but when I get to <code>cd ~/libxml2-2.9.1</code> the directory does not exist. Here is my actual output:</p>
<pre><code>pi@rpi:~ $ sudo apt-get install python-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
libglew1.10 liborcus-0.8-0 libpython3.4 libpython3.4-dev libpython3.4-minimal libpython3.4-stdlib
libwps-0.3-3 python3.4 python3.4-dev python3.4-minimal
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
libpython-dev libpython-stdlib libpython2.7 libpython2.7-dev libpython2.7-minimal libpython2.7-stdlib
python python-minimal python2.7 python2.7-dev python2.7-minimal
Suggested packages:
python-doc python-tk python2.7-doc
The following NEW packages will be installed:
libpython-dev libpython2.7-dev python-dev python2.7-dev
The following packages will be upgraded:
libpython-stdlib libpython2.7 libpython2.7-minimal libpython2.7-stdlib python python-minimal python2.7
python2.7-minimal
8 upgraded, 4 newly installed, 0 to remove and 784 not upgraded.
Need to get 32.6 MB of archives.
After this operation, 37.6 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://archive.raspbian.org/raspbian stretch/main armhf python2.7 armhf 2.7.12-2 [277 kB]
Get:2 http://archive.raspbian.org/raspbian stretch/main armhf libpython2.7 armhf 2.7.12-2 [913 kB]
Get:3 http://archive.raspbian.org/raspbian stretch/main armhf libpython2.7-stdlib armhf 2.7.12-2 [1,843 kB]
Get:4 http://archive.raspbian.org/raspbian stretch/main armhf python2.7-minimal armhf 2.7.12-2 [1,173 kB]
Get:5 http://archive.raspbian.org/raspbian stretch/main armhf libpython2.7-minimal armhf 2.7.12-2 [388 kB]
Get:6 http://archive.raspbian.org/raspbian stretch/main armhf python-minimal armhf 2.7.11-2 [40.3 kB]
Get:7 http://archive.raspbian.org/raspbian stretch/main armhf python armhf 2.7.11-2 [153 kB]
Get:8 http://archive.raspbian.org/raspbian stretch/main armhf libpython-stdlib armhf 2.7.11-2 [19.8 kB]
Get:9 http://archive.raspbian.org/raspbian stretch/main armhf libpython2.7-dev armhf 2.7.12-2 [27.5 MB]
Get:10 http://archive.raspbian.org/raspbian stretch/main armhf libpython-dev armhf 2.7.11-2 [19.8 kB]
Get:11 http://archive.raspbian.org/raspbian stretch/main armhf python2.7-dev armhf 2.7.12-2 [278 kB]
Get:12 http://archive.raspbian.org/raspbian stretch/main armhf python-dev armhf 2.7.11-2 [1,132 B]
Fetched 32.6 MB in 25s (1,284 kB/s)
Reading changelogs... Done
(Reading database ... 130446 files and directories currently installed.)
Preparing to unpack .../python2.7_2.7.12-2_armhf.deb ...
Unpacking python2.7 (2.7.12-2) over (2.7.9-2) ...
Preparing to unpack .../libpython2.7_2.7.12-2_armhf.deb ...
Unpacking libpython2.7:armhf (2.7.12-2) over (2.7.9-2) ...
Preparing to unpack .../libpython2.7-stdlib_2.7.12-2_armhf.deb ...
Unpacking libpython2.7-stdlib:armhf (2.7.12-2) over (2.7.9-2) ...
Preparing to unpack .../python2.7-minimal_2.7.12-2_armhf.deb ...
Unpacking python2.7-minimal (2.7.12-2) over (2.7.9-2) ...
Preparing to unpack .../libpython2.7-minimal_2.7.12-2_armhf.deb ...
Unpacking libpython2.7-minimal:armhf (2.7.12-2) over (2.7.9-2) ...
Preparing to unpack .../python-minimal_2.7.11-2_armhf.deb ...
Unpacking python-minimal (2.7.11-2) over (2.7.9-1) ...
Processing triggers for gnome-menus (3.13.3-6) ...
Processing triggers for desktop-file-utils (0.22-1) ...
Processing triggers for mime-support (3.58) ...
Processing triggers for man-db (2.7.0.2-5) ...
Processing triggers for libc-bin (2.23-4) ...
Setting up libpython2.7-minimal:armhf (2.7.12-2) ...
Setting up python2.7-minimal (2.7.12-2) ...
Setting up python-minimal (2.7.11-2) ...
(Reading database ... 130445 files and directories currently installed.)
Preparing to unpack .../python_2.7.11-2_armhf.deb ...
Unpacking python (2.7.11-2) over (2.7.9-1) ...
Preparing to unpack .../libpython-stdlib_2.7.11-2_armhf.deb ...
Unpacking libpython-stdlib:armhf (2.7.11-2) over (2.7.9-1) ...
Selecting previously unselected package libpython2.7-dev:armhf.
Preparing to unpack .../libpython2.7-dev_2.7.12-2_armhf.deb ...
Unpacking libpython2.7-dev:armhf (2.7.12-2) ...
Selecting previously unselected package libpython-dev:armhf.
Preparing to unpack .../libpython-dev_2.7.11-2_armhf.deb ...
Unpacking libpython-dev:armhf (2.7.11-2) ...
Selecting previously unselected package python2.7-dev.
Preparing to unpack .../python2.7-dev_2.7.12-2_armhf.deb ...
Unpacking python2.7-dev (2.7.12-2) ...
Selecting previously unselected package python-dev.
Preparing to unpack .../python-dev_2.7.11-2_armhf.deb ...
Unpacking python-dev (2.7.11-2) ...
Processing triggers for man-db (2.7.0.2-5) ...
Setting up libpython2.7-stdlib:armhf (2.7.12-2) ...
Setting up python2.7 (2.7.12-2) ...
Setting up libpython-stdlib:armhf (2.7.11-2) ...
Setting up libpython2.7:armhf (2.7.12-2) ...
Setting up libpython2.7-dev:armhf (2.7.12-2) ...
Setting up python2.7-dev (2.7.12-2) ...
Setting up python (2.7.11-2) ...
Setting up libpython-dev:armhf (2.7.11-2) ...
Setting up python-dev (2.7.11-2) ...
Processing triggers for libc-bin (2.23-4) ...
pi@rpi:~ $ sudo apt-get install python-lxml
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
libglew1.10 liborcus-0.8-0 libpython3.4 libpython3.4-dev libpython3.4-minimal libpython3.4-stdlib
libwps-0.3-3 python3.4 python3.4-dev python3.4-minimal
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
python-bs4
Suggested packages:
python-lxml-dbg python-lxml-doc
The following NEW packages will be installed:
python-bs4 python-lxml
0 upgraded, 2 newly installed, 0 to remove and 784 not upgraded.
Need to get 761 kB of archives.
After this operation, 2,991 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://archive.raspbian.org/raspbian stretch/main armhf python-bs4 all 4.5.0-1 [85.5 kB]
Get:2 http://archive.raspbian.org/raspbian stretch/main armhf python-lxml armhf 3.6.0-1 [675 kB]
Fetched 761 kB in 2s (301 kB/s)
Selecting previously unselected package python-bs4.
(Reading database ... 130580 files and directories currently installed.)
Preparing to unpack .../python-bs4_4.5.0-1_all.deb ...
Unpacking python-bs4 (4.5.0-1) ...
Selecting previously unselected package python-lxml.
Preparing to unpack .../python-lxml_3.6.0-1_armhf.deb ...
Unpacking python-lxml (3.6.0-1) ...
Setting up python-bs4 (4.5.0-1) ...
Setting up python-lxml (3.6.0-1) ...
pi@rpi:~ $ sudo dpkg -l |grep libxml2
ii libxml2:armhf 2.9.1+dfsg1-5+deb8u2 armhf GNOME XML library
ii python-lxml 3.6.0-1 armhf pythonic binding for the libxml2 and libxslt libraries
</code></pre>
<p>Any ideas?</p>
| 0 | 2016-08-14T00:10:59Z | 38,977,880 | <p>"784 not upgraded."</p>
<p>Are you updated whenever your raspian? Maybe you can't install this because you haven't stable packages. </p>
| 0 | 2016-08-16T14:41:31Z | [
"python",
"raspberry-pi",
"debian",
"raspbian",
"libxml2"
] |
Why can't python recognize my month column in a dataset? | 38,938,064 | <p>This is what the dataframe looks like:</p>
<pre><code>Date Time (HHMM) Site Plot Replicate Temperature \
0 2002-05-01 600 Barre Woods 16 5 4.5
1 2002-05-01 600 Barre Woods 21 7 4.5
2 2002-05-01 600 Barre Woods 31 9 6.5
3 2002-05-01 600 Barre Woods 10 2 5.3
4 2002-05-01 600 Barre Woods 2 1 4.0
5 2002-05-01 600 Barre Woods 13 4 5.5
6 2002-05-01 600 Barre Woods 11 3 5.0
7 2002-05-01 600 Barre Woods 28 8 5.0
8 2002-05-01 600 Barre Woods 18 6 4.5
9 2002-05-01 1400 Barre Woods 2 1 10.3
10 2002-05-01 1400 Barre Woods 31 9 9.0
11 2002-05-01 1400 Barre Woods 13 4 11.0
import pandas as pd
import datetime as dt
from datetime import datetime
df=pd.read_csv('F:/data32.csv',parse_dates=['Date'])
df['Date']=pd.to_datetime(df['Date'],format='%m/%d/%y')
</code></pre>
<p>This is where i get the error</p>
<pre><code>df2=df.groupby(pd.TimeGrouper(freq='M'))
</code></pre>
<p>The error reads: <em>Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'</em></p>
| 0 | 2016-08-14T00:12:40Z | 38,938,313 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow">set_index</a> first:</p>
<pre><code>dfx = df.set_index('Date')
</code></pre>
<p>Then, you can <code>groupby</code>:</p>
<pre><code>dfx.groupby(lambda x : x.month).mean() #just for an example I am using .mean()
</code></pre>
| 1 | 2016-08-14T01:04:31Z | [
"python",
"datetime",
"pandas",
"group-by"
] |
Why can't python recognize my month column in a dataset? | 38,938,064 | <p>This is what the dataframe looks like:</p>
<pre><code>Date Time (HHMM) Site Plot Replicate Temperature \
0 2002-05-01 600 Barre Woods 16 5 4.5
1 2002-05-01 600 Barre Woods 21 7 4.5
2 2002-05-01 600 Barre Woods 31 9 6.5
3 2002-05-01 600 Barre Woods 10 2 5.3
4 2002-05-01 600 Barre Woods 2 1 4.0
5 2002-05-01 600 Barre Woods 13 4 5.5
6 2002-05-01 600 Barre Woods 11 3 5.0
7 2002-05-01 600 Barre Woods 28 8 5.0
8 2002-05-01 600 Barre Woods 18 6 4.5
9 2002-05-01 1400 Barre Woods 2 1 10.3
10 2002-05-01 1400 Barre Woods 31 9 9.0
11 2002-05-01 1400 Barre Woods 13 4 11.0
import pandas as pd
import datetime as dt
from datetime import datetime
df=pd.read_csv('F:/data32.csv',parse_dates=['Date'])
df['Date']=pd.to_datetime(df['Date'],format='%m/%d/%y')
</code></pre>
<p>This is where i get the error</p>
<pre><code>df2=df.groupby(pd.TimeGrouper(freq='M'))
</code></pre>
<p>The error reads: <em>Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'</em></p>
| 0 | 2016-08-14T00:12:40Z | 38,938,821 | <p>Group by <code>df['Date'].dt.month</code>. For example, to compute the average temperature you can do the following.</p>
<pre><code>import io
import pandas as pd
data = io.StringIO('''\
Date,Time (HHMM),Site,Plot,Replicate,Temperature
0,2002-05-01,600,Barre Woods,16,5,4.5
1,2002-05-01,600,Barre Woods,21,7,4.5
2,2002-05-01,600,Barre Woods,31,9,6.5
3,2002-05-01,600,Barre Woods,10,2,5.3
4,2002-05-01,600,Barre Woods,2,1,4.0
5,2002-05-01,600,Barre Woods,13,4,5.5
6,2002-05-01,600,Barre Woods,11,3,5.0
7,2002-05-01,600,Barre Woods,28,8,5.0
8,2002-05-01,600,Barre Woods,18,6,4.5
9,2002-05-01,1400,Barre Woods,2,1,10.3
10,2002-05-01,1400,Barre Woods,31,9,9.0
11,2002-05-01,1400,Barre Woods,13,4,11.0
''')
df = pd.read_csv(data)
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d')
df.groupby(df['Date'].dt.month)['Temperature'].mean()
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>Date
5 6.258333
Name: Temperature, dtype: float64
</code></pre>
| 1 | 2016-08-14T03:14:27Z | [
"python",
"datetime",
"pandas",
"group-by"
] |
What's the equivalent of peewee's DoesNotExist in SQLAlchemy? | 38,938,116 | <p>I've been using peewee with SQLite for some time and now I'm switching to SQLAlchemy with Postgres and I can't find equivalent of DoesNotExist (see example) </p>
<pre><code>try:
return models.User.get(models.User.id == userid)
except models.DoesNotExist:
return None
</code></pre>
<p>Do you know how to achieve the same with SQLAlchemy? I've checked stuff which I can import from sqlalchemy.ext but nothing seemed right.</p>
| 0 | 2016-08-14T00:23:51Z | 38,938,155 | <p>The closest could be this one: - <a href="http://docs.sqlalchemy.org/en/latest/orm/exceptions.html#sqlalchemy.orm.exc.NoResultFound" rel="nofollow">http://docs.sqlalchemy.org/en/latest/orm/exceptions.html#sqlalchemy.orm.exc.NoResultFound</a> </p>
<p><strong>Code Sample:</strong></p>
<pre><code>from sqlalchemy.orm.exc import NoResultFound
try:
user = session.query(User).one()
except NoResultFound, e:
print "No users found"
</code></pre>
| -1 | 2016-08-14T00:32:00Z | [
"python",
"postgresql",
"flask-sqlalchemy",
"peewee"
] |
What's the equivalent of peewee's DoesNotExist in SQLAlchemy? | 38,938,116 | <p>I've been using peewee with SQLite for some time and now I'm switching to SQLAlchemy with Postgres and I can't find equivalent of DoesNotExist (see example) </p>
<pre><code>try:
return models.User.get(models.User.id == userid)
except models.DoesNotExist:
return None
</code></pre>
<p>Do you know how to achieve the same with SQLAlchemy? I've checked stuff which I can import from sqlalchemy.ext but nothing seemed right.</p>
| 0 | 2016-08-14T00:23:51Z | 39,113,947 | <p>Peewee <em>does</em> work with Postgresql, you know. ;)</p>
| -1 | 2016-08-24T03:31:07Z | [
"python",
"postgresql",
"flask-sqlalchemy",
"peewee"
] |
Simplifying, printing text instead of boolean value, Python | 38,938,182 | <p>Using python to grade student scores. Trying to simplify from</p>
<pre><code>A = ((float(scptratio)) >= (0.9) and (float(scptratio) <= 1))
B = ((float(scptratio)) >= (0.8) and (float(scptratio) <= (0.89)))
if A == True:
print (studentname, (" has scored an A on the test."))
elif B == True:
print (studentname, (" has scored an B on the test."))
elif C == True:
print (studentname, (" has scored an C on the test."))
</code></pre>
<p>etc. to something along the lines of </p>
<pre><code>A = (((float(scptratio)) >= (0.9) and (float(scptratio) <= 1)), "A")
B = (((float(scptratio)) >= (0.8) and (float(scptratio) <= (0.89))), "B")
Pass = [A, B, C, D]
if Pass:
print (studentname, "passed the test with a coefficient of", scptratio, ("scoring a grade of {}".format(Pass)))
elif F:
print (studentname, "has failed the test.")
else:
print ("Error! Negative value entered.")
</code></pre>
<p>How can i get it to print the actual letter score instead of boolean values?</p>
| 2 | 2016-08-14T00:38:20Z | 38,938,225 | <p>I'd suggest making an easily-editable list containing the minimum score required for a specific grade, from high to low:</p>
<pre><code>minimum_scores = [("A", 9), ("B", 8), ("C", 7), ("D", 6)]
</code></pre>
<p>Then go through this list and print the first grade for which the student passed.</p>
<pre><code>for grade, score in minimum_scores:
if float(scptratio) >= score:
print(studentname, "passed the test with a coefficient of", str(scptratio), "scoring a grade of", grade)
break
else: #No break hit, so the student didn't pass any of the minimum requirements.
print(studentname, "has failed the test.")
</code></pre>
| 1 | 2016-08-14T00:45:35Z | [
"python"
] |
Separate by threshold | 38,938,189 | <p>I am trying to take the value of <code>c_med</code> one value as threshold from input:1 and separate the above and below values in two different outputs from input:2. Write <code>above.csv</code> & <code>below.csv</code> with reference to column <code>c_total</code>.</p>
<p>Read the <code>above.csv</code> as input and categorize them with percentage as mentioned in point 2 written in pure python.</p>
<p>Input: 1 </p>
<pre><code>date_count,all_hours,c_min,c_max,c_med,c_med_med,u_min,u_max,u_med,u_med_med
2,12,2309,19072,12515,13131,254,785,686,751
</code></pre>
<p>Input: 2 <code>['date','startTime','endTime','day','c_total','u_total']</code></p>
<pre><code>2004-01-05,22:00:00,23:00:00,Mon,18944,790
2004-01-05,23:00:00,00:00:00,Mon,17534,750
2004-01-06,00:00:00,01:00:00,Tue,17262,747
2004-01-06,01:00:00,02:00:00,Tue,19072,777
2004-01-06,02:00:00,03:00:00,Tue,18275,785
2004-01-06,03:00:00,04:00:00,Tue,13589,757
2004-01-06,04:00:00,05:00:00,Tue,16053,735
2004-01-06,05:00:00,06:00:00,Tue,11440,636
2004-01-06,06:00:00,07:00:00,Tue,5972,513
2004-01-06,07:00:00,08:00:00,Tue,3424,382
2004-01-06,08:00:00,09:00:00,Tue,2696,303
2004-01-06,09:00:00,10:00:00,Tue,2350,262
2004-01-06,10:00:00,11:00:00,Tue,2309,254
</code></pre>
<ol>
<li>I am trying to read a threshold value from another input csv <code>c_med</code></li>
</ol>
<p>I am getting following error:</p>
<pre><code>Traceback (most recent call last):
File "class_med.py", line 10, in <module>
above_median = df_data['c_total'] > df_med['c_med']
File "/usr/local/lib/python2.7/dist-packages/pandas/core/ops.py", line 735, in wrapper
raise ValueError('Series lengths must match to compare')
ValueError: Series lengths must match to compare
</code></pre>
<ol start="2">
<li><p>filter the separated data column <code>c_total</code> with percentage. Pure python solution given below but I am looking for a pandas solution. like in <a href="http://stackoverflow.com/a/28683530/5056548">Reference one</a> </p>
<p><code>for row in csv.reader(inp):
if int(row[1])<(.20 * max_value):
val = 'viewers'
elif int(row[1])>=(0.20*max_value) and int(row[1])<(0.40*max_value):
val= 'event based'<br>
elif int(row[1])>=(0.40*max_value) and int(row[1])<(0.60*max_value):
val= 'situational'
elif int(row[1])>=(0.60*max_value) and int(row[1])<(0.80*max_value):
val = 'active'
else:
val= 'highly active'
writer.writerow([row[0],row[1],val])</code></p></li>
</ol>
<p>Code:</p>
<pre><code>import pandas as pd
import numpy as np
df_med = pd.read_csv('stat_result.csv')
df_med.columns = ['date_count', 'all_hours', 'c_min', 'c_max', 'c_med', 'c_med_med', 'u_min', 'u_max', 'u_med', 'u_med_med']
df_data = pd.read_csv('mini_out.csv')
df_data.columns = ['date', 'startTime', 'endTime', 'day', 'c_total', 'u_total']
above = df_data['c_total'] > df_med['c_med']
#print above_median
above.to_csv('above.csv', index=None, header=None)
df_above = pd.readcsv('above_median.csv')
df_above.columns = ['date', 'startTime', 'endTime', 'day', 'c_total', 'u_total']
#Percentage block should come here
</code></pre>
<p><strong>Edit:</strong> In case of single column value the <code>qcut</code> is the simplest solution. But when it comes to using two values from two different columns how to achieve that in pandas ? </p>
<pre><code>for row in csv.reader(inp):
if int(row[1])>(0.80*max_user) and int(row[2])>(0.80*max_key):
val='highly active'
elif int(row[1])>=(0.60*max_user) and int(row[2])<=(0.60*max_key):
val='active'
elif int(row[1])<=(0.40*max_user) and int(row[2])>=(0.40*max_key):
val='event based'
elif int(row[1])<(0.20*max_user) and int(row[2])<(0.20*max_key):
val ='situational'
else:
val= 'viewers'
</code></pre>
| 1 | 2016-08-14T00:39:07Z | 38,940,990 | <p>assuming you have the following DFs:</p>
<pre><code>In [7]: df1
Out[7]:
date_count all_hours c_min c_max c_med c_med_med u_min u_max u_med u_med_med
0 2 12 2309 19072 12515 13131 254 785 686 751
In [8]: df2
Out[8]:
date startTime endTime day c_total u_total
0 2004-01-05 22:00:00 23:00:00 Mon 18944 790
1 2004-01-05 23:00:00 00:00:00 Mon 17534 750
2 2004-01-06 00:00:00 01:00:00 Tue 17262 747
3 2004-01-06 01:00:00 02:00:00 Tue 19072 777
4 2004-01-06 02:00:00 03:00:00 Tue 18275 785
5 2004-01-06 03:00:00 04:00:00 Tue 13589 757
6 2004-01-06 04:00:00 05:00:00 Tue 16053 735
7 2004-01-06 05:00:00 06:00:00 Tue 11440 636
8 2004-01-06 06:00:00 07:00:00 Tue 5972 513
9 2004-01-06 07:00:00 08:00:00 Tue 3424 382
10 2004-01-06 08:00:00 09:00:00 Tue 2696 303
11 2004-01-06 09:00:00 10:00:00 Tue 2350 262
12 2004-01-06 10:00:00 11:00:00 Tue 2309 254
</code></pre>
<p>separate by threshold (you can compare two series with the same length or with a scalar value - i assume you will to separate your second data set, comparing it to the scalar value (<code>c_med</code> column) from the first of your first data set:</p>
<pre><code>In [22]: above = df2[df2.c_total > df1.ix[0, 'c_med']]
In [23]: above
Out[23]:
date startTime endTime day c_total u_total
0 2004-01-05 22:00:00 23:00:00 Mon 18944 790
1 2004-01-05 23:00:00 00:00:00 Mon 17534 750
2 2004-01-06 00:00:00 01:00:00 Tue 17262 747
3 2004-01-06 01:00:00 02:00:00 Tue 19072 777
4 2004-01-06 02:00:00 03:00:00 Tue 18275 785
5 2004-01-06 03:00:00 04:00:00 Tue 13589 757
6 2004-01-06 04:00:00 05:00:00 Tue 16053 735
</code></pre>
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.qcut.html" rel="nofollow">qcut()</a> method in order to categorize your data:</p>
<pre><code>In [29]: df2['cat'] = pd.qcut(df2.c_total,
....: q=[0, .2, .4, .6, .8, 1.],
....: labels=['viewers','event based','situational','active','highly active'])
In [30]: df2
Out[30]:
date startTime endTime day c_total u_total cat
0 2004-01-05 22:00:00 23:00:00 Mon 18944 790 highly active
1 2004-01-05 23:00:00 00:00:00 Mon 17534 750 active
2 2004-01-06 00:00:00 01:00:00 Tue 17262 747 active
3 2004-01-06 01:00:00 02:00:00 Tue 19072 777 highly active
4 2004-01-06 02:00:00 03:00:00 Tue 18275 785 highly active
5 2004-01-06 03:00:00 04:00:00 Tue 13589 757 situational
6 2004-01-06 04:00:00 05:00:00 Tue 16053 735 situational
7 2004-01-06 05:00:00 06:00:00 Tue 11440 636 situational
8 2004-01-06 06:00:00 07:00:00 Tue 5972 513 event based
9 2004-01-06 07:00:00 08:00:00 Tue 3424 382 event based
10 2004-01-06 08:00:00 09:00:00 Tue 2696 303 viewers
11 2004-01-06 09:00:00 10:00:00 Tue 2350 262 viewers
12 2004-01-06 10:00:00 11:00:00 Tue 2309 254 viewers
</code></pre>
<p>check:</p>
<pre><code>In [32]: df2.assign(pct=df2.c_total/df2.c_total.max())[['c_total','pct','cat']]
Out[32]:
c_total pct cat
0 18944 0.993289 highly active
1 17534 0.919358 active
2 17262 0.905096 active
3 19072 1.000000 highly active
4 18275 0.958211 highly active
5 13589 0.712510 situational
6 16053 0.841705 situational
7 11440 0.599832 situational
8 5972 0.313129 event based
9 3424 0.179530 event based
10 2696 0.141359 viewers
11 2350 0.123217 viewers
12 2309 0.121068 viewers
</code></pre>
| 1 | 2016-08-14T09:44:24Z | [
"python",
"csv",
"pandas",
"numpy"
] |
Why WSGI Server need reload Python file when modified but PHP not need? | 38,938,191 | <p>I'm confused about this question. When do Django development, if I have modified the <code>py</code> file or static file, the build-in server will reload. But on PHP app development, if I have modified the files, the Apache Server do not need reload and the modified content will show on browser.</p>
<p>Why?</p>
| 0 | 2016-08-14T00:39:47Z | 38,941,344 | <p>Django used to do the same back when CGI was the most common way to run dynamic web applications. It would create a new python process on each request, which would load all the files on the fly. But while PHP is optimized for this use-case with a fast startup time, Python, as a general purpose language, isn't, and there were some pretty heavy performance drawbacks. WSGI (and FastCGI before it) solves this performance issue by running the Python code in a persistent background process.</p>
<p>So while WSGI gives a lot of benefits, one of the "drawbacks" is that it only loads code when the process is (re)started, so you have to restart the process for any changes to take effect. In development this is easily solved by using an autoreloader, such as the one in Django's <code>manage.py runserver</code> command.</p>
<p>In production, there are quite a few reasons why you would want to delay the restart until the environment is ready. For example, if you pull in code changes that include a migration to add a database field, the new version of your code wouldn't be able to run before you've ran the migration. In such a case, you don't want the new code to run until you've actually ran all the necessary migrations. </p>
| 1 | 2016-08-14T10:30:40Z | [
"php",
"python",
"django"
] |
How to override the pip command to Python3.x instead of Python2.7? | 38,938,205 | <p>I am using OSX and I have pip installed for both Python3.5 and Python2.7. I know I can run the command <code>pip2</code> to use Python2 and when I use the command <code>pip3</code> Python3.x will be used.
The problem is that the default of <code>pip</code> is set to Python2.7 and I want it to be Python3.x.</p>
<p>How can I change that? </p>
<p>edit:
No, I am not running a virtual environment yet. If it was a virtual environment I could just run Python3.x and forget all about Python2.7, unfortunately since OSX requires Python2.7 for it's use I can't do that. Hence why I'm asking this.</p>
<p>Thanks for the answer. I however don't want to change what running <code>python</code> does. Instead I would like to change the path that running <code>pip</code> takes. At the moment <code>pip -V</code> shows me <code>pip 8.1.2 from /Library/Python/2.7/site-packages (python 2.7)</code>, but I am looking for <code>pip 8.1.2 from /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (python 3.5)</code> I am sure there has to be a way to do this. Any ideas?</p>
| 3 | 2016-08-14T00:42:32Z | 38,938,246 | <p>I always just run it via Python itself, this way:</p>
<pre><code>python3 -m pip install some_module
</code></pre>
<p>or</p>
<pre><code>python2 -m pip install some_module
</code></pre>
<p>The <code>-m</code> calls the <code>__main__.py</code> module of a specified package. Pip supports this.</p>
| 0 | 2016-08-14T00:50:00Z | [
"python",
"python-3.x",
"pip"
] |
How to override the pip command to Python3.x instead of Python2.7? | 38,938,205 | <p>I am using OSX and I have pip installed for both Python3.5 and Python2.7. I know I can run the command <code>pip2</code> to use Python2 and when I use the command <code>pip3</code> Python3.x will be used.
The problem is that the default of <code>pip</code> is set to Python2.7 and I want it to be Python3.x.</p>
<p>How can I change that? </p>
<p>edit:
No, I am not running a virtual environment yet. If it was a virtual environment I could just run Python3.x and forget all about Python2.7, unfortunately since OSX requires Python2.7 for it's use I can't do that. Hence why I'm asking this.</p>
<p>Thanks for the answer. I however don't want to change what running <code>python</code> does. Instead I would like to change the path that running <code>pip</code> takes. At the moment <code>pip -V</code> shows me <code>pip 8.1.2 from /Library/Python/2.7/site-packages (python 2.7)</code>, but I am looking for <code>pip 8.1.2 from /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (python 3.5)</code> I am sure there has to be a way to do this. Any ideas?</p>
| 3 | 2016-08-14T00:42:32Z | 38,938,280 | <p>For your projects, you should be using a <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="nofollow">virtualenv</a>.</p>
<p>You can choose which python will be that of the virtualenv at creation time, by specifying it on the command line:</p>
<pre><code>virtualenv -p python3 env
# then
. env/bin/activate
python # â will run python3
</code></pre>
<p>That python interpreter will be the one used when you run <code>python</code> or <code>pip</code> while the virtualenv is active.</p>
<p>Under the hood, activating the virtualenv will:</p>
<ul>
<li>modify your <code>PATH</code> environment setting so binaries in <code>env/bin</code>
override those from your system.</li>
<li>modify your <code>PYTHONHOME</code>
environment setting so python modules are loaded from <code>env/lib</code>.</li>
</ul>
<p>So <code>python</code>, <code>pip</code> and any other package you install with <code>pip</code> will be run from the virtualenv, with the python version you chose and the package versions you installed in the virtualenv.</p>
<p>Other than this, running <code>python</code> without using virtualenv will just run the default python of the system, which you cannot usually change as it would break a lot of system scripts.</p>
| 2 | 2016-08-14T00:57:13Z | [
"python",
"python-3.x",
"pip"
] |
How to override the pip command to Python3.x instead of Python2.7? | 38,938,205 | <p>I am using OSX and I have pip installed for both Python3.5 and Python2.7. I know I can run the command <code>pip2</code> to use Python2 and when I use the command <code>pip3</code> Python3.x will be used.
The problem is that the default of <code>pip</code> is set to Python2.7 and I want it to be Python3.x.</p>
<p>How can I change that? </p>
<p>edit:
No, I am not running a virtual environment yet. If it was a virtual environment I could just run Python3.x and forget all about Python2.7, unfortunately since OSX requires Python2.7 for it's use I can't do that. Hence why I'm asking this.</p>
<p>Thanks for the answer. I however don't want to change what running <code>python</code> does. Instead I would like to change the path that running <code>pip</code> takes. At the moment <code>pip -V</code> shows me <code>pip 8.1.2 from /Library/Python/2.7/site-packages (python 2.7)</code>, but I am looking for <code>pip 8.1.2 from /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (python 3.5)</code> I am sure there has to be a way to do this. Any ideas?</p>
| 3 | 2016-08-14T00:42:32Z | 38,938,282 | <p>Although <a href="https://www.python.org/dev/peps/pep-0394/" rel="nofollow">PEP 394</a> does not specifically mention <code>pip</code>, it does discuss a number of other Python-related commands (including <code>python</code> itself). The short version is that, for reasons of backwards compatibility, the unversioned commands should refer to Python 2.x for the immediate future on most reasonable systems.</p>
<p>Generally, these aliases are implemented as symbolic links, and you can just flip the symlink to point at the version you want (e.g. with <code>ln -f -s $(which pip3) $(which pip)</code> as root). But it may not be a good idea if you have any software that expects to interact with Python 2 (which may be more than you think since a lot of software interacts with Python).</p>
<p>The saner option is to set up a <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">Virtualenv</a> with Python 3. Then, <em>within the Virtualenv</em>, all Python-related commands will refer to 3.x instead of 2.x. This will not break the system, unlike the previous paragraph which could well break things.</p>
| 0 | 2016-08-14T00:57:36Z | [
"python",
"python-3.x",
"pip"
] |
How to override the pip command to Python3.x instead of Python2.7? | 38,938,205 | <p>I am using OSX and I have pip installed for both Python3.5 and Python2.7. I know I can run the command <code>pip2</code> to use Python2 and when I use the command <code>pip3</code> Python3.x will be used.
The problem is that the default of <code>pip</code> is set to Python2.7 and I want it to be Python3.x.</p>
<p>How can I change that? </p>
<p>edit:
No, I am not running a virtual environment yet. If it was a virtual environment I could just run Python3.x and forget all about Python2.7, unfortunately since OSX requires Python2.7 for it's use I can't do that. Hence why I'm asking this.</p>
<p>Thanks for the answer. I however don't want to change what running <code>python</code> does. Instead I would like to change the path that running <code>pip</code> takes. At the moment <code>pip -V</code> shows me <code>pip 8.1.2 from /Library/Python/2.7/site-packages (python 2.7)</code>, but I am looking for <code>pip 8.1.2 from /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (python 3.5)</code> I am sure there has to be a way to do this. Any ideas?</p>
| 3 | 2016-08-14T00:42:32Z | 38,938,367 | <p>Can't you <code>alias pip='pip3'</code> in your <code>~/.bash_profile</code>?</p>
<p>In Terminal, run <code>nano ~/.bash_profile</code>, then add a line to the end that reads <code>alias pip='pip3'</code>. This is safe; it won't affect system processes, only your terminal.</p>
| 1 | 2016-08-14T01:16:43Z | [
"python",
"python-3.x",
"pip"
] |
How to override the pip command to Python3.x instead of Python2.7? | 38,938,205 | <p>I am using OSX and I have pip installed for both Python3.5 and Python2.7. I know I can run the command <code>pip2</code> to use Python2 and when I use the command <code>pip3</code> Python3.x will be used.
The problem is that the default of <code>pip</code> is set to Python2.7 and I want it to be Python3.x.</p>
<p>How can I change that? </p>
<p>edit:
No, I am not running a virtual environment yet. If it was a virtual environment I could just run Python3.x and forget all about Python2.7, unfortunately since OSX requires Python2.7 for it's use I can't do that. Hence why I'm asking this.</p>
<p>Thanks for the answer. I however don't want to change what running <code>python</code> does. Instead I would like to change the path that running <code>pip</code> takes. At the moment <code>pip -V</code> shows me <code>pip 8.1.2 from /Library/Python/2.7/site-packages (python 2.7)</code>, but I am looking for <code>pip 8.1.2 from /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (python 3.5)</code> I am sure there has to be a way to do this. Any ideas?</p>
| 3 | 2016-08-14T00:42:32Z | 38,943,188 | <p>Since you have specified in the comments you want syntax like <code>pip install [package]</code> to work, here is a solution:</p>
<ol>
<li><p>Install <code>setuptools</code> for <code>Python3</code>: <code>apt-get install python3-setuptools</code></p></li>
<li><p>Now <code>pip</code> for <code>Python3</code> could be installed by: <code>python3 -m easy_install pip</code> </p></li>
<li><p>Now you can use <code>pip</code> with the specific version of Python to
install package for Python 3 by: <code>pip-3.2 install [package]</code></p></li>
</ol>
| 1 | 2016-08-14T14:26:47Z | [
"python",
"python-3.x",
"pip"
] |
AttributeError: 'module' object has no attribute 'SFrame' | 38,938,236 | <p>I am taking ML course in Coursera and I have installed GraphLab Create and ipython notebook.I am new to ML and python.</p>
<p>I get the following error,</p>
<pre><code>import graphlab
sf = graphlab.SFrame('people-example.csv')
</code></pre>
<blockquote>
<p>AttributeError Traceback (most recent call last)
in ()</p>
<p>----> 1 sf = graphlab.SFrame('people-example.csv')</p>
<p>AttributeError: 'module' object has no attribute 'SFrame'</p>
</blockquote>
<p>How do I fix this error?I have the people-example.csv in the correct path and no spelling mistake on SFrame
Any help is greatly appreciated.Thank you.</p>
| 1 | 2016-08-14T00:48:17Z | 38,938,251 | <p>Change it to:</p>
<pre><code>sf = graphlab.SFrame.read_csv('people-example.csv')
</code></pre>
| 0 | 2016-08-14T00:50:42Z | [
"python",
"graphlab"
] |
AttributeError: 'module' object has no attribute 'SFrame' | 38,938,236 | <p>I am taking ML course in Coursera and I have installed GraphLab Create and ipython notebook.I am new to ML and python.</p>
<p>I get the following error,</p>
<pre><code>import graphlab
sf = graphlab.SFrame('people-example.csv')
</code></pre>
<blockquote>
<p>AttributeError Traceback (most recent call last)
in ()</p>
<p>----> 1 sf = graphlab.SFrame('people-example.csv')</p>
<p>AttributeError: 'module' object has no attribute 'SFrame'</p>
</blockquote>
<p>How do I fix this error?I have the people-example.csv in the correct path and no spelling mistake on SFrame
Any help is greatly appreciated.Thank you.</p>
| 1 | 2016-08-14T00:48:17Z | 38,939,305 | <p>Make sure the library <code>graphlab</code> is updated and works with your current python version. Changes on built-in libraries from python 2x to 3x are likely to cause issues like this one.</p>
| 0 | 2016-08-14T05:02:33Z | [
"python",
"graphlab"
] |
AttributeError: 'module' object has no attribute 'SFrame' | 38,938,236 | <p>I am taking ML course in Coursera and I have installed GraphLab Create and ipython notebook.I am new to ML and python.</p>
<p>I get the following error,</p>
<pre><code>import graphlab
sf = graphlab.SFrame('people-example.csv')
</code></pre>
<blockquote>
<p>AttributeError Traceback (most recent call last)
in ()</p>
<p>----> 1 sf = graphlab.SFrame('people-example.csv')</p>
<p>AttributeError: 'module' object has no attribute 'SFrame'</p>
</blockquote>
<p>How do I fix this error?I have the people-example.csv in the correct path and no spelling mistake on SFrame
Any help is greatly appreciated.Thank you.</p>
| 1 | 2016-08-14T00:48:17Z | 38,955,228 | <p>You need to restart the ipython kernel on your iPython/Jupyter notebook for graphlab to see the dependencies in the correct locations.</p>
<p>menu options:</p>
<p><code>Kernel > Restart</code></p>
<p>and try again. Worked for me.</p>
| 0 | 2016-08-15T12:37:23Z | [
"python",
"graphlab"
] |
AttributeError: 'module' object has no attribute 'SFrame' | 38,938,236 | <p>I am taking ML course in Coursera and I have installed GraphLab Create and ipython notebook.I am new to ML and python.</p>
<p>I get the following error,</p>
<pre><code>import graphlab
sf = graphlab.SFrame('people-example.csv')
</code></pre>
<blockquote>
<p>AttributeError Traceback (most recent call last)
in ()</p>
<p>----> 1 sf = graphlab.SFrame('people-example.csv')</p>
<p>AttributeError: 'module' object has no attribute 'SFrame'</p>
</blockquote>
<p>How do I fix this error?I have the people-example.csv in the correct path and no spelling mistake on SFrame
Any help is greatly appreciated.Thank you.</p>
| 1 | 2016-08-14T00:48:17Z | 38,971,441 | <p>In your iPython/Jupyter notebook follow these steps in this particular order.</p>
<ol>
<li>This will download and install dependencies. <code>graphlab.get_dependencies()</code> </li>
<li><p>Restart Kernel :
<code>Kernel > Restart</code></p></li>
<li><p>Now import graphlab: <code>import graphlab</code></p></li>
<li><code>sf = graphlab.SFrame('people-example.csv')</code></li>
</ol>
<p>Hope this helps. Cheers!</p>
| 2 | 2016-08-16T09:38:33Z | [
"python",
"graphlab"
] |
Cleaning data more efficiently in Pandas | 38,938,254 | <p>I have a python script that pulls EPS information from streetinsider.com. Currently I'm cleaning the data using an entirely inefficient method as seen below. Wondering if someone can show how this can be done more efficiently. </p>
<p>The following example is very very scaled down, there are many more columns and many many more rows. </p>
<pre><code>eps_table = DataFrame({'% Beat': '+1,405%', '% Week': '+123%'}, index=[0])
things_to_remove = ['% Beat', '% Week']
for i in things_to_remove:
eps_table[i] = eps_table[i].replace("%", "",regex=True)
eps_table[i] = eps_table[i].replace("\+", "", regex=True)
eps_table[i] = eps_table[i].replace("\,", "", regex=True)
</code></pre>
<p>Thanks.</p>
| 0 | 2016-08-14T00:51:07Z | 38,938,731 | <p>This is probably the easiest way to do it:</p>
<pre><code>eps_table.replace('\+', '', regex=True).replace('%', '', regex=True).replace(',', '', regex=True)
</code></pre>
<p>output:</p>
<pre><code> % Beat % Week
0 1405 123
</code></pre>
| 0 | 2016-08-14T02:51:14Z | [
"python",
"pandas",
"data-cleaning"
] |
Cleaning data more efficiently in Pandas | 38,938,254 | <p>I have a python script that pulls EPS information from streetinsider.com. Currently I'm cleaning the data using an entirely inefficient method as seen below. Wondering if someone can show how this can be done more efficiently. </p>
<p>The following example is very very scaled down, there are many more columns and many many more rows. </p>
<pre><code>eps_table = DataFrame({'% Beat': '+1,405%', '% Week': '+123%'}, index=[0])
things_to_remove = ['% Beat', '% Week']
for i in things_to_remove:
eps_table[i] = eps_table[i].replace("%", "",regex=True)
eps_table[i] = eps_table[i].replace("\+", "", regex=True)
eps_table[i] = eps_table[i].replace("\,", "", regex=True)
</code></pre>
<p>Thanks.</p>
| 0 | 2016-08-14T00:51:07Z | 38,938,748 | <p>Do it all at once:</p>
<pre><code>eps_table.replace(r'[%+,]', '', regex=True)
</code></pre>
| 3 | 2016-08-14T02:54:42Z | [
"python",
"pandas",
"data-cleaning"
] |
Why apply sometimes isn't faster than for-loop in pandas dataframe? | 38,938,318 | <p>It seems <code>apply</code> could accelerate the operation process on dataframe in most cases. But when I use <code>apply</code> I doesn't find the speedup. Here comes my example, I have a dataframe with two columns</p>
<pre><code>>>>df
index col1 col2
1 10 20
2 20 30
3 30 40
</code></pre>
<p>What I want to do is to calculate values for each row in dataframe by implementing a function <code>R(x)</code> on <code>col1</code> and the result will be divided by the values in <code>col2</code>. For example, the result of the first row should be <code>R(10)/20</code>.
So here is my function which will be called in <code>apply</code></p>
<pre><code>def _f(input):
return R(input['col1'])/input['col2']
</code></pre>
<p>Then I call <code>_f</code> in <code>apply</code>: <code>df.apply(_f, axis=1)</code></p>
<p>But I find in this case, <code>apply</code> is much slower than for loop, like</p>
<pre><code>for i in list(df.index)
new_df.loc[i] = R(df.loc[i,'col1'])/df.loc[i,'col2']
</code></pre>
<p>Can anyone explain the reason?</p>
| 1 | 2016-08-14T01:05:50Z | 38,938,507 | <p>It is my understanding that <code>.apply</code> is <strong>not</strong> generally faster than iteration over the axis. I believe underneath the hood it is merely a loop over the axis, except you are incurring the overhead of a function call each time in this case. </p>
<p>If we look at the <a href="https://github.com/pydata/pandas/blob/master/pandas/core/frame.py#L4153" rel="nofollow">source code</a>, we can see that essentially we are iterating over the indicated axis and applying the function, building the individual results as series into a dictionary, and the finally calling the dataframe constructor on the dictionary returning a new DataFrame:</p>
<pre><code> if axis == 0:
series_gen = (self._ixs(i, axis=1)
for i in range(len(self.columns)))
res_index = self.columns
res_columns = self.index
elif axis == 1:
res_index = self.index
res_columns = self.columns
values = self.values
series_gen = (Series.from_array(arr, index=res_columns, name=name,
dtype=dtype)
for i, (arr, name) in enumerate(zip(values,
res_index)))
else: # pragma : no cover
raise AssertionError('Axis must be 0 or 1, got %s' % str(axis))
i = None
keys = []
results = {}
if ignore_failures:
successes = []
for i, v in enumerate(series_gen):
try:
results[i] = func(v)
keys.append(v.name)
successes.append(i)
except Exception:
pass
# so will work with MultiIndex
if len(successes) < len(res_index):
res_index = res_index.take(successes)
else:
try:
for i, v in enumerate(series_gen):
results[i] = func(v)
keys.append(v.name)
except Exception as e:
if hasattr(e, 'args'):
# make sure i is defined
if i is not None:
k = res_index[i]
e.args = e.args + ('occurred at index %s' %
pprint_thing(k), )
raise
if len(results) > 0 and is_sequence(results[0]):
if not isinstance(results[0], Series):
index = res_columns
else:
index = None
result = self._constructor(data=results, index=index)
result.columns = res_index
if axis == 1:
result = result.T
result = result._convert(datetime=True, timedelta=True, copy=False)
else:
result = Series(results)
result.index = res_index
return result
</code></pre>
<p>Specifically:</p>
<pre><code>for i, v in enumerate(series_gen):
results[i] = func(v)
keys.append(v.name)
</code></pre>
<p>Where <code>series_gen</code> was constructed based on the requested axis. </p>
<p>To get more performance out of a function, you can follow the advice given <a href="http://pandas.pydata.org/pandas-docs/stable/enhancingperf.html" rel="nofollow">here</a>. </p>
<p>Essentially, your options are:</p>
<ol>
<li>Write a C extension</li>
<li>Use <code>numba</code> (a JIT compiler)</li>
<li>Use <code>pandas.eval</code> to squeeze performance out of large Dataframes</li>
</ol>
| 2 | 2016-08-14T01:52:31Z | [
"python",
"pandas"
] |
urllib3 segfault (core dumped) | 38,938,381 | <p>I'm getting a segfault ("Illegal operation (core dumped)") for a python program that I've run every week without fault for ages. I'm also running Ubuntu on Nitrous. I recall dealing with these yonks ago when coding in C, and I haven't had to deal with them very much recently.</p>
<p>Importing the library urllib3 seems to be causing the problem. Does anyone know a fix?</p>
<p>Also, can someone advise or link to the best workflow for diagnosing these problems in future?</p>
<p>Thanks!</p>
| 1 | 2016-08-14T01:20:02Z | 38,939,568 | <blockquote>
<p>"Illegal operation"</p>
</blockquote>
<p>This <em>usually</em> means that you are running code compiled for a more capable processor (e.g. <a href="https://en.wikipedia.org/wiki/Haswell_(microarchitecture)" rel="nofollow">Haswell</a>) on a less capable one (e.g. <a href="https://en.wikipedia.org/wiki/Ivy_Bridge_(microarchitecture)" rel="nofollow">Ivy Bridge</a>).</p>
<blockquote>
<p>Importing the library urllib3 seems to be causing the problem.</p>
</blockquote>
<p>On my Ubuntu machine, <code>import urllib3</code> loads <code>libssl.so.1.0.0</code>, <code>libcrypto.so.1.0.0</code> and <code>_ssl.x86_64-linux-gnu.so</code>. These crypto libraries are very likely to be compiled with <a href="https://en.wikipedia.org/wiki/Advanced_Vector_Extensions" rel="nofollow">AVX</a>, <a href="https://en.wikipedia.org/wiki/Advanced_Vector_Extensions#Advanced_Vector_Extensions_2" rel="nofollow">AVX2</a>, etc. instructions which your processor may not support.</p>
<blockquote>
<p>best workflow for diagnosing these problems</p>
</blockquote>
<p>Your first step should be to find out which instruction is causing the <code>SIGILL</code>. To do so, run:</p>
<pre><code>gdb python
(gdb) run
>>> import urllib3 # do whatever is necessary to reproduce SIGILL
(gdb) x/i $pc
(gdb) info sym $pc
</code></pre>
<p>The last two commands above should give you the instruction that is causing the <code>SIGILL</code>, and the library in which that instruction is used. Once you know what that instruction is, you can verify that your processor doesn't support it, and contact the distributor of the "guilty" library to get a different compilation (one without using instructions that are not supported by your CPU).</p>
| 0 | 2016-08-14T05:53:09Z | [
"python",
"linux",
"segmentation-fault",
"urllib3"
] |
Tweepy Django redirect | 38,938,409 | <p>I am working on a project with tweepy and django for some reason I cannot get the site to stop going to example.com with the response. I have tried deleteting example.com from the admin site and adding my host, as well as changing the default domain and the allowed hosts to my site. This is running on an ec2 instance.
After I login in I get redirected to a '<a href="http://example.com/auth/twitter/callback/?oauth_token=sdfsdfsdfsdfsd&oauth_verifier=sdfsdfwekjfdsljf" rel="nofollow">http://example.com/auth/twitter/callback/?oauth_token=sdfsdfsdfsdfsd&oauth_verifier=sdfsdfwekjfdsljf</a>' (note values returned from callback are made up for security) </p>
<p>UPDATE - I have deployed to apache2 and still get the same error</p>
<p>settings.py </p>
<pre><code>"""
Django settings for starterSite project.
Generated by 'django-admin startproject' using Django 1.9.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '####'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'twitSent',
'django.contrib.sites',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'twitSent.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'starterSite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = [
'http://example.com:8888', # allows viewing of instances directly
]
DEFAULT_DOMAIN = 'http://example.com:8888'
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/twitstat/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
</code></pre>
<p>views.py</p>
<pre><code>#from django.shortcuts import render
# Create your views here.
import tweepy
from django.http import *
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
from django.contrib.auth import logout
CONSUMER_KEY = '####'
CONSUMER_SECRET = '###'
def get_api(request):
# set up and return a twitter api object
oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
access_key = request.session['access_key_tw']
access_secret = request.session['access_secret_tw']
oauth.set_access_token(access_key, access_secret)
api = tweepy.API(oauth)
return api
def main(request):
"""
main view of app, either login page or info page
"""
# if we haven't authorised yet, direct to login page
if check_key(request):
return HttpResponseRedirect(reverse('info'))
else:
return render_to_response('twitSent/login.html')
def unauth(request):
"""
logout and remove all session data
"""
if check_key(request):
api = get_api(request)
request.session.clear()
logout(request)
return HttpResponseRedirect(reverse('main'))
def info(request):
"""
display some user info to show we have authenticated successfully
"""
if check_key(request):
api = get_api(request)
user = api.me()
return render_to_response('twitSent/info.html', {'user' : user})
else:
return HttpResponseRedirect(reverse('main'))
def auth(request):
# start the OAuth process, set up a handler with our details
oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
# direct the user to the authentication url
# if user is logged-in and authorized then transparently goto the callback URL
auth_url = oauth.get_authorization_url(True)
response = HttpResponseRedirect(auth_url)
# store the request token
request.session['unauthed_token_tw'] = (oauth.request_token['oauth_token'], oauth.request_token['oauth_token_secret'])
return response
def callback(request):
verifier = request.GET.get('oauth_verifier')
oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
token = request.session.get('unauthed_token_tw', None)
# remove the request token now we don't need it
request.session.delete('unauthed_token_tw')
oauth.set_request_token(token[0], token[1])
# get the access token and store
try:
oauth.get_access_token(verifier)
except tweepy.TweepError:
print('Error, failed to get access token')
request.session['access_key_tw'] = oauth.access_token.key
request.session['access_secret_tw'] = oauth.access_token.secret
response = HttpResponseRedirect(reverse('info'))
return response
def check_key(request):
"""
Check to see if we already have an access_key stored, if we do then we have already gone through
OAuth. If not then we haven't and we probably need to.
"""
try:
access_key = request.session.get('access_key_tw', None)
if not access_key:
return False
except KeyError:
return False
return True
</code></pre>
<p>urls.py (in app folder)</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [ #'twitter_auth.views',
url(r'^$', views.main, name='main'),
url(r'^callback/$', views.callback, name='auth_return'),
url(r'^logout/$', views.unauth, name='oauth_unauth'),
url(r'^auth/$', views.auth, name='oauth_auth'),
url(r'^info/$', views.info, name='info'),
]
</code></pre>
<p>login.html</p>
<pre><code>{% extends "twitSent/base.html" %}
{% block content %}
<div id="container">
<h2>Welcome!</h2>
<p>Sign in with Twitter to begin.</p>
<p><a href="{% url 'oauth_auth' %}"><img src="https://si0.twimg.com/images/dev/buttons/sign-in-with-twitter-d.png" alt="sign in with twitter" /></a></p>
</div>
{% endblock %}
</code></pre>
<p>info.html</p>
<pre><code>{% extends "twitSent/base.html" %}
{% block content %}
<div id="container">
<img src="{{user.profile_image_url}}" />
<h3>{{user.name}}</h3>
<p>{{user.screen_name}}<p/>
<a href="/logout/" title="logout">logout</a>
</div>
{% endblock %}
</code></pre>
| 1 | 2016-08-14T01:26:58Z | 38,938,690 | <p>When we send the user to Twitter for authentication, Twitter redirects the user to the url we set as call back url in the app settings. </p>
<p>You can however, override this callback url when sending the user to twitter for authorization. </p>
| 0 | 2016-08-14T02:42:21Z | [
"python",
"django",
"tweepy"
] |
How to filter objects in django by hyperlink related field | 38,938,421 | <p>I have a model called car which contains a property <code>session</code> which is a HyperLinkRelatedField</p>
<p>I am trying to filter the objects by that hyperlinkrelated field</p>
<p>I tried something like this:</p>
<pre><code>session_url = "http://localhost:8000/v1/sessions/"+uuid+"/"
print cars.objects.filter(session=session_url)
</code></pre>
<p>I got this error:</p>
<pre><code>ValueError: invalid literal for int() with base 10: 'http://localhost:8000/v1/sessions/4c597c05-5e66-11e6-a79c-9801a78ed96d/'
</code></pre>
<p>The problem is, session is definetly not an integer, so I can not understand why this happens</p>
<p>here is how my serializer looks</p>
<pre><code>class CarSerializer(serializers.Serializer):
altitude = serializers.FloatField()
course = serializers.FloatField()
session = serializers.HyperlinkedRelatedField(
many=False,
queryset=Session.objects.all(),
view_name="session-detail",
lookup_field="uuid"
)
timestamp = serializers.DateTimeField(required=False)
</code></pre>
<p>Any reason why this is not working ? and if it is wrong then how do we filter an object by a HyperLink in django</p>
| 0 | 2016-08-14T01:29:39Z | 38,938,673 | <p>You field <code>session</code> is a serializer field, not a model field. In the DRF these fields are usually computed based on the model data.
The <code>HyperlinkedRelatedField</code> offers an easy way of putting URLs to ressourses into a response. On the other other hand it contais too much hard to parse data to use it for queries to the ORM. To filter by a relation you need an object of the type the relation goes to or a value with the same type as the primary key. In your case an integer.</p>
<p>To solve your problem, I advise to use a <code>PrimaryKeyRelatedField</code> instead of or in addition to your <code>HyperlinkedRelatedField</code>.</p>
<p>Seeing your code, an other solution could be to filter by the UUID, but you did not provide your models, so I can give a proper code example.</p>
| 1 | 2016-08-14T02:38:40Z | [
"python",
"django"
] |
how to solve ? x and y must have same first dimension | 38,938,437 | <pre><code>from sklearn.neighbors import KNeighborsClassifier
import pandas as pd
from sklearn import metrics
from sklearn.cross_validation import train_test_split
import matplotlib.pyplot as plt
r = pd.read_csv("vitalsign_test.csv")
clm_list = []
for column in r.columns:
clm_list.append(column)
X = r[clm_list[1:len(clm_list)-1]].values
y = r[clm_list[len(clm_list)-1]].values
X_train, X_test, y_train, y_test = train_test_split (X,y, test_size = 0.3, random_state=4)
k_range = range(1,25)
scores = []
for k in k_range:
clf = KNeighborsClassifier(n_neighbors = k)
clf.fit(X_train,y_train)
y_pred = clf.predict(X_test)
scores.append(metrics.accuracy_score(y_test,y_pred))
plt.plot(k_range,scores)
plt.xlabel('value of k for clf')
plt.ylabel('testing accuracy')
</code></pre>
<p>reponse that I am getting is </p>
<blockquote>
<p>ValueError: x and y must have same first dimension</p>
</blockquote>
<p>my feature and response shape is: </p>
<pre><code>y.shape
Out[60]: (500,)
X.shape
Out[61]: (500, 6)
</code></pre>
| -1 | 2016-08-14T01:34:22Z | 38,941,788 | <p>It has nothing to do with your <code>X</code> and <code>y</code>, it is about <code>x</code> and <code>y</code> arguments to <strong>plot</strong>, since your <code>scores</code> has one element, and <code>k_range</code> has 25. The error is incorrect indentation:</p>
<pre><code>for k in k_range:
clf = KNeighborsClassifier(n_neighbors = k)
clf.fit(X_train,y_train)
y_pred = clf.predict(X_test)
scores.append(metrics.accuracy_score(y_test,y_pred))
</code></pre>
<p>should be</p>
<pre><code>for k in k_range:
clf = KNeighborsClassifier(n_neighbors = k)
clf.fit(X_train,y_train)
y_pred = clf.predict(X_test)
scores.append(metrics.accuracy_score(y_test,y_pred))
</code></pre>
| 0 | 2016-08-14T11:30:44Z | [
"python",
"matplotlib",
"machine-learning"
] |
python saving multiple subplot figures to pdf | 38,938,454 | <p>I am new with python I am trying to save a huge bunch of data into a pdf with figures using PdfPages of matplotlib and subplots. Problem is that I found a blottleneck I dont know how to solve, the code goes something like:</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
with PdfPages('myfigures.pdf') as pdf:
for i in range(1000):
f,axarr = plt.subplots(2, 3)
plt.subplots(2, 3)
axarr[0, 0].plot(x1, y1)
axarr[1, 0].plot(x2, y2)
pdf.savefig(f)
plt.close('all')
</code></pre>
<p>Creating a figure each loop it is highly time consuming, but if I put that outside the loop it doesnt clear each plot. Other options I tried like clear() or clf() didnt work either or ended in creating multiple different figures, anyone as an idea on how to put this in a different way so that it goes faster?</p>
| 1 | 2016-08-14T01:39:29Z | 38,943,527 | <p>To contain large numbers of subplots as multipage output inside a single pdf, all you need to do is create a new page immediately after detecting that the most recent subplot addition has maxed out the available space in the current page's subplot-array layout. Here's a way to do it where the dimensions controlling the number of subplots per page can easily be changed:</p>
<pre><code>import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import sys
import timeit
from matplotlib.backends.backend_pdf import PdfPages
matplotlib.rcParams.update({'font.size': 6})
# Dimensions for any n-rows x m-cols array of subplots / pg.
n, m = 4, 5
# Don't forget to indent after the with statement
with PdfPages('auto_subplotting.pdf') as pdf:
# Let's time the execution required to create and save
# each full page of subplots to the pdf
start_time = timeit.default_timer()
# Before beginning the iteration through all the data,
# initialize the layout for the plots and create a
# representation of the subplots that can be easily
# iterated over for knowing when to create the next page
# (and also for custom settings like partial axes labels)
f, axarr = plt.subplots(n, m, sharex='col', sharey='row')
arr_ij = [(x,y) for x,y in np.ndindex(axarr.shape)]
subplots = [axarr[index] for index in arr_ij]
# To conserve needed plotting real estate,
# only label the bottom row and leftmost subplots
# as determined automatically using n and m
splot_index = 0
for s,splot in enumerate(subplots):
splot.set_ylim(0,.15)
splot.set_xlim(0,50)
last_row = ( n*m-s < m+1 )
first_in_row = ( s % m == 0 )
if last_row:
splot.set_xlabel("X-axis label")
if first_in_row:
splot.set_ylabel("Y-axis label")
# Iterate through each sample in the data
for sample in range(33):
# As a stand-in for real data, let's just make numpy take 100 random draws
# from a poisson distribution centered around say ~25 and then display
# the outcome as a histogram
scaled_y = np.random.randint(20,30)
random_data = np.random.poisson(scaled_y, 100)
subplots[splot_index].hist(random_data, bins=12, normed=True,
fc=(0,0,0,0), lw=0.75, ec='b')
# Keep subplotting through the samples in the data and increment
# a counter each time. The page will be full once the count is equal
# to the product of the user-set dimensions (i.e. n * m)
splot_index += 1
# We can basically repeat the same exact code block used for the
# first layout initialization, but with the addition of 4 new lines:
# 2 for saving the just-finished page to the pdf, 1 for the
# page's execution time, & 1 more to reset the subplot index
if splot_index == n*m:
pdf.savefig()
plt.close(f)
print(timeit.default_timer()-start_time)
start_time = timeit.default_timer()
f, axarr = plt.subplots(n, m, sharex='col', sharey='row')
arr_ij = [(x,y) for x,y in np.ndindex(axarr.shape)]
subplots = [axarr[index] for index in arr_ij]
splot_index = 0
for s,splot in enumerate(subplots):
splot.set_ylim(0,.15)
splot.set_xlim(0,50)
last_row = ( (n*m)-s < m+1 )
first_in_row = ( s % m == 0 )
if last_row:
splot.set_xlabel("X-axis label")
if first_in_row:
splot.set_ylabel("Y-axis label")
# Done!
# But don't forget the last page
pdf.savefig()
plt.close(f)
</code></pre>
<p>For a 2x3 layout, just change the declarations for n and m accordingly at the beginning of the code block. As an example of an even more compact layout, the 4x5 matrix above with 33 samples to make plots for gave the following two-page output:</p>
<p><a href="http://i.stack.imgur.com/mixOJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/mixOJ.png" alt=""></a></p>
<p>Where you can see on the second page that axes-frames were made for the whole layout, but the last 7 are blank (4x5 x 2 = 40 - 33 = 7).</p>
<p>The printed output from <code>timeit</code> was <code>1.81540203094</code> seconds for creation of the first page. </p>
<hr>
<blockquote>
<p>Note:
The multipage handling should probably be simplified by creating a <code>new_page</code> function; it's better to not repeat code verbatim, especially if you start customizing the plots in which case you won't want to have to mirror every change and type the same thing twice. A more customized aesthetic based off of seaborn and utilizing the available matplotlib parameters like shown below might be preferable too.</p>
</blockquote>
<p>Add a <code>new_page</code> function & some customizations for the subplot style:</p>
<pre><code>from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import random
import seaborn as sns
import timeit
from matplotlib.backends.backend_pdf import PdfPages
# this erases labels for any blank plots on the last page
sns.set(font_scale=0.0)
n, m = 4, 6
datasize = 37
ctheme = ['k', 'gray', 'magenta', 'fuchsia', '#be03fd', '#1e488f',
(0.44313725490196076, 0.44313725490196076, 0.88627450980392153),
'#75bbfd', 'teal', 'lime', 'g', (0.6666674, 0.6666663, 0.29078014184397138),
'y', '#f1da7a', 'tan','orange', 'maroon', 'r']
colors = sns.blend_palette(ctheme, datasize)
fz = 7 # labels fontsize
def new_page(n, m):
global splot_index
splot_index = 0
fig, axarr = plt.subplots(n, m, sharey='row')
plt.subplots_adjust(hspace=0.5, wspace=0.15)
arr_ij = [(x,y) for x,y in np.ndindex(axarr.shape)]
subplots = [axarr[index] for index in arr_ij]
for s,splot in enumerate(subplots):
splot.grid(b=True, which='major', color='gray', linestyle='-',
alpha=0.25, zorder=1, lw=0.5)
splot.set_ylim(0,.15)
splot.set_xlim(0,50)
last_row = ( n*m-s < m+1 )
first_in_row = ( s % m == 0 )
if last_row:
splot.set_xlabel("X-axis label", labelpad=8, fontsize=fz)
if first_in_row:
splot.set_ylabel("Y-axis label", labelpad=8, fontsize=fz)
return(fig, subplots)
with PdfPages('auto_subplotting_colors.pdf') as pdf:
start_time = timeit.default_timer()
fig, subplots = new_page(n, m)
for sample in xrange(datasize):
splot = subplots[splot_index]
splot_index += 1
scaled_y = np.random.randint(20,30)
random_data = np.random.poisson(scaled_y, 100)
splot.hist(random_data, bins=12, normed=True, zorder=2, alpha=0.99,
fc='white', lw=0.75, ec=colors.pop())
splot.set_title("Sample {}".format(sample+1), fontsize=fz)
# tick fontsize & spacing
splot.xaxis.set_tick_params(pad=4, labelsize=6)
splot.yaxis.set_tick_params(pad=4, labelsize=6)
# make new page:
if splot_index == n*m:
pdf.savefig()
plt.close(fig)
print(timeit.default_timer()-start_time)
start_time = timeit.default_timer()
fig, subplots = new_page(n, m)
if splot_index > 0:
pdf.savefig()
plt.close(f)
</code></pre>
<p><br>
This time it took <code>2.51897096634</code> seconds for the first page:</p>
<p><a href="http://i.stack.imgur.com/IlQO7.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/IlQO7.jpg" alt=""></a></p>
| 1 | 2016-08-14T15:09:26Z | [
"python",
"pdf",
"matplotlib"
] |
Simple Python documentation exception | 38,938,457 | <p>My code returns an exception from a documentation string, and I can't see the issue:</p>
<pre><code>def printBreak(title):
"""Prints a dotted line"""
print("------" + title + "------")
def printWords(theWords):
"""Prints the passed array with word length and word"""
for w in theWords:
print(len(w), w)
print("")
def sortWordsByLength(theWords):
"""Word array sorted by length"""
for w in theWords:
for i in range(len(wordsSortedByLength)):
if len(w) > len(wordsSortedByLength[i]):
wordsSortedByLength.insert(i,w)
break
else:
wordsSortedByLength.append(w)
def main():
printBreak("Initial word array")
printWords(words)
printBreak(sortWordsByLength.__doc__)
sortWordsByLength(words[1:])
printWords(wordsSortedByLength)
# Sort some strings
words = ['happy', 'cat', 'window', 'appetite', 'gophery', 'it', 'perky']
wordsSortedByLength = [words[0]]
main()
</code></pre>
<p>Error:</p>
<pre><code>File "/Users/bevilacm/source/Python/Scripts/sortWords.py", line 7
for w in theWords:
^
IndentationError: unindent does not match any outer indentation level
[Finished in 0.1s with exit code 1]
</code></pre>
<p>If the documentation string is commented out in the printWords function documentation string, the code works. I expect it is something simple yet I don't see it.</p>
<p>Thanks!</p>
| 0 | 2016-08-14T01:40:13Z | 38,938,502 | <p>You've mixed tabs and spaces, causing Python to get confused about what statements are at what indentation level. On Python 3, you're supposed to get an error specifically notifying you of inconsistent mixing of tabs and spaces, but it looks like that's not happening for some reason.</p>
<p>Stop mixing tabs and spaces. Turn on "show whitespace" in your editor to make the problem visible, and see if there's a "convert tabs to spaces" tool to find and fix tabs for you.</p>
| 4 | 2016-08-14T01:51:14Z | [
"python",
"python-3.x"
] |
Python - Pass a variable to lambda if it exists | 38,938,464 | <p>I'm curious about how to make code more efficient in Python, I've got to execute an action, which may or may not have a payload attached depending on the length of a list.</p>
<p>Right now, I'm using an if statement to determine if there is a payload. Is there a better or cleaner way to find this?</p>
<pre><code> #If payload, execute action with it
if(len(data) > 1):
action= mec.action(data[1])
#If no payload, then just execute action
else:
action= mec.action()
return action
</code></pre>
| 1 | 2016-08-14T01:41:26Z | 38,938,477 | <p>The code is efficient as is - instead of optimising for efficiency, try optimising for clarity first.
If the code then becomes a performance hotspot... think about looking at the efficiency.</p>
<hr>
<p>Remembering that a <code>return</code> ends a function; this is a slightly cleaner alternative:</p>
<pre><code># execute with payload if exists
if(len(data) > 1):
return mec.action(data[1])
# execute without payload
# this isn't reached if len(data) > 1
return mec.action()
</code></pre>
| 3 | 2016-08-14T01:45:38Z | [
"python",
"lambda"
] |
Python - Pass a variable to lambda if it exists | 38,938,464 | <p>I'm curious about how to make code more efficient in Python, I've got to execute an action, which may or may not have a payload attached depending on the length of a list.</p>
<p>Right now, I'm using an if statement to determine if there is a payload. Is there a better or cleaner way to find this?</p>
<pre><code> #If payload, execute action with it
if(len(data) > 1):
action= mec.action(data[1])
#If no payload, then just execute action
else:
action= mec.action()
return action
</code></pre>
| 1 | 2016-08-14T01:41:26Z | 38,938,503 | <p>Python comes with vararg syntax you can use for this directly.</p>
<pre><code>return mec.action(*data[1:])
</code></pre>
<p>(I'm assuming here that <code>data[2]</code> onwards aren't meaningful, or you could use <code>mec.action(*data[1:2])</code>)</p>
| 1 | 2016-08-14T01:51:42Z | [
"python",
"lambda"
] |
How to find the n-largest edge weights in a network matrix (networkx)? | 38,938,571 | <p>I have the following code that I attempt to use to generate a network matrix. With this matrix, I would like to find the 20 highest-weighted edges that ARE NOT on the diagnal (<em>i.e.</em> <code>i!=j</code> in the matrix). I also would like to get the names of the nodes (in pairs) composed of these edges.</p>
<pre><code>import heapq
def mapper_network(self, _, info):
G = nx.Graph() #create a graph
for i in range(len(info)):
edge_from = info[0] # edge from
edge_to = info[1] # edge to
weight = info[2] # edge weight
G.add_edge(edge_from, edge_to, weight=weight) #insert the edge to the graph
A = nx.adjacency_matrix(G) # create an adjacency matrix
A_square = A * A # find the product of the matrix
print heapq.nlargest(20, A_square) # to print out the 20 highest weighted edges
</code></pre>
<p>With this code, however, I failed to generate the 20 most weighted edges. I obtain <code>raise ValueError("The truth value of an array with more than one "
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().</code> </p>
<p>Instead, with this</p>
<pre><code> print heapq.nlargest(20, range(len(A_square)), A_square.take)
</code></pre>
<p>It gives me:</p>
<pre><code> raise TypeError("sparse matrix length is ambiguous; use getnnz()"
TypeError: sparse matrix length is ambiguous; use getnnz() or shape[0]
</code></pre>
<p>With</p>
<pre><code> def mapper_network(self, _, info):
G = nx.Graph()
for i in range(len(info)):
edge_from = info[0]
edge_to = info[1]
weight = info[2]
G.add_edge(edge_from, edge_to, weight=weight)
A = nx.adjacency_matrix(G)
A_square = A * A #can print (A_square.todense())
weight = nx.get_edge_attributes(A_square, weight)
edges = A_square.edges(data = True)
s = sorted(G.edges(data=True), key=lambda (source, target, data): data['weight'])
print s
</code></pre>
<p>I received</p>
<pre><code> File "/tmp/MRQ7_trevor.vagrant.20160814.040827.770006/job_local_dir/1/mapper/0/mrjob.tar.gz/mrjob/job.py", line 433, in run
mr_job.execute()
File "/tmp/MRQ7_trevor.vagrant.20160814.040827.770006/job_local_dir/1/mapper/0/mrjob.tar.gz/mrjob/job.py", line 442, in execute
self.run_mapper(self.options.step_num)
File "/tmp/MRQ7_trevor.vagrant.20160814.040827.770006/job_local_dir/1/mapper/0/mrjob.tar.gz/mrjob/job.py", line 507, in run_mapper
for out_key, out_value in mapper(key, value) or ():
File "MRQ7_trevor.py", line 90, in mapper_network
weight = nx.get_edge_attributes(A_square, weight)
File "/home/vagrant/anaconda/lib/python2.7/site-packages/networkx/classes/function.py", line 428, in get_edge_attributes
if G.is_multigraph():
File "/home/vagrant/anaconda/lib/python2.7/site-packages/scipy/sparse/base.py", line 499, in __getattr__
raise AttributeError(attr + " not found")
</code></pre>
<p>AttributeError: is_multigraph not found</p>
<p>Could someone help me solve this question? Thank you very much!</p>
| 1 | 2016-08-14T02:11:24Z | 38,940,008 | <p>The issue with this line:</p>
<pre><code>heapq.nlargest(20, A_square)
</code></pre>
<p>Is that <code>nlargest</code> does not expect an iterable of iterables, but an interable of numbers.</p>
<p>So you could do this instead:</p>
<pre><code>heapq.nlargest(20, itertools.chain.from_iterable(A_square))
</code></pre>
<p><a href="https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable" rel="nofollow"><code>itertools.chain.iterables</code></a> takes an iterable of iterables, and creates a new iterable with the content of all the inner iterables.</p>
<hr>
<p>However, that won't entierly solve your initial problem, for two reasons:</p>
<ol>
<li><p>Why do you take the square of the adjacency matrix? Doing so would only give you the highest weighted sum of paths of length 2 in the graph, which is quite different from what you want. Just use the adjacency matrix instead.</p></li>
<li><p>Nowhere in your code you remove the diagonal. You could do it like this: <code>for n in G.number_of_nodes(): A[n][n] = 0</code></p></li>
</ol>
| 1 | 2016-08-14T07:14:13Z | [
"python",
"matrix",
"heap",
"networkx"
] |
String variable doesn't print correctly | 38,938,629 | <p>So I am writing a multi-client chat and I would like to display the name of every client in front of the message. when I print the variable "client_name" in the main function (the line "clients_dictionary[current_socket.getpeername()]" returns the value it's supposed to, doesn't return None) by itself it shows up fine, but when I try to join it to the body of the message ("data = client_name + ": " + data") it prints as ": <em>whatever was in the variable data</em>". What am I doing wrong?</p>
<pre><code>import socket
import select
HOST = ""
PORT = ""
open_client_sockets = []
messages_to_send = []
clients_dictionary = {}
def handle(server_socket):
client_socket, client_address = server_socket.accept()
open_client_sockets.append(client_socket)
client_name = client_socket.recv(1024)
clients_dictionary[client_address] = client_name
def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
while True:
r, w, x = select.select([server_socket] + open_client_sockets, open_client_sockets, [])
for current_socket in r:
if current_socket == server_socket:
handle(server_socket)
else:
try:
data = current_socket.recv(1024)
except socket.error:
data = ""
if data == "":
open_client_sockets.remove(current_socket)
else:
client_name = clients_dictionary[current_socket.getpeername()]
data = ": " + data
data = client_name + data
print data
messages_to_send.append((current_socket, data))
w.remove(current_socket)
for client_socket in w:
if client_socket != current_socket:
client_socket.send(data)
if __name__ == "__main__":
main()
</code></pre>
| 1 | 2016-08-14T02:28:15Z | 38,939,944 | <p>anyway you better be use python string formatting: </p>
<pre><code>chat_msg = '{}: {}'.format(client_name, data)
</code></pre>
| 3 | 2016-08-14T07:01:53Z | [
"python",
"python-2.7",
"sockets",
"chat"
] |
Different renders of RGB data in scipy vs pyplot | 38,938,640 | <p>I'm implementing a fractal-flame renderer for kicks and giggles, and got hung up on a silly little color problem. After running the algorithm, I get a RGBA matrix (HxWxC, specifically I have 1080x1440x4), but I get different results when rendering it with pyplot than I do with scipy. Here's the output code:</p>
<pre><code>condensed = prepare_image(condensed, **condensed_args)
condensed[np.isnan(condensed)] = 0
name += '.png' if not name.endswith('.png') else ''
sc.misc.imsave("sc_" + name, condensed, format='png')
plt.imsave("pl_" + name, condensed)
</code></pre>
<p>And here's the two output images:</p>
<p>Scipy:
<img src="http://i.stack.imgur.com/j0pM9.png" alt="Scipy's output image"></p>
<p>Pyplot:
<img src="http://i.stack.imgur.com/ndOzD.png" alt="Pyplot's output image"></p>
<p>Ignoring the background color (the alpha there is 0, so I can deal with that manually), the details are totally different in color: scipy produces a smooth cyan'ish color, whereas pyplot produces a static'y hodgepodge of random colors. If I load scipy's image back in with pyplot.imread and display it, I get the nice cyan, so there must be something with how pyplot is interpreting my original RGBA matrix. I'm not setting any color map or index anywhere else that I can see. The documentation for both imsave functions seem to say they behave the same way (and pyplot's imshow behaves the same as its imsave, as should be expected).</p>
<p>If I had to guess, it looks like pyplot is interpreting my data as HSL, or some other color space. The Scipy one is closer to what I'm expecting, and what the algorithm is supposed to produce.</p>
<p>Anyone see what I'm doing wrong here? Help would be greatly appreciated.</p>
| 1 | 2016-08-14T02:30:37Z | 38,939,075 | <p>When saving a floating point array, <code>scipy.misc.imsave()</code> (which uses Pillow to do the actual work) effectively scales the values in the array to the interval [0, 1]. <code>plt.imsave()</code>, on the other hand, appears to <em>clip</em> the values to the interval [0, 1], without changing the values that are within [0, 1].</p>
<p>If you transform the values in <code>condensed</code> to the interval [0, 1] with something like</p>
<pre><code>condensed = (condensed - condensed.min())/condensed.ptp()
</code></pre>
<p>before saving the image using <code>plt.imsave()</code>, it should produce the same image as <code>scipy.misc.imsave()</code>.</p>
| 0 | 2016-08-14T04:17:18Z | [
"python",
"numpy",
"matplotlib",
"colors",
"scipy"
] |
Django Flatpages Using: Site matching query does not exist | 38,938,649 | <p>I'm a noob at Django.</p>
<p>I've created a flatpages object in my admin console when I visit the url which I run on a local server, I get a "Site Matching query does not exist" error.
Can someone help me?</p>
<pre><code>urlpatterns = [
url(r'^', include('main.urls')),
url(r'^home/', include('django.contrib.flatpages.urls')),
url(r'^admin/', admin.site.urls),
]
</code></pre>
<p>Here's the error log:</p>
<pre><code>Traceback:
File "/usr/local/lib/python2.7/dist-packages/Django-1.10-py2.7.egg/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/Django-1.10-py2.7.egg/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/Django-1.10-py2.7.egg/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/Django-1.10-py2.7.egg/django/contrib/flatpages/views.py" in flatpage
35. site_id = get_current_site(request).id
File "/usr/local/lib/python2.7/dist-packages/Django-1.10-py2.7.egg/django/contrib/sites/shortcuts.py" in get_current_site
15. return Site.objects.get_current(request)
File "/usr/local/lib/python2.7/dist-packages/Django-1.10-py2.7.egg/django/contrib/sites/models.py" in get_current
67. return self._get_site_by_request(request)
File "/usr/local/lib/python2.7/dist-packages/Django-1.10-py2.7.egg/django/contrib/sites/models.py" in _get_site_by_request
44. SITE_CACHE[host] = self.get(domain__iexact=host)
File "/usr/local/lib/python2.7/dist-packages/Django-1.10-py2.7.egg/django/db/models/manager.py" in manager_method
85. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/Django-1.10-py2.7.egg/django/db/models/query.py" in get
385. self.model._meta.object_name
Exception Type: DoesNotExist at /default/
Exception Value: Site matching query does not exist.
</code></pre>
| 1 | 2016-08-14T02:33:08Z | 38,939,515 | <p>Perhaps you have not defined <a href="https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-SITE_ID" rel="nofollow">SITE_ID</a> in settings.</p>
| 0 | 2016-08-14T05:43:28Z | [
"python",
"django"
] |
Django .all() query on a unique_together model | 38,938,655 | <p>I have a model with two fields that are unique together:</p>
<pre><code>class Servers(models.Model):
server_id = models.IntegerField(db_column='server_id')
nodename = models.CharField(max_length=40)
tag_name = models.CharField(max_length=180)
customer = models.ForeignKey(Customers, on_delete=models.CASCADE)
os = models.ForeignKey(Operatingsystems, on_delete=models.CASCADE)
active = models.IntegerField()
class Meta:
managed = False
db_table = 'servers'
unique_together = (('server_id', 'nodename'),)
</code></pre>
<p>When I run the following query:</p>
<pre><code>>>> Servers.objects.all()
</code></pre>
<p>I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/django/db/models/query.py", line 232, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/django/db/models/query.py", line 256, in __iter__
self._fetch_all()
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/django/db/models/query.py", line 1085, in _fetch_all
self._result_cache = list(self.iterator())
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/django/db/models/query.py", line 54, in __iter__
results = compiler.execute_sql()
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 112, in execute
return self.cursor.execute(query, args)
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/MySQLdb/cursors.py", line 226, in execute
self.errorhandler(self, exc, value)
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorvalue
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/MySQLdb/cursors.py", line 217, in execute
res = self._query(query)
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/MySQLdb/cursors.py", line 378, in _query
rowcount = self._do_query(q)
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/MySQLdb/cursors.py", line 341, in _do_query
db.query(q)
File "/Users/rlthompson/.virtualenvs/venv/lib/python3.5/site-packages/MySQLdb/connections.py", line 280, in query
_mysql.connection.query(self, query)
django.db.utils.OperationalError: (1054, "Unknown column 'servers.id' in 'field list'")
</code></pre>
<p>I ran <code>makemigration</code> and <code>migrate</code> on the database and the error persists. So my question is how would one do a <code>.all()</code> query on a database with the <code>unique_together</code> meta set?</p>
| 0 | 2016-08-14T02:34:47Z | 38,938,710 | <p>You have <code>managed</code> set to <code>False</code>. So, Django is not creating the default primary key (<code>id</code>) on the table. </p>
<p>When you're later trying to query it, Django ORM looks for the <code>id</code> and it fails. </p>
<p>You need to have at least one primary key. So create a new field or set the <code>primary_key=True</code> on an existing field. </p>
| 2 | 2016-08-14T02:47:20Z | [
"python",
"mysql",
"django",
"django-forms"
] |
Why does cos(x) give me a result of x as x was in radians? | 38,938,664 | <p>I am using Python but there is something strange. Why does cos(x) give me a result of x as was in radians? while cos(radians(x)) gives the answer as x was in degree</p>
<p>for example :</p>
<pre><code>>>> cos(75)
0.9217512697247493
</code></pre>
<p>but the truth is if 75 is in degree, then cos(75) = 0.26 </p>
<pre><code>>>> cos(radians(75))
0.25881904510252074
</code></pre>
<p>but the truth is if 75 is in radians, then cos(75) = 0.90</p>
<p>I am wrong ? why is that happening ? </p>
| -1 | 2016-08-14T02:37:05Z | 38,938,685 | <ul>
<li><code>cos(75)</code> means "the cosine of 75 radians". (See <a href="https://docs.python.org/3/library/math.html#trigonometric-functions">documentation</a>.)</li>
<li><code>radians(75)</code> means "convert 75° to radians", i.e. "the number of radians that's equivalent to 75°". (See <a href="https://docs.python.org/3/library/math.html#angular-conversion">documentation</a>.)</li>
<li>so <code>cos(radians(75))</code> means "the cosine of {the number of radians that's equivalent to 75°} radians", i.e. "the cosine of 75°".</li>
</ul>
| 5 | 2016-08-14T02:41:19Z | [
"python",
"math",
"cos"
] |
Convert list of Dictionaries of lists to DataFrame Table in Python | 38,938,680 | <p>I have a list of dictionaries that i'd like to convert into a data frame table. I know the question in the title is a little confusing, so ill post the dictionary:</p>
<pre><code>[{'MESSAGE': ['RECEIVED SUCCESSFULLY AWAITING STOCKING PROCESS'], 'BIN': ['8FHA9D83H 82HG7D9F'], 'INV': 'SSXR 98-20LM NM CORN CREAM'}, {'MESSAGE': ['RECEIVED SUCCESSFULLY AWAITING STOCKING PROCESS', '#2956- INVALID STOCK COUPON CODE (MISSING).', 'RECEIVED SUCCESSFULLY AWAITING STOCKING PROCESS'], 'BIN': ['HA8DHWO2H HAHD0138', '8SHDNAIDU 00AD0123', '938273548 0967HDBR'], 'INV': 'FPBC *SOUP CANS LENTILS'}]
</code></pre>
<p>I've tried many methods of Pandas, but because there are multiple values for each key, it's a slightly harder problem to solve. I've tried to tweak conventional methods of pd.DataFrame, but i can't quite figure it out. I need the df table to show this output when printed:</p>
<pre><code> BIN INV CODE MESSAGE
8FHA9D83H82HG7D9F SSXR-98-20LM NM CORN CREAM RECEIVED SUCCESSFULLY AWAITING STOCKING PROCESS
HA8DHWO2HHAHD0138 FPBC-*SOUP CANS LENTILS RECEIVED SUCCESSFULLY AWAITING STOCKING PROCESS
8SHDNAIDU00AD0123 FPBC-*SOUP CANS LENTILS #2956- INVALID STOCK COUPON CODE (MISSING).
9382735480967HDBR FPBC-*SOUP CANS LENTILS RECEIVED SUCCESSFULLY AWAITING STOCKING PROCESS
</code></pre>
<p>I'm pretty new to Python 2.7, so any help would be appreciated :)</p>
| -1 | 2016-08-14T02:40:16Z | 38,942,473 | <p>Assuming L is your list of dicts:</p>
<pre><code>pd.concat(pd.DataFrame(l) for l in L)
Out:
BIN INV \
0 8FHA9D83H 82HG7D9F SSXR 98-20LM NM CORN CREAM
0 HA8DHWO2H HAHD0138 FPBC *SOUP CANS LENTILS
1 8SHDNAIDU 00AD0123 FPBC *SOUP CANS LENTILS
2 938273548 0967HDBR FPBC *SOUP CANS LENTILS
MESSAGE
0 RECEIVED SUCCESSFULLY AWAITING STOCKING PROCESS
0 RECEIVED SUCCESSFULLY AWAITING STOCKING PROCESS
1 #2956- INVALID STOCK COUPON CODE (MISSING).
2 RECEIVED SUCCESSFULLY AWAITING STOCKING PROCESS
</code></pre>
| 2 | 2016-08-14T12:58:02Z | [
"python",
"pandas",
"dictionary"
] |
Python: Generating list of numbers 1-10, but 1 ends up at the end of the list? | 38,938,688 | <p>I have just started learning how to program using Python, and have been going through some exercises to help me improve. For one of the exercises, I have to program a Sieve of Eratosthenes, and as part of doing this, I wanted to generate a list of numbers 1 through <em>n</em>. </p>
<p>My code is as follows:</p>
<pre><code>def primelist(n): #returns a list of all primes lower than or equal to n
grid=[]
k=1
while k in range (1, n+1):
grid.insert(-1, k)
k+=1
return grid
</code></pre>
<p>This is as far as I got, because when I tested what I had written so far with:</p>
<pre><code>print(primelist(10))
</code></pre>
<p>my code output the list [2, 3, 4, 5, 6, 7, 8, 9, 10, 1] and I can't figure out why it is doing this. Any explanation would be much appreciated!</p>
| 1 | 2016-08-14T02:41:28Z | 38,938,730 | <p>I don't know why it's backwards, but your code is not the way to add elements to a list. Also you don't use the variable <code>n</code> in your code (probably a typo), so I will just add the function to generate a list through 1 to <code>n</code>.</p>
<pre><code>def primelist(n):
grid=[]
for k in range(1,n+1):
grid.append(k)
return grid
</code></pre>
<p>This code will return <code>[1,2,3,4,5,6,7,8,9,10]</code> as you requested.</p>
| 0 | 2016-08-14T02:51:13Z | [
"python",
"list"
] |
Python: Generating list of numbers 1-10, but 1 ends up at the end of the list? | 38,938,688 | <p>I have just started learning how to program using Python, and have been going through some exercises to help me improve. For one of the exercises, I have to program a Sieve of Eratosthenes, and as part of doing this, I wanted to generate a list of numbers 1 through <em>n</em>. </p>
<p>My code is as follows:</p>
<pre><code>def primelist(n): #returns a list of all primes lower than or equal to n
grid=[]
k=1
while k in range (1, n+1):
grid.insert(-1, k)
k+=1
return grid
</code></pre>
<p>This is as far as I got, because when I tested what I had written so far with:</p>
<pre><code>print(primelist(10))
</code></pre>
<p>my code output the list [2, 3, 4, 5, 6, 7, 8, 9, 10, 1] and I can't figure out why it is doing this. Any explanation would be much appreciated!</p>
| 1 | 2016-08-14T02:41:28Z | 38,938,749 | <p>In Python, <code>list.insert(index, item)</code>
actually inserts <code>item</code> BEFORE <code>index</code>. </p>
<p>So <code>list.insert(-1, k)</code>inserts <code>k</code> before -1. Hence your results.</p>
<p>To do what you want to do properly, the following two lines are equivalent</p>
<pre><code>list.insert(len(list), k)
list.append(k)
</code></pre>
<p>Both methods modify the actual list (instead of returning a new list), as expected.</p>
<p>See more here: <a href="https://mail.python.org/pipermail/tutor/2010-January/073754.html" rel="nofollow">https://mail.python.org/pipermail/tutor/2010-January/073754.html</a></p>
| 3 | 2016-08-14T02:55:00Z | [
"python",
"list"
] |
Python: Generating list of numbers 1-10, but 1 ends up at the end of the list? | 38,938,688 | <p>I have just started learning how to program using Python, and have been going through some exercises to help me improve. For one of the exercises, I have to program a Sieve of Eratosthenes, and as part of doing this, I wanted to generate a list of numbers 1 through <em>n</em>. </p>
<p>My code is as follows:</p>
<pre><code>def primelist(n): #returns a list of all primes lower than or equal to n
grid=[]
k=1
while k in range (1, n+1):
grid.insert(-1, k)
k+=1
return grid
</code></pre>
<p>This is as far as I got, because when I tested what I had written so far with:</p>
<pre><code>print(primelist(10))
</code></pre>
<p>my code output the list [2, 3, 4, 5, 6, 7, 8, 9, 10, 1] and I can't figure out why it is doing this. Any explanation would be much appreciated!</p>
| 1 | 2016-08-14T02:41:28Z | 38,938,831 | <p>xrange can do this for you, remember to give xrange a end value that is one more than the one you want. </p>
<p>So to generate numbers from 1 to n : xrange(1,n+1)</p>
<p>The example below will give you a list from 1 to 10.</p>
<pre><code>>>> primelist=list(xrange(1,11))
>>> primelist
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code></pre>
| 0 | 2016-08-14T03:17:33Z | [
"python",
"list"
] |
Python: Generating list of numbers 1-10, but 1 ends up at the end of the list? | 38,938,688 | <p>I have just started learning how to program using Python, and have been going through some exercises to help me improve. For one of the exercises, I have to program a Sieve of Eratosthenes, and as part of doing this, I wanted to generate a list of numbers 1 through <em>n</em>. </p>
<p>My code is as follows:</p>
<pre><code>def primelist(n): #returns a list of all primes lower than or equal to n
grid=[]
k=1
while k in range (1, n+1):
grid.insert(-1, k)
k+=1
return grid
</code></pre>
<p>This is as far as I got, because when I tested what I had written so far with:</p>
<pre><code>print(primelist(10))
</code></pre>
<p>my code output the list [2, 3, 4, 5, 6, 7, 8, 9, 10, 1] and I can't figure out why it is doing this. Any explanation would be much appreciated!</p>
| 1 | 2016-08-14T02:41:28Z | 38,938,881 | <p><code>insert</code> method for list inserts the element at the index before the first argument. <code>-1</code> is the index of last element. So, when you are inserting at <code>-1</code>, you are always inserting just before the last element. For example you have a list <code>a</code> as:</p>
<pre><code>a = [1,2,3,4]
print a[-1] # It will print 4
</code></pre>
<p>So, when you are trying to insert first element (1) in your list using <code>grid.insert(-1, k)</code>, it goes to last (or first as it will be only element), as there is no other element. All insert operations after first element add the elements to the second last position in the list. </p>
<p>This leads you see only <code>1</code> at last position while all other elements are in order as you expect.</p>
<p>As already mentioned by @coln, you can either use <code>list.append(k)</code> or <code>list.insert(len(list), k)</code> to insert/append/add elements to the end of the list.</p>
| 1 | 2016-08-14T03:30:53Z | [
"python",
"list"
] |
Why does virtualenv create the environments with Python2.7 if I installed it using pip3? | 38,938,700 | <p>I installed virtualenv using <code>sudo pip3 install virtualenv --upgrade</code>, and yet every time I create a new environment (<code>virtualenv test</code>) it's running python2.7... </p>
<p>I know I can create the env. via <code>virtualenv -p python3 test</code>, but I don't want to do that. Virtualenv states that the default interpreter is the interpreter that virtualenv was installed with, but that's not the case. </p>
<p>Any ideas?</p>
<p>PS: I am running on OSX, my default Python interpreter is Python2.7 but I made sure to install virtualenv with pip3.</p>
| 0 | 2016-08-14T02:45:00Z | 38,938,770 | <p>On my machine, when I do this:</p>
<pre><code>$ virtualenv[hit-tab-now-for-autocomplete]
virtualenv virtualenv-2.7 virtualenv-3.4
</code></pre>
<p>So, I can simply do:</p>
<pre><code>$ virtualenv-3.4 test
</code></pre>
| 1 | 2016-08-14T02:59:54Z | [
"python",
"pip",
"virtualenv"
] |
How can i print the square roots of odd numbers in a given list by using lis comprehension only? | 38,938,811 | <p>The below gives only the odd numbers, but not the square roots.
How can I add additional features like writing the square roots for the odd numbers?</p>
<pre><code>my_list=[x for x in range(1,10) if x%2!=0]
print my_list
</code></pre>
| -1 | 2016-08-14T03:11:31Z | 38,938,815 | <p>Where you insert the value of <code>x</code> into the array, take the square root of it.</p>
<pre><code>my_list=[x**.5 for x in range(1,10) if x%2!=0]
</code></pre>
<p>You can also use the <strong><a href="https://docs.python.org/2/library/math.html" rel="nofollow"><code>math</code></a></strong> module, and specifically, the <a href="https://docs.python.org/2/library/math.html#math.sqrt" rel="nofollow"><strong><code>math.sqrt</code></strong></a> function.</p>
<pre><code>import math
my_list = [math.sqrt(x) for x in range(1,10) if x%2!=0]
</code></pre>
| 2 | 2016-08-14T03:13:23Z | [
"python"
] |
Pycharm can't change interpreter from python 2.7 to 3.4 | 38,938,830 | <p>Im currently working on an open source Python project on Xubuntu Linux 3.19.0-51-generic x86_64 using Pycharm.
Even though I my project requires Python 3.4 or greater, the IDE seems to force the project to use Python 2.7. I've tried to change the interpreter from the Project Interpreter menu (see screenshot), and went so far as to remove the Python 2.7 entry from the Project Interpreter menu..All to no avail. I have attached a screenshot of Project Interpreter menu and here is the first line of my debugger session to illustrate the problem:</p>
<pre><code>/usr/bin/python2.7 /home/bluejay/pycharm/pycharm-community-2016.2.1/helpers/pydev/pydevd.py --cmd-line --multiproc --qt-support --client 127.0.0.1 --port 45167 --file /root/PycharmProjects/anki/runanki
</code></pre>
<p><a href="http://i.stack.imgur.com/JWpB1.png" rel="nofollow"><img src="http://i.stack.imgur.com/JWpB1.png" alt="Project Interpreter Menu"></a></p>
<p>Any help is vastly appreciated!</p>
| 0 | 2016-08-14T03:17:28Z | 38,939,339 | <p>Try to setup different interpreter in run/debug configuration in the same manner as suggested in <a href="https://stackoverflow.com/a/23524553/5485944">this answer</a>.</p>
<p>Main Menu -> Run -> Edit Configurations...</p>
<p><a href="http://i.stack.imgur.com/gpnJp.png" rel="nofollow"><img src="http://i.stack.imgur.com/gpnJp.png" alt="enter image description here"></a></p>
| 2 | 2016-08-14T05:09:24Z | [
"python",
"pycharm",
"jetbrains",
"anki"
] |
script to split file name into part1 and part2 and create directory part1 and put file part2 into part1 directory | 38,938,908 | <p>I have bunch of files of the form st_hwk.txt If you must know, this is how Moodle downloads assignments for grading. It takes the name of the hwk and prepands the user name.
This solution needs to work on Linux bc that is what I am working on.
Ex:
I download j smith_hwk1a.txt, j smith_hwk1b.txt, m wong_hwk1a.txt, m wong_hwk1b.txt. (yes the file names have fname space lname)</p>
<p>It should read the files names and create dir jsmith, and mwong. (no space)
Put into jsmith files hwk1a.txt and hwk1b.txt. (the hwk1 that came from jsmith)
Put into mwong files hwk1a.txt and hwk1b.txt. (the hwk1 that came from mwong).
You can use any tool on typical linux, bash, php, ...?
thank you</p>
| -2 | 2016-08-14T03:38:32Z | 39,032,194 | <pre><code>for f in *_hwk*.txt; do
n=$(echo "$f"|tr -d ' '|tr _ /); # delete spaces, convert _ to /
mkdir -p "$(dirname "$n")"; # make directory if needed
mv "$f" "$n"; # move the file
done
</code></pre>
| 0 | 2016-08-19T06:11:48Z | [
"python",
"linux",
"bash",
"split",
"directory"
] |
Installing weblate 2.3: from django.db.models.sql.aggregates ImportError: No module named aggregates | 38,938,947 | <p>While installing <a href="https://weblate.org/en/" rel="nofollow">weblate</a> 2.3 (older version), I had the following error:</p>
<blockquote>
<p>File "/srv/weblate/weblate/trans/boolean_sum.py", line 27, in
from django.db.models.sql.aggregates import Sum as BaseSQLSum ImportError: No module named aggregates</p>
</blockquote>
| 0 | 2016-08-14T03:46:40Z | 38,938,948 | <p>I took a look at my django version, and it was the latest one, which doesn't have a <code>aggregates.py</code> in <a href="https://github.com/django/django/tree/master/django/db/models/sql" rel="nofollow"><code>django/db/models/sql/</code></a>. I took a look at <a href="https://github.com/nijel/weblate/blob/weblate-2.3/requirements.txt#L1" rel="nofollow">weblate 2.3 's <code>requirements.txt</code></a> and it contains the following line:</p>
<pre><code>Django>=1.7
</code></pre>
<p>This was installing <code>1.10</code>. I changed the line to</p>
<pre><code>Django==1.7
</code></pre>
<p>Installed the right version with <code>pip</code> and now everything works as expected.<br>
Hope it helps someone else. :)</p>
<p>Similar problem could also happen in weblate 2.7 and higher as their <code>requirements.txt</code> still uses <code>>=</code> on <a href="https://github.com/nijel/weblate/blob/master/requirements.txt#L1" rel="nofollow"><code>master</code></a> and on <a href="https://github.com/nijel/weblate/blob/weblate-2.7/requirements.txt#L1" rel="nofollow"><code>weblate-2.7</code></a> tag.</p>
| 1 | 2016-08-14T03:46:40Z | [
"python",
"django",
"pip",
"importerror",
"weblate"
] |
Python - Convert a list to a list of lists | 38,938,957 | <p>I'm trying to create a list of lists, such that each inner list has 8 elements, in a python one-liner.</p>
<p>So far I have the following:</p>
<pre><code>locations = [[alphabet.index(j) for j in test]]
</code></pre>
<p>That maps to one big list inside of a list:</p>
<pre><code>[[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]]
</code></pre>
<p>But I want to split it up to be multiple inner lists, each 8 elements:</p>
<pre><code>[[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16]]
</code></pre>
<p>Any idea how I can acheive this?</p>
| 1 | 2016-08-14T03:48:50Z | 38,938,981 | <p>Use list slicing with <code>range()</code> to get the starting indexes:</p>
<pre><code>In [3]: test = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
In [4]: [test[i:i+8] for i in range(0, len(test), 8)]
Out[4]: [[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16]]
</code></pre>
<p>As a function:</p>
<pre><code>In [7]: def slicing(list_, elem_):
...: return [list_[i:i+elem_] for i in range(0, len(list_), elem_)]
In [8]: slicing(test, 8)
Out[8]: [[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16]]
</code></pre>
| 1 | 2016-08-14T03:55:17Z | [
"python",
"list",
"nested-lists"
] |
Python - Convert a list to a list of lists | 38,938,957 | <p>I'm trying to create a list of lists, such that each inner list has 8 elements, in a python one-liner.</p>
<p>So far I have the following:</p>
<pre><code>locations = [[alphabet.index(j) for j in test]]
</code></pre>
<p>That maps to one big list inside of a list:</p>
<pre><code>[[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]]
</code></pre>
<p>But I want to split it up to be multiple inner lists, each 8 elements:</p>
<pre><code>[[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16]]
</code></pre>
<p>Any idea how I can acheive this?</p>
| 1 | 2016-08-14T03:48:50Z | 38,939,534 | <p>Another solution could be to use NumPy</p>
<pre><code>import numpy as np
data = [x for x in xrange(0, 64)]
data_split = np.array_split(np.asarray(data), 8)
</code></pre>
<p>Output:</p>
<pre><code>for a in data_split:
print a
[0 1 2 3 4 5 6 7]
[ 8 9 10 11 12 13 14 15]
[16 17 18 19 20 21 22 23]
[24 25 26 27 28 29 30 31]
[32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47]
[48 49 50 51 52 53 54 55]
[56 57 58 59 60 61 62 63]
</code></pre>
| 0 | 2016-08-14T05:46:09Z | [
"python",
"list",
"nested-lists"
] |
within python for loop calling more than one functions | 38,938,992 | <p>the following code filters images, now I would like to call two functions for each image in a for loop one by one; first <code>check_image_size</code> and then <code>binarization</code>. I am having trouble figuring out the correct syntax. </p>
<pre><code>import os, sys
check_image_size(pic)
binarization(pic)
folder = '../6'
names = [check_image_size(os.path.join(folder, name))
for name in os.listdir(folder)
if not name.endswith('bin.png')
if not name.endswith('.jpg')
if not name.endswith('.nrm.png')
]
</code></pre>
| 1 | 2016-08-14T03:57:29Z | 38,939,004 | <p>What you are doing here is not the actual way to define a for loop. What you are using is list comprehension.</p>
<h1>What is list comprehension?</h1>
<p>List comprehension is used to quickly equate values for loops. For example:</p>
<pre><code>x = []
for i in range(10):
if i % 2 == 0:
x.append(i)
</code></pre>
<p>Is equivalent to:</p>
<pre><code>x = [i for i in range(10) if i % 2 == 0]
</code></pre>
<p>Both will give the value of:</p>
<pre><code>>>> x
[0, 2, 4, 6, 8]
</code></pre>
<h1>Ok... then how is a for loop defined?</h1>
<p>A for loop is defined using the <code>for</code> keyword at the start of the statement, not a continuation of a statement. As you can see above, your code can be converted into something like:</p>
<pre><code># ...
names = []
for name in os.listdir(folder):
if not name.endswith('bin.png') if not name.endswith('.jpg') if not name.endswith('.nrm.png'):
names.append(check_image_size(os.path.join(folder, name)))
</code></pre>
<p>Now, you would see that you can add more lines after <code>check_image_size(os.path.join(folder, name))</code> by keeping the same indentation level:</p>
<pre><code># ...
names = []
for name in os.listdir(folder):
if not name.endswith('bin.png') if not name.endswith('.jpg') if not name.endswith('.nrm.png'):
names.append(check_image_size(os.path.join(folder, name)))
# Add more things here
my_other_function_to_run(x)
more_other_functions(y)
</code></pre>
<h1>My code still doesn't run!</h1>
<p>That's because you cannot have more than one <code>if</code> in an <code>if</code> statement. Use <code>and</code> to denote a strictly true relationship instead.</p>
<pre><code># ...
names = []
for name in os.listdir(folder):
if not name.endswith('bin.png') and not name.endswith('.jpg') and not name.endswith('.nrm.png'):
names.append(check_image_size(os.path.join(folder, name)))
# Add more things here
my_other_function_to_run(x)
more_other_functions(y)
</code></pre>
<p>Of course, you could do nested <code>if</code> statements but they aren't very nice:</p>
<pre><code># ...
names = []
for name in os.listdir(folder):
if not name.endswith('bin.png')
if not name.endswith('.jpg')
if not name.endswith('.nrm.png'):
names.append(check_image_size(os.path.join(folder, name)))
# Add more things here
my_other_function_to_run(x)
more_other_functions(y)
</code></pre>
<h1>One last note</h1>
<p>As I said above, you should not have more than one <code>if</code> keyword in an <code>if</code> statement. This also applies likewise for list comprehension. So your original code should have been:</p>
<pre><code># ...
names = [check_image_size(os.path.join(folder, name))
for name in os.listdir(folder)
if not name.endswith('bin.png')
and not name.endswith('.jpg')
and not name.endswith('.nrm.png')
]
</code></pre>
| 1 | 2016-08-14T04:01:44Z | [
"python"
] |
python split string that by space and new line character | 38,939,022 | <p>I have this code:</p>
<pre><code>f1=open('test.txt','r')
d={}
line = f1.read().replace('\n',' ')
line2= line.split("\n")
</code></pre>
<p><code>line = "This is line1\nthis isline2\nthis is line3"</code></p>
<p>My question is: can I do a split with multiple delimiters rather than replace
first, then do a split?</p>
| 1 | 2016-08-14T04:06:01Z | 38,939,049 | <p>Use <a href="https://docs.python.org/2/library/re.html#re.split" rel="nofollow"><code>re.split()</code></a>.</p>
<p>Splitting on <code>\n</code> and <code>\t</code>:</p>
<pre><code>In [23]: line = "This is line1\nthis isline2\tthis is line3"
In [24]: re.split(r'[\n\t]', line)
Out[24]: ['This is line1', 'this isline2', 'this is line3']
</code></pre>
| 2 | 2016-08-14T04:11:31Z | [
"python",
"split"
] |
Vim & GAE - Is there anyway to debug python gae applications using vim? | 38,939,029 | <p>I know that there are plugins to debugging python in vim like this one:<a href="https://github.com/joonty/vdebug" rel="nofollow">https://github.com/joonty/vdebug</a></p>
<p>What I'm struggling is to find a way to debug GAE apps, is that even possible? If so what steps should I take to make it work?</p>
<p>Thanks</p>
| 2 | 2016-08-14T04:08:07Z | 38,947,127 | <p>If you're running the GAE app locally with the development server, you should be able to debug the python runtime the same way that you'd debug other local processes.</p>
<p>You can't use vim to debug processes running on the Google runtimes in Google's datacenters. You might be able to use the <a href="https://cloud.google.com/debugger/" rel="nofollow">Stackdriver Debugger</a> to get stack traces; according to <a href="https://cloud.google.com/debugger/docs/setting-up-python-on-app-engine" rel="nofollow">this page</a>, the debugger is supported with Python on both the standard and the python-compat flex runtimes.</p>
| 1 | 2016-08-14T22:21:06Z | [
"python",
"google-app-engine",
"debugging",
"vim"
] |
Saving model in tensorflow | 38,939,081 | <p>Tensorflow allows us to save/load model's structure, using method tf.train.write_graph, so that we can restore it in the future to continue our training session. However, I'm wondering that if this is necessary because I can create a module, e.g GraphDefinition.py, and use this module to re-create the model.
So, which is the better way to save the model structure or are there any rule of thumb that suggest which way should I use when saving a model?</p>
| 0 | 2016-08-14T04:19:20Z | 38,951,015 | <p>First of all you have to understand, that tensorflow graph does not have current weights in it (until you save them manually there) and if you load model structure from graph.pb, you will start you train from the very beginning. But if you want to continue train or use your trained model, you have to save checkpoint (using tf Saver) with the values of the variables in it, not only the structure.
Check out this tread: <a href="http://stackoverflow.com/questions/33759623/tensorflow-how-to-restore-a-previously-saved-model-python/">Tensorflow: How to restore a previously saved model (python)</a></p>
| 0 | 2016-08-15T07:33:05Z | [
"python",
"python-2.7",
"tensorflow"
] |
Spotify - access token from command line | 38,939,085 | <p>I am testing my <code>app</code> using the <code>terminal</code>, which is quite handy in a pre-development phase.</p>
<p>so far, I have used <code>spotipy.Spotify(client_credentials_manager=client_credentials_manager)</code> within my <code>python</code> scripts in order to access data. </p>
<p><code>SpotifyClientCredentials()</code> requires <code>client_id</code>and <code>client_secret</code> as parameters.</p>
<p>now I need to access <code>analysis_url</code> data, which requires an <code>access token</code>.</p>
<p>Is there a way to include this <code>access token</code> requirement via my <code>python</code> script ran at <code>command line</code> or do I have to build an <code>app</code> on the <code>browser</code> just to do a simple test?</p>
<p>many thanks on advance.</p>
| 0 | 2016-08-14T04:19:58Z | 39,049,945 | <p>Copy and paste the entire redirect URI from your browser to the terminal (when prompted) after successful authentication. Your access token will be cached in the directory (look for <code>.cache.<username></code>) </p>
| 0 | 2016-08-20T02:41:02Z | [
"python",
"command-line",
"spotify",
"spotipy"
] |
How to effectively update the attributes of an object | 38,939,096 | <p>I am creating a "pet game" in order to train my computing skills in python (that is just an excuse: it is because it is fun).</p>
<p>I decided to do a simple RPG game. For that, I defined the class <em>hero</em>:</p>
<pre><code>class hero:
#Common class for the main character
def __init__(self, name, lvl, str, agi, vit, int, luk, prof):
self.name = name
self.lvl = lvl
self.str = str
self.agi = agi
self.vit = vit
self.int = int
self.luk = luk
self.prof = prof
self.exp = 0
if prof==1:
self.dmg=3*(self.str)+1*(self.agi)
self.skillList=['heavySlash01']
self.strUp=3
self.agiUp=1
self.vitUp=2
self.intUp=1
self.lukUp=1
if prof==2:
self.dmg=1*(self.str)+3*(self.agi)
self.skillList=['doubleAttack02']
self.strUp=1
self.agiUp=3
self.vitUp=1
self.intUp=1
self.lukUp=2
if prof==3:
self.dmg=4*(self.int)
self.skillList=['fireBall03']
self.strUp=1
self.agiUp=1.5
self.vitUp=0.5
self.intUp=3.5
self.lukUp=1.5
self.hp=19*vit
</code></pre>
<p>However, I noticed that whenever the hero leveled up, I needed to update all of its status separately. For instance, I needed to manually update the <code>hero.dmg</code>. Changing the <code>agi</code>, <code>str</code> and <code>int</code> did not automatically change the <code>dmg</code> as I would expect.</p>
<p>My question is then: Is there a way to make the <code>dmg</code> automatically update itself, based on its formula?</p>
| 0 | 2016-08-14T04:22:27Z | 38,939,120 | <p>Make <code>dmg</code> a property instead of setting in the <code>__init__</code> function. The <code>__init__</code> only runs when the instance is initialized, which is why things aren't updating. However, making it a property runs the method whenever the property is accessed.</p>
<pre><code>@property
def dmg(self):
if prof==1:
return 3*(self.str)+1*(self.agi)
if prof==2:
...
</code></pre>
| 1 | 2016-08-14T04:26:18Z | [
"python",
"object"
] |
How to effectively update the attributes of an object | 38,939,096 | <p>I am creating a "pet game" in order to train my computing skills in python (that is just an excuse: it is because it is fun).</p>
<p>I decided to do a simple RPG game. For that, I defined the class <em>hero</em>:</p>
<pre><code>class hero:
#Common class for the main character
def __init__(self, name, lvl, str, agi, vit, int, luk, prof):
self.name = name
self.lvl = lvl
self.str = str
self.agi = agi
self.vit = vit
self.int = int
self.luk = luk
self.prof = prof
self.exp = 0
if prof==1:
self.dmg=3*(self.str)+1*(self.agi)
self.skillList=['heavySlash01']
self.strUp=3
self.agiUp=1
self.vitUp=2
self.intUp=1
self.lukUp=1
if prof==2:
self.dmg=1*(self.str)+3*(self.agi)
self.skillList=['doubleAttack02']
self.strUp=1
self.agiUp=3
self.vitUp=1
self.intUp=1
self.lukUp=2
if prof==3:
self.dmg=4*(self.int)
self.skillList=['fireBall03']
self.strUp=1
self.agiUp=1.5
self.vitUp=0.5
self.intUp=3.5
self.lukUp=1.5
self.hp=19*vit
</code></pre>
<p>However, I noticed that whenever the hero leveled up, I needed to update all of its status separately. For instance, I needed to manually update the <code>hero.dmg</code>. Changing the <code>agi</code>, <code>str</code> and <code>int</code> did not automatically change the <code>dmg</code> as I would expect.</p>
<p>My question is then: Is there a way to make the <code>dmg</code> automatically update itself, based on its formula?</p>
| 0 | 2016-08-14T04:22:27Z | 38,939,213 | <p>It's better to use inheritance in your case:</p>
<pre><code>class Hero(object):
def __init__(self, name, lvl, _str, agi, vit, _int, luk):
self.name = name
self.lvl = lvl
self._str = _str # Should not use "str" because of reserved keyword of the same name
self.agi = agi
self.vit = vit
self._int = _int # Should not use "int" because of reserved keyword of the same name
self.luk = luk
self.exp = 0
@property
def hp(self):
return 19 * self.vit
class HeroProf_1(Hero):
skillList = ['heavySlash01']
strUp = 3
agiUp = 1
vitUp = 2
intUp = 1
lukUp = 1
@property
def dmg(self):
return 3 * self._str + 1 * self.agi
class HeroProf_2(Hero):
skillList = ['doubleAttack02']
strUp = 1
agiUp = 3
vitUp = 1
intUp = 1
lukUp = 2
@property
def dmg(self):
return 1 * self._str + 3 * self.agi
class HeroProf_3(Hero):
skillList = ['fireBall03']
strUp = 1
agiUp = 1.5
vitUp = 0.5
intUp = 3.5
lukUp = 1.5
@property
def dmg(self):
return 4 * self._int
</code></pre>
| 1 | 2016-08-14T04:47:00Z | [
"python",
"object"
] |
Random picking 3 chosen numbers | 38,939,129 | <p>Ok, I am creating a game and no matter what I do, it just isn't working. So I have 3 numbers chosen, 25,50,75.
I want to be able to random pick one of them. Then I will need to be able to add it to a total making it obviously an integer. I have imported random. I have tried random.sample but I can't get that one to be an number that I can add. I tried random.randint and that did not work at all. I have tried looking it up but it is pretty much all random in a range and not specific. Any ideas? Thanks in advance. I am using python 3.4.3. </p>
| 1 | 2016-08-14T04:28:22Z | 38,939,137 | <p>Use <a href="https://docs.python.org/2/library/random.html#random.choice" rel="nofollow"><code>random.choice</code></a>:</p>
<pre><code>>>> import random
>>> random.choice([25,50,75])
25
>>> random.choice([25,50,75])
25
>>> random.choice([25,50,75])
75
</code></pre>
| 4 | 2016-08-14T04:30:09Z | [
"python"
] |
Random picking 3 chosen numbers | 38,939,129 | <p>Ok, I am creating a game and no matter what I do, it just isn't working. So I have 3 numbers chosen, 25,50,75.
I want to be able to random pick one of them. Then I will need to be able to add it to a total making it obviously an integer. I have imported random. I have tried random.sample but I can't get that one to be an number that I can add. I tried random.randint and that did not work at all. I have tried looking it up but it is pretty much all random in a range and not specific. Any ideas? Thanks in advance. I am using python 3.4.3. </p>
| 1 | 2016-08-14T04:28:22Z | 38,939,196 | <p><a href="https://docs.python.org/3/library/random.html#random.choice" rel="nofollow"><code>random.choice()</code></a> is the way to go, however, <a href="https://docs.python.org/3/library/random.html#random.sample" rel="nofollow"><code>random.sample()</code></a> will also work if you use a sample size of 1 <em>and</em> you access the first element of the returned list.</p>
<pre><code>>>> import random
>>> data = [25, 50, 75]
>>> random.choice(data)
50
>>> random.sample(data, 1)
[75]
>>> random.sample(data, 1)[0]
25
</code></pre>
<p>The point here is that <code>random.sample()</code> returns a <em>list</em> because that function is designed to select multiple values from the population. That's why you can not immediately use the result as an integer.</p>
| 0 | 2016-08-14T04:41:59Z | [
"python"
] |
Simple TensorFlow Neural Network minimizes cost function yet all results are close to 1 | 38,939,221 | <p>So I tried implementing the neural network from:</p>
<p><a href="http://iamtrask.github.io/2015/07/12/basic-python-network/" rel="nofollow">http://iamtrask.github.io/2015/07/12/basic-python-network/</a></p>
<p>but using TensorFlow instead. I printed out the cost function twice during training and the error is appears to be getting smaller according yet all the values in the output layer are close to 1 when only two of them should be. I imagine it might be something wrong with my maths but I'm not sure. There is no difference when I try with a hidden layer or use Error Squared as cost function. Here is my code:</p>
<pre><code>import tensorflow as tf
import numpy as np
input_layer_size = 3
output_layer_size = 1
x = tf.placeholder(tf.float32, [None, input_layer_size]) #holds input values
y = tf.placeholder(tf.float32, [None, output_layer_size]) # holds true y values
tf.set_random_seed(1)
input_weights = tf.Variable(tf.random_normal([input_layer_size, output_layer_size]))
input_bias = tf.Variable(tf.random_normal([1, output_layer_size]))
output_layer_vals = tf.nn.sigmoid(tf.matmul(x, input_weights) + input_bias)
cross_entropy = -tf.reduce_sum(y * tf.log(output_layer_vals))
training = tf.train.AdamOptimizer(0.1).minimize(cross_entropy)
x_data = np.array(
[[0,0,1],
[0,1,1],
[1,0,1],
[1,1,1]])
y_data = np.reshape(np.array([0,0,1,1]).T, (4, 1))
with tf.Session() as ses:
init = tf.initialize_all_variables()
ses.run(init)
for _ in range(1000):
ses.run(training, feed_dict={x: x_data, y:y_data})
if _ % 500 == 0:
print(ses.run(output_layer_vals, feed_dict={x: x_data}))
print(ses.run(cross_entropy, feed_dict={x: x_data, y:y_data}))
print('\n\n')
</code></pre>
<p>And this is what it outputs:</p>
<pre><code>[[ 0.82036656]
[ 0.96750367]
[ 0.87607527]
[ 0.97876281]]
0.21947 #first cross_entropy error
[[ 0.99937409]
[ 0.99998224]
[ 0.99992537]
[ 0.99999785]]
0.00062825 #second cross_entropy error, as you can see, it's smaller
</code></pre>
| 0 | 2016-08-14T04:48:06Z | 38,939,400 | <p>First of all: you have no hidden layer. As far as I remember basic perceptrons could possibly model the XOR problem, but it needed some adjustments. However, AI is just invented by biology, but it does not model real neural networks exactly. Thus, you have to at least build an MLP (<a href="https://en.wikipedia.org/wiki/Multilayer_perceptron" rel="nofollow">Multilayer perceptron</a>), which consits of at least one input, one hidden and one output layer. The XOR problem needs at least two neurons + bias in the hidden layer to be solved correctly (with a high precision).</p>
<p>Additionally your learning rate is too high. <code>0.1</code> is a very high learning rate. To put it simply: it basically means that you update/adapt your current state by 10% of one single learning step. This lets your network forget about already learned invariants quickly. Usually the learning rate is something in between 1e-2 to 1e-6, depending on your problem, network size and general architecture.</p>
<p>Moreover you implemented the "simplified/short" version of cross-entropy. See wikipedia for the full version: <a href="https://en.wikipedia.org/wiki/Cross_entropy" rel="nofollow">cross-entropy</a>. However, to avoid some edge cases TensorFlow already has its own version of cross-entropy: for example <code>tf.nn.softmax_cross_entropy_with_logits</code>.</p>
<p>Finally you should remember that the cross-entropy error is a logistic loss function that operates on probabilities of your classes. Although your sigmoid function squashes the output layer into an interval of <code>[0, 1]</code>, this does only work in your case because you have one single output neuron. As soon as you have more than one output neuron, you also need the sum of the output layer to be exactly <code>1,0</code> in order to really describes probabilities for every class on the output layer.</p>
| 1 | 2016-08-14T05:19:55Z | [
"python",
"machine-learning",
"neural-network",
"tensorflow"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.