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
List of integers in dictionary python
38,939,356
<p>i am learning python currently with the Python Crash Course text. I am at the part about having lists in dictionaries specifically the try it yourself. The text explains how to access values that are in list form in python when they are strings but not integers. I have gotten my code to work so far but it prints the favorite numbers list twice in list form. How do i fix this so it prints it only once, and plainly without the brackets?</p> <p>here is my code so far.</p> <pre><code>favorite_numbers = { 'king': ['7','10'], 'jake': ['29','77'], 'mr robot': ['234','1337'], 'elliot': ['1234' ,'89'], } for name, number in favorite_numbers.items(): print( "Hey, " + name.title() + " your favorite numbers are: " ) for numbers in number: print(number) </code></pre> <p>Help? please and thank you.</p>
0
2016-08-14T05:11:40Z
38,939,380
<p>This will fix your current code:</p> <pre><code>for numbers in number: print(numbers) </code></pre> <p>But it's kind of a backward way to name the variables. How about this instead?</p> <pre><code>for name, numbers in favorite_numbers.items(): print( "Hey, " + name.title() + " your favorite numbers are: " ) for number in numbers: print(number) </code></pre>
1
2016-08-14T05:16:42Z
[ "python", "list", "dictionary" ]
List of integers in dictionary python
38,939,356
<p>i am learning python currently with the Python Crash Course text. I am at the part about having lists in dictionaries specifically the try it yourself. The text explains how to access values that are in list form in python when they are strings but not integers. I have gotten my code to work so far but it prints the favorite numbers list twice in list form. How do i fix this so it prints it only once, and plainly without the brackets?</p> <p>here is my code so far.</p> <pre><code>favorite_numbers = { 'king': ['7','10'], 'jake': ['29','77'], 'mr robot': ['234','1337'], 'elliot': ['1234' ,'89'], } for name, number in favorite_numbers.items(): print( "Hey, " + name.title() + " your favorite numbers are: " ) for numbers in number: print(number) </code></pre> <p>Help? please and thank you.</p>
0
2016-08-14T05:11:40Z
38,939,385
<p>You are confused because you have similarly-named variables. In your case, this line:</p> <pre><code>for name, number in favorite_numbers.items(): </code></pre> <p>binds <code>number</code> to successive values in the dictionary. In this example, they are specifically lists containing strings.</p> <p>This line:</p> <pre><code>for numbers in number: </code></pre> <p>binds <code>numbers</code> to successive strings in the list.</p> <p>This line:</p> <pre><code>print(number) </code></pre> <p>prints the <strong>list</strong>, not the <strong>string</strong>.</p> <p>Try this:</p> <pre><code>for name, list_of_numbers in favorite_numbers.items(): print( "Hey, " + name.title() + " your favorite numbers are: " ) for number in list_of_numbers: print(number) </code></pre>
0
2016-08-14T05:17:28Z
[ "python", "list", "dictionary" ]
List of integers in dictionary python
38,939,356
<p>i am learning python currently with the Python Crash Course text. I am at the part about having lists in dictionaries specifically the try it yourself. The text explains how to access values that are in list form in python when they are strings but not integers. I have gotten my code to work so far but it prints the favorite numbers list twice in list form. How do i fix this so it prints it only once, and plainly without the brackets?</p> <p>here is my code so far.</p> <pre><code>favorite_numbers = { 'king': ['7','10'], 'jake': ['29','77'], 'mr robot': ['234','1337'], 'elliot': ['1234' ,'89'], } for name, number in favorite_numbers.items(): print( "Hey, " + name.title() + " your favorite numbers are: " ) for numbers in number: print(number) </code></pre> <p>Help? please and thank you.</p>
0
2016-08-14T05:11:40Z
38,939,407
<p>I think your naming confused you a little. Look at your use of <code>number</code> and <code>numbers</code>. Fixed version below. Also check out `print( "foo", end = "" ) to have multiple print statements that don't terminate in a new line, if you want to clean up the appearance of the output a little.</p> <pre><code>favorite_numbers = { 'king': ['7','10'], 'jake': ['29','77'], 'mr robot': ['234','1337'], 'elliot': ['1234' ,'89'], } for name, numbers in favorite_numbers.items(): print( "Hey, " + name.title() + " your favorite numbers are: " ) for number in numbers: print(number) </code></pre>
2
2016-08-14T05:21:31Z
[ "python", "list", "dictionary" ]
Python+kivy+SQLite: How to use them together
38,939,416
<p>I am new to python, kivy and sqlite. But I have to do this difficult task. :-( Any kind of help will be highly appreciated. Thanks in advance! </p> <p>The task is: to display the data from a <code>.db</code> file on the <code>kivy</code> screen on android. </p> <p>I made the database file from <a href="http://zetcode.com/db/sqlitepythontutorial/" rel="nofollow">http://zetcode.com/db/sqlitepythontutorial/</a></p> <p>Here I post the code again. </p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import sqlite3 as lite import sys con = lite.connect('test.db') with con: cur = con.cursor() cur.execute("CREATE TABLE Cars(Id INT, Name TEXT, Price INT)") cur.execute("INSERT INTO Cars VALUES(1,'Audi',52642)") cur.execute("INSERT INTO Cars VALUES(2,'Mercedes',57127)") cur.execute("INSERT INTO Cars VALUES(3,'Skoda',9000)") cur.execute("INSERT INTO Cars VALUES(4,'Volvo',29000)") cur.execute("INSERT INTO Cars VALUES(5,'Bentley',350000)") cur.execute("INSERT INTO Cars VALUES(6,'Citroen',21000)") cur.execute("INSERT INTO Cars VALUES(7,'Hummer',41400)") cur.execute("INSERT INTO Cars VALUES(8,'Volkswagen',21600)") </code></pre> <p>The database is then saved to <code>C:\\test.db</code>.</p> <p>Then I made a <code>kivy</code> screen with a <code>label</code> and a <code>button</code>. </p> <pre><code># -*- coding: utf-8 -*- from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.lang import Builder import random root_widget = Builder.load_string(''' BoxLayout: orientation: 'vertical' Label: text: 'Hello' #How to define it? font_size: 30 Button: size: root.width/2, 15 text: 'next random' font_size: 30 # on_release: #How to define it? ''') class TestApp(App): def build(self): return root_widget if __name__ == '__main__': TestApp().run() </code></pre> <p>I want to have a <code>random</code> <strong>car name</strong> from the <code>db file</code> shown on the <code>label</code>, when the <code>button</code> is clicked everytime. </p> <p>The initial <code>label</code> text, which is now the word "Hello", should be replaced by a random car name. So that everytime the programm is run, a car name is shown on the <code>label</code>. </p> <p>But I really dont know how to write the code. </p> <p>Thank you for your help. </p> <p><strong>#Update</strong></p> <p>I wrote the code but it does not work. </p> <pre><code># -*- coding: utf-8 -*- from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.lang import Builder from kivy.clock import mainthread import sqlite3 import random class MyBoxLayout(BoxLayout): def init(self, **kwargs): super().__init__(**kwargs) @mainthread # execute within next frame def delayed(): self.load_random_car() delayed() def load_random_car(self): conn = sqlite3.connect("C:\\test.db") cur = conn.cursor() ####Length of db file with conn: cur = conn.cursor() cur.execute("SELECT * FROM Cars") rows = cur.fetchall() LengthSQLFile = len(rows) print LengthSQLFile CurrentNo = random.randint(0, LengthSQLFile) CurrentNo_ForSearch = (CurrentNo ,) cur.execute("select * from Cars where rowid = ?" , CurrentNo_ForSearch) CurrentAll = cur.fetchone() CurrentAll = list(CurrentAll) # Change it from tuple to list print CurrentAll Current = CurrentAll[1] self.ids.label.text = Current #"fetch random car data from db and put here" root_widget = Builder.load_string(''' BoxLayout: orientation: 'vertical' Label: id: label font_size: 30 Button: size: root.width/2, 15 text: 'next random' font_size: 30 on_release: root.load_random_car() ''') class TestApp(App): def build(self): # MyBoxLayout(BoxLayout) return root_widget if __name__ == '__main__': TestApp().run() </code></pre> <p><strong>#2 Update:</strong></p> <p>The code now is... It shows the error message: <code>AttributeError: 'BoxLayout' object has no attribute 'load_random_car'</code></p> <pre><code># -*- coding: utf-8 -*- from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.lang import Builder from kivy.clock import mainthread import sqlite3 import random class MyBoxLayout(BoxLayout): def init(self, **kwargs): super().__init__(**kwargs) @mainthread # execute within next frame def delayed(): self.load_random_car() delayed() def load_random_car(self): conn = sqlite3.connect("C:\\test.db") cur = conn.cursor() cur.execute("SELECT * FROM Cars ORDER BY RANDOM() LIMIT 1;") currentAll = cur.fetchone() currentAll = list(currentAll) # Change it from tuple to list print currentAll current = currentAll[1] self.ids.label.text = current #"fetch random car data from db and put here" root_widget = Builder.load_string(''' BoxLayout: orientation: 'vertical' Label: id: label font_size: 30 Button: size: root.width/2, 15 text: 'next random' font_size: 30 on_release: root.load_random_car() ''') class TestApp(App): def build(self): # MyBoxLayout(BoxLayout) return root_widget if __name__ == '__main__': TestApp().run() </code></pre>
0
2016-08-14T05:23:41Z
38,943,364
<p>The easiest way would be writing a custom <code>init</code> method for the box layout:</p> <pre><code>from kivy.uix.boxlayout import BoxLayout from kivy.clock import mainthread class MyBoxLayout(BoxLayout): def init(self, **kwargs): super().__init__(**kwargs) @mainthread # execute within next frame def delayed(): self.load_random_car() delayed() def load_random_car(self): self.ids.label.text = "fetch random car data from db and put here" </code></pre> <p>This is how the updated widget structure would look like:</p> <pre><code>MyBoxLayout: Label: id: label Button: on_release: root.load_random_car() </code></pre>
1
2016-08-14T14:50:12Z
[ "python", "sqlite", "kivy" ]
Parsing all the text inside a tag using lxml in python
38,939,418
<p>I am trying to parse an HTML file which kind of is as shown below</p> <pre><code>&lt;ol&gt; &lt;li&gt; &lt;div class="c1"&gt; &lt;span class="s1"&gt;hi&lt;/span&gt; " hello " &lt;span class="s2"&gt;world!&lt;/span&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="c2"&gt; &lt;span class="s3"&gt;abc&lt;/span&gt; " def ghijkl " &lt;span class="s1"&gt;mno&lt;/span&gt; " pqr!" &lt;/div&gt; &lt;/li&gt; &lt;/ol&gt; </code></pre> <p>I tried to parse using the following code</p> <pre><code>tree = html.fromstring(code.content) sol = tree.xpath('//ol//text()') for x in sol: print x </code></pre> <p>I get the result as this</p> <pre><code>hi hello world! abc def ghijkl mno pqr! </code></pre> <p>What can I do to get all the text in each <code>&lt;li&gt;</code> tag in one line. i.e. I want the output to be</p> <pre><code>hi hello world! abc def ghijkl mno pqr! </code></pre>
0
2016-08-14T05:23:57Z
38,939,595
<pre><code>$ cat a.py from lxml import etree xml = """&lt;ol&gt; &lt;li&gt; &lt;div class="c1"&gt; &lt;span class="s1"&gt;hi&lt;/span&gt; " hello " &lt;span class="s2"&gt;world!&lt;/span&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="c2"&gt; &lt;span class="s3"&gt;abc&lt;/span&gt; " def ghijkl " &lt;span class="s1"&gt;mno&lt;/span&gt; " pqr!" &lt;/div&gt; &lt;/li&gt; &lt;/ol&gt;""" tree = etree.fromstring(xml) sol = tree.xpath('//ol//li') for a in sol: print " ".join([t.strip() for t in a.itertext()]).strip() $ python a.py hi " hello " world! abc " def ghijkl " mno " pqr!" </code></pre>
1
2016-08-14T05:56:44Z
[ "python", "html", "parsing", "lxml" ]
Parsing all the text inside a tag using lxml in python
38,939,418
<p>I am trying to parse an HTML file which kind of is as shown below</p> <pre><code>&lt;ol&gt; &lt;li&gt; &lt;div class="c1"&gt; &lt;span class="s1"&gt;hi&lt;/span&gt; " hello " &lt;span class="s2"&gt;world!&lt;/span&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="c2"&gt; &lt;span class="s3"&gt;abc&lt;/span&gt; " def ghijkl " &lt;span class="s1"&gt;mno&lt;/span&gt; " pqr!" &lt;/div&gt; &lt;/li&gt; &lt;/ol&gt; </code></pre> <p>I tried to parse using the following code</p> <pre><code>tree = html.fromstring(code.content) sol = tree.xpath('//ol//text()') for x in sol: print x </code></pre> <p>I get the result as this</p> <pre><code>hi hello world! abc def ghijkl mno pqr! </code></pre> <p>What can I do to get all the text in each <code>&lt;li&gt;</code> tag in one line. i.e. I want the output to be</p> <pre><code>hi hello world! abc def ghijkl mno pqr! </code></pre>
0
2016-08-14T05:23:57Z
38,941,322
<p>You can get each li and use <a href="https://msdn.microsoft.com/en-us/library/ms256063(v=vs.110).aspx" rel="nofollow">normalize-space</a>:</p> <pre><code>from lxml import html h = """&lt;ol&gt; &lt;li&gt; &lt;div class="c1"&gt; &lt;span class="s1"&gt;hi&lt;/span&gt; " hello " &lt;span class="s2"&gt;world!&lt;/span&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="c2"&gt; &lt;span class="s3"&gt;abc&lt;/span&gt; " def ghijkl " &lt;span class="s1"&gt;mno&lt;/span&gt; " pqr!" &lt;/div&gt; &lt;/li&gt; &lt;/ol&gt;""" tree = html.fromstring(h) for li in tree.xpath("//ol/li"): print(li.xpath("normalize-space(.)")) </code></pre> <p>Which gives you:</p> <pre><code>hi " hello " world! abc " def ghijkl " mno " pqr!" </code></pre>
1
2016-08-14T10:28:07Z
[ "python", "html", "parsing", "lxml" ]
Trying to replicate Python's struct.unpack ">L" in JavaScript with TypedArrays
38,939,519
<p>I am trying to reproduce the following Python code in JavaScript.</p> <pre><code>import struct val = struct.unpack("&gt;L", "MACS")[0] </code></pre> <p><code>val</code> is now <code>1296122707</code> (the same as <code>0x4d414353</code>). Trying the same with <code>htk1</code> gives <code>1752460081</code>, the same as <code>0x68746b31</code>.</p> <p>I was trying to bring this to JavaScript so I got to studying and came across this documentation on Python: <em><a href="https://docs.python.org/3/library/stdtypes.html#int.from_bytes" rel="nofollow">classmethod int.from_bytes()</a></em></p> <p>So the above is the same as:</p> <pre><code>int.from_bytes(b"MACS", "big") </code></pre> <p>However I am not able to port it to JavaScript. Can you please help me understand this to port, or if it's already available out there?</p> <p>Here was my attempt:</p> <pre><code>function unpackL(fourCharCode) { var buf = new ArrayBuffer(8); var view = new DataView(buf); view.setUint8(0, String.charCodeAt(fourCharCode[0]), true); view.setUint8(2, String.charCodeAt(fourCharCode[1]), true); view.setUint8(4, String.charCodeAt(fourCharCode[2]), true); view.setUint8(6, String.charCodeAt(fourCharCode[3]), true); return new Uint32Array(buf); } </code></pre> <p>However <code>unpackL('htk1')</code> gives me <code>Uint32Array [ 7602280, 3211371 ]</code>.</p>
0
2016-08-14T05:44:13Z
38,939,620
<p>Here's a function that does this (returning undefined if the string is the wrong length):</p> <pre><code>function stringToUnsignedInt(string) { if (string.length !== 4) { return undefined; } return (string.charCodeAt(0) &lt;&lt; 24) + (string.charCodeAt(1) &lt;&lt; 16) + (string.charCodeAt(2) &lt;&lt; 8) + string.charCodeAt(3); } console.log(stringToUnsignedInt("MACS") === 1296122707); // true console.log(stringToUnsignedInt("htk1") === 1752460081); // true </code></pre>
2
2016-08-14T06:02:14Z
[ "javascript", "python" ]
Convert string from Latin-1 to UTF-8 and back to Latin-1
38,939,565
<p>A system (not under my control) sends a <code>latin-1</code> encoded string (such as Öland) which I can convert to <code>utf-8</code> but not back to <code>latin-1</code>. </p> <p>Consider this code:</p> <pre><code>text = '\xc3\x96land' # This is what the external system sends iso = text.encode(encoding='latin-1') # this is my best guess print(iso.decode('utf-8')) print(u"Öland".encode(encoding='latin-1')) </code></pre> <p><br> This is the output:</p> <pre>Öland b'\xd6land' </pre> <p>Now, how to I mimic the system? Obviously <code>'\xc3\x96land'</code> is not <code>'\xd6land'</code></p>
-2
2016-08-14T05:52:37Z
38,939,655
<p>if your external system sends it to you then you should first decode it rather than encoding it since it is sent as encoded.</p> <p>you don't have to encode the encoded!!</p> <p><code>hey=u"Öland".encode('latin-1') print hey </code></p> <p>gives output like this <code>?land</code></p> <p><code>print hey.decode('latin-1')</code> gives output like this <code>Öland</code></p>
0
2016-08-14T06:07:38Z
[ "python" ]
Convert string from Latin-1 to UTF-8 and back to Latin-1
38,939,565
<p>A system (not under my control) sends a <code>latin-1</code> encoded string (such as Öland) which I can convert to <code>utf-8</code> but not back to <code>latin-1</code>. </p> <p>Consider this code:</p> <pre><code>text = '\xc3\x96land' # This is what the external system sends iso = text.encode(encoding='latin-1') # this is my best guess print(iso.decode('utf-8')) print(u"Öland".encode(encoding='latin-1')) </code></pre> <p><br> This is the output:</p> <pre>Öland b'\xd6land' </pre> <p>Now, how to I mimic the system? Obviously <code>'\xc3\x96land'</code> is not <code>'\xd6land'</code></p>
-2
2016-08-14T05:52:37Z
38,940,040
<p>Turns out the external system send the data in utf-8 already. Converting the string forth and back works like this now: </p> <pre><code>#!/usr/bin/env python3.4 # -*- coding: utf-8 -*- text = '\xc3\x96land' encoded = text.encode(encoding='raw_unicode_escape') print(encoded) utf8 = encoded.decode('utf-8') print(utf8) mimic = utf8.encode('utf-8', 'unicode_escape') print(mimic) </code></pre> <p>And the output</p> <pre> b'\xc3\x96land' Öland b'\xc3\x96land' </pre> <p>Thank you for your support!</p>
0
2016-08-14T07:20:33Z
[ "python" ]
Calculate and store the total score for each student and calculate the average score for the whole class.
38,939,586
<p>This is what I have done so far. Need help in finding the total score and average score. </p> <pre><code>name = '' results = [] result = 0 question =1 while question &lt;= 30: name = input("Enter student number "+str(question)+"'s name\n") result = input("Enter student number " + str(question) + "'s result\n") result = int(result) #takes the var and makes it into int typeChecker = type(result) #checks the var type while typeChecker != int: result = input("Enter student number " + str(question) + "'s result\n") result = int(result) #takes the var and makes it into int results += (name + result) print (results) question += 1 pass </code></pre>
-1
2016-08-14T05:55:47Z
38,939,631
<p>(I'm assuming you are using Python 3)</p> <p>You have a few issues.</p> <pre><code>result = int(result) #takes the var and makes it into int typeChecker = type(result) #checks the var type while typeChecker != int: . . </code></pre> <p>This <code>while</code> is useless. The type of <code>result</code> can never be anything else than <code>int</code> by the time you check it. If the user inputted an invalid number then a <code>ValueError</code> would have been raised already without you catching it. <br/><br/><br/></p> <pre><code> results += (name + result) </code></pre> <p>This line has 2 problems. It will always raise a <code>TypeError</code> as it tries to concat a <code>str</code> and an <code>int</code>. Then it also tries to concat a <code>list</code> and whatever you expect the type of <code>name + result</code> to be. These are 2 <code>TypeError</code>s. <br/><br/><br/></p> <p>If you want to keep this simple, you should think about storing your data in a different container, perhaps a list of tuples where the first index is the name and the second is the score.</p> <p>Then you can iterate over the list to calculate the sum and the average.</p>
1
2016-08-14T06:03:20Z
[ "python" ]
change key in python dict and print only the key value with value
38,939,598
<p>I am trying to manipulate a dict as:</p> <pre><code>op = {'File:Directory': '/var/tmp/Mkbib/Trial2', 'PDF:Title': 'Antiferromagnetic-ferromagnetic transition in FeRh', 'PDF:Author': 'V. L. Moruzzi and P. M. Marcus', 'File:FileSize': '636 kB', 'File:FileInodeChangeDate': '2016:08:13 19:45:15+02:00'} fields = ["author", "year", "journal", "title", "publisher"] new_op = {} for field in fields: # new_op = dict((field, value) for key, value in op.items() if field in key.lower()) new_op[field] = value for key, value in op.items() if field in key.lower()) print(new_op) </code></pre> <p>My goal is to change <code>op</code>'s key to matching(if any) <code>field from fields</code>, and create new_op with the new key, and value if it has a matching key.</p> <p>So, in the above example, my new_op should be:</p> <pre><code>new_op = {'title': 'Antiferromagnetic-ferromagnetic transition in FeRh', 'author': 'V. L. Moruzzi and P. M. Marcus'} </code></pre> <p>The commented line is working, but obviously creating new dict for each item., and also printing for all loop, as obvious.</p>
1
2016-08-14T05:57:50Z
38,939,677
<p>You can use dictionary comprehension here.</p> <pre><code>op = { 'File:Directory': '/var/tmp/Mkbib/Trial2', 'PDF:Title': 'Antiferromagnetic-ferromagnetic transition in FeRh', 'PDF:Author': 'V. L. Moruzzi and P. M. Marcus', 'File:FileSize': '636 kB', 'File:FileInodeChangeDate': '2016:08:13 19:45:15+02:00' } fields = [ 'author', 'year', 'journal', 'title', 'publisher' ] new_op = { field: value for field in fields for key, value in op.items() if field in key.lower() } print(new_op) # {'title': 'Antiferromagnetic-ferromagnetic transition in FeRh', 'author': 'V. L. Moruzzi and P. M. Marcus'} </code></pre>
3
2016-08-14T06:11:53Z
[ "python", "python-3.x", "dictionary" ]
What is the simplest python code to plot a simple graph (simpler than matlab)
38,939,691
<p>If I want to draw a y=x^2 graph from 0 to 9 in matlab, I can do </p> <pre><code>a = [0:1:10] b = a.^2 plot(a,b) </code></pre> <p>Using python, I can do the same like below </p> <pre><code>import matplotlib.pyplot as plt import numpy as np a=[x for x in xrange(10)] b=np.square(a) plt.plot(a,b) plt.show() </code></pre> <p>But to the contrary to my belief that python code is simpler, this takes more lines that matlab. (I guess python tries to make things light weight, so we need to import things when we actually need them, thus more lines..) Can I make above python code simpler(I mean shorter)?</p> <p>EDIT : I know it doesn't matter and meaningless when it comes to processing time but I was just curious how short the code can become. </p>
-4
2016-08-14T06:15:30Z
38,939,734
<p>This is a bit simpler</p> <pre><code>import matplotlib.pyplot as plt X = range(10) plt.plot(X, [x*x for x in X]) plt.show() </code></pre> <p>but remember that Python is a general purpose language, so it's not surprising it requires a bit more than a specific charting/math tool.</p> <p>The main clutter is however importing the libraries that help about chart plotting and numeric computation, as this is implied for matlab because it's a tool just designed around that.</p> <p>These lines are however going to be needed only once: they're not a factor, but just an additive constant, going to be negligible even in just slightly more serious examples.</p>
0
2016-08-14T06:24:40Z
[ "python", "matlab", "matplotlib", "plot" ]
Can someone explain how this leetcode solution works with negative numbers?
38,939,781
<p>This is a solution for <a href="https://leetcode.com/problems/sum-of-two-integers/" rel="nofollow">leetcode problem 371</a>,<code>Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.</code></p> <p>Why we need <code>MOD</code> and <code>MAX_INT</code> and what is this part doing? <code>~(a &amp; MAX_INT) ^ MAX_INT</code></p> <pre><code>def getSum( a, b): """ :type a: int :type b: int :rtype: int """ MOD = 0xFFFFFFFF MAX_INT = 0x7FFFFFFF while b != 0: a, b = (a ^ b) &amp; MOD, ((a &amp; b) &lt;&lt; 1) &amp; MOD return a if a &lt;= MAX_INT else ~(a &amp; MAX_INT) ^ MAX_INT print getSum4(-4,2) -2 </code></pre> <p>The solution is from <a href="https://www.hrwhisper.me/leetcode-sum-two-integers/" rel="nofollow">this blog</a></p>
1
2016-08-14T06:33:53Z
38,940,568
<p>The reason for <code>MOD</code>, <code>MAX_INT</code> and <code>~(a &amp; MAX_INT) ^ MAX_INT</code> is to simulate 32-bit integers. This is needed because in Python integers are not bounded.</p> <p>After doing a calculation, <code>&amp; MOD</code> is used to only keep the 32-bit least significant bits of the result. In systems where integers are only 32-bits, this is effectively what happens; the extra bits are simply dropped.</p> <p>The usage of <code>MAX_INT</code> is to properly deal with what would be an integer overflow with 32-bit integers. If you add <code>0x40000000</code> and <code>0x40000000</code>, you'll get <code>0x80000000</code>, which in Python is just a positive integer. With 32-bit integers, this would be an overflow and the value is equal to <code>-0x80000000</code>.</p> <p>The <code>a &amp; MAX_INT</code> is to remove the most-significant bit, which in 32-bit integers is essentially used as sign. The <code>~(...) ^ MAX_INT</code> is a way to extend the 31-bit number to the number of bits actually used. For example, if Python would only use 42 bits, <code>-0x80000000</code> would be represented as <code>0xff80000000</code>. In other words, just set every bit beyond the least significant 31 bits to <code>1</code>. (Doing <code>~x</code> is the same as doing <code>x ^ 0xff...ff</code>, so <code>~x ^ MAX_INT</code> is the same as <code>x ^ (0xff..ff MAX_INT)</code> and <code>x ^ 0xff...ff80000000</code> and even <code>x | 0xff...ff80000000</code> if <code>x</code> "uses" only 31 bits).</p> <p>Of course, Python conceptually doesn't have a fixed number of bits it uses, but you can kind of look at it as if there will be an infinite number of bits set to 1. It just doesn't store all those bits, just like it doesn't store all 0 bits in positive numbers (e.g. 0x00...001).</p> <p>An alternative way would be to do <code>~x ^ MOD</code>, where you use that the 32nd bit is already correctly set.</p>
1
2016-08-14T08:45:13Z
[ "python", "bit-manipulation" ]
Can someone explain how this leetcode solution works with negative numbers?
38,939,781
<p>This is a solution for <a href="https://leetcode.com/problems/sum-of-two-integers/" rel="nofollow">leetcode problem 371</a>,<code>Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.</code></p> <p>Why we need <code>MOD</code> and <code>MAX_INT</code> and what is this part doing? <code>~(a &amp; MAX_INT) ^ MAX_INT</code></p> <pre><code>def getSum( a, b): """ :type a: int :type b: int :rtype: int """ MOD = 0xFFFFFFFF MAX_INT = 0x7FFFFFFF while b != 0: a, b = (a ^ b) &amp; MOD, ((a &amp; b) &lt;&lt; 1) &amp; MOD return a if a &lt;= MAX_INT else ~(a &amp; MAX_INT) ^ MAX_INT print getSum4(-4,2) -2 </code></pre> <p>The solution is from <a href="https://www.hrwhisper.me/leetcode-sum-two-integers/" rel="nofollow">this blog</a></p>
1
2016-08-14T06:33:53Z
38,941,567
<p>I'm not surprised you're having a hard time trying to understand that code, definitely it works alright but I'd recommend you to start from scratch. First be sure you master bit operators, <a href="https://en.wikipedia.org/wiki/Signed_number_representations" rel="nofollow">integer representation</a> of numbers and <a href="https://en.wikipedia.org/wiki/Two%27s_complement" rel="nofollow">two's complement</a> for negative ones. Then just try to understand these 2 simpler functions with a couple of tests:</p> <pre><code>def add_32bits_buggy(a, b): MOD = 0xFFFFFFFF while (a != 0): c = (b &amp; a) &amp; MOD b = (b ^ a) &amp; MOD a = (c &lt;&lt; 1) &amp; MOD return b def add_32bits(a, b): MOD = 0xFFFFFFFF MAX_INT = 0x7FFFFFFF while (a != 0): c = (b &amp; a) &amp; MOD b = (b ^ a) &amp; MOD a = (c &lt;&lt; 1) &amp; MOD if b &lt;= MAX_INT: return b else: return ~(b &amp; MAX_INT) ^ MAX_INT # value to test edge_cases max_v = 0xFFFFFFFF # Positive integers i = 1 while i &lt;= max_v: i *= 2 a, b = max_v + 1, i print "{0:10d}\t{1:10d}".format( add_32bits(a, b), add_32bits_buggy(a, b), ) print '-'*80 # Negative integers i = 1 while i &lt;= max_v: i *= 2 a, b = max_v + 1, i print "{0:10d}\t{1:10d}".format( add_32bits(a, -b), add_32bits_buggy(a, -b), ) </code></pre> <p>The function add_32bits_buggy will answer your question "Why we need <code>MOD</code> and <code>MAX_INT</code> and what is this part doing? <code>~(a &amp; MAX_INT) ^ MAX_INT</code>". Then add_32bits (which is equivalent to your original code) will show how those cases are fixed because of the return.</p> <p>Hope it helps.</p>
-1
2016-08-14T11:03:43Z
[ "python", "bit-manipulation" ]
Regex Search in Multiple PyMongo Document Fields
38,939,836
<h2>The Goal</h2> <p>Search the corpus of Enron emails to find emails to and from Ken Lay, securities fraudster extraordinaire.</p> <h2>The Data</h2> <p>One such email document, of 500k+ emails named <code>workdocs</code>, are structured like below:</p> <p>One such document:</p> <pre><code> {'headers': {'To': 'eric.bass@enron.com', 'Subject': 'Re: Plays and other information', 'X-cc': '', 'X-To': 'Eric Bass', 'Date': 'Tue, 14 Nov 2000 08:22:00 -0800 (PST)', 'Message-ID': '&lt;6884142.1075854677416.JavaMail.evans@thyme&gt;', 'From': 'michael.simmons@enron.com', 'X-From': 'Michael Simmons', 'X-bcc': ''}, 'subFolder': 'notes_inbox', 'mailbox': 'bass-e', '_id': ObjectId('4f16fc97d1e2d32371003e27'), 'body': "the scrimmage is still up in the air...\n\n\nwebb said that they didnt want to scrimmage...\n\nthe aggies are scrimmaging each other... (the aggie teams practiced on \nSunday)\n\nwhen I called the aggie captains to see if we could use their field.... they \nsaid that it was tooo smalll for us to use...\n\n\nsounds like bullshit to me... but what can we do....\n\n\nanyway... we will have to do another practice Wed. night.... and I dont' \nknow where we can practice.... any suggestions...\n\n\nalso, we still need one more person..."} </code></pre> <p>The fields I'm interested in are <code>{'To':...,'From':...,'X-cc':...,'X-bcc':...}</code>, which are found in the field <code>'headers'</code>.</p> <h2>The Implementation (and error)</h2> <p>Doing a search across the entire document for <code>'klay@enron'</code> seems to work using <code>workdocs.find({'$text':{'$search':'klay@enron.com'}})</code> but I'm interested in capturing many possible email aliases with a regex. How do I find the documents that match a regex <code>ken_email</code> (below) in the fields <code>To</code>, <code>From</code>, <code>X-bcc</code>, and <code>X-cc</code>?</p> <pre><code>from pymongo import MongoClient import re re_email = '^(K|Ken|Kenneth)[A-Z0-9._%+-]*Lay@[A-Z0-9._%+-]+\.[A-Z]{2,4}$' ken_email = re.compile(re_email, re.IGNORECASE) </code></pre>
0
2016-08-14T06:42:55Z
38,944,459
<p>To only search those four fields, you can use:</p> <pre><code>(?:to|from|x-b?cc)'\s*:\s*'K[A-Z0-9._%+-]*Lay@[A-Z0-9._%+-]+\.[A-Z]{2,4} </code></pre> <p>That version removes the capture group around his first name, which is unnecessary for the match to happen. (It would be faster to extract after the regex is finished.)</p> <p>I'm also not convinced it's necessary to validate the email address. You're already looking in fields that should have nothing but email addresses. You could further shorten the regex:</p> <pre><code>(?:to|from|x-b?cc)'\s*:\s*'K[A-Z0-9._%+-]*Lay </code></pre> <p>This will have the added bonus of matching <code>klay123@example.com</code></p> <hr> <p>It's not terribly efficient (especially with long strings of text), but there are some ways to speed it up. The easiest way is to remove the body beforehand. (This may also help prevent false positives.) You could just remove everything after the first <code>}</code>.</p> <p>Just for kicks, here's a regex to match that:</p> <pre><code>\}.* </code></pre> <p>Simply replace with an empty string to remove it.</p>
1
2016-08-14T16:55:00Z
[ "python", "regex", "mongodb", "pymongo" ]
KeyError: 'PYTHONPATH', how can I fix PYTHONPATH? (Python 3.5.2)
38,939,936
<p>I have seen this post asked before in stackoverflow but it was 4 years ago (<a href="http://stackoverflow.com/questions/9320305/how-to-fix-the-python-path">How to fix the python path</a>) so I am not sure wether this is the right solution because I am using a newer version of python (3.5.2). This is what I see in a Python Shell:</p> <pre><code>Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; os.environ['PYTHONPATH'].split(os.pathsep) Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in &lt;module&gt; os.environ['PYTHONPATH'].split(os.pathsep) File "C:\Users\John\AppData\Local\Programs\Python\Python35\lib\os.py", line 725, in __getitem__ raise KeyError(key) from None KeyError: 'PYTHONPATH' </code></pre> <p>I want to find the pythonpath.So, how can I fix this error?</p>
0
2016-08-14T06:59:59Z
38,939,957
<p>There is no PYTHONPATH variable in your OS Environemental variables. Hence the error.</p> <p>It is not created by Python installation (atleast in windows). You have to create one variable.</p> <p>To check if there is one such environmental variable, type below command:</p> <pre><code>SET PYTHONPATH </code></pre> <p>You can also create and set it using below command</p> <pre><code>SETX PYTHONPATH &lt;your desired path&gt; </code></pre>
0
2016-08-14T07:04:36Z
[ "python", "python-3.x" ]
KeyError: 'PYTHONPATH', how can I fix PYTHONPATH? (Python 3.5.2)
38,939,936
<p>I have seen this post asked before in stackoverflow but it was 4 years ago (<a href="http://stackoverflow.com/questions/9320305/how-to-fix-the-python-path">How to fix the python path</a>) so I am not sure wether this is the right solution because I am using a newer version of python (3.5.2). This is what I see in a Python Shell:</p> <pre><code>Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; os.environ['PYTHONPATH'].split(os.pathsep) Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in &lt;module&gt; os.environ['PYTHONPATH'].split(os.pathsep) File "C:\Users\John\AppData\Local\Programs\Python\Python35\lib\os.py", line 725, in __getitem__ raise KeyError(key) from None KeyError: 'PYTHONPATH' </code></pre> <p>I want to find the pythonpath.So, how can I fix this error?</p>
0
2016-08-14T06:59:59Z
38,939,975
<p>You may want to check <a href="https://docs.python.org/3.5/library/sys.html?highlight=sys#sys.path" rel="nofollow">sys.path</a> </p> <blockquote> <p>A list of strings that specifies the search path for modules. Initialized from the environment variable <strong>PYTHONPATH</strong>, plus an installation-dependent default.</p> </blockquote>
0
2016-08-14T07:07:53Z
[ "python", "python-3.x" ]
"if not item in list" not functioning properly in Python?
38,940,026
<p>I have a simple program that checks the user's 'passcode' that either allows them access or denies them access.</p> <p>If the user types in the correct passcode, the print statement "Login successful! Passcode used:", passcode" is printed, however, if the passcode is wrong, it simply asks for their passcode again <strong>without</strong> printing the statement "Login unsuccessful."... </p> <p>Why is this? Thankyou.</p> <pre><code>LoginCorrect = 0 lst = ['1234', '2345', '3456', '4567', '5678', '6789'] while LoginCorrect == 0: passcode = input("Please enter your passcode: ") for item in lst: if item == passcode: print("Login successful! Passcode used:", passcode) LoginCorrect = 1 if not item in lst == False: print("Login unsuccessful.") </code></pre>
0
2016-08-14T07:18:09Z
38,940,054
<p>You're over complicating things. Instead of iterating over the list yourself, you could just check if the <code>passcode</code> is there:</p> <pre><code>LoginCorrect = False lst = ['1234', '2345', '3456', '4567', '5678', '6789'] while LoginCorrect: passcode = input("Please enter your passcode: ") if passcode in lst: print("Login successful! Passcode used:", passcode) LoginCorrect = True else: print("Login unsuccessful.") </code></pre>
4
2016-08-14T07:23:13Z
[ "python", "python-3.x" ]
"if not item in list" not functioning properly in Python?
38,940,026
<p>I have a simple program that checks the user's 'passcode' that either allows them access or denies them access.</p> <p>If the user types in the correct passcode, the print statement "Login successful! Passcode used:", passcode" is printed, however, if the passcode is wrong, it simply asks for their passcode again <strong>without</strong> printing the statement "Login unsuccessful."... </p> <p>Why is this? Thankyou.</p> <pre><code>LoginCorrect = 0 lst = ['1234', '2345', '3456', '4567', '5678', '6789'] while LoginCorrect == 0: passcode = input("Please enter your passcode: ") for item in lst: if item == passcode: print("Login successful! Passcode used:", passcode) LoginCorrect = 1 if not item in lst == False: print("Login unsuccessful.") </code></pre>
0
2016-08-14T07:18:09Z
38,940,110
<p>I hope that this is just an excersise and not a production code to perform login, because it is <strong>super not secured</strong>.</p> <p>Here is a working version of your snippet:</p> <pre><code>lst = ['1234', '2345', '3456', '4567', '5678', '6789'] LoginCorrect = False while not LoginCorrect: passcode = input("Please enter your passcode: ") if passcode in lst: print("Login successful! Passcode used:", passcode) LoginCorrect = True else: print("Login unsuccessful.") </code></pre>
0
2016-08-14T07:31:45Z
[ "python", "python-3.x" ]
"if not item in list" not functioning properly in Python?
38,940,026
<p>I have a simple program that checks the user's 'passcode' that either allows them access or denies them access.</p> <p>If the user types in the correct passcode, the print statement "Login successful! Passcode used:", passcode" is printed, however, if the passcode is wrong, it simply asks for their passcode again <strong>without</strong> printing the statement "Login unsuccessful."... </p> <p>Why is this? Thankyou.</p> <pre><code>LoginCorrect = 0 lst = ['1234', '2345', '3456', '4567', '5678', '6789'] while LoginCorrect == 0: passcode = input("Please enter your passcode: ") for item in lst: if item == passcode: print("Login successful! Passcode used:", passcode) LoginCorrect = 1 if not item in lst == False: print("Login unsuccessful.") </code></pre>
0
2016-08-14T07:18:09Z
38,940,201
<p>To answer your specific question: <code>not item in lst</code> works fine, but <code>not item in lst == False</code> is evaluated differently than you probably expect. Python converts chains of logical tests like <code>(a == b == c)</code> or <code>(a in b in c)</code> to <code>(a == b) and (b == c)</code> or <code>(a in b) and (b in c)</code>. It also does this When it sees <code>in</code> and <code>==</code> in the same expression. So <code>not item in lst == False</code> is evaluated as <code>not ((item in lst) and (lst == False))</code>, which is always <code>True</code>. (Without the <code>not</code>, it would always be <code>False</code>, which may be what prompted your original question). </p> <p>You could fix this by putting parentheses around your first test: <code>(not item in lst) == False</code> (or maybe you mean <code>True</code>?). But a better way to write this test would be <code>if item not in lst:</code>. There are also a couple of other problems with the organization of your code, which I've pointed out in comments below:</p> <pre><code>LoginCorrect = 0 # probably better to use True/False here lst = ['1234', '2345', '3456', '4567', '5678', '6789'] while LoginCorrect == 0: # The next line will not work right on Python 2.x, which has a different # input() function; if your code might run on 2.x you should adjust for that. passcode = input("Please enter your passcode: ") for item in lst: if item == passcode: print("Login successful! Passcode used:", passcode) LoginCorrect = 1 # you could use a 'break' here to avoid comparing to more items # As noted above, `if item not in lst:` would work better for the next line. # This test should also probably occur after the `for` loop instead of # inside it, and act based on `LoginCorrect` instead of `item`. As it is, # you are testing whether `item` is in `lst`, which it always is, and you # are doing this test once for each `item`, which is more checks than needed. if not item in lst == False: print("Login unsuccessful.") </code></pre> <p>You mentioned in a comment on a different answer that you have to use a <code>for</code> loop to test the passcode against each item. If that's true, then the revised code below could work well:</p> <pre><code>try: # Python 2 compatibility input = raw_input except NameError: pass LoginCorrect = False lst = ['1234', '2345', '3456', '4567', '5678', '6789'] while not LoginCorrect: passcode = input("Please enter your passcode: ") for item in lst: if item == passcode: print("Login successful! Passcode used:", passcode) LoginCorrect = True break if not LoginCorrect: print("Login unsuccessful.") </code></pre> <p>Or, if you are willing to drop the <code>for</code> loop, you can make your code much simpler:</p> <pre><code>try: # Python 2 compatibility input = raw_input except NameError: pass lst = ['1234', '2345', '3456', '4567', '5678', '6789'] while True: passcode = input("Please enter your passcode: ") if passcode in lst: print("Login successful! Passcode used:", passcode) break else: print("Login unsuccessful.") </code></pre>
1
2016-08-14T07:46:00Z
[ "python", "python-3.x" ]
"if not item in list" not functioning properly in Python?
38,940,026
<p>I have a simple program that checks the user's 'passcode' that either allows them access or denies them access.</p> <p>If the user types in the correct passcode, the print statement "Login successful! Passcode used:", passcode" is printed, however, if the passcode is wrong, it simply asks for their passcode again <strong>without</strong> printing the statement "Login unsuccessful."... </p> <p>Why is this? Thankyou.</p> <pre><code>LoginCorrect = 0 lst = ['1234', '2345', '3456', '4567', '5678', '6789'] while LoginCorrect == 0: passcode = input("Please enter your passcode: ") for item in lst: if item == passcode: print("Login successful! Passcode used:", passcode) LoginCorrect = 1 if not item in lst == False: print("Login unsuccessful.") </code></pre>
0
2016-08-14T07:18:09Z
38,940,574
<p>How about a <code>while</code> statement with <code>continue</code> and <code>break</code>?</p> <pre><code>lst = ['1234', '2345', '3456', '4567', '5678', '6789'] while True: passcode = input('Please enter your passcode: ') if passcode not in lst: continue else: print("Login successful! Passcode used:", passcode) break </code></pre> <p>You state "if the passcode is wrong, it simply asks for their passcode again without printing the statement "Login unsuccessful."<br> That being the case, why are you coding for "Login Unsuccessful" ?</p>
0
2016-08-14T08:45:43Z
[ "python", "python-3.x" ]
"if not item in list" not functioning properly in Python?
38,940,026
<p>I have a simple program that checks the user's 'passcode' that either allows them access or denies them access.</p> <p>If the user types in the correct passcode, the print statement "Login successful! Passcode used:", passcode" is printed, however, if the passcode is wrong, it simply asks for their passcode again <strong>without</strong> printing the statement "Login unsuccessful."... </p> <p>Why is this? Thankyou.</p> <pre><code>LoginCorrect = 0 lst = ['1234', '2345', '3456', '4567', '5678', '6789'] while LoginCorrect == 0: passcode = input("Please enter your passcode: ") for item in lst: if item == passcode: print("Login successful! Passcode used:", passcode) LoginCorrect = 1 if not item in lst == False: print("Login unsuccessful.") </code></pre>
0
2016-08-14T07:18:09Z
38,940,664
<p>The logic of your code is somewhat unclear. I <em>think</em> you meant to do something like this:</p> <pre><code>LoginCorrect = 0 lst = ['1234', '2345', '3456', '4567', '5678', '6789'] while LoginCorrect == 0: passcode = input("Please enter your passcode: ") for item in lst: if item == passcode: print("Login successful! Passcode used:", passcode) LoginCorrect = 1 break if passcode not in lst: print("Login unsuccessful.") </code></pre> <p>BTW, it would be more usual in Python to use the booleans <code>False</code> and <code>True</code> for your <code>LoginCorrect</code> flag, eg</p> <pre><code>lst = ['1234', '2345', '3456', '4567', '5678', '6789'] LoginCorrect = False while not LoginCorrect: passcode = input("Please enter your passcode: ") for item in lst: if item == passcode: print("Login successful! Passcode used:", passcode) LoginCorrect = True break if passcode not in lst: print("Login unsuccessful.") </code></pre> <p>However, as others have said, it's inefficient to use a Python loop to test if <code>passcode</code> is in <code>lst</code>. An <code>in</code> test does that more efficiently, and it would be even more efficient if <code>lst</code> were instead a <code>set</code> of valid passcodes. </p> <pre><code>lst = {'1234', '2345', '3456', '4567', '5678', '6789'} while True: passcode = input("Please enter your passcode: ") if passcode in lst: print("Login successful! Passcode used:", passcode) break print("Login unsuccessful.") </code></pre> <hr> <p>I have to mention that one of the <code>if</code> statements in your code does <em>not</em> do what you think it does:</p> <pre><code>if not item in lst == False: </code></pre> <p>To explain why, I need to take a slight detour. :)</p> <p>Python syntax supports the chaining of relational operators. This allows you to do things like</p> <pre><code>if 0 &lt;= a &lt; 5: </code></pre> <p>or even</p> <pre><code>if 0 &lt;= a &lt; 5 &lt;= b &lt; 10: </code></pre> <p>The chained test <code>0 &lt;= a &lt; 5</code> is equivalent to <code>(0 &lt;= a) and (a &lt; 5)</code>,<br> and <code>0 &lt;= a &lt; 5 &lt;= b &lt; 10</code> is equivalent to</p> <pre><code>(0 &lt;= a) and (a &lt; 5) and (5 &lt;= b) and (b &lt; 10) </code></pre> <p>The <code>and</code> operator short-circuits, which means that in </p> <pre><code>left_expression and right_expression </code></pre> <p>it <em>only</em> evaluates <code>right_expression</code> if <code>bool(left_expression)</code> is True. So in those chained tests, Python works from left to right, breaking out of the chain if it detects a falsey result at any stage.</p> <p>Also, in chained tests any of the intermediate expressions are guaranteed to be evaluated at most once. Eg, in <code>f() &lt; g() &lt; h()</code> the function <code>g</code> is called once at most, and it will only be called if <code>f()</code> returns a non-falsey result.</p> <p>Now, to get back to your code. :)</p> <p>The <code>in</code> operator is a relational operator, so it can be used in chained tests. So</p> <pre><code>if item in lst == True: </code></pre> <p>is equivalent to </p> <pre><code>if (item in lst) and (lst == True): </code></pre> <p>and</p> <pre><code>if not item in lst == False: </code></pre> <p>is equivalent to </p> <pre><code>if not ((item in lst) and (lst == False)): </code></pre> <p>I think you'll agree that's <strong>not</strong> what you meant to say! :)</p> <p>And now you should be able to understand why this weird piece of code prints <code>True</code></p> <pre><code>ab = ('a', 'b') print('b' in ab in [('a', 'b'), 'c']) </code></pre>
1
2016-08-14T09:00:25Z
[ "python", "python-3.x" ]
Selenium in Python using Chrome, How to select element for clicking of Personal Info. options and then click on Personal Details
38,940,084
<p>There is drop menu in a frame, in code it starts with <code>&lt;div tag id=masterdiv, div class=submenu and onclick="SwitchMenu('sub1')"&gt;</code>, I have to click first on <code>Personal Info</code>., and then select <code>Personal Details</code> I tried </p> <pre><code>driver.find_element_by_xpath("//a[contains(href,'PersonalInfo/EmpPersonalInfo.jsp') </code></pre> <p>and </p> <pre><code>contains(@class,'submenu')]") </code></pre> <p>and</p> <pre><code>driver.find_element_by_link_text("//a [@href=\"../EmployeeFiles/AcademicInfo/DailyStudentAttendanceEntry.jsp\"]") </code></pre> <p>None works.</p> <pre><code>&lt;div id="masterdiv"&gt; &lt;div class="menutitle" onclick="SwitchMenu('sub1')"&gt;Personal Info.&amp;nbsp &lt;img src="../Images/arrow.gif"&gt;&lt;/div&gt; &lt;span class="submenu" id="sub1" style="display: none;"&gt; &lt;img src="../Images/bullet4.gif"&gt;&amp;nbsp;&lt;a target="DetailSection" title="Personal Information" href="PersonalInfo/EmpPersonalInfo.jsp"&gt;&lt;font face="Arial" color="white" size="2"&gt;Personal Detail&lt;/font&gt;&lt;/a&gt;&lt;br&gt; &lt;img src="../Images/bullet4.gif"&gt;&amp;nbsp;&lt;a target="DetailSection" title="Personal Information" href="PersonalInfo/imprestAcc.jsp"&gt;&lt;font face="Arial" color="white" size="2"&gt;My Imprest Account&lt;/font&gt;&lt;/a&gt;&lt;br&gt; &lt;img src="../Images/bullet4.gif"&gt;&amp;nbsp;&lt;a target="DetailSection" title="Self Attendance Detail" href="PersonalInfo\SelfAttendanceDetail.jsp"&gt;&lt;font face="Arial" color="white" size="2"&gt;Self Attendance&lt;/font&gt;&lt;/a&gt;&lt;br&gt; &lt;img src="../Images/bullet4.gif"&gt;&amp;nbsp;&lt;a target="DetailSection" title="Change eMailID/Contact Numbers" href="PersonalInfo/EmpModifyEmailIDTelephone.jsp"&gt;&lt;font face="Arial" color="white" size="2"&gt;Edit Info.&lt;/font&gt;&lt;/a&gt;&lt;br&gt; } </code></pre>
0
2016-08-14T07:28:18Z
39,044,004
<p>Actually your provided locator looks incorrect that's why are unable to find element, you should try using <code>WebDriverWait</code> to wait until element present as below :-</p> <pre><code>from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC #first switch to frame if present driver.switch_to_frame("frame id or name") wait = WebDriverWait(driver, 10) # now find menu and click menu = wait.until(EC.presence_of_element_located((By.XPATH, ".//*[contains(., 'Personal Info')]"))) menu.click() #now find submemu and click submemu = wait.until(EC.presence_of_element_located((By.XPATH, ".//*[contains(., 'Personal Detail')]"))) submemu.click() </code></pre>
0
2016-08-19T16:40:12Z
[ "python", "google-chrome", "selenium-webdriver" ]
User Permissions from django admin
38,940,101
<p>I have the model Profile related with model User by OneToOne:</p> <pre><code>class Profile(models.Model): user = models.OneToOneField(User) ... </code></pre> <p>Also i have the model Books related with model Profile by ForeignKey:</p> <pre><code>class Books(models.Model): profile = models.ForeignKey(Profile) ... </code></pre> <p>admin.py:</p> <pre><code>class ProfileInLine(admin.StackedInline): model = Profile ... </code></pre> <p>I need to create user in django admin, and that user:</p> <ol> <li>Can login in django admin</li> <li>Can edit and see his data (Profile and User models)</li> <li>Can edit only his Books</li> </ol> <p>I will appreciate for examples.</p>
0
2016-08-14T07:30:14Z
38,982,795
<p>Just create a new admin user</p> <pre><code>python manage.py createsuperuser </code></pre> <p>then go into django admin and:</p> <ul> <li>deselect super user</li> <li>desleect all permissions you don't want to give them</li> </ul> <p>then save the admin user</p>
0
2016-08-16T19:15:28Z
[ "python", "django", "django-models", "django-admin", "django-admin-filters" ]
AWS Lambda support for python 3.4 and cronjobs
38,940,140
<p>I´ve created a set up using python 3.4 code (as I need the library pyrebase) as well as using Cronjobs. </p> <p>AWS Lambda would do the job perfect if it wasn´t for the lack of Python 3-support. </p> <p>Any ideas of other AWS computer services supporting Python and Cronjobs? (or other cloud computing services that would support the project?)</p>
0
2016-08-14T07:36:52Z
38,983,206
<p>The environment that Lambda runs your scripts in has Python 3 available to it, so it is possible to run Python 3 code via Lambda, but it takes a bit of work (I've not done it myself). Here's a similar question: <a href="http://stackoverflow.com/questions/36143563/using-python-3-with-aws-lamba">using Python 3 with AWS lamba</a> </p> <p>And the a link from the answer in that question with some good info: <a href="http://www.cloudtrek.com.au/blog/running-python-3-on-aws-lambda/" rel="nofollow">http://www.cloudtrek.com.au/blog/running-python-3-on-aws-lambda/</a></p> <p>Basically you'd have a small chunk of Python 2.7 code with the lambda handler function, which then creates a Python 3 virtualenv in which to run your Python 3 code.</p> <p>As for cronjobs, you could probably put something together with timers in SWS: <a href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dg-timers.html" rel="nofollow">http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dg-timers.html</a> . If it has to be literal cronjobs (vs. running something on a schedule, regardless of method), you'd need an EC2 instance running cron and calling out to other services.</p>
1
2016-08-16T19:43:14Z
[ "python", "amazon-web-services", "cron", "aws-lambda" ]
How do I create dataframes from the groups that have been arranged by groupby?
38,940,209
<p>I have separated my data set by months, there are a total of 8 groups for 8 different months, I want to create two separate dataframes which one will include the data that is found on months:5,6,7,8 and the other dataframe will include the months:4,9,10,11. How can I tell groupby to create these two separate datasets?</p> <pre><code>df['Date']=pd.to_datetime(df['Date'],format='%m/%d/%y') df['year'] = pd.DatetimeIndex(df['Date']).year df['month'] = pd.DatetimeIndex(df['Date']).month df2=df.groupby('month') </code></pre>
1
2016-08-14T07:47:25Z
38,940,384
<p>Try:</p> <pre><code>df1 = df[df.month.isin([5, 6, 7, 8])] df2 = df[df.month.isin([4, 9, 10, 11])] </code></pre>
1
2016-08-14T08:13:00Z
[ "python", "datetime", "pandas", "group-by" ]
How can I detect collision between two objects only once in pygame?
38,940,220
<p>In my game, I have a population of fish (10). Each fish has a line of sight (an arc object in front of them). There are sharks, which are predators (they are moving around the room randomly). Each fish is assigned an intelligence number at the beginning. When a shark enters in a fish' line of sight, I want the fish to reverse his direction (or at least get away in the best direction) only if his intelligence number is greater than a random generated number.</p> <p>The issue is that when I try to implement this and the shark gets in the line of sight of the fish, pygame keeps detecting a collision, so python keeps generating a random number. For example, a fish might have a very low intelligence level, but still has a very high probability to escape from the shark because python keeps detecting the collision, and it has many tries to pass the bar. For that example, I'd actually want the fish to very likely not change directions when the shark is in the line of sight. </p> <p>Ideally, I want python to detect the collision once, and of course detect again if the shark goes through the line of sight again a separate time. </p> <p>Here is my code, don't know how much it'd help:</p> <pre><code>class RedFish(pygame.sprite.Sprite): def __init__(self, newDNA): pygame.sprite.Sprite.__init__(self) self.direction = random.uniform(0, math.pi*2) self.speed = 2 self.intelligence = 100 def update(self): self.rect.x -= math.sin(self.direction) * self.speed self.rect.y -= math.cos(self.direction) * self.speed for shark in sharks: if pygame.sprite.collide_mask(arcsList[self.arcIndex], shark): temp = random.randrange(400) if (temp &lt; self.intelligence): self.direction = self.direction*-1 </code></pre> <p>Thanks!</p>
0
2016-08-14T07:49:22Z
38,940,418
<p>You can store the last shark that the fish "saw" and compare that in each iteration of the update loop.</p> <ul> <li>If the fish sees the same shark again, don't recalculate.</li> <li>If the fish sees another shark, recalculate and remember that shark.</li> <li>If it sees no sharks, reset its "memory".</li> </ul> <p><strong>Note:</strong> I've intentionally left out a lot of your calculation code to keep this example as simple as possible.</p> <pre><code>class RedFish(pygame.sprite.Sprite): def __init__(self, newDNA): self.last_shark_seen = None def update(self): # track how many sharks we have collisions with shark_collisions = 0 for shark in sharks: if pygame.sprite.collide_mask(arcsList[self.arcIndex], shark): shark_collisions += 1 if shark != self.last_shark_seen: self.last_shark_seen = shark # calculate new direction here break # no collisions means no sharks seen, reset the fish's memory self.last_shark_seen = None </code></pre>
2
2016-08-14T08:18:46Z
[ "python", "pygame", "sprite", "collision", "detection" ]
How can I detect collision between two objects only once in pygame?
38,940,220
<p>In my game, I have a population of fish (10). Each fish has a line of sight (an arc object in front of them). There are sharks, which are predators (they are moving around the room randomly). Each fish is assigned an intelligence number at the beginning. When a shark enters in a fish' line of sight, I want the fish to reverse his direction (or at least get away in the best direction) only if his intelligence number is greater than a random generated number.</p> <p>The issue is that when I try to implement this and the shark gets in the line of sight of the fish, pygame keeps detecting a collision, so python keeps generating a random number. For example, a fish might have a very low intelligence level, but still has a very high probability to escape from the shark because python keeps detecting the collision, and it has many tries to pass the bar. For that example, I'd actually want the fish to very likely not change directions when the shark is in the line of sight. </p> <p>Ideally, I want python to detect the collision once, and of course detect again if the shark goes through the line of sight again a separate time. </p> <p>Here is my code, don't know how much it'd help:</p> <pre><code>class RedFish(pygame.sprite.Sprite): def __init__(self, newDNA): pygame.sprite.Sprite.__init__(self) self.direction = random.uniform(0, math.pi*2) self.speed = 2 self.intelligence = 100 def update(self): self.rect.x -= math.sin(self.direction) * self.speed self.rect.y -= math.cos(self.direction) * self.speed for shark in sharks: if pygame.sprite.collide_mask(arcsList[self.arcIndex], shark): temp = random.randrange(400) if (temp &lt; self.intelligence): self.direction = self.direction*-1 </code></pre> <p>Thanks!</p>
0
2016-08-14T07:49:22Z
38,941,172
<p>You need to track when the shark was seen, or which shark was seen. Basically update the collision detector one tenth (or 12th or 100th) as often as you update position.</p> <p>Or, once a fish fails to see a shark, it's doomed, so you can add that list to a list of sharks it's seen and failed to avoid (in case it sees another shark), then when you update you can just go through the list saying that in order to change direction, a fish must beat the random number generator and also not have lost to the shark already</p> <p>You could try a different random distribution, maybe something that skews left, so even if a dumb fish had multiple tries, the combined probability would still be low</p> <p>Then again, if you're trying to simulate "real" fish, some might be slower to react, but they still get multiple chances.</p> <p>Maybe you could shorten the arc?</p>
1
2016-08-14T10:09:19Z
[ "python", "pygame", "sprite", "collision", "detection" ]
how to scrapy from a table with multi td nested tags
38,940,281
<p>I have scrapy the data from this page (<a href="http://www.itjuzi.com/company/934" rel="nofollow">http://www.itjuzi.com/company/934</a>), but what I want to get is a list with children td tags,and a list with parent td tags.</p> <p>the code is below:</p> <pre><code>response.xpath("//table[@class='list-round-v2']//tr/td[4]//text()").extract() </code></pre> <p>and the result I want just like below:</p> <pre><code>[["骊悦投资","长山兴资本"], ["中信产业基金","高瓴资本Hillhouse Capital","IDG资本","北极光创投","DCM中国"]] </code></pre> <p><a href="http://i.stack.imgur.com/5CNqJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/5CNqJ.png" alt="enter image description here"></a></p>
0
2016-08-14T07:57:27Z
38,942,195
<p>This will do the job</p> <pre><code>textlist=[] for row in response.xpath("//table[contains(@class,'list-round-v2')]//tr"): textlist.append(row.xpath("td[4]//text()[parent::a|parent::span]").extract()) </code></pre>
1
2016-08-14T12:19:55Z
[ "python", "xpath", "scrapy" ]
Python how to output characters as raw text
38,940,331
<p>Whenever I try to get the unicode number from a string that has "\xff" in it I get an error.</p> <pre><code>test = ord(str(tmp1)) TypeError: ord() expected a character, but string of length 4 found </code></pre> <p>How can I avoid this?</p> <p>Edit - The output of <code>print(repr(tmp1))</code> is <code>'\\xff'</code></p> <p>Edit - Is there anyway you can find the byte version of a character? eg 255 -> \xff instead of getting ÿ</p>
0
2016-08-14T08:04:45Z
38,940,455
<p>you have to encode your text</p> <pre><code>test = ord(tmp1.encode('utf-16')) </code></pre> <p>this way you can avoid this error.</p>
0
2016-08-14T08:25:33Z
[ "python", "python-3.x" ]
How do I use multiple images with the same sprite on pygame?
38,940,383
<p>Im learning how to use pygame and I'm trying to use multiple images with the same sprite. I want the sprites image to change when i press a button on my keyboard. Whenever i press the right arrow key and attempt to change the sprites image I get the error: </p> <pre><code>Traceback (most recent call last): File "C:\Users\theotheo36\workspace\NomadsPie\main.py", line 55, in &lt;module&gt; game.execute() File "C:\Users\theotheo36\workspace\NomadsPie\main.py", line 50, in execute self.render() File "C:\Users\theotheo36\workspace\NomadsPie\main.py", line 32, in render self.all.draw(self.screen) File "C:\Users\theotheo36\Downloads\WinPython-64bit-3.4.4.3Qt5\python-3.4.4.amd64\lib\site-packages\pygame\sprite.py", line 475, in draw self.spritedict[spr] = surface_blit(spr.image, spr.rect) TypeError: invalid destination position for blit </code></pre> <p>Here is my code:</p> <pre><code>import pygame from pygame.locals import * class Camel(pygame.sprite.Sprite): def __init__(self,x,y): super().__init__() self.faceleft=True self.faceright=False self.image=pygame.image.load('camel.png').convert() self.rect=self.image.get_rect() self.rect.x=x self.rect.y=y def look(self): if self.faceleft==True: self.image=pygame.image.load('camel.png').convert() self.rect=self.image.get_rect() elif self.faceright==True: self.image=pygame.image.load('camelright.png').convert() self.rect=self.image.get_rect class Game(Camel): def __init__(self): pygame.init() self.screen=pygame.display.set_mode((800,800)) self.all=pygame.sprite.Group() self.camel=Camel(200,200) self.all.add(self.camel) self.running=True def render(self): self.screen.fill((255,255,255)) self.all.draw(self.screen) pygame.display.update() def events(self,event): if event.type==pygame.QUIT: self.running=False if event.type==KEYDOWN: if event.key==K_RIGHT: self.camel.faceleft=False self.camel.faceright=True self.camel.look() if event.key==K_LEFT: self.camel.faceright=False self.camel.faceleft=True self.camel.look() def collisons(self): pass def execute(self): while (self.running): self.render() for event in pygame.event.get(): self.events(event) game=Game() game.execute() </code></pre>
0
2016-08-14T08:12:36Z
38,943,807
<p>Don't forget the parentheses after <code>self.rect=self.image.get_rect</code> in your <code>look</code> method. Without parenthesis <code>self.rect</code> is assigned to the function instead of the returned rectangle. Since this rectangle is used to draw the image it will cause this position error.</p>
0
2016-08-14T15:40:40Z
[ "python", "pygame", "sprite" ]
Processing a list whilst using threading
38,940,385
<p>My code has a loop which checks a list and if there are items in the list it will process them and remove them from the list. The items are continuously inserted into the list by another thread.</p> <p>Here is the code: </p> <pre><code>while True: for item in list: Process(item) Remove(item) </code></pre> <p><strong>Problem 1:</strong> </p> <p>What I have above works but the problem is that it is very intensive on the cpu.<br> I can put something like 'time.sleep' in the code but this program needs to process the items in the list immediately without any delay. How do I make it less intensive on the cpu (remember that I am concurrently running another thread).</p> <p><strong>Problem 2</strong>: </p> <p>I want to stop the loop from running when the list is empty and continue to process when something is added to the list. How do I go about doing this?</p>
0
2016-08-14T08:13:00Z
38,940,450
<p>It seems that the <a href="https://docs.python.org/3.5/library/queue.html?highlight=queue#module-queue" rel="nofollow">queue</a> module will be useful for you. It implements multi-producer, multi-consumer queues and allows synchronize between threads without busy waiting.</p> <p>see also <a href="http://www.napuzba.com/story/producer-consumer-python/" rel="nofollow">Solution to producer and consumer problem in python</a> which uses this <code>queue</code> module. </p>
1
2016-08-14T08:24:42Z
[ "python", "multithreading", "loops", "signals", "cpu" ]
tkMessageBox Crashes Python Application Upon Running (Resolved)
38,940,423
<p>Here is the code</p> <pre><code>import Tkinter import tkMessageBox def created(): tkMessageBox.showinfo('File Created!', 'Letter.html Created on Desktop') class simpleapp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.grid() --- Everything Fine Here --- self.B = Tkinter.Button(self, text = 'Create Document', command = self.OnButtonClick) self.B.grid(column = 0, row = 6) def OnButtonClick(self): created() if __name__ == "__main__": app = simpleapp_tk(None) app.title('Receipt Form') app.iconbitmap(os.getcwd() + '/M.tiff') app.mainloop() </code></pre> <p>I use py2app to create a standalone application with this, but when I run it and press the button, it seems to crash. </p> <p>I am very certain it is tkMessageBox that is causing the problem but the message box works perfectly fine in IDLE.</p> <p>It also worked fine on my windows 10 computer with pyinstaller.</p> <p><strong>EDIT</strong>: Problem seemed to fix itself</p>
0
2016-08-14T08:19:21Z
38,941,330
<p>py2exe is windows version of py2app.</p> <p>first of all to build we need a setup file like this:</p> <p><strong>[setup.py]</strong></p> <pre><code>from distutils.core import setup import py2exe #in your case import py2app setup(console=['myFile.py']) </code></pre> <p>on running this file using <strong>python setup.py py2exe</strong> :</p> <p>it will call setup and tell it that we want a single console application and the main entry point is "<strong>myFile.py</strong>".</p> <p>On complete build, two directories are created . Look into the dist directory and run your app.</p> <p>It is working completely fine.</p> <p>No errors</p> <p>PS - make sure path to your icon is correct</p> <p><a href="http://i.stack.imgur.com/kZjKm.png" rel="nofollow">output screenshot here</a></p>
0
2016-08-14T10:29:04Z
[ "python", "osx", "python-2.7", "tkinter", "tkmessagebox" ]
Killing child processes, and getting child processes pid without psutil or subprocess
38,940,429
<p>I'm encountering a lot of problems with this, I want to kill all my child processes without destroying my own process OR kill all the processes of some group OR get all the child processes PID... and all of this WITHOUT using either <code>subprocess</code> or <code>psutil</code> library in python anyone has any idea how</p>
0
2016-08-14T08:20:43Z
38,940,705
<p>If you really cannot access those libraries, you can use <code>os</code> if push comes to shove.<br> For example:</p> <pre><code>my_pid = os.popen('ps --no-headers -C name_of_process').read(5) if my_pid != "": my_pid = int(my_pid) os.kill(my_pid, signal.SIGTERM) </code></pre> <p>'name_of_process' would be the name of your executable<br> You might also want to look further at the commands <code>ps</code> and <code>pkill</code>.<br> Note: I am assuming you are using a Linux OS </p>
0
2016-08-14T09:05:36Z
[ "python", "linux", "process", "pid" ]
Filter ForeignKey in django admin panel
38,940,438
<p>I'll start from showing how my model look:</p> <pre><code>from django.db import models class Project(models.Model): #..... pu = models.ForeignKey('Person', default='', related_name='pu') se = models.ForeignKey('Person', default='', related_name='se') class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) department = models.ForeignKey('Department', default='') class Department(models.Model): abbreviation = models.CharField(default='', max_length=3) full_name = models.CharField(default='', max_length=20) </code></pre> <p>I want to keep all persons in one table but in my admin panel I want to show two separated filtered lists:</p> <ul> <li>for pu I want to show only Persons which abbreviation of Department is 'pu'</li> <li>for se I want to show only Persons which abbreviation of Department is 'se'</li> </ul> <p>I searched a lot but I'm very new to django and Python. </p> <p>How can I achieve it?</p>
0
2016-08-14T08:22:40Z
38,982,948
<p>django admin work arounds are usually possible, with a bit of hacking.</p> <p>Try creating a myapp/admin.py file</p> <pre><code>from django.contrib import admin from .models import Project, Person class ProjectAdmin(admin.ModelAdmin): ... filter_horizontal = ('pu', 'se') def get_form(self, request, obj=None, **kwargs): form = super(ProjectAdmin, self).get_form(request, obj, **kwargs) if obj: form.base_fields['pu'].queryset = Person.objects.filter(department__abbreviation__startswith='pu') form.base_fields['se'].queryset = Person.objects.filter(department__abbreviation__startswith='se') return form admin.site.register(Project, ProjectAdmin) # register it </code></pre>
0
2016-08-16T19:25:41Z
[ "python", "django" ]
Filter ForeignKey in django admin panel
38,940,438
<p>I'll start from showing how my model look:</p> <pre><code>from django.db import models class Project(models.Model): #..... pu = models.ForeignKey('Person', default='', related_name='pu') se = models.ForeignKey('Person', default='', related_name='se') class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) department = models.ForeignKey('Department', default='') class Department(models.Model): abbreviation = models.CharField(default='', max_length=3) full_name = models.CharField(default='', max_length=20) </code></pre> <p>I want to keep all persons in one table but in my admin panel I want to show two separated filtered lists:</p> <ul> <li>for pu I want to show only Persons which abbreviation of Department is 'pu'</li> <li>for se I want to show only Persons which abbreviation of Department is 'se'</li> </ul> <p>I searched a lot but I'm very new to django and Python. </p> <p>How can I achieve it?</p>
0
2016-08-14T08:22:40Z
39,062,517
<p>I've changed my model. I won't use Person and Department, I've switched to django's User and Group.</p> <p>To filter it as I needed i used <code>limit_choices_to</code>.</p> <pre><code>pu = models.ForeignKey("auth.User", related_name='pu', limit_choices_to={'groups__name': "Purchasing"}) se = models.ForeignKey("auth.User", related_name='se', limit_choices_to={'groups__name': "Sales"}) </code></pre> <p>I based on this answer: <a href="http://stackoverflow.com/questions/11118179/django-filter-users-by-group-in-a-model-foreign-key">Django, filter users by group in a model foreign key</a></p>
0
2016-08-21T08:56:03Z
[ "python", "django" ]
TemplateSyntaxError in Django at /admin/login (default requires 2 arguments, 1 provided)
38,940,457
<p>I looked thoroughly into my files and I could not find one error. Staring and reading my files for 45 minutes was a pain. I now need someone's help, I can't do this</p> <p>this is the path of the app: </p> <pre><code>website music project1 #this is the main folder that includes settings.py db.sqlite3 manage.py </code></pre> <p><strong>urls.py from project1 (main) folder:</strong></p> <pre><code>from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^music/', include('music.urls')), ] </code></pre> <p><strong>urls.py from music folder</strong>:</p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] </code></pre> <p><strong>admin.py in music folder:</strong></p> <pre><code>from django.contrib import admin # Register your models here. </code></pre> <p><strong>apps.py in music.py</strong></p> <pre><code>from __future__ import unicode_literals from django.apps import AppConfig class MusicConfig(AppConfig): name = 'music' </code></pre> <p><strong>And here is the error page im getting when I enter <a href="http://127.0.0.1:8000/admin" rel="nofollow">http://127.0.0.1:8000/admin</a></strong></p> <pre><code> TemplateSyntaxError at /admin/login/ default requires 2 arguments, 1 provided Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 1.10 Exception Type: TemplateSyntaxError Exception Value: default requires 2 arguments, 1 provided Exception Location: C:\Python27\lib\site-packages\django\template\base.py in parse, line 518 Python Executable: C:\Python27\python.exe Python Version: 2.7.12 Python Path: ['C:\\Users\\Chris (Local acc)\\desktop\\website', 'C:\\Windows\\SYSTEM32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages', 'C:\\Python27\\lib\\site-packages\\setuptools-25.1.6-py2.7.egg'] Server time: Sun, 14 Aug 2016 01:01:19 -0700 Error during template rendering In template C:\Python27\lib\site-packages\django\contrib\admin\templates\admin\base_site.html, error at line 6 default requires 2 arguments, 1 provided 1 {% extends "admin/base.html" %} 2 3 {% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} 4 5 {% block branding %} 6 &lt;h1 id="site-name"&gt;&lt;a href="{% url 'admin:index' %}"&gt;{{ site_header|default:('Kweli's webby') }}&lt;/a&gt;&lt;/h1&gt; 7 {% endblock %} 8 9 {% block nav-global %}{% endblock %} 10 Traceback Switch to copy-and-paste view C:\Python27\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) ... ▶ Local vars C:\Python27\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars C:\Python27\lib\site-packages\django\core\handlers\base.py in _get_response response = response.render() ... ▶ Local vars C:\Python27\lib\site-packages\django\template\response.py in render self.content = self.rendered_content ... ▶ Local vars C:\Python27\lib\site-packages\django\template\response.py in rendered_content content = template.render(context, self._request) ... ▶ Local vars C:\Python27\lib\site-packages\django\template\backends\django.py in render return self.template.render(context) ... ▶ Local vars C:\Python27\lib\site-packages\django\template\base.py in render return self._render(context) ... ▶ Local vars C:\Python27\lib\site-packages\django\template\base.py in _render return self.nodelist.render(context) ... ▶ Local vars C:\Python27\lib\site-packages\django\template\base.py in render bit = node.render_annotated(context) ... ▶ Local vars C:\Python27\lib\site-packages\django\template\base.py in render_annotated return self.render(context) ... ▶ Local vars C:\Python27\lib\site-packages\django\template\loader_tags.py in render compiled_parent = self.get_parent(context) ... ▶ Local vars C:\Python27\lib\site-packages\django\template\loader_tags.py in get_parent return self.find_template(parent, context) ... ▶ Local vars C:\Python27\lib\site-packages\django\template\loader_tags.py in find_template template_name, skip=history, ... ▶ Local vars C:\Python27\lib\site-packages\django\template\engine.py in find_template name, template_dirs=dirs, skip=skip, ... ▶ Local vars C:\Python27\lib\site-packages\django\template\loaders\base.py in get_template contents, origin, origin.template_name, self.engine, ... ▶ Local vars C:\Python27\lib\site-packages\django\template\base.py in __init__ self.nodelist = self.compile_nodelist() ... ▶ Local vars C:\Python27\lib\site-packages\django\template\base.py in compile_nodelist return parser.parse() ... ▶ Local vars C:\Python27\lib\site-packages\django\template\base.py in parse raise self.error(token, e) ... ▶ Local vars Request information USER AnonymousUser GET Variable Value next u'/admin/' POST No POST data FILES No FILES data COOKIES Variable Value csrftoken 'ttgNoBhEHMAfCPizp52kDZOIaa0xx93eZa84BfRiJkBsT1GWcQXRhzAHumyJHBIM' META Variable Value ALLUSERSPROFILE 'C:\\ProgramData' APPDATA 'C:\\Users\\Chris (Local acc)\\AppData\\Roaming' COMMONPROGRAMFILES 'C:\\Program Files\\Common Files' COMMONPROGRAMFILES(X86) 'C:\\Program Files (x86)\\Common Files' COMMONPROGRAMW6432 'C:\\Program Files\\Common Files' COMPUTERNAME 'CHRIS' COMSPEC 'C:\\Windows\\system32\\cmd.exe' CONTENT_LENGTH '' CONTENT_TYPE 'text/plain' CSRF_COOKIE 'ttgNoBhEHMAfCPizp52kDZOIaa0xx93eZa84BfRiJkBsT1GWcQXRhzAHumyJHBIM' DJANGO_SETTINGS_MODULE 'project1.settings' FP_NO_HOST_CHECK 'NO' GATEWAY_INTERFACE 'CGI/1.1' HOMEDRIVE 'C:' HOMEPATH '\\Users\\Chris (Local acc)' HTTP_ACCEPT 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' HTTP_ACCEPT_ENCODING 'gzip, deflate, sdch' HTTP_ACCEPT_LANGUAGE 'en-US,en;q=0.8' HTTP_CONNECTION 'keep-alive' HTTP_COOKIE 'csrftoken=ttgNoBhEHMAfCPizp52kDZOIaa0xx93eZa84BfRiJkBsT1GWcQXRhzAHumyJHBIM' HTTP_HOST '127.0.0.1:8000' HTTP_UPGRADE_INSECURE_REQUESTS '1' HTTP_USER_AGENT 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36' LOCALAPPDATA 'C:\\Users\\Chris (Local acc)\\AppData\\Local' LOGONSERVER '\\\\MicrosoftAccount' NUMBER_OF_PROCESSORS '8' OS 'Windows_NT' PATH 'C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files (x86)\\ATI Technologies\\ATI.ACE\\Core-Static;C:\\Windows\\system32\\config\\systemprofile\\.dnx\\bin;C:\\Python27;C:\\Python27\\Lib;C:\\Users\\Chris (Local acc)\\stuff\\;C:\\Python27\\Scripts\\;' PATHEXT '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL' PATH_INFO u'/admin/login/' PROCESSOR_ARCHITECTURE 'AMD64' PROCESSOR_IDENTIFIER 'AMD64 Family 21 Model 2 Stepping 0, AuthenticAMD' PROCESSOR_LEVEL '21' PROCESSOR_REVISION '0200' PROGRAMDATA 'C:\\ProgramData' PROGRAMFILES 'C:\\Program Files' PROGRAMFILES(X86) 'C:\\Program Files (x86)' PROGRAMW6432 'C:\\Program Files' PSMODULEPATH 'C:\\Users\\Chris (Local acc)\\Documents\\WindowsPowerShell\\Modules;C:\\Program Files\\WindowsPowerShell\\Modules;C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules\\' PUBLIC 'C:\\Users\\Public' QUERY_STRING 'next=/admin/' REMOTE_ADDR '127.0.0.1' REMOTE_HOST '' REQUEST_METHOD 'GET' RUN_MAIN 'true' SCRIPT_NAME u'' SERVER_NAME 'activate.adobe.com' SERVER_PORT '8000' SERVER_PROTOCOL 'HTTP/1.1' SERVER_SOFTWARE 'WSGIServer/0.1 Python/2.7.12' SESSIONNAME 'Console' SYSTEMDRIVE 'C:' SYSTEMROOT 'C:\\Windows' TEMP 'C:\\Users\\CHRIS(~1\\AppData\\Local\\Temp' TMP 'C:\\Users\\CHRIS(~1\\AppData\\Local\\Temp' USERDOMAIN 'CHRIS' USERDOMAIN_ROAMINGPROFILE 'CHRIS' USERNAME 'Chris (Local acc)' USERPROFILE 'C:\\Users\\Chris (Local acc)' VS140COMNTOOLS 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\Tools\\' WINDIR 'C:\\Windows' wsgi.errors &lt;open file '&lt;stderr&gt;', mode 'w' at 0x000000000244B150&gt; wsgi.file_wrapper '' wsgi.input &lt;socket._fileobject object at 0x0000000004033480&gt; wsgi.multiprocess False wsgi.multithread True wsgi.run_once False wsgi.url_scheme 'http' wsgi.version (1, 0) Settings Using settings module project1.settings Setting Value ABSOLUTE_URL_OVERRIDES {} ADMINS [] ALLOWED_HOSTS [] APPEND_SLASH True AUTHENTICATION_BACKENDS [u'django.contrib.auth.backends.ModelBackend'] AUTH_PASSWORD_VALIDATORS u'********************' AUTH_USER_MODEL u'auth.User' BASE_DIR 'C:\\Users\\Chris (Local acc)\\desktop\\website' CACHES {u'default': {u'BACKEND': u'django.core.cache.backends.locmem.LocMemCache'}} CACHE_MIDDLEWARE_ALIAS u'default' CACHE_MIDDLEWARE_KEY_PREFIX u'********************' CACHE_MIDDLEWARE_SECONDS 600 CSRF_COOKIE_AGE 31449600 CSRF_COOKIE_DOMAIN None CSRF_COOKIE_HTTPONLY False CSRF_COOKIE_NAME u'csrftoken' CSRF_COOKIE_PATH u'/' CSRF_COOKIE_SECURE False CSRF_FAILURE_VIEW u'django.views.csrf.csrf_failure' CSRF_HEADER_NAME u'HTTP_X_CSRFTOKEN' CSRF_TRUSTED_ORIGINS [] DATABASES {'default': {'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'ENGINE': 'django.db.backends.sqlite3', 'HOST': '', 'NAME': 'C:\\Users\\Chris (Local acc)\\desktop\\website\\db.sqlite3', 'OPTIONS': {}, 'PASSWORD': u'********************', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIRROR': None, 'NAME': None}, 'TIME_ZONE': None, 'USER': ''}} DATABASE_ROUTERS [] DATA_UPLOAD_MAX_MEMORY_SIZE 2621440 DATA_UPLOAD_MAX_NUMBER_FIELDS 1000 DATETIME_FORMAT u'N j, Y, P' DATETIME_INPUT_FORMATS [u'%Y-%m-%d %H:%M:%S', u'%Y-%m-%d %H:%M:%S.%f', u'%Y-%m-%d %H:%M', u'%Y-%m-%d', u'%m/%d/%Y %H:%M:%S', u'%m/%d/%Y %H:%M:%S.%f', u'%m/%d/%Y %H:%M', u'%m/%d/%Y', u'%m/%d/%y %H:%M:%S', u'%m/%d/%y %H:%M:%S.%f', u'%m/%d/%y %H:%M', u'%m/%d/%y'] DATE_FORMAT u'N j, Y' DATE_INPUT_FORMATS [u'%Y-%m-%d', u'%m/%d/%Y', u'%m/%d/%y', u'%b %d %Y', u'%b %d, %Y', u'%d %b %Y', u'%d %b, %Y', u'%B %d %Y', u'%B %d, %Y', u'%d %B %Y', u'%d %B, %Y'] DEBUG True DEBUG_PROPAGATE_EXCEPTIONS False DECIMAL_SEPARATOR u'.' DEFAULT_CHARSET u'utf-8' DEFAULT_CONTENT_TYPE u'text/html' DEFAULT_EXCEPTION_REPORTER_FILTER u'django.views.debug.SafeExceptionReporterFilter' DEFAULT_FILE_STORAGE u'django.core.files.storage.FileSystemStorage' DEFAULT_FROM_EMAIL u'webmaster@localhost' DEFAULT_INDEX_TABLESPACE u'' DEFAULT_TABLESPACE u'' DISALLOWED_USER_AGENTS [] EMAIL_BACKEND u'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST u'localhost' EMAIL_HOST_PASSWORD u'********************' EMAIL_HOST_USER u'' EMAIL_PORT 25 EMAIL_SSL_CERTFILE None EMAIL_SSL_KEYFILE u'********************' EMAIL_SUBJECT_PREFIX u'[Django] ' EMAIL_TIMEOUT None EMAIL_USE_SSL False EMAIL_USE_TLS False FILE_CHARSET u'utf-8' FILE_UPLOAD_DIRECTORY_PERMISSIONS None FILE_UPLOAD_HANDLERS [u'django.core.files.uploadhandler.MemoryFileUploadHandler', u'django.core.files.uploadhandler.TemporaryFileUploadHandler'] FILE_UPLOAD_MAX_MEMORY_SIZE 2621440 FILE_UPLOAD_PERMISSIONS None FILE_UPLOAD_TEMP_DIR None FIRST_DAY_OF_WEEK 0 FIXTURE_DIRS [] FORCE_SCRIPT_NAME None FORMAT_MODULE_PATH None IGNORABLE_404_URLS [] INSTALLED_APPS ['music.apps.MusicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] INTERNAL_IPS [] LANGUAGES [(u'af', u'Afrikaans'), (u'ar', u'Arabic'), (u'ast', u'Asturian'), (u'az', u'Azerbaijani'), (u'bg', u'Bulgarian'), (u'be', u'Belarusian'), (u'bn', u'Bengali'), (u'br', u'Breton'), (u'bs', u'Bosnian'), (u'ca', u'Catalan'), (u'cs', u'Czech'), (u'cy', u'Welsh'), (u'da', u'Danish'), (u'de', u'German'), (u'dsb', u'Lower Sorbian'), (u'el', u'Greek'), (u'en', u'English'), (u'en-au', u'Australian English'), (u'en-gb', u'British English'), (u'eo', u'Esperanto'), (u'es', u'Spanish'), (u'es-ar', u'Argentinian Spanish'), (u'es-co', u'Colombian Spanish'), (u'es-mx', u'Mexican Spanish'), (u'es-ni', u'Nicaraguan Spanish'), (u'es-ve', u'Venezuelan Spanish'), (u'et', u'Estonian'), (u'eu', u'Basque'), (u'fa', u'Persian'), (u'fi', u'Finnish'), (u'fr', u'French'), (u'fy', u'Frisian'), (u'ga', u'Irish'), (u'gd', u'Scottish Gaelic'), (u'gl', u'Galician'), (u'he', u'Hebrew'), (u'hi', u'Hindi'), (u'hr', u'Croatian'), (u'hsb', u'Upper Sorbian'), (u'hu', u'Hungarian'), (u'ia', u'Interlingua'), (u'id', u'Indonesian'), (u'io', u'Ido'), (u'is', u'Icelandic'), (u'it', u'Italian'), (u'ja', u'Japanese'), (u'ka', u'Georgian'), (u'kk', u'Kazakh'), (u'km', u'Khmer'), (u'kn', u'Kannada'), (u'ko', u'Korean'), (u'lb', u'Luxembourgish'), (u'lt', u'Lithuanian'), (u'lv', u'Latvian'), (u'mk', u'Macedonian'), (u'ml', u'Malayalam'), (u'mn', u'Mongolian'), (u'mr', u'Marathi'), (u'my', u'Burmese'), (u'nb', u'Norwegian Bokm\xe5l'), (u'ne', u'Nepali'), (u'nl', u'Dutch'), (u'nn', u'Norwegian Nynorsk'), (u'os', u'Ossetic'), (u'pa', u'Punjabi'), (u'pl', u'Polish'), (u'pt', u'Portuguese'), (u'pt-br', u'Brazilian Portuguese'), (u'ro', u'Romanian'), (u'ru', u'Russian'), (u'sk', u'Slovak'), (u'sl', u'Slovenian'), (u'sq', u'Albanian'), (u'sr', u'Serbian'), (u'sr-latn', u'Serbian Latin'), (u'sv', u'Swedish'), (u'sw', u'Swahili'), (u'ta', u'Tamil'), (u'te', u'Telugu'), (u'th', u'Thai'), (u'tr', u'Turkish'), (u'tt', u'Tatar'), (u'udm', u'Udmurt'), (u'uk', u'Ukrainian'), (u'ur', u'Urdu'), (u'vi', u'Vietnamese'), (u'zh-hans', u'Simplified Chinese'), (u'zh-hant', u'Traditional Chinese')] LANGUAGES_BIDI [u'he', u'ar', u'fa', u'ur'] LANGUAGE_CODE 'en-us' LANGUAGE_COOKIE_AGE None LANGUAGE_COOKIE_DOMAIN None LANGUAGE_COOKIE_NAME u'django_language' LANGUAGE_COOKIE_PATH u'/' LOCALE_PATHS [] LOGGING {} LOGGING_CONFIG u'logging.config.dictConfig' LOGIN_REDIRECT_URL u'/accounts/profile/' LOGIN_URL u'/accounts/login/' LOGOUT_REDIRECT_URL None MANAGERS [] MEDIA_ROOT u'' MEDIA_URL u'' MESSAGE_STORAGE u'django.contrib.messages.storage.fallback.FallbackStorage' MIDDLEWARE ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] MIDDLEWARE_CLASSES [u'django.middleware.common.CommonMiddleware', u'django.middleware.csrf.CsrfViewMiddleware'] MIGRATION_MODULES {} MONTH_DAY_FORMAT u'F j' NUMBER_GROUPING 0 PASSWORD_HASHERS u'********************' PASSWORD_RESET_TIMEOUT_DAYS u'********************' PREPEND_WWW False ROOT_URLCONF 'project1.urls' SECRET_KEY u'********************' SECURE_BROWSER_XSS_FILTER False SECURE_CONTENT_TYPE_NOSNIFF False SECURE_HSTS_INCLUDE_SUBDOMAINS False SECURE_HSTS_SECONDS 0 SECURE_PROXY_SSL_HEADER None SECURE_REDIRECT_EXEMPT [] SECURE_SSL_HOST None SECURE_SSL_REDIRECT False SERVER_EMAIL u'root@localhost' SESSION_CACHE_ALIAS u'default' SESSION_COOKIE_AGE 1209600 SESSION_COOKIE_DOMAIN None SESSION_COOKIE_HTTPONLY True SESSION_COOKIE_NAME u'sessionid' SESSION_COOKIE_PATH u'/' SESSION_COOKIE_SECURE False SESSION_ENGINE u'django.contrib.sessions.backends.db' SESSION_EXPIRE_AT_BROWSER_CLOSE False SESSION_FILE_PATH None SESSION_SAVE_EVERY_REQUEST False SESSION_SERIALIZER u'django.contrib.sessions.serializers.JSONSerializer' SETTINGS_MODULE 'project1.settings' SHORT_DATETIME_FORMAT u'm/d/Y P' SHORT_DATE_FORMAT u'm/d/Y' SIGNING_BACKEND u'django.core.signing.TimestampSigner' SILENCED_SYSTEM_CHECKS [] STATICFILES_DIRS [] STATICFILES_FINDERS [u'django.contrib.staticfiles.finders.FileSystemFinder', u'django.contrib.staticfiles.finders.AppDirectoriesFinder'] STATICFILES_STORAGE u'django.contrib.staticfiles.storage.StaticFilesStorage' STATIC_ROOT None STATIC_URL '/static/' TEMPLATES [{'APP_DIRS': True, 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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']}}] TEST_NON_SERIALIZED_APPS [] TEST_RUNNER u'django.test.runner.DiscoverRunner' THOUSAND_SEPARATOR u',' TIME_FORMAT u'P' TIME_INPUT_FORMATS [u'%H:%M:%S', u'%H:%M:%S.%f', u'%H:%M'] TIME_ZONE 'UTC' USE_ETAGS False USE_I18N True USE_L10N True USE_THOUSAND_SEPARATOR False USE_TZ True USE_X_FORWARDED_HOST False USE_X_FORWARDED_PORT False WSGI_APPLICATION 'project1.wsgi.application' X_FRAME_OPTIONS u'SAMEORIGIN' YEAR_MONTH_FORMAT u'F Y' </code></pre> <p>Please help, thanks!</p>
-1
2016-08-14T08:25:44Z
38,941,084
<p>Your login template has a syntax error as you did not escape the apostrophe (<code>'</code>) in your string literal. Change the following</p> <pre><code>{{ site_header|default:('Kweli's webby') }} </code></pre> <p>to</p> <pre><code>{{ site_header|default:_("Kweli's webby") }} </code></pre> <p>Also note the underscore (<code>_</code>) before the string argument which is used for localization. If you don't need multiple languages, you can get rid of parantheses and simply write</p> <pre><code>{{ site_header|default:"Kweli's webby" }} </code></pre>
1
2016-08-14T09:56:20Z
[ "python", "django", "get", "admin" ]
Add our own mapping of magic methods
38,940,497
<p>Recently I was reading about magic methods in Python, which make the code a lot easier to read. Can we define our own mappings? If so, is there any pointer for this and how complicated it would be?</p> <p>For example, <code>+</code> is always mapped to <code>__add__</code>. Could I define a mapping for <code>?</code>, which would call <code>__is_valid__</code> in my class?</p> <pre><code>c = Car() print(c?) # invokes __is_valid__ of Car to get the result </code></pre>
0
2016-08-14T08:32:22Z
38,940,516
<p>You seem to be asking if you can create your own syntax in Python, adding new symbols that are implemented via magic methods. The answer is no. The only operators available are the ones that already exist (<code>+</code>, <code>*</code>, etc.), and each has its corresponding magic methods. You can't add new ones.</p>
0
2016-08-14T08:34:13Z
[ "python", "magic-methods" ]
Converting a list of datetime objects to a list of number of days since a certain date
38,940,665
<p>I have a large list of dates that are datetime objects like for example</p> <pre><code>[datetime.datetime(2016,8,14),datetime.datetime(2016,8,13),datetime.datetime(2016,8,12),....etc.] </code></pre> <p>Instead of datetime objects of the date what I want instead is a list of numerical integer values since the date <strong>1/1/1900</strong>. I have defined 1/1/1900 as the base date and in the <em>for</em> loop below, I have calculated the days between the date in the list since that base date:</p> <pre><code>baseDate = datetime(1900,1,1) numericalDates = [] for i in enumerate(dates): a=i[1]-baseDate numericalDates.append(a) print(numericalDates) </code></pre> <p>However when I print this out, I get <em>datetime.timedelta</em> objects instead</p> <pre><code>[datetime.timedelta(42592), datetime.timedelta(42591), datetime.timedelta(42590),...etc.] </code></pre> <p>Any ideas on how I can convert it the proper way?</p>
2
2016-08-14T09:00:35Z
38,940,696
<p><code>timedelta</code> objects have <code>days</code> attribute, so you can simply append that as an <code>int</code>:</p> <pre><code>numericalDates.append(a.days) </code></pre> <p>will result with <code>numericalDates</code> being <code>[42594, 42593, 42592]</code>.</p> <p>Note that you can also simplify your code a bit by using list comprehension:</p> <pre><code>numericalDates = [(d - baseDate).days for d in dates] </code></pre>
3
2016-08-14T09:04:28Z
[ "python", "datetime", "python-datetime" ]
How can I get column name and type from an existing table in SQLAlchemy?
38,940,682
<p>Suppose I have the table <code>users</code> and I want to know what the column names are and what the types are for each column.</p> <p>I connect like this; </p> <pre><code>connectstring = ('mssql+pyodbc:///?odbc_connect=DRIVER%3D%7BSQL' '+Server%7D%3B+server%3D.....') engine = sqlalchemy.create_engine(connectstring).connect() md = sqlalchemy.MetaData() table = sqlalchemy.Table('users', md, autoload=True, autoload_with=engine) columns = table.c </code></pre> <p>If I call </p> <pre><code>for c in columns: print type(columns) </code></pre> <p>I get the output</p> <pre><code>&lt;class 'sqlalchemy.sql.base.ImmutableColumnCollection'&gt; </code></pre> <p>printed once for each column in the table. Furthermore, </p> <pre><code>print columns </code></pre> <p>prints </p> <pre><code>['users.column_name_1', 'users.column_name_2', 'users.column_name_3'....] </code></pre> <p>Is it possible to get the column names without the table name being included? </p>
0
2016-08-14T09:02:48Z
38,940,923
<p>You could call the column names from the Information Schema:</p> <p>SELECT * FROM information_schema.columns WHERE TABLE_NAME = 'users'</p> <p>Then sort the result as an array, and loop through them.</p>
0
2016-08-14T09:35:26Z
[ "python", "sql", "sql-server-2008", "orm", "sqlalchemy" ]
How can I get column name and type from an existing table in SQLAlchemy?
38,940,682
<p>Suppose I have the table <code>users</code> and I want to know what the column names are and what the types are for each column.</p> <p>I connect like this; </p> <pre><code>connectstring = ('mssql+pyodbc:///?odbc_connect=DRIVER%3D%7BSQL' '+Server%7D%3B+server%3D.....') engine = sqlalchemy.create_engine(connectstring).connect() md = sqlalchemy.MetaData() table = sqlalchemy.Table('users', md, autoload=True, autoload_with=engine) columns = table.c </code></pre> <p>If I call </p> <pre><code>for c in columns: print type(columns) </code></pre> <p>I get the output</p> <pre><code>&lt;class 'sqlalchemy.sql.base.ImmutableColumnCollection'&gt; </code></pre> <p>printed once for each column in the table. Furthermore, </p> <pre><code>print columns </code></pre> <p>prints </p> <pre><code>['users.column_name_1', 'users.column_name_2', 'users.column_name_3'....] </code></pre> <p>Is it possible to get the column names without the table name being included? </p>
0
2016-08-14T09:02:48Z
38,940,927
<p>columns have <code>name</code> and <code>type</code> attributes</p> <pre><code>for c in columns: print c.name, c.type </code></pre>
0
2016-08-14T09:35:56Z
[ "python", "sql", "sql-server-2008", "orm", "sqlalchemy" ]
Some questions about switches in python
38,940,826
<p>This is my first Question here at StackOverflow, so please be patient with me if some info isn't present or I missed something important, but anyways i'll do my best :)</p> <p>Recently I started to code in Python2.7, so I'm not very good at it. While playing with PyGtk, PyGObject, Glade, etc I found something particular about switches (Haven't tried with any other widget, so I don't know if it happens somewhere else. Most likely it doesn't, I hope...)</p> <p>I made a very basic GUI with a single "window" plus a "switch" using Glade</p> <p>My objective was to deactivate switch after user tried to activate it if some exeption raised up before, something like:</p> <ul> <li>Activate it --> * Found error --> * Deactivate it</li> </ul> <p>I made some code, and after a while, I noted that THIS piece of code created a loop-like block, blocking GUI's window afterwards:</p> <pre><code>builder = Gtk.Builder() window1 = builder.get_object('window') switchie = builder.get_object('switchie') switchie.set_active(False) def Hi(switch, active): print switchie.get_active() switchie.set_active(not switchie.get_active()) switchie.connect("""notify::active""", Hi) window1.set_position(Gtk.WindowPosition.CENTER) window1.connect("delete-event", Gtk.main_quit) window1.show_all() </code></pre> <p>If i'm right, "switchie.connect" links "switchie" object with "Hi" func whenever "switchie" gets clicked.</p> <p>But if I execute this and try to turn switch on, GUI hangs up. I did try to execute this via script &amp; command-line and adding the "print switch state", resulting in an endless loop (True &amp; False)</p> <p>I tried with many other funcs I made, but neither of them could solve this issue. In fact, this is the "essence" of all the other funcs I made.</p> <p>Why does this happen? </p> <p>Where's the loop?</p> <p>Am I wrong in some line?</p> <p>Help is appreciated! </p> <p>(If you need to see the rest of my faulty funcs, just ask for 'em, but I don't think they'll help...)</p>
2
2016-08-14T09:22:56Z
39,694,877
<p>You want to hook up the switch like this:</p> <p><code>switchie.connect("""activate""", Hi)</code></p> <p>This will only get called <strong>once</strong> for every time it is clicked. What you were doing is hooking up to the signal after it changed, so it was constantly changing, and never catching up. You will also want to change</p> <p><code>def Hi(switch, active):</code></p> <p>to</p> <p><code>def Hi(switch, active = None):</code></p> <p>for keyboard support.</p>
0
2016-09-26T04:45:08Z
[ "python", "python-2.7", "pygtk", "glade", "pygobject" ]
How to acquire video feed in python using a wireless webcam setup on my android device?
38,940,874
<p>Alright, so my basic aim is to do some video processing. But I want to do so in real time using the feed from a camera. I've downloaded this app on my android phone called <a href="https://play.google.com/store/apps/details?id=com.pas.webcam&amp;hl=en" rel="nofollow">IP webcam</a>. Using this app I can create a wireless camera feed, which I'm able to access using the link <a href="http://192.168.1.2:8080/video" rel="nofollow">http://192.168.1.2:8080/video</a></p> <p>If I insert the above link in my browser I'm able to retrieve the video feed, however I'm not able to do so using python. I tried doing something along the lines of <code>cv2.VideoCapture('http://192.168.1.2:8080/video')</code>, but I wasn't able to retrieve the video feed.</p> <p>I'm using python v2.7.12, numPy and openCV v2.4.13</p> <p>It would be really helpful if you could tell me why my current method is failing and what I'm supposed to do, or give me an alternative approach to the problem (keeping in mind I want to use my android device as a wireless webcam and acquire the video feed in python).</p>
0
2016-08-14T09:29:20Z
38,978,973
<p>Without an error code, or some other debugging information, there is too little information to give a definitive answer, but here is something that worked for me when I had a similar problem.</p> <p>I am using an AXIS IP webcam and to view the stream, I go to <code>http://192.168.206.241/view/viewer_index.shtml?id=392</code>. However this includes the video stream embedded in a viewer. Using this URL confuses the <code>VideoCapture()</code> object. Instead, I had to drag the embedded stream into a new tab, which gave me a new URL, <code>http://192.168.206.241/mjpg/video.mjpg</code>. Using this as the string for the <code>VideoCapture()</code> parameter, I have success. </p> <p>Just looking at the URL you use, it doesn't seem to have an extension. This might be the problem.</p>
0
2016-08-16T15:32:45Z
[ "python", "python-2.7", "opencv", "webcam", "video-capture" ]
Average of multiple dataframes with the same columns and indices
38,940,946
<p>I have a few dataframes. Each of them has the same columns and the same indices. For each index I want to average the values in each column (if these would be matrices, I would just sum them up and divide by the number of matrices).</p> <p>Here is the example.</p> <pre><code>v1 = pd.DataFrame([['ind1', 1, 2, 3], ['ind2', 4, 5, 6]], columns=['id', 'c1', 'c2', 'c3']).set_index('id') v2 = pd.DataFrame([['ind1', 2, 3, 4], ['ind2', 6, 1, 2]], columns=['id', 'c1', 'c2', 'c3']).set_index('id') v3 = pd.DataFrame([['ind1', 1, 2, 1], ['ind2', 1, 1, 3]], columns=['id', 'c1', 'c2', 'c3']).set_index('id') </code></pre> <p>In real situation indices and columns can be in different order.</p> <p>For this situation the result will be </p> <p><a href="http://i.stack.imgur.com/4ckKGm.png" rel="nofollow"><img src="http://i.stack.imgur.com/4ckKGm.png" alt="enter image description here"></a></p> <p>(the value for ind1, c1 is <code>(1 + 1 + 2) / 3</code>, for ind2, c2 is <code>(1 + 5 + 1) / 3</code> and so on).</p> <p>Currently I do this with loops:</p> <pre><code>dfs = [v1, v2, v3] cols= ['c1', 'c2', 'c3'] data = [] for ind, _ in dfs[0].iterrows(): vals = [sum(df.loc[ind][col] for df in dfs) / float(len(dfs)) for col in cols] data.append([ind] + vals) pd.DataFrame(data, columns=['id'] + cols).set_index('id') </code></pre> <p>, but this is clearly inefficient for big dataframes with a lot of columns. So how can I achieve this without loops?</p>
3
2016-08-14T09:37:55Z
38,940,997
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#cython-optimized-aggregation-functions" rel="nofollow"><code>groupby.mean</code></a> on the <code>index</code> level after concatenating the dataframes:</p> <pre><code>pd.concat([v1, v2, v3]).groupby(level=0).mean() c1 c2 c3 id ind1 1.333333 2.333333 2.666667 ind2 3.666667 2.333333 3.666667 </code></pre>
3
2016-08-14T09:45:24Z
[ "python", "pandas" ]
"ImportError: No module named urls" while following Django Tutorial
38,940,996
<p>I am following the official django tutorial <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial04/" rel="nofollow">https://docs.djangoproject.com/en/1.10/intro/tutorial04/</a></p> <p>I am using Django 1.9.8 and I am now getting the following error in <code>/polls/views.py</code>:</p> <pre><code>File "C:\Users\hk\Documents\mysite\polls\views.py", line 4, in &lt;module&gt; from django.urls import reverse ImportError: No module named urls </code></pre> <p><strong>polls/views.py</strong></p> <pre><code>from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from .models import Choice, Question # ... </code></pre> <p><strong>mysite/urls.py</strong></p> <pre><code>from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() urlpatterns=[ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), ] </code></pre> <p><strong>mysite/mysite/urls.py</strong></p> <pre><code>from django.conf.urls import include,url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), ] </code></pre>
3
2016-08-14T09:44:59Z
38,941,050
<p>That tutorial requires Django 1.10 while you seem to be using an older version. In this case, you should import <code>reverse</code> as follows:</p> <pre><code>from django.core.urlresolvers import reverse </code></pre> <p>To upgrade your Django version, use the following command (in your command line, <em>not</em> in the Python shell):</p> <pre><code>pip install --upgrade django </code></pre>
5
2016-08-14T09:52:06Z
[ "python", "django" ]
Python urllib unicode exception in 302 redirection
38,941,075
<p>The situation is: I'm scraping one website, the urls for the pages follow the pattern:</p> <pre><code>http://www.pageadress/somestuff/ID-HERE/ </code></pre> <p>Nothing unusual. I have a lot of id's that i need to scrape and most of them work correctly. However, the page behaves in portal-like way. In browser, when you enter such address, you get redirected to:</p> <pre><code>http://www.pageadress/somestuff/ID-HERE-title_of_subpage </code></pre> <p>What might be problematic is that sometimes that title might contain non-ascii characters (approximately 0.01% of cases), therefore (i think that's the issue) i get the exception:</p> <pre><code> File "/usr/lib/python3.4/urllib/request.py", line 161, in urlopen return opener.open(url, data, timeout) File "/usr/lib/python3.4/urllib/request.py", line 469, in open response = meth(req, response) File "/usr/lib/python3.4/urllib/request.py", line 579, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python3.4/urllib/request.py", line 501, in error result = self._call_chain(*args) File "/usr/lib/python3.4/urllib/request.py", line 441, in _call_chain result = func(*args) File "/usr/lib/python3.4/urllib/request.py", line 684, in http_error_302 return self.parent.open(new, timeout=req.timeout) File "/usr/lib/python3.4/urllib/request.py", line 463, in open response = self._open(req, data) File "/usr/lib/python3.4/urllib/request.py", line 481, in _open '_open', req) File "/usr/lib/python3.4/urllib/request.py", line 441, in _call_chain result = func(*args) File "/usr/lib/python3.4/urllib/request.py", line 1210, in http_open return self.do_open(http.client.HTTPConnection, req) File "/usr/lib/python3.4/urllib/request.py", line 1182, in do_open h.request(req.get_method(), req.selector, req.data, headers) File "/usr/lib/python3.4/http/client.py", line 1088, in request self._send_request(method, url, body, headers) File "/usr/lib/python3.4/http/client.py", line 1116, in _send_request self.putrequest(method, url, **skips) File "/usr/lib/python3.4/http/client.py", line 973, in putrequest self._output(request.encode('ascii')) UnicodeEncodeError: 'ascii' codec can't encode characters in position 38-39: ordinal not in range(128). </code></pre> <p>The bizarre thing is that no unicode characters in url i'm redirected to are actually on position 38-39, but there are on others.</p> <p>The code being used:</p> <pre><code>import socket import urllib.parse import urllib.request socket.setdefaulttimeout(30) url = "https://www.bettingexpert.com/archive/tip/3207221" headers = {'User-Agent': 'Mozilla/5.0'} content = urllib.request.urlopen(urllib.request.Request(url, None, headers)).read().decode('utf-8') </code></pre> <p>Any method to get around it, preferably without using other libraries?</p> <p>//Oh the glorious world of python, creating 1000s of problems i wouldn't even think were possible if i was writing in ruby.</p>
1
2016-08-14T09:54:48Z
38,942,785
<p>So, i've found out solution to my specific problem. I've just gathered the remaining part of the 'url' from their api, and after some minor transformations i can access the page without any redirections. That, of course, doesn't mean that i solved the general problem- it might come back later in the future, so i've developed a 'solution'.</p> <p>By posting this code here i've basically guaranteed myself that i won't ever be employed as programmer, so don't look at it if you're eating.</p> <p>"Capybara" gem and poltergeist needed because why not?</p> <pre><code>#test.py import socket import urllib.parse import urllib.request import os tip_id = 3207221 socket.setdefaulttimeout(30) url = "http://www.bettingexpert.com/archive/tip/" + tip_id.__str__() headers = {'User-Agent': 'Mozilla/5.0'} try: content = urllib.request.urlopen(urllib.request.Request(url, None, headers)).read().decode('utf-8') except UnicodeEncodeError: print("Overkill activated") os.system('ruby test.rb ' + tip_id.__str__()) with open(tip_id.__str__(), 'r') as file: content = file.read() os.remove(tip_id.__str__()) print(content) </code></pre> <p>.</p> <pre><code>#test.rb require 'capybara' require 'capybara/dsl' require 'capybara/poltergeist' Capybara.register_driver :poltergeist_no_timeout do |app| driver = Capybara::Poltergeist::Driver.new(app, timeout: 30) driver.browser.url_blacklist = %w( http://fonts.googleapis.com http://html5shiv.googlecode.com ) driver end Capybara.default_driver = :poltergeist_no_timeout Capybara.run_server = false include Capybara::DSL begin page.reset_session! page.visit("http://www.bettingexpert.com/archive/tip/#{ARGV[0]}") rescue retry end File.open(ARGV[0], 'w') do |file| file.print(page.html) end </code></pre>
0
2016-08-14T13:38:22Z
[ "python", "python-3.4", "urllib", "http-status-code-302" ]
parsing part of the table for data using BeautifulSoup
38,941,097
<p>I have a self-project to scrape data online using BeautifulSoup and Python, and I think historical stocks data would be a good one for me to practice. I looked at the source code <a href="https://uk.finance.yahoo.com/q/hp?s=AAPL" rel="nofollow">here</a> to analyze how I can use BeautifulSoup's select() or findall() to parse part of the data from the table. Here is the code I use, but it parsed things other than the table. </p> <p><code> soup = bs4.BeautifulSoup(res.text, 'lxml') table = soup.findAll( 'td', {'class':'yfnc_tabledata1'} ) print table </code></p> <p>My Question: How to I parse only the 2 rows showing the 2 days of data from the table?</p> <p>Here is the table that has 2 days of the historical data:</p> <pre><code>&lt;table class="yfnc_datamodoutline1" width="100%" cellpadding="0" cellspacing="0" border="0"&gt; &lt;tr valign="top"&gt; &lt;td&gt; &lt;table border="0" cellpadding="2" cellspacing="1" width="100%"&gt; &lt;tr&gt; &lt;th scope="col" class="yfnc_tablehead1" align="right" width="16%"&gt;Date&lt;/th&gt; &lt;th scope="col" class="yfnc_tablehead1" align="right" width="12%"&gt;Open&lt;/th&gt; &lt;th scope="col" class="yfnc_tablehead1" align="right" width="12%"&gt;High&lt;/th&gt; &lt;th scope="col" class="yfnc_tablehead1" align="right" width="12%"&gt;Low&lt;/th&gt; &lt;th scope="col" class="yfnc_tablehead1" align="right" width="12%"&gt;close&lt;/th&gt; &lt;th scope="col" class="yfnc_tablehead1" align="right" width="16%"&gt;Volume&lt;/th&gt; &lt;th scope="col" class="yfnc_tablehead1" align="right" width="15%"&gt;Adj Close*&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="yfnc_tabledata1" nowrap align="right"&gt;12 Aug 2016&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;107.78&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;108.44&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;107.78&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;108.18&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;18,612,300&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;108.18&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="yfnc_tabledata1" nowrap align="right"&gt;11 Aug 2016&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;108.52&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;108.93&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;107.85&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;107.93&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;27,484,500&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;107.93&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="yfnc_tabledata1" colspan="7" align="center"&gt; * &lt;small&gt;Close price adjusted for dividends and splits.&lt;/small&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>I only need the specific 2 rows of data from above:</p> <pre><code>&lt;tr&gt; &lt;td class="yfnc_tabledata1" nowrap align="right"&gt;12 Aug 2016&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;107.78&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;108.44&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;107.78&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;108.18&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;18,612,300&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;108.18&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="yfnc_tabledata1" nowrap align="right"&gt;11 Aug 2016&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;108.52&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;108.93&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;107.85&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;107.93&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;27,484,500&lt;/td&gt; &lt;td class="yfnc_tabledata1" align="right"&gt;107.93&lt;/td&gt; &lt;/tr&gt; </code></pre>
0
2016-08-14T09:57:55Z
38,946,771
<p>You can select the all the rows from the nested table inside the <em>yfnc_datamodoutline1</em> table and index the first two:</p> <pre><code>soup = BeautifulSoup(html) table_rows = soup.select("table.yfnc_datamodoutline1 table tr + tr") row1, row2 = table_rows[0:2] print(row1) print(row2) </code></pre> <p>Which would give you:</p> <pre><code>&lt;tr&gt; &lt;td align="right" class="yfnc_tabledata1" nowrap=""&gt;12 Aug 2016&lt;/td&gt; &lt;td align="right" class="yfnc_tabledata1"&gt;107.78&lt;/td&gt; &lt;td align="right" class="yfnc_tabledata1"&gt;108.44&lt;/td&gt; &lt;td align="right" class="yfnc_tabledata1"&gt;107.78&lt;/td&gt; &lt;td align="right" class="yfnc_tabledata1"&gt;108.18&lt;/td&gt; &lt;td align="right" class="yfnc_tabledata1"&gt;18,612,300&lt;/td&gt; &lt;td align="right" class="yfnc_tabledata1"&gt;108.18&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td align="right" class="yfnc_tabledata1" nowrap=""&gt;11 Aug 2016&lt;/td&gt; &lt;td align="right" class="yfnc_tabledata1"&gt;108.52&lt;/td&gt; &lt;td align="right" class="yfnc_tabledata1"&gt;108.93&lt;/td&gt; &lt;td align="right" class="yfnc_tabledata1"&gt;107.85&lt;/td&gt; &lt;td align="right" class="yfnc_tabledata1"&gt;107.93&lt;/td&gt; &lt;td align="right" class="yfnc_tabledata1"&gt;27,484,500&lt;/td&gt; &lt;td align="right" class="yfnc_tabledata1"&gt;107.93&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>To get the td data just extract the text from each td:</p> <pre><code>print([td.text for td in row1.find_all("td")]) print([td.text for td in row2.find_all("td")]) </code></pre> <p>Which would give you:</p> <pre><code>[u'12 Aug 2016', u'107.78', u'108.44', u'107.78', u'108.18', u'18,612,300', u'108.18'] [u'11 Aug 2016', u'108.52', u'108.93', u'107.85', u'107.93', u'27,484,500', u'107.93'] </code></pre> <p><em>table.yfnc_datamodoutline1 table tr + tr</em> selects all the rows inside the inner table skipping the first which is the header row. </p>
0
2016-08-14T21:26:36Z
[ "python", "html", "beautifulsoup" ]
Django 1.9. template inheritance. Block doesn't display
38,941,118
<p>I have 2 html pages in my Django templates. I am trying to insert cats.html in index.html as a block, but nothing happens. No errors, no display. I already looked in django documentation and in the youtube. Just can't understand where is problem</p> <p>index.html:</p> <pre><code> {% load static %} &lt;!DOCTYPE doctype html&gt; &lt;html class="no-js" lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"/&gt; &lt;meta content="width=device-width, initial-scale=1.0" name="viewport"/&gt; &lt;link rel="stylesheet" type="text/css" href="{% static 'items/index-style.css' %}" /&gt; &lt;title&gt; my site &lt;/title&gt; &lt;/head&gt; &lt;body&gt; {% block cats %} {% endblock cats %} &lt;/body&gt; &lt;/html&gt; </code></pre> <p>cats.html:</p> <pre><code>{% extends "index.html" %} {% block cats %} &lt;div class="row column"&gt; &lt;p class="lead"&gt; Категории товаров &lt;/p&gt; &lt;/div&gt; &lt;div class="row small-up-1 medium-up-2 large-up-3"&gt; {% for category in categories %} &lt;div class="column"&gt; &lt;a href="/{{category.alias}}"&gt; &lt;div class="callout"&gt; &lt;p&gt; {{category.name}} &lt;/p&gt; &lt;p&gt; &lt;img alt="image of a planet called Pegasi B" src="{{category.image}}"/&gt; &lt;/p&gt; &lt;p class="lead"&gt; &lt;!-- Цена: {{tovar.price}} --&gt; &lt;/p&gt; &lt;p class="subheader"&gt; &lt;!-- {{tovar.short_description}} --&gt; &lt;/p&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; {% endfor %} &lt;/div&gt; {% endblock cats %} </code></pre> <p>views.py:</p> <pre><code>from django.shortcuts import render from django.http import HttpResponse, Http404 from django.template.loader import render_to_string from items.models import * # Create your views here. def home(request): try: categories = Category.objects.all() except: raise Http404() context = { 'categories':categories, } return render(request,"index.html",context) </code></pre>
2
2016-08-14T10:01:53Z
38,941,193
<p>You are confusing the block name with template name. You are <em>not</em> inserting <code>cats.html</code> into <code>index.html</code> as you expect, but you are extending <code>index.html</code> in your <code>cats.html</code>. You should use your child template (<code>cats.html</code>) in your view, ie change the last line to:</p> <pre><code>return render(request, 'cats.html', context) </code></pre>
1
2016-08-14T10:12:48Z
[ "python", "html", "django", "templates", "inheritance" ]
Django 1.9. template inheritance. Block doesn't display
38,941,118
<p>I have 2 html pages in my Django templates. I am trying to insert cats.html in index.html as a block, but nothing happens. No errors, no display. I already looked in django documentation and in the youtube. Just can't understand where is problem</p> <p>index.html:</p> <pre><code> {% load static %} &lt;!DOCTYPE doctype html&gt; &lt;html class="no-js" lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"/&gt; &lt;meta content="width=device-width, initial-scale=1.0" name="viewport"/&gt; &lt;link rel="stylesheet" type="text/css" href="{% static 'items/index-style.css' %}" /&gt; &lt;title&gt; my site &lt;/title&gt; &lt;/head&gt; &lt;body&gt; {% block cats %} {% endblock cats %} &lt;/body&gt; &lt;/html&gt; </code></pre> <p>cats.html:</p> <pre><code>{% extends "index.html" %} {% block cats %} &lt;div class="row column"&gt; &lt;p class="lead"&gt; Категории товаров &lt;/p&gt; &lt;/div&gt; &lt;div class="row small-up-1 medium-up-2 large-up-3"&gt; {% for category in categories %} &lt;div class="column"&gt; &lt;a href="/{{category.alias}}"&gt; &lt;div class="callout"&gt; &lt;p&gt; {{category.name}} &lt;/p&gt; &lt;p&gt; &lt;img alt="image of a planet called Pegasi B" src="{{category.image}}"/&gt; &lt;/p&gt; &lt;p class="lead"&gt; &lt;!-- Цена: {{tovar.price}} --&gt; &lt;/p&gt; &lt;p class="subheader"&gt; &lt;!-- {{tovar.short_description}} --&gt; &lt;/p&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; {% endfor %} &lt;/div&gt; {% endblock cats %} </code></pre> <p>views.py:</p> <pre><code>from django.shortcuts import render from django.http import HttpResponse, Http404 from django.template.loader import render_to_string from items.models import * # Create your views here. def home(request): try: categories = Category.objects.all() except: raise Http404() context = { 'categories':categories, } return render(request,"index.html",context) </code></pre>
2
2016-08-14T10:01:53Z
38,941,260
<p>actually the problem is you use index.html as a base template and then inherit in your cats.html so you have to render cat.html to get the desired result <a href="http://tutorial.djangogirls.org/en/template_extending/" rel="nofollow">THIS IS HELPFUL FOR YOU</a></p> <pre><code>return render(request, 'cats.html', context) </code></pre> <p>thanks :) </p>
-1
2016-08-14T10:20:54Z
[ "python", "html", "django", "templates", "inheritance" ]
PySide Custom widget doesn't auto fit in QTableWidget
38,941,180
<p>I am trying to create a custom widget <code>RangeSpinBox</code>. The widget doesn't auto fit in a <code>QTableWidget</code> like in the image attached below.</p> <p><a href="http://i.stack.imgur.com/W4FP8.png" rel="nofollow"><img src="http://i.stack.imgur.com/W4FP8.png" alt="enter image description here"></a></p> <pre><code>import sys from PySide import QtGui class RangeSpinBox(QtGui.QWidget): def __init__(self, *args, **kwargs): super(RangeSpinBox, self).__init__(*args, **kwargs) self.__minimum = 0 self.__maximum = 100 main_layout = QtGui.QHBoxLayout() self.__minimum_spin_box = QtGui.QSpinBox() self.__range_label = QtGui.QLabel('-') self.__maximum_spin_box = QtGui.QSpinBox() main_layout.addWidget(self.__minimum_spin_box) main_layout.addWidget(self.__range_label) main_layout.addWidget(self.__maximum_spin_box) self.setLayout(main_layout) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) spin_box = RangeSpinBox() table_widget = QtGui.QTableWidget() table_widget.setColumnCount(2) table_widget.setRowCount(1) table_widget.setCellWidget(0, 0, spin_box) table_widget.setCellWidget(0, 1, QtGui.QSpinBox()) table_widget.show() app.exec_() </code></pre>
2
2016-08-14T10:10:35Z
38,947,429
<p>You need to remove the default margins on the layout, and also change the size-policy on the spin-boxes to expand in both directions:</p> <pre><code> main_layout = QtGui.QHBoxLayout() main_layout.setContentsMargins(0, 0, 0, 0) size_policy = QtGui.QSizePolicy( QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.MinimumExpanding) self.__minimum_spin_box = QtGui.QSpinBox() self.__minimum_spin_box.setSizePolicy(size_policy) self.__range_label = QtGui.QLabel('-') self.__maximum_spin_box = QtGui.QSpinBox() self.__maximum_spin_box.setSizePolicy(size_policy) </code></pre>
1
2016-08-14T23:11:25Z
[ "python", "qt", "pyqt4", "pyside", "pyqt5" ]
AttributeError at /circular/1/detail/ 'CircularDetail' object has no attribute 'pk' in Django
38,941,276
<pre><code>class CircularDetail(DeleteView): model = Circular template_name = 'genre/circular_detail.html' def get_context_data(self, **kwargs): ctx = super(CircularDetail, self).get_context_data(**kwargs) ctx['c'] = Circular.objects.get(pk=self.pk) ctx['sittings'] = Sitting.objects.all() ctx['ballot'] = Sitting.objects.all() return ctx </code></pre> <p>Above view give me following errors:</p> <p><strong>Traceback:</strong></p> <pre><code>File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/detail.py" in get 118. context = self.get_context_data(object=self.object) File "/home/ohid/test_venv/myapp/genre/views.py" in get_context_data 126. ctx['c'] = Circular.objects.get(pk=self.pk) Exception Type: AttributeError at /circular/1/detail/ Exception Value: 'CircularDetail' object has no attribute 'pk' </code></pre> <p>I need your assistance to fix this issues. </p>
1
2016-08-14T10:22:35Z
38,941,424
<p>URL parameters are passed via kwargs, so you can access it this way </p> <pre><code>self.kwargs.get("pk") </code></pre> <p>so change</p> <pre><code>ctx['c'] = Circular.objects.get(pk=self.pk) </code></pre> <p>to</p> <pre><code>ctx['c'] = Circular.objects.get(pk=self.kwargs.get("pk")) </code></pre>
0
2016-08-14T10:42:46Z
[ "python", "django" ]
AttributeError at /circular/1/detail/ 'CircularDetail' object has no attribute 'pk' in Django
38,941,276
<pre><code>class CircularDetail(DeleteView): model = Circular template_name = 'genre/circular_detail.html' def get_context_data(self, **kwargs): ctx = super(CircularDetail, self).get_context_data(**kwargs) ctx['c'] = Circular.objects.get(pk=self.pk) ctx['sittings'] = Sitting.objects.all() ctx['ballot'] = Sitting.objects.all() return ctx </code></pre> <p>Above view give me following errors:</p> <p><strong>Traceback:</strong></p> <pre><code>File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/detail.py" in get 118. context = self.get_context_data(object=self.object) File "/home/ohid/test_venv/myapp/genre/views.py" in get_context_data 126. ctx['c'] = Circular.objects.get(pk=self.pk) Exception Type: AttributeError at /circular/1/detail/ Exception Value: 'CircularDetail' object has no attribute 'pk' </code></pre> <p>I need your assistance to fix this issues. </p>
1
2016-08-14T10:22:35Z
38,941,723
<p>First of all, fix your base class to <code>DetailView</code> (instead of <code>DeleteView</code>)</p> <p><code>DetailView</code> inherited from <code>django.views.generic.detail.SingleObjectMixin</code> (<a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin</a>) which expects primary key to be in <code>slug</code> parameter, so fix your URL regexp to</p> <pre><code>r'^circular/(?P&lt;slug&gt;[-\w]+)/detail$' </code></pre> <p>and access your object using <code>self.object</code> in view or just <code>{{ object }}</code> in template.</p>
0
2016-08-14T11:23:16Z
[ "python", "django" ]
Strange error in Python (IndexError)
38,941,303
<p>Sorry if this is a dumb question but I am having a few issues with my code.</p> <p>I have a Python script that scrapes Reddit and sets the top picture as my desktop background.</p> <p>I want it to only download if the picture is big enough, but I am getting a strange error.</p> <pre><code>&gt;&gt;&gt; m = '1080x608' &gt;&gt;&gt; w = m.rsplit('x', 1)[0] &gt;&gt;&gt; print(w) 1080 &gt;&gt;&gt; h = m.rsplit('x', 1)[1] &gt;&gt;&gt; print(h) 608 </code></pre> <p>This works fine, but the following doesn't, despite being almost the same.</p> <pre><code>&gt;&gt;&gt; m = '1280×721' &gt;&gt;&gt; w = m.rsplit('x', 1)[0] &gt;&gt;&gt; h = m.rsplit('x', 1)[1] Traceback (most recent call last): File "&lt;pyshell#35&gt;", line 1, in &lt;module&gt; h = m.rsplit('x', 1)[1] IndexError: list index out of range </code></pre>
1
2016-08-14T10:26:03Z
38,941,324
<p><code>×</code> != <code>x</code>. Split returns one-element list, and you are trying to retrieve second element from it.</p> <pre><code>'1080x608'.rsplit('x', 1) # ['1080', '608'] '1280×721'.rsplit('x', 1) # ['1280\xc3\x97721'] </code></pre> <p>In second case <em>there is no</em> second element in list - it contains only one element.</p> <p>MCVE would be:</p> <pre><code>l = ['something'] l[1] </code></pre> <p>With exception:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IndexError: list index out of range </code></pre> <p>To ensure that you split string to two parts you may use a <a href="https://docs.python.org/2/library/stdtypes.html#str.partition" rel="nofollow"><code>partition</code></a>.</p> <blockquote> <p>Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.</p> </blockquote> <pre><code>w, sep, h = m.partition('x') # h and sep will be empty if there is no separator in m </code></pre>
0
2016-08-14T10:28:11Z
[ "python" ]
Strange error in Python (IndexError)
38,941,303
<p>Sorry if this is a dumb question but I am having a few issues with my code.</p> <p>I have a Python script that scrapes Reddit and sets the top picture as my desktop background.</p> <p>I want it to only download if the picture is big enough, but I am getting a strange error.</p> <pre><code>&gt;&gt;&gt; m = '1080x608' &gt;&gt;&gt; w = m.rsplit('x', 1)[0] &gt;&gt;&gt; print(w) 1080 &gt;&gt;&gt; h = m.rsplit('x', 1)[1] &gt;&gt;&gt; print(h) 608 </code></pre> <p>This works fine, but the following doesn't, despite being almost the same.</p> <pre><code>&gt;&gt;&gt; m = '1280×721' &gt;&gt;&gt; w = m.rsplit('x', 1)[0] &gt;&gt;&gt; h = m.rsplit('x', 1)[1] Traceback (most recent call last): File "&lt;pyshell#35&gt;", line 1, in &lt;module&gt; h = m.rsplit('x', 1)[1] IndexError: list index out of range </code></pre>
1
2016-08-14T10:26:03Z
38,941,349
<p>In your second example <code>×</code> is not the same as <code>x</code>, it is instead a multiplication sign. If you are getting these stings from somewhere and then parsing them, you should first do</p> <pre><code>m = m.replace('×', 'x') </code></pre>
0
2016-08-14T10:31:32Z
[ "python" ]
Django deletes previous entry when submiting new one
38,941,396
<p>Title is pretty self-explanatory the thing is when I try to submit a new entry django deletes the previous one. I think that the problem is in the delete function because when I disable it I can sumbit as many entries as I want. Here are my files:</p> <p><strong>Form.py</strong></p> <pre><code>class FinancesForm(forms.Form): description = forms.CharField(max_length = 50) value = forms.DecimalField(max_digits = 10, decimal_places = 2) </code></pre> <p><strong>Models.py</strong></p> <pre><code>class Finances(models.Model): date = models.DateField(auto_now = True) description = models.CharField(max_length = 50) value = models.DecimalField(max_digits = 10, decimal_places = 2) total = models.DecimalField(max_digits = 10, decimal_places = 2, null = True) </code></pre> <p><strong>Views.py</strong></p> <pre><code>@login_required def finances(request): if request.method == 'POST': form = FinancesForm(request.POST) if form.is_valid(): newEntry = Finances() newEntry.description = form.cleaned_data['description'] newEntry.value = form.cleaned_data['value'] if Finances.objects.all().aggregate(Sum('value')).values()[0] == None: newEntry.total = newEntry.value; else: newEntry.total = Finances.objects.all().aggregate(Sum('value')).values()[0] + newEntry.value newEntry.save() return HttpResponseRedirect(reverse('finances')) form = Finances() entries = Finances.objects.all() total = Finances.objects.all().aggregate(Sum('value')).values()[0] return render(request, 'coop/finances.html', {'entries': entries, 'form':form, 'total': total}) @login_required def fdelete(request): if request.method != 'POST': raise HTTP404 entryId = request.POST.get('entry', None) entToDel = get_object_or_404(Finances, pk = entryId) entToDel.delete() return HttpResponseRedirect(reverse('finances')) </code></pre> <p><strong>Finances.html</strong></p> <pre><code>&lt;tbody&gt; {% if entries %} {% for entry in entries %} {% if forloop.last %} &lt;tr&gt; &lt;td&gt;{{ entry.date }}&lt;/td&gt; &lt;td&gt;{{ entry.description }}&lt;/td&gt; {% if entry.value &gt;= 0 %} &lt;td class="positive"&gt;{{ entry.value }}&lt;/td&gt; {% else %} &lt;td class="negative"&gt;{{ entry.value}}&lt;/td&gt; {% endif %} &lt;td&gt;{{entry.total}}&lt;/td&gt; &lt;td&gt; &lt;form action="{% url "fdelete" %}" method="post" enctype="multipart/form-data"&gt; {% csrf_token %} &lt;input type="hidden" name="entry" value="{{ entry.pk }}"/&gt; &lt;input class="btn btn-primary" type="submit" value="Eliminar"/&gt; &lt;/td&gt; &lt;/tr&gt; {% else %} &lt;tr&gt; &lt;td&gt;{{ entry.date }}&lt;/td&gt; &lt;td&gt;{{ entry.description }}&lt;/td&gt; {% if entry.value &gt;= 0 %} &lt;td class="positive"&gt;{{ entry.value }}&lt;/td&gt; {% else %} &lt;td class="negative"&gt;{{ entry.value}}&lt;/td&gt; {% endif %} &lt;td&gt;{{entry.total}}&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; {% endif %} {% endfor %} {% endif %} &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;form class="input-group" action="{% url "finances" %}" method="post" enctype="multipart/form-data"&gt; {% csrf_token %} &lt;td&gt;&lt;input class="form-control" type="text" placeholder="Concepte" name="description"/&gt;&lt;/td&gt; &lt;td&gt;&lt;input class="form-control" type="text" placeholder="Quantitat €" name="value" onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"/&gt;&lt;/td&gt; &lt;/form&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tbody&gt; </code></pre> <p>Thanks for yout time</p>
0
2016-08-14T10:39:01Z
38,941,901
<p>You have not closed your first form</p> <pre><code> &lt;td&gt; &lt;form action="{% url "fdelete" %}" method="post" enctype="multipart/form-data"&gt; {% csrf_token %} &lt;input type="hidden" name="entry" value="{{ entry.pk }}"/&gt; &lt;input class="btn btn-primary" type="submit" value="Eliminar"/&gt; &lt;/td&gt; </code></pre> <p>Add closing <code>&lt;/form&gt;</code> tag</p>
0
2016-08-14T11:45:49Z
[ "python", "django" ]
Porting a function and an array from C to Python
38,941,441
<p>I'm trying to port this to python:</p> <pre><code>uint8 formatHwInfo[0x40*4] = { // todo: Convert to struct // each entry is 4 bytes 0x00,0x00,0x00,0x01,0x08,0x03,0x00,0x01,0x08,0x01,0x00,0x01,0x00,0x00,0x00,0x01, 0x00,0x00,0x00,0x01,0x10,0x07,0x00,0x00,0x10,0x03,0x00,0x01,0x10,0x03,0x00,0x01, 0x10,0x0B,0x00,0x01,0x10,0x01,0x00,0x01,0x10,0x03,0x00,0x01,0x10,0x03,0x00,0x01, 0x10,0x03,0x00,0x01,0x20,0x03,0x00,0x00,0x20,0x07,0x00,0x00,0x20,0x03,0x00,0x00, 0x20,0x03,0x00,0x01,0x20,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x03,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x20,0x03,0x00,0x01,0x00,0x00,0x00,0x01, 0x00,0x00,0x00,0x01,0x20,0x0B,0x00,0x01,0x20,0x0B,0x00,0x01,0x20,0x0B,0x00,0x01, 0x40,0x05,0x00,0x00,0x40,0x03,0x00,0x00,0x40,0x03,0x00,0x00,0x40,0x03,0x00,0x00, 0x40,0x03,0x00,0x01,0x00,0x00,0x00,0x00,0x80,0x03,0x00,0x00,0x80,0x03,0x00,0x00, 0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x10,0x01,0x00,0x00, 0x10,0x01,0x00,0x00,0x20,0x01,0x00,0x00,0x20,0x01,0x00,0x00,0x20,0x01,0x00,0x00, 0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x60,0x01,0x00,0x00, 0x60,0x01,0x00,0x00,0x40,0x01,0x00,0x01,0x80,0x01,0x00,0x01,0x80,0x01,0x00,0x01, 0x40,0x01,0x00,0x01,0x80,0x01,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }; uint32 surfaceGetBitsPerPixel(uint32 surfaceFormat) { uint32 hwFormat = surfaceFormat&amp;0x3F; uint32 bpp = 0; bpp = formatHwInfo[hwFormat*4+0]; return bpp; } </code></pre> <p>I've already gotten (ported) the surfaceGetBitsPerPixel() part, as you can see here:</p> <pre><code>def surfaceGetBitsPerPixel(surfaceFormat): hwFormat = surfaceFormat&amp;0x3F bpp = formatHwInfo[hwFormat*4+0] return bpp </code></pre> <p>But I don't know what to do with that big array above of it, please help. :(</p>
0
2016-08-14T10:44:43Z
38,941,482
<p>Convert the array to a byte string:</p> <pre><code>formatHwInfo = b"\x00\x00\x00\x01\x08\x03\x00\x01\x08\x01\x00\x01\x00\x00\x00\x01" \ b"\x00\x00\x00\x01\x10\x07\x00\x00\x10\x03\x00\x01\x10\x03\x00\x01" \ b"\x10\x0B\x00\x01\x10\x01\x00\x01\x10\x03\x00\x01\x10\x03\x00\x01" \ b"\x10\x03\x00\x01\x20\x03\x00\x00\x20\x07\x00\x00\x20\x03\x00\x00" \ b"\x20\x03\x00\x01\x20\x05\x00\x00\x00\x00\x00\x00\x20\x03\x00\x00" \ b"\x00\x00\x00\x00\x00\x00\x00\x01\x20\x03\x00\x01\x00\x00\x00\x01" \ b"\x00\x00\x00\x01\x20\x0B\x00\x01\x20\x0B\x00\x01\x20\x0B\x00\x01" \ b"\x40\x05\x00\x00\x40\x03\x00\x00\x40\x03\x00\x00\x40\x03\x00\x00" \ b"\x40\x03\x00\x01\x00\x00\x00\x00\x80\x03\x00\x00\x80\x03\x00\x00" \ b"\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x01\x10\x01\x00\x00" \ b"\x10\x01\x00\x00\x20\x01\x00\x00\x20\x01\x00\x00\x20\x01\x00\x00" \ b"\x00\x01\x00\x01\x00\x01\x00\x00\x00\x01\x00\x00\x60\x01\x00\x00" \ b"\x60\x01\x00\x00\x40\x01\x00\x01\x80\x01\x00\x01\x80\x01\x00\x01" \ b"\x40\x01\x00\x01\x80\x01\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00" \ b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" \ b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" def surfaceGetBitsPerPixel(surfaceFormat): hwFormat = surfaceFormat &amp; 0x3F return ord(formatHwInfo[hwFormat*4 + 0]) </code></pre>
1
2016-08-14T10:51:19Z
[ "python", "c", "arrays" ]
pocketsphinx python example
38,941,443
<p>I use the raspberry pi with pocketsphinx python and I found an example <a href="https://pypi.python.org/pypi/pocketsphinx#basic-usage" rel="nofollow">here</a>. From that script I use the same path as described in the script. When I try to run this script it give me an error:</p> <pre><code>ERROR: "acmod.c", line 83: Folder 'deps/pocketsphinx/model/en-us/en-us' does not contain acoustic model definition 'mdef' Traceback (most recent call last): File "test.py", line 15, in &lt;module&gt; decoder = ps.Decoder(config) File "/usr/local/lib/python2.7/dist-packages/pocketsphinx/pocketsphinx.py", line 271, in __init__ this = _pocketsphinx.new_Decoder(*args) RuntimeError: new_Decoder returned -1 </code></pre> <p>Does anyone know what the problem is?</p>
-1
2016-08-14T10:44:51Z
38,942,371
<p>Better use absolute path, for ex: if your 'deps' dir present under '/home/pi' then your code will looks like below:</p> <pre><code>MODELDIR = '/home/pi/deps/pocketsphinx/model' DATADIR = '/home/pi/deps/pocketsphinx/test/data' # Create a decoder with certain model config = ps.Decoder.default_config() config.set_string('-hmm', os.path.join(MODELDIR, 'en-us/en-us')) config.set_string('-lm', os.path.join(MODELDIR, 'en-us/en-us.lm.bin')) config.set_string('-dict', os.path.join(MODELDIR, 'en-us/cmudict-en-us.dict')) decoder = ps.Decoder(config) </code></pre>
1
2016-08-14T12:43:20Z
[ "python", "pocketsphinx" ]
Django Invalid block tag: 'static' means what exactly?
38,941,491
<p>(I'm using Django 1.3 - Python 2.7)</p> <p>Been through all the related questions without any resolution.</p> <p>The syntax error is in line 5, not line one:</p> <pre><code>{% load static %} &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" href="{% static 'css/home.css' %}"&gt; </code></pre> <p>After reviewing related questions, some suggested first line should change to:</p> <pre><code>{% load staticfiles %} </code></pre> <p>I tried that, instead of "Invalid block tag: 'static'" error, I get :</p> <blockquote> <p>'staticfiles' is not a valid tag library: Template library staticfiles not found, tried django.templatetags.staticfiles,django.contrib.admin.templatetags.staticfiles</p> </blockquote> <p>I double checked the setting files:</p> <pre><code>STATIC_ROOT = '/home/username/mysite/static' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'mysite.myapp', ) </code></pre> <p>Turned "Debug = False"</p> <p>... and other suggestions. But I still get the same two errors.</p> <p>The file structure is:</p> <p>mysite contains the following folders/files: myapp , media , static , settings.py , ...</p> <p>myapp contains the following folders/files: static , templates , views.py , ...</p> <p>both mysite -> static and myapp -> static contain identical folders and files.</p> <p>Please ask if you require more information.</p> <p>Any help/direction would be appreciated. Thanks.</p>
1
2016-08-14T10:52:36Z
38,941,613
<p>In Django 1.3 there's no static tag, and you must use it like this:</p> <pre><code>{% load static %} &lt;img src="{% get_static_prefix %}images/hi.jpg" /&gt; </code></pre> <p>or add static to TEMPLATE_CONTEXT_PROCESSORS and use STATIC_URL directly from template:</p> <pre><code># settings.py TEMPLATE_CONTEXT_PROCESSORS = ( # other processors ’django.core.context_processors.static’, ) # some.html &lt;img src="{{ STATIC_URL }}images/hi.jpg" /&gt; </code></pre>
3
2016-08-14T11:09:53Z
[ "python", "django" ]
Pandas Time Series: How to plot only times of day (no dates) against other values?
38,941,557
<p>As I am preparing to do some regressions on a rather big dataset I would like to visualize the data at first.</p> <p>The data we are talking about is data about the New York subway (hourly entries, rain, weather and such) for May, 2011.</p> <p>When creating the dataframe I converted hours and time to pandas datetime format.<br> Now I realize that what I want to do does not make much sense from a logical point of view for the example at hand. However, I would still like to plot the exact time of day against the hourly entries. Which, as I said, is not very meaningful since ENTRIESn_hourly is aggregated. But let's for the sake of the argument assume the ENTRIESn_hourly would be explicitly related to the exact timestamp.</p> <p>Now how would I go about taking only the times and ignoring the dates and then plot that out?</p> <p>Please find the jupyter notebook here: <a href="https://github.com/FBosler/Udacity/blob/master/Example.ipynb" rel="nofollow">https://github.com/FBosler/Udacity/blob/master/Example.ipynb</a></p> <p>Thx alot!</p>
1
2016-08-14T11:01:58Z
38,941,711
<p>IIUC you can do it this way:</p> <pre><code>In [9]: weather_turnstile.plot.line(x=weather_turnstile.Date_Time.dt.time, y='ENTRIESn_hourly', marker='o', alpha=0.3) Out[9]: &lt;matplotlib.axes._subplots.AxesSubplot at 0xc2a63c8&gt; </code></pre> <p><a href="http://i.stack.imgur.com/xFOkI.png" rel="nofollow"><img src="http://i.stack.imgur.com/xFOkI.png" alt="enter image description here"></a></p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/api.html#datetimelike-properties" rel="nofollow">.dt accessor</a> gives you access to the following attributes:</p> <pre><code>In [10]: weather_turnstile.Date_Time.dt. weather_turnstile.Date_Time.dt.ceil weather_turnstile.Date_Time.dt.is_quarter_end weather_turnstile.Date_Time.dt.strftime weather_turnstile.Date_Time.dt.date weather_turnstile.Date_Time.dt.is_quarter_start weather_turnstile.Date_Time.dt.time weather_turnstile.Date_Time.dt.day weather_turnstile.Date_Time.dt.is_year_end weather_turnstile.Date_Time.dt.to_period weather_turnstile.Date_Time.dt.dayofweek weather_turnstile.Date_Time.dt.is_year_start weather_turnstile.Date_Time.dt.to_pydatetime weather_turnstile.Date_Time.dt.dayofyear weather_turnstile.Date_Time.dt.microsecond weather_turnstile.Date_Time.dt.tz weather_turnstile.Date_Time.dt.days_in_month weather_turnstile.Date_Time.dt.minute weather_turnstile.Date_Time.dt.tz_convert weather_turnstile.Date_Time.dt.daysinmonth weather_turnstile.Date_Time.dt.month weather_turnstile.Date_Time.dt.tz_localize weather_turnstile.Date_Time.dt.floor weather_turnstile.Date_Time.dt.nanosecond weather_turnstile.Date_Time.dt.week weather_turnstile.Date_Time.dt.freq weather_turnstile.Date_Time.dt.normalize weather_turnstile.Date_Time.dt.weekday weather_turnstile.Date_Time.dt.hour weather_turnstile.Date_Time.dt.quarter weather_turnstile.Date_Time.dt.weekday_name weather_turnstile.Date_Time.dt.is_month_end weather_turnstile.Date_Time.dt.round weather_turnstile.Date_Time.dt.weekofyear weather_turnstile.Date_Time.dt.is_month_start weather_turnstile.Date_Time.dt.second weather_turnstile.Date_Time.dt.year </code></pre>
2
2016-08-14T11:21:34Z
[ "python", "pandas", "matplotlib", "time-series" ]
How does List Comprehension exactly work in Python?
38,941,643
<p>I am going trough the docs of Python 3.X, I have doubt about List Comprehension speed of execution and how it exactly work. </p> <p>Let's take the following example: </p> <p><strong>Listing 1</strong></p> <pre><code>... L = range(0,10) L = [x ** 2 for x in L] ... </code></pre> <p>Now in my knowledge this return a new listing, and it's <strong>equivalent</strong> to write down:</p> <p><strong>Listing 2</strong></p> <pre><code>... res = [] for x in L: res.append(x ** 2) ... </code></pre> <p>The main difference is the speed of execution if I am correct. Listing 1 is supposed to be performed at C language speed inside the interpreter, meanwhile Listing 2 is not. </p> <p>But Listing 2 is what the list comprehension does internally (<strong>not sure</strong>), so <strong>why Listing 1 is executed at C Speed inside the interpreter &amp; Listing 2 is not</strong>? Both are converted to byte code before being processed, or am I missing something? </p>
2
2016-08-14T11:13:40Z
38,941,718
<p>The answer is actually in your question.</p> <p>When you run any built in python function you are running something that has been written in C and compiled into machine code.</p> <p>When you write your own version of it, that code must be converted into CPython objects which are handled by the interpreter.</p> <p>In consequence the built-in approach or function is always quicker (or takes less space) in Python than writing your own function.</p>
2
2016-08-14T11:22:44Z
[ "python" ]
How does List Comprehension exactly work in Python?
38,941,643
<p>I am going trough the docs of Python 3.X, I have doubt about List Comprehension speed of execution and how it exactly work. </p> <p>Let's take the following example: </p> <p><strong>Listing 1</strong></p> <pre><code>... L = range(0,10) L = [x ** 2 for x in L] ... </code></pre> <p>Now in my knowledge this return a new listing, and it's <strong>equivalent</strong> to write down:</p> <p><strong>Listing 2</strong></p> <pre><code>... res = [] for x in L: res.append(x ** 2) ... </code></pre> <p>The main difference is the speed of execution if I am correct. Listing 1 is supposed to be performed at C language speed inside the interpreter, meanwhile Listing 2 is not. </p> <p>But Listing 2 is what the list comprehension does internally (<strong>not sure</strong>), so <strong>why Listing 1 is executed at C Speed inside the interpreter &amp; Listing 2 is not</strong>? Both are converted to byte code before being processed, or am I missing something? </p>
2
2016-08-14T11:13:40Z
38,941,897
<p>Look at the actual bytecode that is produced. I've put the two fragments of code into fuctions called f1 and f2. </p> <p>The comprehension does this:</p> <pre><code> 3 15 LOAD_CONST 3 (&lt;code object &lt;listcomp&gt; at 0x7fbf6c1b59c0, file "&lt;stdin&gt;", line 3&gt;) 18 LOAD_CONST 4 ('f1.&lt;locals&gt;.&lt;listcomp&gt;') 21 MAKE_FUNCTION 0 24 LOAD_FAST 0 (L) 27 GET_ITER 28 CALL_FUNCTION 1 (1 positional, 0 keyword pair) 31 STORE_FAST 0 (L) </code></pre> <p>Notice there is no loop in the bytecode. The loop happens in C.</p> <p>Now the for loop does this:</p> <pre><code> 4 21 SETUP_LOOP 31 (to 55) 24 LOAD_FAST 0 (L) 27 GET_ITER &gt;&gt; 28 FOR_ITER 23 (to 54) 31 STORE_FAST 2 (x) 34 LOAD_FAST 1 (res) 37 LOAD_ATTR 1 (append) 40 LOAD_FAST 2 (x) 43 LOAD_CONST 3 (2) 46 BINARY_POWER 47 CALL_FUNCTION 1 (1 positional, 0 keyword pair) 50 POP_TOP 51 JUMP_ABSOLUTE 28 &gt;&gt; 54 POP_BLOCK </code></pre> <p>In contrast to the comprehension, the loop is clearly here in the bytecode. So the loop occurs in python. </p> <p>The bytecodes are different, and the first should be faster.</p>
2
2016-08-14T11:45:32Z
[ "python" ]
Have problems with SQLite in Python
38,941,645
<p>I want to add into my SQLite table a list of values. To be more accurate, I want to add it in Stock column. But I have some problems when running my app. Here is my database before app running.</p> <p><a href="http://i.stack.imgur.com/qt9o4.png" rel="nofollow"><img src="http://i.stack.imgur.com/qt9o4.png" alt="enter image description here"></a></p> <p>And when I try running my programm, I got wrong column data. Here is my code </p> <pre><code>def count(ui): i = [] z = 0 v = 0 if ui.comboBox.currentText() == '50НР4': cur.execute("""SELECT Part, Stock FROM Details WHERE Pumps = '50НР4' OR Pumps = '50НР4/6'""") elif ui.comboBox.currentText() == '50НР6.3': cur.execute("""SELECT Part, Stock FROM Details WHERE Pumps = '50НР6' OR Pumps = '50НР4/6'""") for row, form in enumerate(cur): i.append(form[1]) for element in i: i[z] -= 1 z += 1 if ui.comboBox.currentText() == '50НР4': z = 0 for elem in i: cur.execute("""UPDATE Details SET Stock = (?) WHERE Pumps = '50НР4' OR Pumps = '50НР4/6' AND ROWID = (?)""", [i[z], v]) v += 1 z += 1 elif ui.comboBox.currentText() == '50НР6.3': z = 0 for elem in i: cur.execute("""UPDATE Details SET Stock = (?) WHERE Pumps = '50НР6' OR Pumps = '50НР4/6' AND ROWID = (?)""", [i[z], v]) v += 1 z += 1 elif ui.comboBox.currentText() == '50НР4' or ui.comboBox.currentText() == '50НР6': z = 0 for elem in i: cur.execute("""UPDATE Details SET Stock = (?) WHERE Pumps = '50НР4/6' AND ROWID = (?)""", [i[z], v]) v += 1 z += 1 print(i) con.commit() </code></pre>
0
2016-08-14T11:13:49Z
38,941,825
<p>If you want to change the values of rows, just let the database do it for you internally:</p> <pre><code>def count(ui): if ui.comboBox.currentText() == '50НР4': condition = "Pumps = '50НР4' OR Pumps = '50НР4/6'" elif ui.comboBox.currentText() == '50НР6.3': condition = "Pumps = '50НР6' OR Pumps = '50НР4/6'" else: condition = "Pumps = '50НР4/6'" cur.execute("""UPDATE Details SET Stock = Stock - 1 WHERE %s""" % condition) con.commit() </code></pre>
1
2016-08-14T11:36:23Z
[ "python", "sqlite", "pyqt" ]
Slicing every nth range within a list with a for and a while loop
38,941,659
<p>So I have a short list called <strong>someList</strong> with some numbers in it. What I want to do is output every 3 elements of the list while iterating over it every 3rd slice range.</p> <p>So if I have </p> <pre><code>someList = [1,2,3,4,5,6,7,8,9,10] </code></pre> <p>The output of my <strong>someList</strong> should be like this</p> <pre><code>[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]] </code></pre> <p>Here is my code where I have defined a new <strong>temp</strong> list to store the output values</p> <pre><code>someList = [1,2,3,4,5,6,7,8,9,10] lookupRange = 3 temp = [] for index,i in enumerate(someList): while index &lt;= len(someList): temp.append(someList[index:index+lookupRange]) index += 1 print(temp) </code></pre> <p>However upon running this code I get some rather unexpected results...</p> <pre><code>[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10], [10], [], [2, 3, 4, 5, 6, 7, 8, 9, 10], [3, 4, 5, 6, 7, 8, 9, 10], [4, 5, 6, 7, 8, 9, 10], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [3, 4, 5, 6, 7, 8, 9, 10], [4, 5, 6, 7, 8, 9, 10], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [4, 5, 6, 7, 8, 9, 10], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [8, 9, 10], [9, 10], [10], [], [9, 10], [10], [], [10], []] </code></pre> <p>As you can see, for the first few lines, I do indeed get the desired output with slice range period of 3. But after that it just goes crazy...</p> <p>Any ideas on whats going wrong here?</p> <p>PS:I know there are probably simpler one liner ways to do this (such as the numpy.convolve function), but this problem in particular requires I do it with just for and while loops.</p>
1
2016-08-14T11:15:24Z
38,941,745
<p>You have nested loops, but you only need one loop.</p> <pre><code>someList = [1,2,3,4,5,6,7,8,9,10] lookupRange = 3 temp = [] for index in range(len(someList) - lookupRange + 1): temp.append(someList[index:index+lookupRange]) </code></pre>
4
2016-08-14T11:25:27Z
[ "python", "iteration", "slice" ]
Slicing every nth range within a list with a for and a while loop
38,941,659
<p>So I have a short list called <strong>someList</strong> with some numbers in it. What I want to do is output every 3 elements of the list while iterating over it every 3rd slice range.</p> <p>So if I have </p> <pre><code>someList = [1,2,3,4,5,6,7,8,9,10] </code></pre> <p>The output of my <strong>someList</strong> should be like this</p> <pre><code>[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]] </code></pre> <p>Here is my code where I have defined a new <strong>temp</strong> list to store the output values</p> <pre><code>someList = [1,2,3,4,5,6,7,8,9,10] lookupRange = 3 temp = [] for index,i in enumerate(someList): while index &lt;= len(someList): temp.append(someList[index:index+lookupRange]) index += 1 print(temp) </code></pre> <p>However upon running this code I get some rather unexpected results...</p> <pre><code>[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10], [10], [], [2, 3, 4, 5, 6, 7, 8, 9, 10], [3, 4, 5, 6, 7, 8, 9, 10], [4, 5, 6, 7, 8, 9, 10], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [3, 4, 5, 6, 7, 8, 9, 10], [4, 5, 6, 7, 8, 9, 10], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [4, 5, 6, 7, 8, 9, 10], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [8, 9, 10], [9, 10], [10], [], [9, 10], [10], [], [10], []] </code></pre> <p>As you can see, for the first few lines, I do indeed get the desired output with slice range period of 3. But after that it just goes crazy...</p> <p>Any ideas on whats going wrong here?</p> <p>PS:I know there are probably simpler one liner ways to do this (such as the numpy.convolve function), but this problem in particular requires I do it with just for and while loops.</p>
1
2016-08-14T11:15:24Z
38,941,779
<p>Using list comprehension:</p> <pre><code>&gt;&gt;&gt; someList = [1,2,3,4,5,6,7,8,9,10] &gt;&gt;&gt; chunk = 3 &gt;&gt;&gt; [someList[i : i + chunk] for i in range(len(someList) - chunk + 1)] [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]] </code></pre>
1
2016-08-14T11:29:42Z
[ "python", "iteration", "slice" ]
Slicing every nth range within a list with a for and a while loop
38,941,659
<p>So I have a short list called <strong>someList</strong> with some numbers in it. What I want to do is output every 3 elements of the list while iterating over it every 3rd slice range.</p> <p>So if I have </p> <pre><code>someList = [1,2,3,4,5,6,7,8,9,10] </code></pre> <p>The output of my <strong>someList</strong> should be like this</p> <pre><code>[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]] </code></pre> <p>Here is my code where I have defined a new <strong>temp</strong> list to store the output values</p> <pre><code>someList = [1,2,3,4,5,6,7,8,9,10] lookupRange = 3 temp = [] for index,i in enumerate(someList): while index &lt;= len(someList): temp.append(someList[index:index+lookupRange]) index += 1 print(temp) </code></pre> <p>However upon running this code I get some rather unexpected results...</p> <pre><code>[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10], [10], [], [2, 3, 4, 5, 6, 7, 8, 9, 10], [3, 4, 5, 6, 7, 8, 9, 10], [4, 5, 6, 7, 8, 9, 10], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [3, 4, 5, 6, 7, 8, 9, 10], [4, 5, 6, 7, 8, 9, 10], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [4, 5, 6, 7, 8, 9, 10], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [7, 8, 9, 10], [8, 9, 10], [9, 10], [10], [], [8, 9, 10], [9, 10], [10], [], [9, 10], [10], [], [10], []] </code></pre> <p>As you can see, for the first few lines, I do indeed get the desired output with slice range period of 3. But after that it just goes crazy...</p> <p>Any ideas on whats going wrong here?</p> <p>PS:I know there are probably simpler one liner ways to do this (such as the numpy.convolve function), but this problem in particular requires I do it with just for and while loops.</p>
1
2016-08-14T11:15:24Z
38,942,423
<p>Here's a pure Python one-liner; Numpy isn't required.</p> <pre><code>someList = [1,2,3,4,5,6,7,8,9,10] lookupRange = 3 temp = list(zip(*(someList[i:] for i in range(lookupRange)))) print(temp) </code></pre> <p><strong>output</strong></p> <pre><code>[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 10)] </code></pre> <p>In Python 2, the assignment to <code>temp</code> can be simplified to</p> <pre><code>temp = zip(*(someList[i:] for i in range(lookupRange))) </code></pre> <p>If you <em>really</em> need a list of lists instead of a list of tuples, you can change it to</p> <pre><code>temp = [list(u) for u in zip(*(someList[i:] for i in range(lookupRange)))] </code></pre> <p>which works equally well in Python 2 or 3. </p> <p>But I'd stick with the tuples (unless you need to mutate those inner lists): tuples use less RAM, and code that uses tuples is often faster than the equivalent list-based code.</p> <hr> <p>Here's that last version done with a couple of traditional <code>for</code> loops instead of a generator expression nested inside a list comprehension.</p> <pre><code>someList = [1,2,3,4,5,6,7,8,9,10] lookupRange = 3 offset_lists = [] for i in range(lookupRange): offset_lists.append(someList[i:]) temp = [] for u in zip(*offset_lists): temp.append(list(u)) print(temp) </code></pre> <p><strong>output</strong></p> <pre><code>[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]] </code></pre>
2
2016-08-14T12:51:04Z
[ "python", "iteration", "slice" ]
How to sort dataframe by a row?
38,941,735
<p>I have a dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame(data={'x':[7,1,9], 'y':[4,5,6],'z':[1,8,3]}, index=['a', 'b', 'c']) </code></pre> <p>It shows:</p> <p><a href="http://i.stack.imgur.com/mJEps.png" rel="nofollow"><img src="http://i.stack.imgur.com/mJEps.png" alt="enter image description here"></a></p> <p>How to sort this dataframe by row['a']: After sort the dataframe, it might be:</p> <p><a href="http://i.stack.imgur.com/wJDXE.png" rel="nofollow"><img src="http://i.stack.imgur.com/wJDXE.png" alt="enter image description here"></a></p>
0
2016-08-14T11:24:28Z
38,941,764
<pre><code>In [7]: df.iloc[:, np.argsort(df.loc['a'])] Out[7]: z y x a 1 4 7 b 8 5 1 c 3 6 9 </code></pre> <hr> <p><code>np.argsort</code> returns the indices one would use to sort the <code>a</code> row, <code>df.loc['a']</code>:</p> <pre><code>In [6]: np.argsort(df.loc['a']) Out[6]: x 2 y 1 z 0 Name: a, dtype: int64 </code></pre> <p>Once you have those indices, you can use them to reorder the columns of <code>df</code> (by using <code>df.iloc</code>).</p>
3
2016-08-14T11:27:23Z
[ "python", "pandas", "dataframe" ]
How to sort dataframe by a row?
38,941,735
<p>I have a dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame(data={'x':[7,1,9], 'y':[4,5,6],'z':[1,8,3]}, index=['a', 'b', 'c']) </code></pre> <p>It shows:</p> <p><a href="http://i.stack.imgur.com/mJEps.png" rel="nofollow"><img src="http://i.stack.imgur.com/mJEps.png" alt="enter image description here"></a></p> <p>How to sort this dataframe by row['a']: After sort the dataframe, it might be:</p> <p><a href="http://i.stack.imgur.com/wJDXE.png" rel="nofollow"><img src="http://i.stack.imgur.com/wJDXE.png" alt="enter image description here"></a></p>
0
2016-08-14T11:24:28Z
38,941,774
<p>You can use <code>axis=1</code> when calling <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort.html" rel="nofollow"><code>sort</code></a>:</p> <pre><code>df.sort(axis=1, ascending=False) &gt;&gt; z y x a 1 4 7 b 8 5 1 c 3 6 9 </code></pre> <p>Note that <code>sort</code> is not inplace by default, so either reassign its return value or use <code>inplace=True</code>.</p>
1
2016-08-14T11:29:18Z
[ "python", "pandas", "dataframe" ]
How to sort dataframe by a row?
38,941,735
<p>I have a dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame(data={'x':[7,1,9], 'y':[4,5,6],'z':[1,8,3]}, index=['a', 'b', 'c']) </code></pre> <p>It shows:</p> <p><a href="http://i.stack.imgur.com/mJEps.png" rel="nofollow"><img src="http://i.stack.imgur.com/mJEps.png" alt="enter image description here"></a></p> <p>How to sort this dataframe by row['a']: After sort the dataframe, it might be:</p> <p><a href="http://i.stack.imgur.com/wJDXE.png" rel="nofollow"><img src="http://i.stack.imgur.com/wJDXE.png" alt="enter image description here"></a></p>
0
2016-08-14T11:24:28Z
38,941,800
<p>You can use <code>reindex_axis</code> method:</p> <pre><code>&gt;&gt;&gt; df.reindex_axis(sorted(df.columns, key=lambda x: df[x]['a']), axis=1) z y x a 1 4 7 b 8 5 1 c 3 6 9 </code></pre>
2
2016-08-14T11:32:58Z
[ "python", "pandas", "dataframe" ]
How to sort dataframe by a row?
38,941,735
<p>I have a dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame(data={'x':[7,1,9], 'y':[4,5,6],'z':[1,8,3]}, index=['a', 'b', 'c']) </code></pre> <p>It shows:</p> <p><a href="http://i.stack.imgur.com/mJEps.png" rel="nofollow"><img src="http://i.stack.imgur.com/mJEps.png" alt="enter image description here"></a></p> <p>How to sort this dataframe by row['a']: After sort the dataframe, it might be:</p> <p><a href="http://i.stack.imgur.com/wJDXE.png" rel="nofollow"><img src="http://i.stack.imgur.com/wJDXE.png" alt="enter image description here"></a></p>
0
2016-08-14T11:24:28Z
39,429,537
<p>In v0.19 you can sort by rows:</p> <pre><code>pd.__version__ Out: '0.19.0rc1' df.sort_values(by='a', axis=1) Out: z y x a 1 4 7 b 8 5 1 c 3 6 9 </code></pre>
1
2016-09-10T18:58:22Z
[ "python", "pandas", "dataframe" ]
Windows: How to run a shell script out of a simple CGI python server
38,941,743
<p>I have made a python Srver using http.server </p> <pre><code>python -m http.server --cgi 8000 </code></pre> <p>Server is running and i am able to run a python script on it. I am trying to <strong>run shell file</strong> with similar content. I think i am not bale to make the shell file executable. Lookign for soemthing like <strong>chmod +x filename.sh</strong> in windows.</p> <p>Ubuntu Equivalent link: <a href="http://askubuntu.com/questions/229589/how-to-make-a-file-e-g-a-sh-script-executable-so-it-can-be-ran-from-terminal">http://askubuntu.com/questions/229589/how-to-make-a-file-e-g-a-sh-script-executable-so-it-can-be-ran-from-terminal</a></p> <p>Currently i am getting this error:</p> <pre><code>Content-type text/htmlException happened during processing of request from ('127.0.0.1', 1659) Traceback (most recent call last): File "C:\Users\ABC\AppData\Local\Programs\Python\Python35-32\lib\socketserver.py", line 313, in _handle_request_noblock self.process_request(request, client_address) File "C:\Users\ABC\AppData\Local\Programs\Python\Python35-32\lib\socketserver.py", line 341, in process_request self.finish_request(request, client_address) File "C:\Users\ABC\AppData\Local\Programs\Python\Python35-32\lib\socketserver.py", line 354, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\ABC\AppData\Local\Programs\Python\Python35-32\lib\socketserver.py", line 681, in __init__ self.handle() File "C:\Users\ABC\AppData\Local\Programs\Python\Python35-32\lib\http\server.py", line 422, in handle self.handle_one_request() File "C:\Users\ABC\AppData\Local\Programs\Python\Python35-32\lib\http\server.py", line 410, in handle_one_request method() File "C:\Users\ABC\AppData\Local\Programs\Python\Python35-32\lib\http\server.py", line 645, in do_GET f = self.send_head() File "C:\Users\ABC\AppData\Local\Programs\Python\Python35-32\lib\http\server.py", line 953, in send_head return self.run_cgi() File "C:\Users\ABC\AppData\Local\Programs\Python\Python35-32\lib\http\server.py", line 1161, in run_cgi env = env File "C:\Users\ABC\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 947, in __init__ restore_signals, start_new_session) File "C:\Users\ABC\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 1224, in _execute_child startupinfo) OSError: [WinError 193] %1 is not a valid Win32 application &lt; h1 &gt;Hello World&lt; /h1 &gt; </code></pre> <p><strong>Updated</strong></p> <p><strong>Content of Python file:</strong></p> <pre><code>#!/usr/bin/env python print("Content-type text/html") print("") print("&lt; h1 &gt; Hello World &lt; / h1 &gt;")` </code></pre> <p><strong>Output:</strong>(on browser screen)</p> <pre><code>Hello World </code></pre> <p><strong>Shell File Content</strong></p> <pre><code>#!/bin/bash echo "Content-type text/html" echo "" echo "&lt; h1 &gt;Hello World&lt; /h1 &gt;" ` </code></pre> <p><strong>Output:</strong> Above mentioned error.</p> <p>Want the similar output <strong>Hello World.</strong></p>
0
2016-08-14T11:25:10Z
38,967,838
<p>In windows there are no bash-scripts. You only have .bat-Files with very limited syntax. If you try to run your script as <code>filename.sh</code> windows tries to find a program associated with the extension <code>.sh</code> and fails. You should rename your file to <code>filename.bat</code>.</p>
0
2016-08-16T06:19:44Z
[ "python", "shell", "cgi" ]
Why is my Python3 pip package not working eventhough it shows on PyPi?
38,941,840
<p>Here is a little library that I'm trying to make available on PyPi for others to use.</p> <p><a href="https://github.com/rojavacrypto/python-libbitcoin" rel="nofollow">https://github.com/rojavacrypto/python-libbitcoin</a></p> <p>I use this command to upload the package:</p> <pre><code>$ python setup.py sdist bdist_wheel upload </code></pre> <p>I also tried this:</p> <pre><code>$ python setup.py sdist bdist_egg upload </code></pre> <p>Both seem to run fine without errors, and it's even <a href="https://pypi.python.org/pypi/python-libbitcoin" rel="nofollow">listed on PyPi</a></p> <p>But for some reason when I try to pip install on Ubuntu, it gives me an error.</p> <pre><code># pip3 install libbitcoin Collecting libbitcoin Could not find a version that satisfies the requirement libbitcoin (from versions: ) No matching distribution found for libbitcoin </code></pre> <p>Why is this happening?</p> <p>Thanks</p>
0
2016-08-14T11:39:09Z
38,941,876
<p>The name of your package in PyPI is "python-libbitcoin":</p> <pre><code>pip3 install python-libbitcoin </code></pre> <p>and here you go:</p> <pre><code>Downloading/unpacking python-libbitcoin http://pypi.python.org/simple/python-libbitcoin/ uses an insecure transport scheme (http). Consider using https if pypi.python.org has it available Downloading python-libbitcoin-1.2.2.tar.gz Running setup.py (path:/home/lukas/x/build/python-libbitcoin/setup.py) egg_info for package python-libbitcoin </code></pre>
1
2016-08-14T11:43:21Z
[ "python", "python-3.x", "pip", "bitcoin" ]
AttributeError: 'module' object has no attribute 'maketrans' - PyCharm
38,941,915
<p>I've got this strange problem on my PC with Python 2.7 + PyCharm 2016.2 + Windows 10 (64).</p> <p>While running script:</p> <pre><code>import urllib from BeautifulSoup import * url = raw_input('Enter -') if (len(url) &lt; 1): url = "http://python-data.dr-chuck.net/comments_292106.html" html = urllib.urlopen(url).read() soup = BeautifulSoup(html) lst = list() tags = soup('span') for tag in tags: # print 'TAG:', tag # print 'URL:', tag.get('href', None) # print 'Contents:', tag.contents # print 'Attrs:', tag.attrs num = int(tag.contents[0]) lst.append(num) print sum(lst) </code></pre> <p>I've got such message:</p> <pre><code>C:\Python27\python.exe E:/python/coursera/following_links.py 23 0.8475 Traceback (most recent call File "E:/python/coursera/following_links.py", line 1, in &lt;module&gt; import urllib File "C:\Python27\lib\urllib.py", line 30, in &lt;module&gt; import base64 File "C:\Python27\lib\base64.py", line 98, in &lt;module&gt; _urlsafe_encode_translation = string.maketrans(b'+/', b'-_') AttributeError: 'module' object has no attribute 'maketrans' Process finished with exit code 1 </code></pre> <p>Same situation occurs in WingIDE. </p> <p>Funny is, that while using python's Idle this script works.</p> <p>Also it works on my second PC with Windows 8 (64) (Python 2.7 and PyCharm 2016.2)</p>
1
2016-08-14T11:47:18Z
38,943,367
<p>I think this is happening behind the scenes. In order to carry out your commands, Python has to do some work and it is not finding the files it needs. That might explain why it may work in Idle and on your PC but not in others like Wing IDE.</p>
-1
2016-08-14T14:50:26Z
[ "python", "python-2.7", "base64", "pycharm", "urllib" ]
Why is this SyntaxError? (Python, dictionary comprehension with inline if)
38,942,073
<p>In a dictionary, I want to make sure that a specific key has a specific encoding.</p> <pre><code>test_dictionary = { k:v.encode('latin-1') if k=="test_key" else k:v for k,v in test_dictionary.items() } </code></pre> <p>I get <code>SyntaxError</code>. I expected this to be allowed though.</p>
0
2016-08-14T12:06:40Z
38,942,103
<p>Try this instead:</p> <pre><code>test_dictionary = { k:v.encode('latin-1') if k=="test_key" else v for k,v in test_dictionary.items() } </code></pre> <p>The second <code>:</code> has been removed so the inline <code>if</code> either encodes <code>v</code>, or leaves it as it is depending on the condition.</p> <p>To clarify I've added parentheses to the expression below to make it clearer that this is the "value" part of the list comprehension:</p> <pre><code>{ k: (v.encode('latin-1') if k=="test_key" else v) for k,v in test_dictionary.items() } ^___________________________________________^ </code></pre>
3
2016-08-14T12:10:18Z
[ "python" ]
Conditional raplacement with index shift in Pandas
38,942,382
<p>having following column in dataframe:</p> <pre><code>0 0 0 0 0 5 </code></pre> <p>I would like to check for values greater than a threshold. If found, set to zero and move up by the difference value-threshold, setting threshold on the new position. Let's say threshold=3, then the resulting column has to be:</p> <pre><code>0 0 0 3 0 0 </code></pre> <p>Any idea for fast transformation?</p>
-1
2016-08-14T12:44:33Z
38,942,726
<p>For this DataFrame:</p> <pre>df Out: A 0 0 1 0 2 0 3 0 4 0 5 5 6 0 7 0 8 0 9 0 10 6 11 0 12 0</pre> <pre><code>threshold = 3 above_threshold = df['A'] &gt; threshold df.loc[df[above_threshold].index - (df.loc[above_threshold, 'A'] - 3).values, 'A'] = 3 df.loc[above_threshold, 'A'] = 0 </code></pre> <pre>df Out: A 0 0 1 0 2 0 3 3 4 0 5 0 6 0 7 3 8 0 9 0 10 0 11 0 12 0</pre>
0
2016-08-14T13:31:08Z
[ "python", "pandas", "dataframe" ]
Parsing strange xml feeds
38,942,386
<p>May not be strange, but I have never used xml, or PHP, which is two of the things I am using for an upcoming project.</p> <p>Anyway, I am parsing <a href="http://www.huffingtonpost.com/feeds/verticals/good-news/index.xml" rel="nofollow">this</a> XML feed. Each <code>&lt;item&gt;</code> contains an <code>&lt;enclosure url=...&gt;</code></p> <p>Where <code>...</code> = URLs &amp; image types etc</p> <p>In Python 3 using <code>feedparser</code> I can use </p> <pre><code>feed = feedparser.parse("http://www.huffingtonpost.com/feeds/verticals/good-news/index.xml") l = feed.entries[12]['title']` </code></pre> <p>just fine, but when I try to get the URL of an image using </p> <p><code>p = feed.entries[12]['enclosure'] </code></p> <p>I get an error </p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#28&gt;", line 1, in &lt;module&gt; p = feed.entries[12]['enclosure'] File "C:\Python34\lib\site-packages\feedparser-5.1.3-py3.4.egg\feedparser.py", line 375, in __getitem__ return dict.__getitem__(self, key) KeyError: 'enclosure' </code></pre> <p>So obviously <code>enclosure</code> isn't coming back with anything, I suspect this is because in the XML it does not use</p> <pre><code>&lt;name of object&gt;Text&lt;/name of object&gt; </code></pre> <p>Instead it uses</p> <pre><code>&lt;enclosure url=... blah blah blah /&gt; </code></pre> <p>How do I get the value of URL? It is equal to a string (<code>url="url is here"</code>)</p>
0
2016-08-14T12:45:09Z
38,943,413
<p>Looking at the <a href="http://pythonhosted.org/feedparser/reference-entry-enclosures.html" rel="nofollow">feedparse docs</a> try using the <em>entries[i].enclosures[j].href</em> reference which returns the URL of the linked file:</p> <pre><code>feed = feedparser.parse("http://www.huffingtonpost.com/feeds/verticals/good-news/index.xml") l = feed.entries[12].enclosures[1].href </code></pre>
0
2016-08-14T14:55:35Z
[ "python", "xml" ]
How to read and filter a raw audio file with python?
38,942,404
<p>I got a <code>.raw</code> file from recording, it was written by the write method from the Java class <code>AudioOutputStream</code> (I wrote bytes).</p> <p>I want to filter this audio file with a Python filter. <a href="http://scipy.github.io/old-wiki/pages/Cookbook/ButterworthBandpass" rel="nofollow">Here</a> it is the guide I'm using, it filters a list of float numbers (the variable x in the guide).</p> <p>My problem is the different types, bytes and floats. Is there a way to make this filter work with that <code>.raw</code> audio?</p> <p>I appreciate any suggestion. Thanks.</p>
-1
2016-08-14T12:48:28Z
38,982,799
<p>I found two useful java classes: <code>DataInputStream</code> and <code>DataOutputStream</code> to write floats for my Python script to use.</p> <p>First I read float values from the <code>.raw</code> file with the <code>readFloat</code> method which reads 4 bytes as a float. </p> <pre><code>FileInputStream is = new FileInputStream(inputName); DataInputStream dis = new DataInputStream(is); ArrayList&lt;Float&gt; fbuffer = new ArrayList&lt;Float&gt;(); try { while(dis.available()&gt;0){ float f = dis.readFloat(); //read 4 bytes as float // this fails if it is not 4x fbuffer.add(f); } } catch (IOException e) { //nothing happens, there are 1,2 or 3 bytes at the end we are going to ignore //e.printStackTrace(); } dis.close(); is.close(); </code></pre> <p>This way I create a file with the float values. This file is read by the python script. Here I use </p> <pre><code>fin = open('fileWithFloatsName') floatList = [line.rstrip('\n') for line in fin] floatList = destringifyList(floatList) fin.close() </code></pre> <p>I get the list of floats, perform the filter as in <a href="http://scipy.github.io/old-wiki/pages/Cookbook/ButterworthBandpass" rel="nofollow">here</a> and get a new list of floats. I write this result in a new file that java is going to read with a <code>Scanner</code> object. </p> <p>Finally we create a new <code>.raw</code> file and write the floats as bytes with the <code>writeFloat</code> method.</p> <p>That's all. If someone suggest something better (partially or not), I will appreciate it.</p>
0
2016-08-16T19:15:38Z
[ "java", "python", "audio" ]
Value Object Django
38,942,445
<p>Good morning, first sorry my English because I'm using Google Translate.</p> <p>I'm starting now with Python and Django and me a question arose in the creation of my models. I would like to create something like:</p> <p>Person (models.Model)</p> <ul> <li>Name</li> <li>...</li> <li>Address</li> </ul> <p>Address(models.Model)</p> <ul> <li>PublicPlace</li> <li>Neighborhood</li> <li>...</li> </ul> <p>That is, the address as a separate ValueObject in order to use more than one model. In the database fields within the address class will be persisted within the People table and other entities that may arise (Enterprise, Client, "Anyone who may have address"). So avoid duplicating all address fields for each model you need.</p> <p>I saw that would to do by setting the Meta class address for abstract and inheriting the others. But if I want to do more ValueObjects, have to inherit from several classes for this, I wonder if there is a more correct way.</p> <p>Thank you.</p>
0
2016-08-14T12:53:21Z
38,942,731
<p>You want something like:</p> <pre><code>class Person(models.Model): LastName = models.CharField(max_length=30) FirstName = models.CharField(max_length=30) ... address = models.ManyToManyField(Address) </code></pre> <p>In this many, one person could have multiple addresses, and each address could have multiple people. If you want to allow only one address per person, use</p> <pre><code> address = models.ForeignKey(Address) </code></pre> <p>This still allows multiple people per address.</p>
1
2016-08-14T13:31:37Z
[ "python", "django", "django-models" ]
Extracting plain text from HTML using Python
38,942,474
<p>I'm trying to extract plain text from a website using python. My code is something like this (a slightly modified version of what I found here):</p> <pre><code>import requests import urllib from bs4 import BeautifulSoup url = "http://www.thelatinlibrary.com/vergil/aen1.shtml" r = requests.get(url) k = r.content file = open('C:\\Users\\Anirudh\\Desktop\\NEW2.txt','w') soup = BeautifulSoup(k) for script in soup(["Script","Style"]): script.exctract() text = soup.get_text file.write(repr(text)) </code></pre> <p>This doesn't seem to work. I'm guessing that <code>beautifulsoup</code> doesn't accept <code>r.content</code>. What can I do to fix this?</p> <p>This is the error - </p> <pre><code>UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently. The code that caused this warning is on line 8 of the file C:/Users/Anirudh/PycharmProjects/untitled/test/__init__.py. To get rid of this warning, change code that looks like this: BeautifulSoup([your markup]) to this: BeautifulSoup([your markup], "html.parser") markup_type=markup_type)) Traceback (most recent call last): File "C:/Users/Anirudh/PycharmProjects/untitled/test/__init__.py", line 12, in &lt;module&gt; file.write(repr(text)) File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\x97' in position 2130: character maps to &lt;undefined&gt; Process finished with exit code 1 </code></pre>
1
2016-08-14T12:58:09Z
38,942,666
<p>The "error" is a warning, and is of no consequence. Quieten it with <code>soup = BeautifulSoup(k, 'html.parser')</code> </p> <p>There seems to be a typo <code>script.exctract()</code> The word <code>extract</code> is spelt incorrectly.</p> <p>The actual error seems to be that the content is a bytestring, but you are writing in text mode. The source contains an em dash. Handling this character is the problem.</p> <p>You can encode with <code>soup.encode("utf-8")</code>. This means hardcoding the encoding into your script (which is bad). Or try using binary mode for the file <code>open(..., 'wb')</code>, or converting the content to a string before passing it to Beautiful Soup, using the correct encoding for that file, with <code>k = str(r.content,"utf-8")</code>.</p>
2
2016-08-14T13:21:41Z
[ "python", "beautifulsoup" ]
Extracting plain text from HTML using Python
38,942,474
<p>I'm trying to extract plain text from a website using python. My code is something like this (a slightly modified version of what I found here):</p> <pre><code>import requests import urllib from bs4 import BeautifulSoup url = "http://www.thelatinlibrary.com/vergil/aen1.shtml" r = requests.get(url) k = r.content file = open('C:\\Users\\Anirudh\\Desktop\\NEW2.txt','w') soup = BeautifulSoup(k) for script in soup(["Script","Style"]): script.exctract() text = soup.get_text file.write(repr(text)) </code></pre> <p>This doesn't seem to work. I'm guessing that <code>beautifulsoup</code> doesn't accept <code>r.content</code>. What can I do to fix this?</p> <p>This is the error - </p> <pre><code>UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently. The code that caused this warning is on line 8 of the file C:/Users/Anirudh/PycharmProjects/untitled/test/__init__.py. To get rid of this warning, change code that looks like this: BeautifulSoup([your markup]) to this: BeautifulSoup([your markup], "html.parser") markup_type=markup_type)) Traceback (most recent call last): File "C:/Users/Anirudh/PycharmProjects/untitled/test/__init__.py", line 12, in &lt;module&gt; file.write(repr(text)) File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\x97' in position 2130: character maps to &lt;undefined&gt; Process finished with exit code 1 </code></pre>
1
2016-08-14T12:58:09Z
38,982,654
<p>There was a — on the code which resulted in an error , '—' being non utf-8 . Changing the encoding before passing text on to BeautifulSoup fixed the issue .</p> <p>Another error was due to soup.get_text . Missing out () implied I was referencing the method , not the output . </p>
0
2016-08-16T19:06:17Z
[ "python", "beautifulsoup" ]
python3 login website tumblr.com
38,942,476
<p>How can I log in tumblr using requests in python3? Here is my code but it dosn't work well and go back to the login page. I used request.post to post a log-in form data, and failed.</p> <pre><code>import requests from bs4 import BeautifulSoup start_url = 'https://www.tumblr.com' # set a session for request s = requests.Session() s.headers.update({'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0', 'accept-language': 'zh-CN,zh;'} ) # get the form_key for login_in r = s.get(start_url) login_soup = BeautifulSoup(r.text, 'lxml') hidden_div = login_soup.find('div', class_='form_row_hidden').find_all('input') key_dict = {} for input_tag in hidden_div: tmp_dict = input_tag.attrs key_dict.update({tmp_dict['name']: tmp_dict['value']}) user_data_dict = {'determine_email': '×××××××××', 'user[email]': '××××××××', 'user[password]': '××××××××', 'user[age]': '', 'tumblelog[name]': ''} key_dict.update(user_data_dict) # log in tumblr r_login=s.post(start_url, headers=headers, data=key_dict) home_soup=BeautifulSoup(r.text, 'lxml') print(home_soup) # the output is still the log-in page. </code></pre>
0
2016-08-14T12:58:23Z
38,944,030
<p>You're nearly to target.</p> <p>Firstly, you have to make a request to tumblr login page (<a href="https://tumblr.com/login" rel="nofollow">https://tumblr.com/login</a>). (You did)</p> <p>Then, you have to parse html page and get <code>form_key</code> value. This value is used to make a real login.</p> <p>Finally, make a post request, with the payload: </p> <pre><code>{'user[email]': your_mail, 'user[password]': your_pass, 'form_key': form_key } </code></pre> <p>Below is sample code in python 2, but I'm not using <code>BeautifulSoup</code> ( you asked to use <code>requests</code> only ;)</p> <pre><code>In [1]: import requests In [2]: from lxml import html In [3]: url = 'https://www.tumblr.com/login' In [4]: ua = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36' In [5]: headers = {'User-Agent': ua} In [6]: s = requests.session() In [7]: lg = s.post(url, headers=headers) In [8]: lg_html = html.fromstring(str(lg.text)) In [9]: form_key = lg_html.xpath("//meta[@name='tumblr-form-key']/@content")[0] In [10]: payload = {'user[email]': 'your_mail', ....: 'user[password]': 'your_pass', ....: 'form_key': form_key} In [11]: # real login In [12]: s.post(url, headers=headers, data=payload) Out[12]: &lt;Response [200]&gt; In [13]: print s.get('https://www.tumblr.com/svc/post/get_post_form_builder_data').text {"meta":{"status":200,"msg":"OK"},"response":{"channels":[{"name":"your_name","tags":[]}],"limits":{"videoSecondsRemaining":300,"preuploadPhotoUsed":0,"preuploadAudioUsed":0,"inlineEmbedsPerPost":5}}} </code></pre>
2
2016-08-14T16:04:56Z
[ "python", "python-3.x", "web-crawler" ]
Error from Python job scheduling module each time I stop server
38,942,506
<p>My models.py file in my Django project contains the code based on the <a href="https://github.com/dbader/schedule" rel="nofollow">following tutorial</a>:</p> <pre><code>import schedule import time def job(): print("I'm working...") schedule.every(3).seconds.do(job) while True: schedule.run_pending() time.sleep(1) </code></pre> <p>Each time I run the application, I get the following output:</p> <pre><code>"C:\Program Files (x86)\JetBrains\PyCharm 2016.1\bin\runnerw.exe" C:\Python27\python.exe D:/blogpodapi/manage.py runserver 8000 I'm working... I'm working... </code></pre> <p>It works as expected, but whenever I close the application, I get the following output:</p> <pre><code>Traceback (most recent call last): File "D:/blogpodapi/manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 302, in execute settings.INSTALLED_APPS File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 55, in __getattr__ self._setup(name) File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "D:\blogpodapi\blogpodapi\__init__.py", line 13, in &lt;module&gt; time.sleep(1) KeyboardInterrupt Process finished with exit code 1 </code></pre> <p>Further to this, my server does not start... as when I remove the abovementioned code, I get the following output:</p> <pre><code>"C:\Program Files (x86)\JetBrains\PyCharm 2016.1\bin\runnerw.exe" C:\Python27\python.exe D:/blogpodapi/manage.py runserver 8000 Performing system checks... System check identified no issues (0 silenced). August 14, 2016 - 14:00:32 Django version 1.9.6, using settings 'blogpodapi.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. </code></pre> <p>I am not to sure what is causing this error. The server won't start when the scheduler is in place and there is an error each time I try to stop the server when it is in place. Ideally I would like the server to start as expected, and the scheduled tasks to start running after this. Any recommendations on how I can fix this?</p> <p>The entirety of the models.py file can be found here: <a href="http://pastebin.com/0DwQWqM8" rel="nofollow">http://pastebin.com/0DwQWqM8</a>.</p>
0
2016-08-14T13:03:03Z
38,942,659
<p>There does not seem to be any problem.</p> <p>The Traceback you posted reports a KeyboardInterrupt which is commonly used to force-quit an application and thus completely normal.</p> <p>The server also seems to have started. Have you tried visiting <a href="http://127.0.0.1:8000/" rel="nofollow">http://127.0.0.1:8000/</a> while the server is running? The last line just tells you to use CTRL-C in the command line if you want to stop the server.</p>
1
2016-08-14T13:21:11Z
[ "python", "django" ]
Why does this not update my table in sqlalchemy?
38,942,545
<p>I have the following code: </p> <pre><code>engine = sqlalchemy.create_engine(connectstring, echo=_echo).connect() md = sqlalchemy.MetaData(engine) table = sqlalchemy.Table('table_name', md, autoload=True, autoload_with=engine) _Session = sessionmaker(bind=engine) session = _Session() for row in reader: table.insert({'key': 'value'}) session.commit() </code></pre> <p>Why does nothing get added to my table? The code runs, but the table is never updated. </p>
0
2016-08-14T13:08:18Z
38,942,929
<p>the insertion was never executed. </p> <pre><code>table.insert({'key': 'value'}).execute() </code></pre> <p>fixes this problem. </p>
1
2016-08-14T13:56:25Z
[ "python", "sql", "sql-server-2008", "orm", "sqlalchemy" ]
TypeError: 'NoneType' object is not iterable error in matoplotlib animation
38,942,549
<p>I've been trying to code an animation using matplolibs FuncAnimation to create a model like the picture below where each frame a circle changes color from white to grey and vice versa. The picture:</p> <p><a href="http://i.stack.imgur.com/WSAQd.png" rel="nofollow">The model</a></p> <p>Below is the code. Consider h as a list containing to separate lists, the first contains the circle to change in each frame and the second the starting colors of the circles in the form of separate 'k' and 'w' strings. An example for h:</p> <pre><code>[[1,3,4,1.....]['k','w','k','w','w'....]] </code></pre> <p>The code:</p> <pre><code>n=5 fig = plt.figure(figsize=(n,n)) x =[i%n+1 for i in range(0,n**2)] y =[i/n+1 for i in range(n**2)] h=giving_data_for_visual(2,n,3,1,2) cl=h[1] colors='' for i in cl: colors+=i changes_list=h[0] scat=plt.scatter(x, y,s=50,facecolors=colors, alpha=0.5) def update(frame): global colors,change_list t=(cl[changes_list[frame]]=='k') cl[changes_list[frame]]='k' if t else 'w' colors=cl scat.set_facecolors(colors) ani=animation.FuncAnimation(fig, update, interval=10, blit=True,frames=len(changes_list)) plt.show() </code></pre> <p>The imports are using are as follows (some aren't meant for this part of the program):</p> <pre><code>from random import randint from random import uniform from math import exp from math import log import matplotlib.pyplot as plt import numpy as np from numpy import std from matplotlib import animation </code></pre> <p>However when i run the code only the first frame appear (something similiar to model i posted above) and when i close its window this error appears:</p> <pre><code>Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Yael\Desktop\WinPython-64bit-2.7.10.2\python-2.7.10.amd64\lib\lib-tk\Tkinter.py", line 1536, in __call__ return self.func(*args) File "C:\Users\Yael\Desktop\WinPython-64bit-2.7.10.2\python-2.7.10.amd64\lib\lib-tk\Tkinter.py", line 587, in callit func(*args) File "C:\Users\Yael\Desktop\WinPython-64bit-2.7.10.2\python-2.7.10.amd64\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 143, in _on_timer TimerBase._on_timer(self) File "C:\Users\Yael\Desktop\WinPython-64bit-2.7.10.2\python-2.7.10.amd64\lib\site-packages\matplotlib\backend_bases.py", line 1290, in _on_timer ret = func(*args, **kwargs) File "C:\Users\Yael\Desktop\WinPython-64bit-2.7.10.2\python-2.7.10.amd64\lib\site-packages\matplotlib\animation.py", line 925, in _step still_going = Animation._step(self, *args) File "C:\Users\Yael\Desktop\WinPython-64bit-2.7.10.2\python-2.7.10.amd64\lib\site-packages\matplotlib\animation.py", line 784, in _step self._draw_next_frame(framedata, self._blit) File "C:\Users\Yael\Desktop\WinPython-64bit-2.7.10.2\python-2.7.10.amd64\lib\site-packages\matplotlib\animation.py", line 802, in _draw_next_frame self._pre_draw(framedata, blit) File "C:\Users\Yael\Desktop\WinPython-64bit-2.7.10.2\python-2.7.10.amd64\lib\site-packages\matplotlib\animation.py", line 815, in _pre_draw self._blit_clear(self._drawn_artists, self._blit_cache) File "C:\Users\Yael\Desktop\WinPython-64bit-2.7.10.2\python-2.7.10.amd64\lib\site-packages\matplotlib\animation.py", line 853, in _blit_clear axes = set(a.axes for a in artists) TypeError: 'NoneType' object is not iterable </code></pre> <p>I cant solve this bug. Thanks in advance for any help :).</p>
0
2016-08-14T13:08:41Z
38,942,896
<p>The <a href="http://matplotlib.org/api/animation_api.html#matplotlib.animation.FuncAnimation" rel="nofollow">documentation of <code>FuncAnimation</code></a> says that the <code>update</code> function should return the changed artists:</p> <pre><code>If blit=True, func and init_func should return an iterable of drawables to clear. </code></pre> <p>You might want to change your function to</p> <pre><code>def update(frame): global colors,change_list t=(cl[changes_list[frame]]=='k') cl[changes_list[frame]]='k' if t else 'w' colors=cl scat.set_facecolors(colors) return scat </code></pre> <p>Note the last line that I added to your code.</p>
0
2016-08-14T13:52:27Z
[ "python", "matplotlib" ]
Python Iterate over NoneType
38,942,625
<p>I have the following code and am attempting to iterate over the results of each line and check if a calculated value in the 'untrained' dictionary is greater than 50%. However, some of the lines are NoneType and I am getting error: TypeError: 'NoneType' oject is not subscriptable. Is there a way I can ovoid this and still iterate to get my desired output below?</p> <pre><code>from collections import namedtuple from itertools import zip_longest trained = {'Dog': 4, 'Cat': 3, 'Bird': 1, 'Fish': 12, 'Mouse': 19, 'Frog': 6} untrained = {'Cat': 6, 'Mouse': 7, 'Dog': 3, 'Wolf': 9} Score = namedtuple('Score', ('total', 'percent', 'name')) trained_scores = [] for t in trained: trained_scores.append( Score(total=trained[t], percent=(trained[t]/(trained[t]+untrained.get(t, 0)))*100, name=t) ) untrained_scores = [] for t in untrained: untrained_scores.append( Score(total=untrained[t], percent=(untrained[t]/(untrained[t]+trained.get(t, 0)))*100, name=t) ) # trained_scores.sort(reverse=True) # untrained_scores.sort(reverse=True) row_template = '{:&lt;30} {:&lt;30}' item_template = '{0.name:&lt;10} {0.total:&gt;3} ({0.percent:&gt;6.2f}%)' print('='*85) print(row_template.format('Trained', 'Untrained')) print('='*85) for trained, untrained in zip_longest(trained_scores, untrained_scores): x = row_template.format( '' if trained is None else item_template.format(trained), '' if untrained is None else item_template.format(untrained) ) print(x) </code></pre> <p>Current Output:</p> <pre><code>===================================================================================== Trained Untrained ===================================================================================== Mouse 19 ( 73.08%) Mouse 7 ( 26.92%) Cat 3 ( 33.33%) Cat 6 ( 66.67%) Frog 6 (100.00%) Wolf 9 (100.00%) Dog 4 ( 57.14%) Dog 3 ( 42.86%) Bird 1 (100.00%) Fish 12 (100.00%) </code></pre> <p>Desired Output:</p> <pre><code>===================================================================================== Trained Untrained ===================================================================================== Mouse 19 ( 73.08%) Mouse 7 ( 26.92%) Cat 3 ( 33.33%) Cat 6 ( 66.67%) &lt;-- Above 50% Frog 6 (100.00%) Wolf 9 (100.00%) &lt;-- Above 50% Dog 4 ( 57.14%) Dog 3 ( 42.86%) Bird 1 (100.00%) Fish 12 (100.00%) </code></pre> <p>Update!:</p> <p>Updated with the suggested code that works. Thanks for all the help!</p> <pre><code>if untrained is not None and untrained[1] &gt; 50: print(x + '&lt;-- Above 50%') else: print(x) </code></pre> <p>Result:</p> <pre><code>===================================================================================== Trained Untrained ===================================================================================== Mouse 19 ( 73.08%) Wolf 9 (100.00%) &lt;-- Above 50% Fish 12 (100.00%) Mouse 7 ( 26.92%) Frog 6 (100.00%) Cat 6 ( 66.67%) &lt;-- Above 50% Dog 4 ( 57.14%) Dog 3 ( 42.86%) Cat 3 ( 33.33%) Bird 1 (100.00%) </code></pre>
0
2016-08-14T13:16:40Z
38,942,653
<p>Skip over None values</p> <pre><code>if untrained is None: continue </code></pre>
4
2016-08-14T13:20:21Z
[ "python", "dictionary", "nonetype" ]
Python Iterate over NoneType
38,942,625
<p>I have the following code and am attempting to iterate over the results of each line and check if a calculated value in the 'untrained' dictionary is greater than 50%. However, some of the lines are NoneType and I am getting error: TypeError: 'NoneType' oject is not subscriptable. Is there a way I can ovoid this and still iterate to get my desired output below?</p> <pre><code>from collections import namedtuple from itertools import zip_longest trained = {'Dog': 4, 'Cat': 3, 'Bird': 1, 'Fish': 12, 'Mouse': 19, 'Frog': 6} untrained = {'Cat': 6, 'Mouse': 7, 'Dog': 3, 'Wolf': 9} Score = namedtuple('Score', ('total', 'percent', 'name')) trained_scores = [] for t in trained: trained_scores.append( Score(total=trained[t], percent=(trained[t]/(trained[t]+untrained.get(t, 0)))*100, name=t) ) untrained_scores = [] for t in untrained: untrained_scores.append( Score(total=untrained[t], percent=(untrained[t]/(untrained[t]+trained.get(t, 0)))*100, name=t) ) # trained_scores.sort(reverse=True) # untrained_scores.sort(reverse=True) row_template = '{:&lt;30} {:&lt;30}' item_template = '{0.name:&lt;10} {0.total:&gt;3} ({0.percent:&gt;6.2f}%)' print('='*85) print(row_template.format('Trained', 'Untrained')) print('='*85) for trained, untrained in zip_longest(trained_scores, untrained_scores): x = row_template.format( '' if trained is None else item_template.format(trained), '' if untrained is None else item_template.format(untrained) ) print(x) </code></pre> <p>Current Output:</p> <pre><code>===================================================================================== Trained Untrained ===================================================================================== Mouse 19 ( 73.08%) Mouse 7 ( 26.92%) Cat 3 ( 33.33%) Cat 6 ( 66.67%) Frog 6 (100.00%) Wolf 9 (100.00%) Dog 4 ( 57.14%) Dog 3 ( 42.86%) Bird 1 (100.00%) Fish 12 (100.00%) </code></pre> <p>Desired Output:</p> <pre><code>===================================================================================== Trained Untrained ===================================================================================== Mouse 19 ( 73.08%) Mouse 7 ( 26.92%) Cat 3 ( 33.33%) Cat 6 ( 66.67%) &lt;-- Above 50% Frog 6 (100.00%) Wolf 9 (100.00%) &lt;-- Above 50% Dog 4 ( 57.14%) Dog 3 ( 42.86%) Bird 1 (100.00%) Fish 12 (100.00%) </code></pre> <p>Update!:</p> <p>Updated with the suggested code that works. Thanks for all the help!</p> <pre><code>if untrained is not None and untrained[1] &gt; 50: print(x + '&lt;-- Above 50%') else: print(x) </code></pre> <p>Result:</p> <pre><code>===================================================================================== Trained Untrained ===================================================================================== Mouse 19 ( 73.08%) Wolf 9 (100.00%) &lt;-- Above 50% Fish 12 (100.00%) Mouse 7 ( 26.92%) Frog 6 (100.00%) Cat 6 ( 66.67%) &lt;-- Above 50% Dog 4 ( 57.14%) Dog 3 ( 42.86%) Cat 3 ( 33.33%) Bird 1 (100.00%) </code></pre>
0
2016-08-14T13:16:40Z
38,942,914
<p>You can not just skip the lines where <code>untrained</code> is <code>None</code> or you will skip the <code>trained</code> values, too. Instead, you should add an additional guard directly to the <code>if</code> condition checking whether the percentage is > 50:</p> <pre><code>if untrained is not None and untrained[1] &gt; 50: print(x + '&lt;-- Above 50%') else: print(x) </code></pre>
1
2016-08-14T13:54:38Z
[ "python", "dictionary", "nonetype" ]
Understanding recursive odd/even functions
38,942,725
<p>I'm currently studying python from <a href="http://www.sololearn.com/Play/Python" rel="nofollow">http://www.sololearn.com/Play/Python</a> and I'm having trouble understanding why this code works.</p> <pre><code>def is_even(x): if x == 0: return True else: return is_odd(x-1) def is_odd(x): return not is_even(x) print(is_odd(1)) </code></pre> <p>I get how recursion works for a fibonacci and factorial but I can't wrap my head around this one.</p>
1
2016-08-14T13:31:05Z
38,942,781
<p>It's based on an inductive definition of evenness:</p> <ul> <li>Zero is even</li> <li>If some number "n" is even, then "n+1" is not even</li> <li>If some number "n" is not even, then "n+1" is even</li> </ul> <p>"odd" is obviously "not even". </p> <p>The code takes this definition, and checks it backwards - using recursion. </p> <ul> <li>If i have zero, then it is even</li> <li>If I have some other number "n" , then it is even if "n-1" is not - that is, if "n-1" is odd. </li> </ul>
1
2016-08-14T13:38:00Z
[ "python", "python-3.x", "recursion" ]
Understanding recursive odd/even functions
38,942,725
<p>I'm currently studying python from <a href="http://www.sololearn.com/Play/Python" rel="nofollow">http://www.sololearn.com/Play/Python</a> and I'm having trouble understanding why this code works.</p> <pre><code>def is_even(x): if x == 0: return True else: return is_odd(x-1) def is_odd(x): return not is_even(x) print(is_odd(1)) </code></pre> <p>I get how recursion works for a fibonacci and factorial but I can't wrap my head around this one.</p>
1
2016-08-14T13:31:05Z
38,942,864
<p>That recursive function is really a bad way to teach recursion, you should apply recursion only when it's useful. In fact, test those functions with negative numbers and you'll get <code>RuntimeError: maximum recursion depth exceeded</code> errors.</p> <p>To check parity numbers you'd better use <code>%</code> operator or <code>&amp;</code> and operator, ie:</p> <pre><code>def is_even(x): return (x &amp; 1) == 0 def is_odd(x): return (x &amp; 1) == 1 </code></pre> <p>That said, I think @Elazar &amp; @DAXaholic answers should give you some insights about that buggy recursive function and wrap your mind about it.</p>
0
2016-08-14T13:48:40Z
[ "python", "python-3.x", "recursion" ]
Understanding recursive odd/even functions
38,942,725
<p>I'm currently studying python from <a href="http://www.sololearn.com/Play/Python" rel="nofollow">http://www.sololearn.com/Play/Python</a> and I'm having trouble understanding why this code works.</p> <pre><code>def is_even(x): if x == 0: return True else: return is_odd(x-1) def is_odd(x): return not is_even(x) print(is_odd(1)) </code></pre> <p>I get how recursion works for a fibonacci and factorial but I can't wrap my head around this one.</p>
1
2016-08-14T13:31:05Z
38,942,897
<p>A little hint:</p> <pre><code>0 -&gt; True 1 -&gt; not True 2 -&gt; not not True 3 -&gt; not not not True ... </code></pre> <p>and so on.</p>
0
2016-08-14T13:52:33Z
[ "python", "python-3.x", "recursion" ]
Understanding recursive odd/even functions
38,942,725
<p>I'm currently studying python from <a href="http://www.sololearn.com/Play/Python" rel="nofollow">http://www.sololearn.com/Play/Python</a> and I'm having trouble understanding why this code works.</p> <pre><code>def is_even(x): if x == 0: return True else: return is_odd(x-1) def is_odd(x): return not is_even(x) print(is_odd(1)) </code></pre> <p>I get how recursion works for a fibonacci and factorial but I can't wrap my head around this one.</p>
1
2016-08-14T13:31:05Z
38,942,979
<p><code>is_even'</code>s base case resolves to <code>True</code>. Since <code>is_odd(x)</code> returns <code>not is_even(x)</code>, the value <code>True</code> will be a part of the expression returned by <code>is_odd</code>. The question is how many times will that <code>True</code> value be <em>negated</em>. By tracing the calls you can see it will be negated an even number of times, and hence "retain" its truthiness, when <code>x</code> is odd [e.g.: <code>x=3</code> ==> <code>(not (not (not (not True))))</code> == <code>True</code>] and an odd number of times, and hence "lose" its truthiness, when <code>x</code> is even [e.g.: <code>x=2</code> ==> <code>(not (not (not True)))</code> == <code>False</code>]. There's probably some term from logic that names this general property of multiple negation.</p>
1
2016-08-14T14:01:47Z
[ "python", "python-3.x", "recursion" ]
Python Pandas Dataframe Append Rows
38,942,790
<p>I'm trying to append the data frame values as rows but its appending them as columns. I have 32 files that i would like to take the second column from (called dataset_code) and append it. But its creating 32 rows and 101 columns. I would like 1 column and 3232 rows.</p> <pre><code>import pandas as pd import os source_directory = r'file_path' df_combined = pd.DataFrame(columns=["dataset_code"]) for file in os.listdir(source_directory): if file.endswith(".csv"): #Read the new CSV to a dataframe. df = pd.read_csv(source_directory + '\\' + file) df = df["dataset_code"] df_combined=df_combined.append(df) print(df_combined) </code></pre>
1
2016-08-14T13:39:15Z
38,942,937
<p><code>df["dataset_code"]</code> is a <code>Series</code>, not a <code>DataFrame</code>. Since you want to append one DataFrame to another, you need to change the Series object to a DataFrame object.</p> <pre><code>&gt;&gt;&gt; type(df) &lt;class 'pandas.core.frame.DataFrame'&gt; &gt;&gt;&gt; type(df['dataset_code']) &lt;class 'pandas.core.series.Series'&gt; </code></pre> <p>To make the conversion, do this:</p> <pre><code>df = df["dataset_code"].to_frame() </code></pre>
3
2016-08-14T13:57:22Z
[ "python", "python-2.7", "pandas", "dataframe" ]
Python Pandas Dataframe Append Rows
38,942,790
<p>I'm trying to append the data frame values as rows but its appending them as columns. I have 32 files that i would like to take the second column from (called dataset_code) and append it. But its creating 32 rows and 101 columns. I would like 1 column and 3232 rows.</p> <pre><code>import pandas as pd import os source_directory = r'file_path' df_combined = pd.DataFrame(columns=["dataset_code"]) for file in os.listdir(source_directory): if file.endswith(".csv"): #Read the new CSV to a dataframe. df = pd.read_csv(source_directory + '\\' + file) df = df["dataset_code"] df_combined=df_combined.append(df) print(df_combined) </code></pre>
1
2016-08-14T13:39:15Z
38,943,318
<p>Alternatively, you can create a dataframe with double square brackets:</p> <pre><code>df = df[["dataset_code"]] </code></pre>
2
2016-08-14T14:44:25Z
[ "python", "python-2.7", "pandas", "dataframe" ]
Python Pandas Dataframe Append Rows
38,942,790
<p>I'm trying to append the data frame values as rows but its appending them as columns. I have 32 files that i would like to take the second column from (called dataset_code) and append it. But its creating 32 rows and 101 columns. I would like 1 column and 3232 rows.</p> <pre><code>import pandas as pd import os source_directory = r'file_path' df_combined = pd.DataFrame(columns=["dataset_code"]) for file in os.listdir(source_directory): if file.endswith(".csv"): #Read the new CSV to a dataframe. df = pd.read_csv(source_directory + '\\' + file) df = df["dataset_code"] df_combined=df_combined.append(df) print(df_combined) </code></pre>
1
2016-08-14T13:39:15Z
38,943,704
<p>You already have two perfectly good answers, but let me make a couple of recommendations.</p> <ol> <li>If you only want the <code>dataset_code</code> column, tell <code>pd.read_csv</code> directly (<code>usecols=['dataset_code']</code>) instead of loading the whole file into memory only to subset the dataframe immediately.</li> <li>Instead of appending to an initially-empty dataframe, collect a list of dataframes and concatenate them in one fell swoop at the end. Appending rows to a pandas <code>DataFrame</code> is costly (it has to create a whole new one), so your approach creates 65 <code>DataFrame</code>s: one at the beginning, one when reading each file, one when appending each of the latter &mdash; maybe even 32 more, with the subsetting. The approach I am proposing only creates 33 of them, and is the common idiom for this kind of importing.</li> </ol> <p>Here is the code:</p> <pre><code>import os import pandas as pd source_directory = r'file_path' dfs = [] for file in os.listdir(source_directory): if file.endswith(".csv"): df = pd.read_csv(os.join.path(source_directory, file), usecols=['dataset_code']) dfs.append(df) df_combined = pd.concat(dfs) </code></pre>
4
2016-08-14T15:29:51Z
[ "python", "python-2.7", "pandas", "dataframe" ]
TypeError: slice indices must be integers in Python 3
38,942,865
<p>I'm new to Python, thus the question,</p> <p>I'm trying to slice an array and find the sub array of the longest length that is less than a particular value. This is my code,</p> <pre><code>def main(): a = [1, 2, 3] print(maxLength(a, 3)) def maxLength(a, k): max = 0 currTotal = 0 for i in enumerate(a): for j in enumerate(a): temp = a[i:i+j:1] currTotal += a[j] if currTotal &lt; k: if len(temp) &gt; max: max = len(temp) currTotal = 0 return max if __name__ == '__main__': main() </code></pre> <p>I'm getting the following error,</p> <pre><code>TypeError: slice indices must be integers or None or have an __index__ method </code></pre> <p>I'm not sure what am I doing wrong with the Slice, any help appreciated.</p>
0
2016-08-14T13:49:05Z
38,942,900
<p>When you use <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a>, it gives you a sequence of tuples.</p> <pre><code>for i,x in enumerate(mylist): # i is the index # x is the item at that index </code></pre> <p>You are assigning that tuple to one variable:</p> <pre><code>for i in enumerate(a): # i is a tuple of (index, item) </code></pre> <p>And then you are trying to use <code>i</code> like it is an integer. It's not an integer.</p> <p>If you want just an integer, use:</p> <pre><code>for i in range(len(a)): for j in range(len(a)): ... </code></pre>
5
2016-08-14T13:52:57Z
[ "python" ]
TypeError: slice indices must be integers in Python 3
38,942,865
<p>I'm new to Python, thus the question,</p> <p>I'm trying to slice an array and find the sub array of the longest length that is less than a particular value. This is my code,</p> <pre><code>def main(): a = [1, 2, 3] print(maxLength(a, 3)) def maxLength(a, k): max = 0 currTotal = 0 for i in enumerate(a): for j in enumerate(a): temp = a[i:i+j:1] currTotal += a[j] if currTotal &lt; k: if len(temp) &gt; max: max = len(temp) currTotal = 0 return max if __name__ == '__main__': main() </code></pre> <p>I'm getting the following error,</p> <pre><code>TypeError: slice indices must be integers or None or have an __index__ method </code></pre> <p>I'm not sure what am I doing wrong with the Slice, any help appreciated.</p>
0
2016-08-14T13:49:05Z
38,942,917
<p><code>enumerate</code> returns an <code>object</code>. Thats why it is giving you that error.</p> <p>if you want to traverse the array, try <code>range(len(a))</code> instead.</p> <pre><code>for i in range(len(a)): for j in range(len(a)): temp = a[i:i+j:1] currTotal += a[j] if currTotal &lt; k: if len(temp) &gt; max: max = len(temp) </code></pre>
0
2016-08-14T13:55:12Z
[ "python" ]
Python and multithreading sys.excepthook is missing
38,942,867
<p>So I have many files to download from a server. Over 1000... So I thought I'd write a script that would do this for me that is multithreaded so that I don't have to wait for ages for it to finish. The problem is that it spits out a bunch of errors. I have searched for this but couldn't really find anything that seemed to be related to the error that I'm having as I don't print out any output in my other threads.</p> <p>my plan was to have the threads chain start each other so that they don't happen to take one file twice and skip some other file.</p> <p>thanks for any help!</p> <pre><code>mylist = [list of filenames in here] mycount = 0 def download(): global mycount url = "http://myserver.com/content/files/" + mylist[mycount] myfile = urllib2.urlopen(url) with open(mylist[mycount],'wb') as output: output.write(myfile.read()) def chain(): global mycount if mycount &lt;= len(mylist) - 1: thread.start_new_thread( download, ()) mycount = mycount + 1 chain() chain() </code></pre>
0
2016-08-14T13:49:15Z
38,944,010
<p>So I actually managed to make it work after some more googling and reading.</p> <p>current code:</p> <pre><code>mycount = 0 mylistLoc = [] for index in range(len(mylist)): mylistLoc.append(index) def download(mycount): global mylistLoc url = "http://myserver.com/content/zips/" + mylist[mycount] try: myfile = urllib2.urlopen(url) with open(mylist[mycount],'wb') as output: output.write(myfile.read()) except: print "Could not open URL: " + url mycount = mycount + 1 mylistLoc = [mycount] from multiprocessing.dummy import Pool as ThreadPool pool = ThreadPool(50) pool.map(download, mylistLoc) </code></pre> <p>First of all I want to mention that the try: statement has nothing to do with the multithreading for all the newbies that may read this.</p> <p>But I found this method on another stackoverflow thread that explains this a bit better.</p> <p><a href="http://stackoverflow.com/questions/2846653/how-to-use-threading-in-python">How to use threading in Python?</a></p> <p>But basically if I understand this correctly, you first import all the necessary functions with the</p> <pre><code>from multiprocessing.dummy import Pool as ThreadPool </code></pre> <p>And then you set how many threads you want active. For me 50 was good. But make sure to read up more on this as having too many can cause problems.</p> <p>then the juice</p> <pre><code>pool.map(download, mylistLoc) </code></pre> <p>Basically, call pool map for every number in mylistLoc.</p> <p>I think it's a weird system but what do I know. It works. Also, I'm a newbie myself.</p>
0
2016-08-14T16:03:10Z
[ "python", "multithreading" ]
Filtering rows containing a string pattern from a Pandas dataframe index
38,943,008
<p>I need to filter rows containing a string pattern from a Pandas dataframe index.</p> <p>I found the following example: <a href="http://stackoverflow.com/questions/27975069/how-to-filter-rows-containing-a-string-pattern-from-a-pandas-dataframe">How to filter rows containing a string pattern from a Pandas dataframe</a> where dataframe is filtered with df[df["col"].str.contains()] which works fine with the example.</p> <pre><code>df = pd.DataFrame({'vals': [1, 2, 3, 4], 'ids': [u'aball', u'bball', u'cnut', u'fball']}) </code></pre> <p>In the example, if I copy the column "ids" to the index, I may use df.index.str.contains("ball"), which also works fine.</p> <p>However, when I use df.index.str.contains("Example") in my dataframe it does not work. </p> <p><strong>I think it doesn't work because in my dataframe the value returned is not an <code>array([ True, False ... , True], dtype=bool)</code>, but an <code>Index([True, False ... , True], dtype='object', length = 667)</code>.</strong></p> <p>How can I reformulate my code so it works?</p> <p>I don't paste my dataframe, because im reading it from a big excel sheet.</p> <p>Thank you!</p>
0
2016-08-14T14:06:24Z
38,943,411
<p>You should ensure that your index is a string. The example below produces an error.</p> <pre><code># Test data df = DataFrame([1,2,3,4], index=['foo', 'foo1', 'foo2', 1], columns=['value']) df[df.index.str.contains('foo')] </code></pre> <p>Converting the index to <code>str</code> permits to obtain the expected result.</p> <pre><code>df.index = df.index.astype('str') df[df.index.str.contains('foo')] value foo 1 foo1 2 foo2 3 </code></pre>
0
2016-08-14T14:55:27Z
[ "python", "pandas" ]
Difference between Python 2 and 3 for shuffle with a given seed
38,943,038
<p>I am writing a program compatible with both Python 2.7 and 3.5. Some parts of it rely on stochastic process. My unit tests use an arbitrary seed, which leads to the same results across executions and languages... except for the code using <code>random.shuffle</code>.</p> <p>Example in Python 2.7:</p> <pre><code>In[]: import random random.seed(42) print(random.random()) l = list(range(20)) random.shuffle(l) print(l) Out[]: 0.639426798458 [6, 8, 9, 15, 7, 3, 17, 14, 11, 16, 2, 19, 18, 1, 13, 10, 12, 4, 5, 0] </code></pre> <p>Same input in Python 3.5:</p> <pre><code>In []: import random random.seed(42) print(random.random()) l = list(range(20)) random.shuffle(l) print(l) Out[]: 0.6394267984578837 [3, 5, 2, 15, 9, 12, 16, 19, 6, 13, 18, 14, 10, 1, 11, 4, 17, 7, 8, 0] </code></pre> <p>Note that the pseudo-random number is the same, but the shuffled lists are different. As expected, reexecuting the cells does not change their respective output.</p> <p>How could I write the same test code for the two versions of Python?</p>
3
2016-08-14T14:09:41Z
38,943,222
<p>In Python 3.2 the random module was refactored a little to make the output uniform across architectures (given the same seed), see <a href="http://bugs.python.org/issue7889" rel="nofollow">issue #7889</a>. The <code>shuffle()</code> method was switched to using <code>Random._randbelow()</code>.</p> <p>However, the <code>_randbelow()</code> method was <em>also</em> adjusted, so simply copying the 3.5 version of <code>shuffle()</code> is not enough to fix this.</p> <p>That said, if you pass in your own <code>random()</code> function, the implementation in Python 3.5 is <em>unchanged from the 2.7</em> version, and thus lets you bypass this limitation:</p> <pre><code>random.shuffle(l, random.random) </code></pre> <p>Note however, than now you are subject to the old 32-bit vs 64-bit architecture differences that #7889 tried to solve.</p> <p>Ignoring several optimisations and special cases, if you include <code>_randbelow()</code> the 3.5 version can be backported as:</p> <pre><code>import random import sys if sys.version_info &gt;= (3, 2): newshuffle = random.shuffle else: try: xrange except NameError: xrange = range def newshuffle(x): def _randbelow(n): "Return a random int in the range [0,n). Raises ValueError if n==0." getrandbits = random.getrandbits k = n.bit_length() # don't use (n-1) here because n can be 1 r = getrandbits(k) # 0 &lt;= r &lt; 2**k while r &gt;= n: r = getrandbits(k) return r for i in xrange(len(x) - 1, 0, -1): # pick an element in x[:i+1] with which to exchange x[i] j = _randbelow(i+1) x[i], x[j] = x[j], x[i] </code></pre> <p>which gives you the same output on 2.7 as 3.5:</p> <pre><code>&gt;&gt;&gt; random.seed(42) &gt;&gt;&gt; print(random.random()) 0.639426798458 &gt;&gt;&gt; l = list(range(20)) &gt;&gt;&gt; newshuffle(l) &gt;&gt;&gt; print(l) [3, 5, 2, 15, 9, 12, 16, 19, 6, 13, 18, 14, 10, 1, 11, 4, 17, 7, 8, 0] </code></pre>
9
2016-08-14T14:31:20Z
[ "python", "python-2.7", "python-3.x", "shuffle", "random-seed" ]
Difference between Python 2 and 3 for shuffle with a given seed
38,943,038
<p>I am writing a program compatible with both Python 2.7 and 3.5. Some parts of it rely on stochastic process. My unit tests use an arbitrary seed, which leads to the same results across executions and languages... except for the code using <code>random.shuffle</code>.</p> <p>Example in Python 2.7:</p> <pre><code>In[]: import random random.seed(42) print(random.random()) l = list(range(20)) random.shuffle(l) print(l) Out[]: 0.639426798458 [6, 8, 9, 15, 7, 3, 17, 14, 11, 16, 2, 19, 18, 1, 13, 10, 12, 4, 5, 0] </code></pre> <p>Same input in Python 3.5:</p> <pre><code>In []: import random random.seed(42) print(random.random()) l = list(range(20)) random.shuffle(l) print(l) Out[]: 0.6394267984578837 [3, 5, 2, 15, 9, 12, 16, 19, 6, 13, 18, 14, 10, 1, 11, 4, 17, 7, 8, 0] </code></pre> <p>Note that the pseudo-random number is the same, but the shuffled lists are different. As expected, reexecuting the cells does not change their respective output.</p> <p>How could I write the same test code for the two versions of Python?</p>
3
2016-08-14T14:09:41Z
38,944,272
<p>Elaborating on Martijn Pieters excellent answer and comments, and on this <a href="http://stackoverflow.com/questions/30585108/disable-hash-randomization-from-within-python-program?noredirect=1&amp;lq=1">discussion</a>, I finally found a workaround, which arguably doesn't answer my very question, but at the same time doesn't require deep changes. To sum up:</p> <ul> <li><code>random.seed</code> actually makes every <code>random</code> function deterministic, but doesn't necessarily produces the same output across versions;</li> <li>setting <code>PYTHONHASHSEED</code> to 0 disables hash randomization for dictionaries and sets, which by default introduces a factor of non-determinism in Python 3.</li> </ul> <p>So, in the bash script which launches the Python 3 tests, I added:</p> <pre><code>export PYTHONHASHSEED=0 </code></pre> <p>Then, I temporarily changed my test functions in order to brute-force my way to an integer seed which would reproduces in Python 3 the results expected in Python 2. Lastly, I reverted my changes and replaced the lines:</p> <pre><code>seed(42) </code></pre> <p>by something like that:</p> <pre><code>seed(42 if sys.version_info.major == 2 else 299) </code></pre> <p>Nothing to brag about, but as the saying goes, sometimes practicality beats purity ;)</p> <p>This quick workaround may be useful to somebody who wants to test the same stochastic code across different versions of Python!</p>
1
2016-08-14T16:34:19Z
[ "python", "python-2.7", "python-3.x", "shuffle", "random-seed" ]
Efficiency issues with finding correlations between lists inside lists
38,943,055
<p>If I have two small lists and I want to find the correlation between each list inside <strong>list1</strong> with each list inside <strong>list2</strong>, I can do this</p> <pre><code>from scipy.stats import pearsonr list1 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] list2 = [[10,20,30],[40,50,60],[77,78,79],[80,78,56]] corrVal = [] for i in list1: for j in list2: corrVal.append(pearsonr(i,j)[0]) print(corrVal) OUTPUT: [1.0, 1.0, 1.0, -0.90112711377916588, 1.0, 1.0, 1.0, -0.90112711377916588, 1.0, 1.0, 1.0, -0.90112711377916588, 1.0, 1.0, 1.0, -0.90112711377916588] </code></pre> <p>Which works out fine...just about. (EDIT: Just noticed my correlation outputs above seem to give the correct answer, but they repeat 4 times. Not exactly sure why its doing that)</p> <p>However for larger datasets with 1000s of values in the lists, my code freezes indefinitely, outputting no errors, hence making me force quit my IDE every time. Any ideas where I'm slipping up here? Not sure whether there is an inherent limit to how much the pearsonr function can handle or whether my coding is causing the problem.</p>
1
2016-08-14T14:10:47Z
38,945,568
<p>Doing the same calculation, but collecting the values in a 4x4 array:</p> <pre><code>In [1791]: res=np.zeros((4,4)) In [1792]: for i in range(4): ...: for j in range(4): ...: res[i,j]=stats.pearsonr(list1[i],list2[j])[0] ...: In [1793]: res Out[1793]: array([[ 1. , 1. , 1. , -0.90112711], [ 1. , 1. , 1. , -0.90112711], [ 1. , 1. , 1. , -0.90112711], [ 1. , 1. , 1. , -0.90112711]]) </code></pre> <p>All sublists are correlated (e.g. <code>[1,2,3]*n</code>) except the last element of <code>list2</code>. </p> <p>I can see where this will slow down as the 2 lists become longer. I don't know how sensitive the <code>pearsonr</code> calculation is to the length of the inputs.</p> <p>The <code>pearsonr</code> code looks straight forward, without loops to slow it down. It might be faster if you could skip the <code>p</code> value; converting each sublist to a zero mean array before hand might also reduce calculation time.</p> <p>Changing the <code>j</code> iteration to avoid recalculating the lower triangle might also help</p> <pre><code>for j in range(i,4): </code></pre>
0
2016-08-14T18:54:25Z
[ "python", "scipy", "correlation" ]
Efficiency issues with finding correlations between lists inside lists
38,943,055
<p>If I have two small lists and I want to find the correlation between each list inside <strong>list1</strong> with each list inside <strong>list2</strong>, I can do this</p> <pre><code>from scipy.stats import pearsonr list1 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] list2 = [[10,20,30],[40,50,60],[77,78,79],[80,78,56]] corrVal = [] for i in list1: for j in list2: corrVal.append(pearsonr(i,j)[0]) print(corrVal) OUTPUT: [1.0, 1.0, 1.0, -0.90112711377916588, 1.0, 1.0, 1.0, -0.90112711377916588, 1.0, 1.0, 1.0, -0.90112711377916588, 1.0, 1.0, 1.0, -0.90112711377916588] </code></pre> <p>Which works out fine...just about. (EDIT: Just noticed my correlation outputs above seem to give the correct answer, but they repeat 4 times. Not exactly sure why its doing that)</p> <p>However for larger datasets with 1000s of values in the lists, my code freezes indefinitely, outputting no errors, hence making me force quit my IDE every time. Any ideas where I'm slipping up here? Not sure whether there is an inherent limit to how much the pearsonr function can handle or whether my coding is causing the problem.</p>
1
2016-08-14T14:10:47Z
38,946,645
<p>The scipy module <a href="http://docs.scipy.org/doc/scipy/reference/spatial.distance.html" rel="nofollow"><code>scipy.spatial.distance</code></a> includes a distance function known as <a href="https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient#Pearson.E2.80.99s_distance" rel="nofollow">Pearson's distance</a>, which is simply 1 minus the correlation coefficient. By using the argument <code>metric='correlation'</code> in <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow"><code>scipy.spatial.distance.cdist</code></a>, you can efficiently compute Pearson's correlation coefficient for each pair of vectors in two inputs.</p> <p>Here's an example. I'll modify your data so the coefficients are more varied:</p> <pre><code>In [96]: list1 = [[1, 2, 3.5], [4, 5, 6], [7, 8, 12], [10, 7, 10]] In [97]: list2 = [[10, 20, 30], [41, 51, 60], [77, 80, 79], [80, 78, 56]] </code></pre> <p>So we know what to expect, here are the correlation coefficients computed using <code>scipy.stats.pearsonr</code>:</p> <pre><code>In [98]: [pearsonr(x, y)[0] for x in list1 for y in list2] Out[98]: [0.99339926779878296, 0.98945694873927104, 0.56362148019067804, -0.94491118252306794, 1.0, 0.99953863896044937, 0.65465367070797709, -0.90112711377916588, 0.94491118252306805, 0.93453339271427294, 0.37115374447904509, -0.99339926779878274, 0.0, -0.030372836961539348, -0.7559289460184544, -0.43355498476205995] </code></pre> <p>It is more convenient to see those in an array:</p> <pre><code>In [99]: np.array([pearsonr(x, y)[0] for x in list1 for y in list2]).reshape(len(list1), len(list2)) Out[99]: array([[ 0.99339927, 0.98945695, 0.56362148, -0.94491118], [ 1. , 0.99953864, 0.65465367, -0.90112711], [ 0.94491118, 0.93453339, 0.37115374, -0.99339927], [ 0. , -0.03037284, -0.75592895, -0.43355498]]) </code></pre> <p>Here's the same result computed using <code>cdist</code>:</p> <pre><code>In [100]: from scipy.spatial.distance import cdist In [101]: 1 - cdist(list1, list2, metric='correlation') Out[101]: array([[ 0.99339927, 0.98945695, 0.56362148, -0.94491118], [ 1. , 0.99953864, 0.65465367, -0.90112711], [ 0.94491118, 0.93453339, 0.37115374, -0.99339927], [ 0. , -0.03037284, -0.75592895, -0.43355498]]) </code></pre> <p>Using <code>cdist</code> is <em>much</em> faster than calling <code>pearsonr</code> in a nested loop. Here I'll use two arrays, <code>data1</code> and <code>data2</code>, each with size (100, 10000):</p> <pre><code>In [102]: data1 = np.random.randn(100, 10000) In [103]: data2 = np.random.randn(100, 10000) </code></pre> <p>I'll use the convenient <code>%timeit</code> command in <code>ipython</code> to measure the execution time:</p> <pre><code>In [104]: %timeit c1 = [pearsonr(x, y)[0] for x in data1 for y in data2] 1 loop, best of 3: 836 ms per loop In [105]: %timeit c2 = 1 - cdist(data1, data2, metric='correlation') 100 loops, best of 3: 4.35 ms per loop </code></pre> <p>That's 836 ms for the nested loop, and 4.35 ms for <code>cdist</code>.</p>
2
2016-08-14T21:07:50Z
[ "python", "scipy", "correlation" ]