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
Python user input for def function
39,803,996
<p>How to do a number input by user first then only display the answer?</p> <pre><code>a = int(raw_input("Enter number: "),twoscomp) def tobin(x, count = 8): return "".join(map(lambda y:str((x&gt;&gt;y)&amp;1), range(count-1, -1, -1))) def twoscomp(bin_str): return tobin(-int(bin_str,2),len(bin_str)) print a </code></pre>
0
2016-10-01T07:16:22Z
39,804,041
<p>I believe this is what you're trying to do?</p> <pre><code>def tobin(x, count = 8): return "".join(map(lambda y:str((x&gt;&gt;y)&amp;1), range(count-1, -1, -1))) def twoscomp(bin_str): return tobin(-int(bin_str,2),len(bin_str)) a = twoscomp(raw_input("Enter number: ")) print a </code></pre> <p>Things to note: </p> <ul> <li>You need to define things before you use them, and that includes functions. </li> <li>Indentation is important, and you should use it.</li> </ul>
3
2016-10-01T07:22:19Z
[ "python", "bit-manipulation", "twos-complement" ]
Python scraping of javascript web pages fails for https pages only
39,804,034
<p>I'm using PyQt5 to scrape web pages, which works great for http:// URLs, but not at all for https:// URLs.</p> <p>The relevant part of my script is below:</p> <pre><code>class WebPage(QWebPage): def __init__(self): super(WebPage, self).__init__() self.timerScreen = QTimer() self.timerScreen.setInterval(2000) self.timerScreen.setSingleShot(True) self.timerScreen.timeout.connect(self.handleLoadFinished) self.loadFinished.connect(self.timerScreen.start) def start(self, urls): self._urls = iter(urls) self.fetchNext() def fetchNext(self): try: url = next(self._urls) except StopIteration: return False else: self.mainFrame().load(QUrl(url)) return True def processCurrentPage(self): url = self.mainFrame().url().toString() html = self.mainFrame().toHtml() #Do stuff with html print('loaded: [%d bytes] %s' % (self.bytesReceived(), url)) def handleLoadFinished(self): self.processCurrentPage() if not self.fetchNext(): qApp.quit() </code></pre> <p>For secure pages, the script returns a blank page. The only html coming back is <code>&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt;</code>.</p> <p>I'm at a bit of a loss. Is there a setting that I'm missing related to handling secure URLs?</p>
11
2016-10-01T07:21:39Z
39,858,556
<p>tested with PyQt4 and normally opened pages with HTTPS</p> <pre><code>import sys from PyQt4.QtGui import QApplication from PyQt4.QtCore import QUrl from PyQt4.QtWebKit import QWebView class Browser(QWebView): def __init__(self): QWebView.__init__(self) self.loadFinished.connect(self._result_available) def _result_available(self, ok): frame = self.page().mainFrame() print(frame.toHtml()) if __name__ == '__main__': app = QApplication(sys.argv) view = Browser() view.load(QUrl('https://www.google.com')) app.exec_() </code></pre>
0
2016-10-04T17:39:51Z
[ "python", "https", "pyqt" ]
Can cPickle save reshaped numpy object reference?
39,804,175
<p>I have a class defined as:</p> <pre><code>class A(): def __init__(): self.a = np.array([0,1,2,3,4,5]) self.b = self.a.reshape((2, 3)) </code></pre> <p>now, b is in fact a reshaped reference of array a. If we change the first element of a:<code>a[0] = 10</code>, <code>b[0, 0]</code> will also change to 10. I use cPickle to save this array, however, when I load the dump. a and b become different array. I want to know whether there are any method to make b still the reference of a?</p>
2
2016-10-01T07:39:28Z
39,804,612
<p>You can use <code>__getstate__</code> and <code>__setstate__</code> to control the pickle:</p> <pre><code>import numpy as np class A: def __init__(self): self.a = np.array([0,1,2,3,4,5]) self.b = self.a.reshape((2, 3)) def __getstate__(self): return {"a":self.a, "b":self.b.shape} def __setstate__(self, state): self.a = state["a"] self.b = self.a.reshape(state["b"]) import pickle x = A() s = pickle.dumps(x) y = pickle.loads(s) y.b.base is y.a </code></pre>
0
2016-10-01T08:39:57Z
[ "python", "numpy", "pickle" ]
Can cPickle save reshaped numpy object reference?
39,804,175
<p>I have a class defined as:</p> <pre><code>class A(): def __init__(): self.a = np.array([0,1,2,3,4,5]) self.b = self.a.reshape((2, 3)) </code></pre> <p>now, b is in fact a reshaped reference of array a. If we change the first element of a:<code>a[0] = 10</code>, <code>b[0, 0]</code> will also change to 10. I use cPickle to save this array, however, when I load the dump. a and b become different array. I want to know whether there are any method to make b still the reference of a?</p>
2
2016-10-01T07:39:28Z
39,804,721
<p>the latest prerelease of jsonpickle does correctly serialize numpy views; pickle sadly does not.</p>
0
2016-10-01T08:52:03Z
[ "python", "numpy", "pickle" ]
Get HTTP 400 Bad Request when login using Python requests
39,804,202
<p>I'm trying to use <code>requests</code> to log into <a href="https://appleid.apple.com/cn" rel="nofollow">https://appleid.apple.com/cn</a> (/us should be the same, but get 400 Bad request returned.</p> <pre><code>session = requests.Session() productURL = &lt;the URL above&gt; headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Encoding": "gzip, deflate, sdch, br", "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.6,en;q=0.4", "Upgrade-Insecure-Requests":"1", "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36" } session.headers = headers r = session.get(productURL) url = "//idmsa.apple.com/appleauth/auth/signin?widgetKey=af1139274f266b22b68c2a3e7ad932cb3c0bbe854e13a79af78dcc73136882c3&amp;language=zh_CN&amp;rv=1" r = session.get(url) url = "//idmsa.apple.com/appleauth/auth/signin" headers = { "Accept":"application/json, text/javascript, */*; q=0.01", "Accept-Encoding":"gzip, deflate, br", "Accept-Language":"zh-CN,zh;q=0.8,zh-TW;q=0.6,en;q=0.4", "Connection":"keep-alive", "Content-Length":"77", "Content-Type":"application/json", "Host":"idmsa.apple.com", "Origin":"https://idmsa.apple.com", "Referer":"//idmsa.apple.com/appleauth/auth/signin?widgetKey=af1139274f266b22b68c2a3e7ad932cb3c0bbe854e13a79af78dcc73136882c3&amp;language=zh_CN&amp;rv=1", "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36", "X-Apple-Domain-Id":1, "X-Apple-I-FD-Client-Info":{"U":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36","L":"en-US","Z":"GMT+08:00","V":"1.1","F":"7da44j1e3NlY5BSo9z4ofjb75PaK4Vpjt4U_98uszHVyVxFAk.lzXJJIneGffLMC7EZ3QHPBirTYKUowRslz8eibjVdxljQlpQJuYY9hte_1an92r5xj6KksmfTPdFdgmVxf7_OLgiPFMJhHFW_jftckkCoqAkCoq4ly_0x0uVMV0jftckcKyAd65hz7fwdGEM6uJ6o6e0T.5EwHXXTSHCSPmtd0wVYPIG_qvoPfybYb5EtCKoxw4EiCvTDfPbJROKjCJcJqOFTsrhsui65KQnK94CaJ6hO3f9p_nH1zDz.ICMpwoNSdqdbAE9XXTneNufuyPBDjaY2ftckuyPB884akHGOg429OMNo71xFmrur.S9RdPQSzOy_Aw7UTlf_0pNA1OXu_Llri5Ly.EKY.6ekL3sdmX.Cr_Jz9KyFxv5icCmVug4WBkl1BQLz4mvmfTT9oaSumKkpjlRiwerbXh8bUu_LzQW5BNv_.BNlYCa1nkBMfs.Byn"}, "X-Apple-Locale":"zh_CN", "X-Apple-Widget-Key":"af1139274f266b22b68c2a3e7ad932cb3c0bbe854e13a79af78dcc73136882c3", "X-Requested-With":"XMLHttpRequest" } session.headers = headers payload = { "accountName" : "accountName", "password" : "password", "rememberMe" : False } r = session.post(url, params=payload) </code></pre> <h3>Headers info</h3> request headers <pre><code>{ 'Content-Length': '77', 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.6,en;q=0.4', 'Accept-Encoding': 'gzip, deflate, br', 'X-Apple-I-FD-Client-Info': { 'F': '7da44j1e3NlY5BSo9z4ofjb75PaK4Vpjt4U_98uszHVyVxFAk.lzXJJIneGffLMC7EZ3QHPBirTYKUowRslz8eibjVdxljQlpQJuYY9hte_1an92r5xj6KksmfTPdFdgmVxf7_OLgiPFMJhHFW_jftckkCoqAkCoq4ly_0x0uVMV0jftckcKyAd65hz7fwdGEM6uJ6o6e0T.5EwHXXTSHCSPmtd0wVYPIG_qvoPfybYb5EtCKoxw4EiCvTDfPbJROKjCJcJqOFTsrhsui65KQnK94CaJ6hO3f9p_nH1zDz.ICMpwoNSdqdbAE9XXTneNufuyPBDjaY2ftckuyPB884akHGOg429OMNo71xFmrur.S9RdPQSzOy_Aw7UTlf_0pNA1OXu_Llri5Ly.EKY.6ekL3sdmX.Cr_Jz9KyFxv5icCmVug4WBkl1BQLz4mvmfTT9oaSumKkpjlRiwerbXh8bUu_LzQW5BNv_.BNlYCa1nkBMfs.Byn', 'Z': 'GMT+08:00', 'U': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36', 'L': 'en-US', 'V': '1.1', }, 'Connection': 'keep-alive', 'X-Apple-Widget-Key': 'af1139274f266b22b68c2a3e7ad932cb3c0bbe854e13a79af78dcc73136882c3', 'Origin': '//idmsa.apple.com', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36', 'Host': 'idmsa.apple.com', 'X-Apple-Domain-Id': 1, 'Referer': '//idmsa.apple.com/appleauth/auth/signin?widgetKey=af1139274f266b22b68c2a3e7ad932cb3c0bbe854e13a79af78dcc73136882c3&amp;language=zh_CN&amp;rv=1', 'X-Apple-Locale': 'zh_CN', 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json', } </code></pre> response headers <pre><code>{ 'X-XSS-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src *; object-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://*.apple.com https://*.cdn-apple.com; style-src 'unsafe-inline' https://*.apple.com https://*.cdn-apple.com; connect-src 'self'; img-src 'self' data: https://*.apple.com https://*.cdn-apple.com https://*.icloud.com https://*.mzstatic.com; media-src * data:;", 'Content-Encoding': 'gzip', 'Transfer-Encoding': 'chunked', 'Set-Cookie': 'dslang=CN-ZH; Domain=.apple.com; Path=/; Secure; HttpOnly, site=CHN; Domain=.apple.com; Path=/; Secure; HttpOnly', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains', 'Vary': 'Accept-Encoding', 'Expires': 'Thu, 01 Jan 1970 00:00:00 GMT', 'Server': 'Apple', 'Connection': 'close', 'X-BuildVersion': 'R15', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache, no-store', 'Date': 'Sat, 01 Oct 2016 04:23:19 GMT', 'X-FRAME-OPTIONS': 'DENY', } </code></pre> <p>I checked all the headers field with the real request headers, "X-Apple-I-FD-Client-Info" is the only one not correct. Dig a little bit, it was calculated by javascript. 'Z','U','L','V' are constant, depends on you browser info and timezone etc. But the 'F' is a very long random string</p> <ul> <li>Is "X-Apple-I-FD-Client-Info" the problem result in 400 Bad request?</li> <li>Is this the right way to write something like auto login? By compareing request headers and cookies one by one?</li> <li>Is it possible to generate or skip header "X-Apple-I-FD-Client-Info"?</li> <li>How can I get this auto login work?</li> </ul>
0
2016-10-01T07:42:59Z
39,805,564
<p>Since I'm new and can't comment (I don't quite understand the reputation system yet), I'll have to write an answer. </p> <p>I know that Google recently blocked the login via scripts (well, via most scripts) because it was rather easy to conduct brute force attacks against accounts. </p> <p>I am presuming that Apple did something very similar and thus making it hard to log onto the AppleId. Do you know for sure that it is possible to login that way?</p> <p>Greetings, Narusan</p>
0
2016-10-01T10:34:16Z
[ "python" ]
Get HTTP 400 Bad Request when login using Python requests
39,804,202
<p>I'm trying to use <code>requests</code> to log into <a href="https://appleid.apple.com/cn" rel="nofollow">https://appleid.apple.com/cn</a> (/us should be the same, but get 400 Bad request returned.</p> <pre><code>session = requests.Session() productURL = &lt;the URL above&gt; headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Encoding": "gzip, deflate, sdch, br", "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.6,en;q=0.4", "Upgrade-Insecure-Requests":"1", "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36" } session.headers = headers r = session.get(productURL) url = "//idmsa.apple.com/appleauth/auth/signin?widgetKey=af1139274f266b22b68c2a3e7ad932cb3c0bbe854e13a79af78dcc73136882c3&amp;language=zh_CN&amp;rv=1" r = session.get(url) url = "//idmsa.apple.com/appleauth/auth/signin" headers = { "Accept":"application/json, text/javascript, */*; q=0.01", "Accept-Encoding":"gzip, deflate, br", "Accept-Language":"zh-CN,zh;q=0.8,zh-TW;q=0.6,en;q=0.4", "Connection":"keep-alive", "Content-Length":"77", "Content-Type":"application/json", "Host":"idmsa.apple.com", "Origin":"https://idmsa.apple.com", "Referer":"//idmsa.apple.com/appleauth/auth/signin?widgetKey=af1139274f266b22b68c2a3e7ad932cb3c0bbe854e13a79af78dcc73136882c3&amp;language=zh_CN&amp;rv=1", "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36", "X-Apple-Domain-Id":1, "X-Apple-I-FD-Client-Info":{"U":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36","L":"en-US","Z":"GMT+08:00","V":"1.1","F":"7da44j1e3NlY5BSo9z4ofjb75PaK4Vpjt4U_98uszHVyVxFAk.lzXJJIneGffLMC7EZ3QHPBirTYKUowRslz8eibjVdxljQlpQJuYY9hte_1an92r5xj6KksmfTPdFdgmVxf7_OLgiPFMJhHFW_jftckkCoqAkCoq4ly_0x0uVMV0jftckcKyAd65hz7fwdGEM6uJ6o6e0T.5EwHXXTSHCSPmtd0wVYPIG_qvoPfybYb5EtCKoxw4EiCvTDfPbJROKjCJcJqOFTsrhsui65KQnK94CaJ6hO3f9p_nH1zDz.ICMpwoNSdqdbAE9XXTneNufuyPBDjaY2ftckuyPB884akHGOg429OMNo71xFmrur.S9RdPQSzOy_Aw7UTlf_0pNA1OXu_Llri5Ly.EKY.6ekL3sdmX.Cr_Jz9KyFxv5icCmVug4WBkl1BQLz4mvmfTT9oaSumKkpjlRiwerbXh8bUu_LzQW5BNv_.BNlYCa1nkBMfs.Byn"}, "X-Apple-Locale":"zh_CN", "X-Apple-Widget-Key":"af1139274f266b22b68c2a3e7ad932cb3c0bbe854e13a79af78dcc73136882c3", "X-Requested-With":"XMLHttpRequest" } session.headers = headers payload = { "accountName" : "accountName", "password" : "password", "rememberMe" : False } r = session.post(url, params=payload) </code></pre> <h3>Headers info</h3> request headers <pre><code>{ 'Content-Length': '77', 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.6,en;q=0.4', 'Accept-Encoding': 'gzip, deflate, br', 'X-Apple-I-FD-Client-Info': { 'F': '7da44j1e3NlY5BSo9z4ofjb75PaK4Vpjt4U_98uszHVyVxFAk.lzXJJIneGffLMC7EZ3QHPBirTYKUowRslz8eibjVdxljQlpQJuYY9hte_1an92r5xj6KksmfTPdFdgmVxf7_OLgiPFMJhHFW_jftckkCoqAkCoq4ly_0x0uVMV0jftckcKyAd65hz7fwdGEM6uJ6o6e0T.5EwHXXTSHCSPmtd0wVYPIG_qvoPfybYb5EtCKoxw4EiCvTDfPbJROKjCJcJqOFTsrhsui65KQnK94CaJ6hO3f9p_nH1zDz.ICMpwoNSdqdbAE9XXTneNufuyPBDjaY2ftckuyPB884akHGOg429OMNo71xFmrur.S9RdPQSzOy_Aw7UTlf_0pNA1OXu_Llri5Ly.EKY.6ekL3sdmX.Cr_Jz9KyFxv5icCmVug4WBkl1BQLz4mvmfTT9oaSumKkpjlRiwerbXh8bUu_LzQW5BNv_.BNlYCa1nkBMfs.Byn', 'Z': 'GMT+08:00', 'U': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36', 'L': 'en-US', 'V': '1.1', }, 'Connection': 'keep-alive', 'X-Apple-Widget-Key': 'af1139274f266b22b68c2a3e7ad932cb3c0bbe854e13a79af78dcc73136882c3', 'Origin': '//idmsa.apple.com', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36', 'Host': 'idmsa.apple.com', 'X-Apple-Domain-Id': 1, 'Referer': '//idmsa.apple.com/appleauth/auth/signin?widgetKey=af1139274f266b22b68c2a3e7ad932cb3c0bbe854e13a79af78dcc73136882c3&amp;language=zh_CN&amp;rv=1', 'X-Apple-Locale': 'zh_CN', 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json', } </code></pre> response headers <pre><code>{ 'X-XSS-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src *; object-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://*.apple.com https://*.cdn-apple.com; style-src 'unsafe-inline' https://*.apple.com https://*.cdn-apple.com; connect-src 'self'; img-src 'self' data: https://*.apple.com https://*.cdn-apple.com https://*.icloud.com https://*.mzstatic.com; media-src * data:;", 'Content-Encoding': 'gzip', 'Transfer-Encoding': 'chunked', 'Set-Cookie': 'dslang=CN-ZH; Domain=.apple.com; Path=/; Secure; HttpOnly, site=CHN; Domain=.apple.com; Path=/; Secure; HttpOnly', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains', 'Vary': 'Accept-Encoding', 'Expires': 'Thu, 01 Jan 1970 00:00:00 GMT', 'Server': 'Apple', 'Connection': 'close', 'X-BuildVersion': 'R15', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache, no-store', 'Date': 'Sat, 01 Oct 2016 04:23:19 GMT', 'X-FRAME-OPTIONS': 'DENY', } </code></pre> <p>I checked all the headers field with the real request headers, "X-Apple-I-FD-Client-Info" is the only one not correct. Dig a little bit, it was calculated by javascript. 'Z','U','L','V' are constant, depends on you browser info and timezone etc. But the 'F' is a very long random string</p> <ul> <li>Is "X-Apple-I-FD-Client-Info" the problem result in 400 Bad request?</li> <li>Is this the right way to write something like auto login? By compareing request headers and cookies one by one?</li> <li>Is it possible to generate or skip header "X-Apple-I-FD-Client-Info"?</li> <li>How can I get this auto login work?</li> </ul>
0
2016-10-01T07:42:59Z
39,805,734
<p>When you are posting JSON you should use requests like:</p> <pre><code>r = requests.post(url, json=payload) </code></pre> <p>also, don't need to hardcode the <code>Content-Length</code> and <code>Content-Type</code> requests package takes care of that.</p>
0
2016-10-01T10:53:29Z
[ "python" ]
Hook in oauth2 code with DRF
39,804,235
<p>I am trying to build an app which has user login and signup functionality.<br>I can create login and signup both from django, and DRF but could not hook in oAuth2 with DRF to make it functional.<br>I have no idea where should i use it.<br><br>Should I generate token on signup or login?<br>How can I make it functional?</p> <p>Here is my code </p> <p><strong>serializers.py</strong></p> <pre><code>class UserSerializer(ModelSerializer): class Meta: model = User class UserCreateSerializer(ModelSerializer): email = EmailField() username = CharField() first_name = CharField(required=False) last_name = CharField(required=False) password = CharField() confirm_password = CharField() class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name', 'password', 'confirm_password' ] extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): username = validated_data['username'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] email = validated_data['email'] password = validated_data['password'] confirm_password = validated_data['password'] user_obj = User( username = username, first_name = first_name, last_name = last_name, email = email ) user_obj.set_password(password) user_obj.save() return validated_data class UserLoginSerializer(ModelSerializer): username = CharField() class Meta: model = User fields = [ 'username', # 'email', 'password', # 'token', ] extra_kwargs = {"password": {"write_only": True} } def validate(self, data): return data </code></pre> <p><strong>views.py</strong></p> <pre><code>class UserCreateAPI(CreateAPIView): serializer_class = UserCreateSerializer queryset = User.objects.all() permission_classes = [AllowAny] class UserLoginAPI(APIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data print('data',data) serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data if new_data: try: user = User.objects.get(username=data['username']) print ('user',user) except ObjectDoesNotExist: return HttpResponse("Can't find this user") login(request, user) return Response(new_data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) </code></pre> <p><strong>tools.py</strong></p> <pre><code>def get_token_json(access_token): return JsonResponse({ 'access_token':access_token.token, 'expires_in':datetime.now() + timedelta(days=365), 'token_type':'Bearer', 'refresh_token':access_token.refresh_token.token, 'scope':access_token.scope }) def get_access_token(user): application = Application.objects.get(name="Foodie") try: old_access_token = AccessToken.objects.get(user=user, application=application) old_refresh_token = RefreshToken.objects.get(user=user, access_token=old_access_token) except ObjectDoesNotExist: return HttpResponse('Have not set any token') else: old_access_token.delete() old_refresh_token.delete() new_token = generate_token() refresh_token = generate_token() access_token=AccessToken.objects.create(user=user, application=app, expires=datetime.now() + timedelta(days=365),token=new_token) RefreshToken.objects.create(user=user, application=app, token=refresh_token, access_token=access_token) print('aceess',AccessToken) return get_token_json(access_token) </code></pre> <p><strong>How can i bridge the gap between DRF and oAuth2 to make login and user registration functional?</strong></p>
0
2016-10-01T07:48:17Z
39,805,256
<p>Try using python social auth.</p> <p>Add <code>social.apps.django_app.default</code> to <code>INSTALLED_APPS</code></p> <p>Add <code>social.backends.facebook.FacebookOAuth2</code> to <code>AUTHENTICATION_BACKENDS</code></p> <p>Add <code>url(r'^auth/', include('social.apps.django_app.urls', namespace='social'))</code> to your <code>urls.py</code></p> <p>However this will work if you have session authentication in your app. If you want to use token based only, then either add a pipe to create the token and send it or take a look at <a href="https://github.com/PhilipGarnero/django-rest-framework-social-oauth2" rel="nofollow">https://github.com/PhilipGarnero/django-rest-framework-social-oauth2</a></p>
0
2016-10-01T09:59:06Z
[ "python", "django", "python-3.x", "oauth-2.0", "django-rest-framework" ]
How to query python list with multiple characters in each one
39,804,239
<p>I know the title is a little messy and if someone wants to fix it, they are more than welcome to.</p> <p>Anyways, I'm having trouble querying a python list with multiple values, I have looked on other Stackoverflow questions and none of seem to match what I'm looking for.</p> <p>So, this is the code I have so far, its supposed to use a for loop statement, so that it goes through each character and then uses and if in statements to check whether a character in the user input matches anything in the list.</p> <p>In my example, it only uses symbols, but hopefully that shouldn't be much of a problem</p> <p>Anyways here is the code</p> <pre><code>string = input("What symbol character would you like to check") symbols=[' ', '!', '#', '$', '%', '&amp;', '"', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '&lt;', '=', '&gt;', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~',"'"] def symbol(): for string in symbols: if string in symbols: return True elif string not in symbols: return False if symbol(): print('ok') if not symbol(): print('What Happened?') </code></pre> <p>*Update, I also need solution to be able to accept letters and numbers as well as the symbols.</p> <p>For example, if user enters !a, that it will still detect the '!' and evaluate to True.</p>
-2
2016-10-01T07:48:49Z
39,805,233
<p>If you loop over the input string, you should be able to get the solution you're looking for. How about something like this?</p> <pre><code>input_string = raw_input("What symbol character would you like to check? ") symbols = [' ', '!', '#', '$', '%', '&amp;', '"', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '&lt;', '=', '&gt;', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~',"'"] def symbol(input_str): for char in input_str: if char in symbols: return True return False if symbol(input_string): print('ok') else: print('What Happened?') </code></pre> <p><code>raw_input()</code> avoids some trouble. Before I changed that, I was getting an <code>unexpected EOF while parsing</code> error. I changed the names of your variables to help a bit and avoid potential conflicts.</p> <p>By moving the <code>return False</code> line outside the <code>for</code> loop, it lets the loop check every character in the input string first. If it checks every one, and nothing matches, then it will default to returning <code>False</code>.</p> <p>Also, you have two calls to <code>symbol()</code> in your question, which I don't think is necessary. One <code>if</code> can check for a <code>True</code> return value. Lacking that, we move to the <code>else</code> statement and can safely know that the function returned <code>False</code>.</p>
1
2016-10-01T09:56:25Z
[ "python", "list", "if-statement", "condition" ]
Print directory where file is saved with Python
39,804,301
<p>how could do print the path directory of my file saved with python. For ad example, i start with idle3 (Fedora 24), i save the IDLE code on: /home/jetson/Desktop/Python/Programs and in the code is written:</p> <pre><code>f = open("Hello.txt","w") f.write("This is a test","\n") f.close() </code></pre> <p>My question is: after f.close i would print the directory grabbed with </p> <pre><code>import sys.os print("The file is saved in ",direcotrysaved) </code></pre> <p>It's possible?</p>
0
2016-10-01T07:58:33Z
39,804,321
<p>If no path is given then the file is opened in the current working directory. This is returned by <code>os.getcwd()</code>.</p>
0
2016-10-01T08:01:12Z
[ "python", "python-3.x" ]
Print directory where file is saved with Python
39,804,301
<p>how could do print the path directory of my file saved with python. For ad example, i start with idle3 (Fedora 24), i save the IDLE code on: /home/jetson/Desktop/Python/Programs and in the code is written:</p> <pre><code>f = open("Hello.txt","w") f.write("This is a test","\n") f.close() </code></pre> <p>My question is: after f.close i would print the directory grabbed with </p> <pre><code>import sys.os print("The file is saved in ",direcotrysaved) </code></pre> <p>It's possible?</p>
0
2016-10-01T07:58:33Z
39,804,355
<p>You can use <code>os.getcwd()</code> for getting the current working directory:</p> <pre><code>import os os.getcwd() </code></pre> <p>Otherwise, you could also specify the full path for the file when opening it, e.g.</p> <pre><code>f.open('/path/to/the/folder/Hello.txt', 'w') </code></pre>
0
2016-10-01T08:04:35Z
[ "python", "python-3.x" ]
Print directory where file is saved with Python
39,804,301
<p>how could do print the path directory of my file saved with python. For ad example, i start with idle3 (Fedora 24), i save the IDLE code on: /home/jetson/Desktop/Python/Programs and in the code is written:</p> <pre><code>f = open("Hello.txt","w") f.write("This is a test","\n") f.close() </code></pre> <p>My question is: after f.close i would print the directory grabbed with </p> <pre><code>import sys.os print("The file is saved in ",direcotrysaved) </code></pre> <p>It's possible?</p>
0
2016-10-01T07:58:33Z
39,804,476
<p>Convert the relative path to absolute path:</p> <pre><code>path = os.path.abspath(filename) </code></pre> <p>Then take just the directory from the absolute path:</p> <pre><code>directory = os.path.dirname(path) </code></pre> <p>That will work regardless of what <code>filename</code> is. It could by just a filename, a relative path or absolute path.</p> <p>See <a href="https://docs.python.org/3/library/os.path.html" rel="nofollow">os.path documentation</a> for other useful functions.</p>
1
2016-10-01T08:21:46Z
[ "python", "python-3.x" ]
Print directory where file is saved with Python
39,804,301
<p>how could do print the path directory of my file saved with python. For ad example, i start with idle3 (Fedora 24), i save the IDLE code on: /home/jetson/Desktop/Python/Programs and in the code is written:</p> <pre><code>f = open("Hello.txt","w") f.write("This is a test","\n") f.close() </code></pre> <p>My question is: after f.close i would print the directory grabbed with </p> <pre><code>import sys.os print("The file is saved in ",direcotrysaved) </code></pre> <p>It's possible?</p>
0
2016-10-01T07:58:33Z
39,805,188
<p>Using f.name provides the file name if you didn't supply it as a separate variable.<br> Using <code>os.path.abspath()</code> provides the full file name including it's directory path i.e. in this case "/home/rolf/def"<br> Using <code>os.path.dirname()</code> strips the file name from the path, as that you already know. </p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; f=open('xxxx.txt','w') &gt;&gt;&gt; f.close() &gt;&gt;&gt; print(f.name,'Stored in', os.path.dirname(os.path.abspath(f.name))) xxxx.txt Stored in /home/rolf/def </code></pre>
0
2016-10-01T09:51:22Z
[ "python", "python-3.x" ]
Print directory where file is saved with Python
39,804,301
<p>how could do print the path directory of my file saved with python. For ad example, i start with idle3 (Fedora 24), i save the IDLE code on: /home/jetson/Desktop/Python/Programs and in the code is written:</p> <pre><code>f = open("Hello.txt","w") f.write("This is a test","\n") f.close() </code></pre> <p>My question is: after f.close i would print the directory grabbed with </p> <pre><code>import sys.os print("The file is saved in ",direcotrysaved) </code></pre> <p>It's possible?</p>
0
2016-10-01T07:58:33Z
39,826,797
<p>Thank's all! It's working, have a nice day!</p>
0
2016-10-03T07:51:41Z
[ "python", "python-3.x" ]
TclError: no display name and no $DISPLAY environment variable on Windows 10 Bash
39,804,366
<p>I tried to install matplotlib on Windows 10 Bash shell.</p> <p>After that, I ran following lines:</p> <pre><code>$ ipython3 </code></pre> <p>then</p> <pre><code>In[1]: %pylab </code></pre> <p>then it gives me a following error:</p> <pre><code>--------------------------------------------------------------------------- TclError Traceback (most recent call last) &lt;ipython-input-1-4ab7ec3413a5&gt; in &lt;module&gt;() ----&gt; 1 get_ipython().magic('pylab') /usr/lib/python3/dist-packages/IPython/core/interactiveshell.py in magic(self, arg_s) 2164 magic_name, _, magic_arg_s = arg_s.partition(' ') 2165 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) -&gt; 2166 return self.run_line_magic(magic_name, magic_arg_s) 2167 2168 #------------------------------------------------------------------------- /usr/lib/python3/dist-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line) 2085 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals 2086 with self.builtin_trap: -&gt; 2087 result = fn(*args,**kwargs) 2088 return result 2089 /usr/lib/python3/dist-packages/IPython/core/magics/pylab.py in pylab(self, line) /usr/lib/python3/dist-packages/IPython/core/magic.py in &lt;lambda&gt;(f, *a, **k) 190 # but it's overkill for just that one bit of state. 191 def magic_deco(arg): --&gt; 192 call = lambda f, *a, **k: f(*a, **k) 193 194 if isinstance(arg, collections.Callable): /usr/lib/python3/dist-packages/IPython/core/magics/pylab.py in pylab(self, line) 129 import_all = not args.no_import_all 130 --&gt; 131 gui, backend, clobbered = self.shell.enable_pylab(args.gui, import_all=import_all) 132 self._show_matplotlib_backend(args.gui, backend) 133 print ("Populating the interactive namespace from numpy and matplotlib") /usr/lib/python3/dist-packages/IPython/core/interactiveshell.py in enable_pylab(self, gui, import_all, welcome_message) 2918 from IPython.core.pylabtools import import_pylab 2919 -&gt; 2920 gui, backend = self.enable_matplotlib(gui) 2921 2922 # We want to prevent the loading of pylab to pollute the user's /usr/lib/python3/dist-packages/IPython/core/interactiveshell.py in enable_matplotlib(self, gui) 2879 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) 2880 -&gt; 2881 pt.activate_matplotlib(backend) 2882 pt.configure_inline_support(self, backend) 2883 /usr/lib/python3/dist-packages/IPython/core/pylabtools.py in activate_matplotlib(backend) 244 matplotlib.rcParams['backend'] = backend 245 --&gt; 246 import matplotlib.pyplot 247 matplotlib.pyplot.switch_backend(backend) 248 /usr/local/lib/python3.4/dist-packages/matplotlib/pyplot.py in &lt;module&gt;() 2510 # are no-ops and the registered function respect `mpl.is_interactive()` 2511 # to determine if they should trigger a draw. -&gt; 2512 install_repl_displayhook() 2513 2514 ################# REMAINING CONTENT GENERATED BY boilerplate.py ############## /usr/local/lib/python3.4/dist-packages/matplotlib/pyplot.py in install_repl_displayhook() 163 ipython_gui_name = backend2gui.get(get_backend()) 164 if ipython_gui_name: --&gt; 165 ip.enable_gui(ipython_gui_name) 166 else: 167 _INSTALL_FIG_OBSERVER = True /usr/lib/python3/dist-packages/IPython/terminal/interactiveshell.py in enable_gui(gui, app) 306 from IPython.lib.inputhook import enable_gui as real_enable_gui 307 try: --&gt; 308 return real_enable_gui(gui, app) 309 except ValueError as e: 310 raise UsageError("%s" % e) /usr/lib/python3/dist-packages/IPython/lib/inputhook.py in enable_gui(gui, app) 526 e = "Invalid GUI request %r, valid ones are:%s" % (gui, list(guis.keys())) 527 raise ValueError(e) --&gt; 528 return gui_hook(app) 529 /usr/lib/python3/dist-packages/IPython/lib/inputhook.py in enable_tk(self, app) 322 if app is None: 323 import tkinter --&gt; 324 app = tkinter.Tk() 325 app.withdraw() 326 self._apps[GUI_TK] = app /usr/lib/python3.4/tkinter/__init__.py in __init__(self, screenName, baseName, className, useTk, sync, use) 1852 baseName = baseName + ext 1853 interactive = 0 -&gt; 1854 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) 1855 if useTk: 1856 self._loadtk() TclError: no display name and no $DISPLAY environment variable </code></pre> <p>I'd appreciate if anybody can point out how to remove this error. Thank you.</p>
2
2016-10-01T08:06:40Z
39,805,613
<p>There is no official display environment for bash on Windows. </p> <ul> <li>You need to install unoffical display environment, i.e. xming (<a href="https://sourceforge.net/projects/xming/" rel="nofollow">https://sourceforge.net/projects/xming/</a>)</li> <li>After installing xming you need to export as <strong>DISPLAY=:0</strong>. </li> <li>You also need to install qtconsole. <strong>sudo apt-get install qtconsole</strong></li> </ul> <p>However, I don't suggest going in this way, there is a much easier way for using ipython on Windows. You can install Anaconda on Windows and you can use ipython without any problems like this (<a href="https://www.continuum.io/downloads" rel="nofollow">https://www.continuum.io/downloads</a>) </p>
2
2016-10-01T10:39:33Z
[ "python", "matplotlib" ]
Python - Sort a list of dics by value of dict`s dict value
39,804,375
<p>I have a list that looks like this:</p> <pre><code>persons = [{'id': 11, 'passport': {'id': 11, 'birth_info':{'date': 10/10/2016...}}},{'id': 22, 'passport': {'id': 22, 'birth_info':{'date': 11/11/2016...}}}] </code></pre> <p>I need to sort the list of persons by their sub key of sub key - their birth_info date.</p> <p>How should I do it ? Thanks</p>
3
2016-10-01T08:07:57Z
39,804,441
<p>Try this</p> <pre><code>from datetime import datetime print(sorted(persons, key=lambda x: datetime.strptime(x['passport']['birth_info']['date'], "%d/%m/%Y"))) #reverse=True for descending order. </code></pre>
2
2016-10-01T08:16:27Z
[ "python", "list", "sorting", "quicksort" ]
Python - Sort a list of dics by value of dict`s dict value
39,804,375
<p>I have a list that looks like this:</p> <pre><code>persons = [{'id': 11, 'passport': {'id': 11, 'birth_info':{'date': 10/10/2016...}}},{'id': 22, 'passport': {'id': 22, 'birth_info':{'date': 11/11/2016...}}}] </code></pre> <p>I need to sort the list of persons by their sub key of sub key - their birth_info date.</p> <p>How should I do it ? Thanks</p>
3
2016-10-01T08:07:57Z
39,804,445
<p>The function <code>sorted()</code> provides the <code>key</code> argument. One can define a callable which returns the key to compare the items:</p> <pre><code>sorted(persons, key=lambda x: x['passport']['birth_info']['date']) </code></pre> <p>The argument x is an item of the given list of persons. </p> <p>If the dates are strings you could use the <code>datetime</code> module:</p> <pre><code>sorted(persons, key=lambda x: datetime.datetime.strptime(x['passport']['birth_info']['date'], '%m/%d/%Y')) </code></pre>
6
2016-10-01T08:17:01Z
[ "python", "list", "sorting", "quicksort" ]
No module named django-extensions
39,804,399
<p>I need help.I am trying to run a django project that requires django-extensions module.i did pip install django-extensions and also in settings.py</p> <pre><code>INSTALLED_APPS = ( .... 'django_extensions', ) </code></pre> <p>but when i try to run the server it says "Import Error,No module named django-extensions.What could be the problem ?</p>
0
2016-10-01T08:11:52Z
39,812,025
<p>Have you look to install this: apt-get install python-django-extensions</p>
0
2016-10-01T22:25:52Z
[ "python", "django" ]
'numpy.ndarray' object is not callable error in python
39,804,439
<p>I was converting LU decomposition matlab code into python.</p> <p>But while I was doing it I encountered with this error </p> <blockquote> <p><code>'numpy.ndarray' object is not callable</code></p> </blockquote> <p>this error occurs when I tried to test my code. Here is my code and can anyone help with this problem?? I'm waiting for your help.</p> <pre><code>import numpy as np def LU(a): [m,m]=a.shape for k in range(0,m-1,1): a[k+1:m-1,k]=a[k+1:m-1,k]/a(k,k) a[k+1:m-1,k+1:m-1]=a[k+1:m-1,k+1:m-1]-a[k+1:m-1,k]*a[k,k+1:m-1] L=np.eye(m,m)+np.tril(a,-1) U=np.triu(a) return [L,U] b=np.array([[1,0,0],[0,1,0],[0,0,1]]) LU(b) </code></pre>
1
2016-10-01T08:16:20Z
39,804,508
<p>The error is occurring because you have used the wrong kind of braces on the 4th line of your function.</p> <pre><code>a[k+1:m-1,k]=a[k+1:m-1,k]/a(k,k) </code></pre> <p>should be corrected to </p> <pre><code>a[k+1:m-1,k]=a[k+1:m-1,k]/a[k,k] </code></pre> <p>i.e. the <code>()</code> braces should be replaced by <code>[]</code>. The error is occurring because <code>[]</code> braces suggest an indexing operation, whereas <code>()</code> braces suggest a function call.</p>
3
2016-10-01T08:26:25Z
[ "python", "numpy", "callable" ]
Assign field from related model as default in another model
39,804,478
<p>How can i assign the default value of current_amount as minimum_price?</p> <pre><code>class Auction(models.Model): minimum_price = models.PositiveIntegerField() ..... class Bid(models.Model): product = models.ForeignKey(Auction, related_name='auction') # i want to set this field's default to value of minimum_price from Auction model current_amount = models.PositiveIntegerField(default=product__minimum_price) #also tried default=product.minimum_price </code></pre> <p>How can i achieve this? </p>
0
2016-10-01T08:21:55Z
39,804,499
<p>One solution is </p> <pre><code>class Bid(models.Model): product = models.ForeignKey(Auction, related_name='auction') current_amount = models.PositiveIntegerField() def save(self, *args, **kwargs): if not self.current_amount: self.current_amount = self.product.minimum_price super(Bid, self).save(*args, **kwargs) </code></pre>
1
2016-10-01T08:24:51Z
[ "python", "django", "database", "sqlite", "django-models" ]
breadth first search optimisation in python
39,804,573
<p>I was solving a problem related to breadth first search. I solved the problem but my solution took the longest time to solve (0.12 as compared to 0.01 and 0.02 done by others). The question is a simple BFS on a graph.</p> <p>Here is how I have implemented BFS:</p> <pre><code>def bfs1(g, s): parent = {s: None} level = {s: 0} frontier = [s] ctr = 1 while frontier: next = [] for i in frontier: for j in g[i]: if j not in parent: parent[j] = i level[j] = ctr next.append(j) frontier = next ctr += 1 return level </code></pre> <p>Here <strong>g</strong> and <strong>s</strong> are adjacency list (dict in case of python) and starting Node respectively.</p> <p>I learned this approach from MIT algorithms course.</p> <p><a href="http://www.spoj.com/problems/NAKANJ/" rel="nofollow">Here</a> is the problem which I was solving.</p> <p>Below is the complete solution which I submitted</p> <pre><code>Here d is the graph which I pre-generated d={'f1': ['d2', 'e3', 'h2', 'g3'], 'f2': ['d1', 'd3', 'e4', 'h1', 'h3', 'g4'], 'f3': ['d2', 'd4', 'e1', 'e5', 'h2', 'h4', 'g1', 'g5'], 'f4': ['d3', 'd5', 'e2', 'e6', 'h3', 'h5', 'g2', 'g6'], 'd8': ['b7', 'c6', 'f7', 'e6'], 'f6': ['d5', 'd7', 'e4', 'e8', 'h5', 'h7', 'g4', 'g8'], 'f7': ['d6', 'd8', 'e5', 'h6', 'h8', 'g5'], 'f8': ['d7', 'e6', 'h7', 'g6'], 'h3': ['f2', 'f4', 'g1', 'g5'], 'h1': ['f2', 'g3'], 'h6': ['f5', 'f7', 'g4', 'g8'], 'h7': ['f6', 'f8', 'g5'], 'h4': ['f3', 'f5', 'g2', 'g6'], 'h5': ['f4', 'f6', 'g3', 'g7'], 'b4': ['a2', 'a6', 'd3', 'd5', 'c2', 'c6'], 'b5': ['a3', 'a7', 'd4', 'd6', 'c3', 'c7'], 'b6': ['a4', 'a8', 'd5', 'd7', 'c4', 'c8'], 'b7': ['a5', 'd6', 'd8', 'c5'], 'b1': ['a3', 'd2', 'c3'], 'b2': ['a4', 'd1', 'd3', 'c4'], 'b3': ['a1', 'a5', 'd2', 'd4', 'c1', 'c5'], 'd6': ['b5', 'b7', 'c4', 'c8', 'f5', 'f7', 'e4', 'e8'], 'd7': ['b6', 'b8', 'c5', 'f6', 'f8', 'e5'], 'd4': ['b3', 'b5', 'c2', 'c6', 'f3', 'f5', 'e2', 'e6'], 'd5': ['b4', 'b6', 'c3', 'c7', 'f4', 'f6', 'e3', 'e7'], 'b8': ['a6', 'd7', 'c6'], 'd3': ['b2', 'b4', 'c1', 'c5', 'f2', 'f4', 'e1', 'e5'], 'd1': ['b2', 'c3', 'f2', 'e3'], 'e1': ['c2', 'd3', 'g2', 'f3'], 'f5': ['d4', 'd6', 'e3', 'e7', 'h4', 'h6', 'g3', 'g7'], 'd2': ['b1', 'b3', 'c4', 'f1', 'f3', 'e4'], 'e5': ['c4', 'c6', 'd3', 'd7', 'g4', 'g6', 'f3', 'f7'], 'h2': ['f1', 'f3', 'g4'], 'e3': ['c2', 'c4', 'd1', 'd5', 'g2', 'g4', 'f1', 'f5'], 'h8': ['f7', 'g6'], 'e2': ['c1', 'c3', 'd4', 'g1', 'g3', 'f4'], 'g7': ['e6', 'e8', 'f5', 'h5'], 'g6': ['e5', 'e7', 'f4', 'f8', 'h4', 'h8'], 'g5': ['e4', 'e6', 'f3', 'f7', 'h3', 'h7'], 'g4': ['e3', 'e5', 'f2', 'f6', 'h2', 'h6'], 'g3': ['e2', 'e4', 'f1', 'f5', 'h1', 'h5'], 'g2': ['e1', 'e3', 'f4', 'h4'], 'g1': ['e2', 'f3', 'h3'], 'e4': ['c3', 'c5', 'd2', 'd6', 'g3', 'g5', 'f2', 'f6'], 'g8': ['e7', 'f6', 'h6'], 'a1': ['c2', 'b3'], 'a3': ['c2', 'c4', 'b1', 'b5'], 'a2': ['c1', 'c3', 'b4'], 'a5': ['c4', 'c6', 'b3', 'b7'], 'a4': ['c3', 'c5', 'b2', 'b6'], 'a7': ['c6', 'c8', 'b5'], 'a6': ['c5', 'c7', 'b4', 'b8'], 'c3': ['a2', 'a4', 'b1', 'b5', 'e2', 'e4', 'd1', 'd5'], 'c2': ['a1', 'a3', 'b4', 'e1', 'e3', 'd4'], 'c1': ['a2', 'b3', 'e2', 'd3'], 'e6': ['c5', 'c7', 'd4', 'd8', 'g5', 'g7', 'f4', 'f8'], 'c7': ['a6', 'a8', 'b5', 'e6', 'e8', 'd5'], 'c6': ['a5', 'a7', 'b4', 'b8', 'e5', 'e7', 'd4', 'd8'], 'c5': ['a4', 'a6', 'b3', 'b7', 'e4', 'e6', 'd3', 'd7'], 'c4': ['a3', 'a5', 'b2', 'b6', 'e3', 'e5', 'd2', 'd6'], 'e7': ['c6', 'c8', 'd5', 'g6', 'g8', 'f5'], 'a8': ['c7', 'b6'], 'c8': ['a7', 'b6', 'e7', 'd6'], 'e8': ['c7', 'd6', 'g7', 'f6']} def bfs1(g, s): # parent = {s: None} level = {s: 0} frontier = [s] ctr = 1 while frontier: next = [] for i in frontier: for j in g[i]: if j not in level: # parent[j] = i level[j] = ctr next.append(j) frontier = next ctr += 1 return level for i in range(int(raw_input())): x, y = raw_input().split() print bfs1(d, x).get(y) </code></pre>
0
2016-10-01T08:34:42Z
39,808,088
<p>The main problem performance-wise seem to be the fact that this is performing a full graph search and returning the distances of all nodes compared to the root node.</p> <p>That is much more than is needed for the problem at hand.</p> <p>In the <a href="http://www.spoj.com/problems/NAKANJ/" rel="nofollow">specific chess problem you are trying to solve</a> (find out how many jumps a knight has to make from A to B), this function will find out how many jumps a knigth needs to make from A to <strong>every other square</strong>.</p> <p>So, it if input asks for the simplest A1-B3 (answer: 1), this function will also calculate A1-C8, A1-H7...</p> <p>There are several options for solving that problem. I would get rid of the <code>level</code> variable entirely and replace writing to it with a yield. So instead of:</p> <pre><code>level[j] = ctr </code></pre> <p>do this:</p> <pre><code>yield j, ctr </code></pre> <p>Then the caller of this function can stop further execution as soon as the wanted result is reached.</p> <h2>Furthermore</h2> <p>I would also rename all the variables, so that it is clear what they are. There is no way you can make meaningful code analysis if it is all cryptic.</p> <p>Then, replace <code>parent = {}</code> with <code>seen = set()</code>, because you only use it to skip nodes which were already seen.</p> <p>With those little changes, you get:</p> <pre><code>def bfs1(adjacency, root): seen = {root} frontier = [root] yield root, 0 next_distance = 1 while frontier: next_frontier = [] for node in frontier: for next_node in adjacency[node]: if next_node in seen: continue seen.add(next_node) yield next_node, next_distance next_frontier.append(next_node) frontier = next_frontier next_distance += 1 </code></pre> <p>And then you need:</p> <pre><code>def get_distance_from_a_to_b(a, b, adjacency): for node, distance in bfs1(adjacency, a): if node == b: return distance </code></pre>
1
2016-10-01T15:02:08Z
[ "python", "algorithm", "graph-algorithm", "bfs" ]
breadth first search optimisation in python
39,804,573
<p>I was solving a problem related to breadth first search. I solved the problem but my solution took the longest time to solve (0.12 as compared to 0.01 and 0.02 done by others). The question is a simple BFS on a graph.</p> <p>Here is how I have implemented BFS:</p> <pre><code>def bfs1(g, s): parent = {s: None} level = {s: 0} frontier = [s] ctr = 1 while frontier: next = [] for i in frontier: for j in g[i]: if j not in parent: parent[j] = i level[j] = ctr next.append(j) frontier = next ctr += 1 return level </code></pre> <p>Here <strong>g</strong> and <strong>s</strong> are adjacency list (dict in case of python) and starting Node respectively.</p> <p>I learned this approach from MIT algorithms course.</p> <p><a href="http://www.spoj.com/problems/NAKANJ/" rel="nofollow">Here</a> is the problem which I was solving.</p> <p>Below is the complete solution which I submitted</p> <pre><code>Here d is the graph which I pre-generated d={'f1': ['d2', 'e3', 'h2', 'g3'], 'f2': ['d1', 'd3', 'e4', 'h1', 'h3', 'g4'], 'f3': ['d2', 'd4', 'e1', 'e5', 'h2', 'h4', 'g1', 'g5'], 'f4': ['d3', 'd5', 'e2', 'e6', 'h3', 'h5', 'g2', 'g6'], 'd8': ['b7', 'c6', 'f7', 'e6'], 'f6': ['d5', 'd7', 'e4', 'e8', 'h5', 'h7', 'g4', 'g8'], 'f7': ['d6', 'd8', 'e5', 'h6', 'h8', 'g5'], 'f8': ['d7', 'e6', 'h7', 'g6'], 'h3': ['f2', 'f4', 'g1', 'g5'], 'h1': ['f2', 'g3'], 'h6': ['f5', 'f7', 'g4', 'g8'], 'h7': ['f6', 'f8', 'g5'], 'h4': ['f3', 'f5', 'g2', 'g6'], 'h5': ['f4', 'f6', 'g3', 'g7'], 'b4': ['a2', 'a6', 'd3', 'd5', 'c2', 'c6'], 'b5': ['a3', 'a7', 'd4', 'd6', 'c3', 'c7'], 'b6': ['a4', 'a8', 'd5', 'd7', 'c4', 'c8'], 'b7': ['a5', 'd6', 'd8', 'c5'], 'b1': ['a3', 'd2', 'c3'], 'b2': ['a4', 'd1', 'd3', 'c4'], 'b3': ['a1', 'a5', 'd2', 'd4', 'c1', 'c5'], 'd6': ['b5', 'b7', 'c4', 'c8', 'f5', 'f7', 'e4', 'e8'], 'd7': ['b6', 'b8', 'c5', 'f6', 'f8', 'e5'], 'd4': ['b3', 'b5', 'c2', 'c6', 'f3', 'f5', 'e2', 'e6'], 'd5': ['b4', 'b6', 'c3', 'c7', 'f4', 'f6', 'e3', 'e7'], 'b8': ['a6', 'd7', 'c6'], 'd3': ['b2', 'b4', 'c1', 'c5', 'f2', 'f4', 'e1', 'e5'], 'd1': ['b2', 'c3', 'f2', 'e3'], 'e1': ['c2', 'd3', 'g2', 'f3'], 'f5': ['d4', 'd6', 'e3', 'e7', 'h4', 'h6', 'g3', 'g7'], 'd2': ['b1', 'b3', 'c4', 'f1', 'f3', 'e4'], 'e5': ['c4', 'c6', 'd3', 'd7', 'g4', 'g6', 'f3', 'f7'], 'h2': ['f1', 'f3', 'g4'], 'e3': ['c2', 'c4', 'd1', 'd5', 'g2', 'g4', 'f1', 'f5'], 'h8': ['f7', 'g6'], 'e2': ['c1', 'c3', 'd4', 'g1', 'g3', 'f4'], 'g7': ['e6', 'e8', 'f5', 'h5'], 'g6': ['e5', 'e7', 'f4', 'f8', 'h4', 'h8'], 'g5': ['e4', 'e6', 'f3', 'f7', 'h3', 'h7'], 'g4': ['e3', 'e5', 'f2', 'f6', 'h2', 'h6'], 'g3': ['e2', 'e4', 'f1', 'f5', 'h1', 'h5'], 'g2': ['e1', 'e3', 'f4', 'h4'], 'g1': ['e2', 'f3', 'h3'], 'e4': ['c3', 'c5', 'd2', 'd6', 'g3', 'g5', 'f2', 'f6'], 'g8': ['e7', 'f6', 'h6'], 'a1': ['c2', 'b3'], 'a3': ['c2', 'c4', 'b1', 'b5'], 'a2': ['c1', 'c3', 'b4'], 'a5': ['c4', 'c6', 'b3', 'b7'], 'a4': ['c3', 'c5', 'b2', 'b6'], 'a7': ['c6', 'c8', 'b5'], 'a6': ['c5', 'c7', 'b4', 'b8'], 'c3': ['a2', 'a4', 'b1', 'b5', 'e2', 'e4', 'd1', 'd5'], 'c2': ['a1', 'a3', 'b4', 'e1', 'e3', 'd4'], 'c1': ['a2', 'b3', 'e2', 'd3'], 'e6': ['c5', 'c7', 'd4', 'd8', 'g5', 'g7', 'f4', 'f8'], 'c7': ['a6', 'a8', 'b5', 'e6', 'e8', 'd5'], 'c6': ['a5', 'a7', 'b4', 'b8', 'e5', 'e7', 'd4', 'd8'], 'c5': ['a4', 'a6', 'b3', 'b7', 'e4', 'e6', 'd3', 'd7'], 'c4': ['a3', 'a5', 'b2', 'b6', 'e3', 'e5', 'd2', 'd6'], 'e7': ['c6', 'c8', 'd5', 'g6', 'g8', 'f5'], 'a8': ['c7', 'b6'], 'c8': ['a7', 'b6', 'e7', 'd6'], 'e8': ['c7', 'd6', 'g7', 'f6']} def bfs1(g, s): # parent = {s: None} level = {s: 0} frontier = [s] ctr = 1 while frontier: next = [] for i in frontier: for j in g[i]: if j not in level: # parent[j] = i level[j] = ctr next.append(j) frontier = next ctr += 1 return level for i in range(int(raw_input())): x, y = raw_input().split() print bfs1(d, x).get(y) </code></pre>
0
2016-10-01T08:34:42Z
39,817,118
<p>There has been some advice to implement a nice bfs. In two dimensional problems you can save half the time by searching from both ends simultanously.</p> <p>But when it comes to brute optimisation for timing you always go for lookup tables. In your case you have quite nice constraints: 64 positions to start and 64 positions to finish. that is a pretty small lookup table of 4096 integers. So use whatever inefficient algorithm in a helper program to fill that lookup table and print it out. paste that table into the source code of your competition code.</p>
0
2016-10-02T12:41:57Z
[ "python", "algorithm", "graph-algorithm", "bfs" ]
How do i fix reshaping my dataset for cross validation?
39,804,629
<pre><code>x_train:(153347,53) x_test:(29039,52) y:(153347,) </code></pre> <p>I am working with sklearn. To cross validate and reshape my dataset i did:</p> <pre><code>x_train, x_test, y_train, y_test = cross_validation.train_test_split( x, y, test_size=0.3) x_train = np.pad(x, [(0,0)], mode='constant') x_test = np.pad(x, [(0,0)], mode='constant') y = np.pad(y, [(0,0)], mode='constant') x_train = np.arange(8127391).reshape((-1,1)) c = x.T np.all(x_train == c) x_test = np.arange(1510028).reshape((-1,1)) c2 = x.T np.all(x_test == c2) y = np.arange(153347).reshape((-1,1)) c3 = x.T np.all(y == c3) </code></pre> <p>My error message is:ValueError: Found arrays with inconsistent numbers of samples: [ 2 153347]</p> <p>I am not sure i need to pad my dataset in this case and the reshape is not working. Any ideas on how i can fix this?</p>
2
2016-10-01T08:41:48Z
39,805,142
<p>With the little we see here one, I believe the call to <code>cross_validation.train_test_split</code> dumps because the the length of the two vectors does not coincide. So for every X (the data tuple we you observe) you need a Y (the data-point that is observed as a result).</p> <p>At least this leads to the error shown above.</p> <p>You should definitely improve on the formulation of the problem. Very much so.</p> <p>regards, fricke</p>
1
2016-10-01T09:45:22Z
[ "python", "numpy", "machine-learning", "scikit-learn", "cross-validation" ]
Scrapy: Problems installing on clean anaconda environment
39,804,652
<p>On a clean environment of anaconda, after running <code>conda install -c scrapinghub scrapy</code> which as of today install scrapy 1.1.2, on python 2.7 for some reason does not create the scrapy-script.py file and scrapy.exe file.</p> <p>Scrapy does not install correctly, command is unrecognized (obviously)..</p>
0
2016-10-01T08:44:32Z
39,804,676
<p>I solved the issue by installing a previous scrapy version:</p> <pre><code>conda install -c anaconda scrapy=1.1.1 </code></pre> <p>beware, this does not solve other issues with scrapy and anaconda, like pyopenssl issues:</p> <pre><code>ImportError: DLL load failed: the operating system cannot run %1. </code></pre>
0
2016-10-01T08:46:45Z
[ "python", "python-2.7", "scrapy", "anaconda" ]
detecting keyboard overrun in tkinter event handler when autorepeating to avoid lag
39,804,732
<p>In my app I want to allow the user to scroll through images by holding down an arrow key. Not surprisingly with larger images the pc can't keep up, and builds up a potentially large buffer that carries on being processed after the key is released.</p> <p>None of this is unexpected, and my normal answer is just to check the timestamp in the event against the current time and discard any events that are more than (say) .2 seconds old. This way the backlog can never get too large.</p> <p>But tkinter uses some random timebase of events so that comparing with time.time() is meaningless, and I can't find a function to get hold of tkinter's own clock. I'm sure its in there, it's just most of the pythonised tkinter documentation is a bit naff, and searching for time or clock isn't helping either.</p> <pre><code>def plotprev(self,p): if time.time() - p.time &gt; .2: return </code></pre> <p>Sadly this test always returns true, where is tkinter's pseudo clock to be found? Any other method will be complex in comparison.</p>
-1
2016-10-01T08:53:37Z
39,870,990
<p>well it's nor very nice, but it isn't too tedious and seems to work quite well: (with a little bit of monitoring as well)</p> <pre><code> def checklag(self,p): if self.lasteventtime is None: #assume first event arrives with no significant delay self.lasteventtime = p.time self.lasteventrealtime = time.time() self.lagok=0 self.lagfail=0 return True ptdiff = (p.time-self.lasteventtime) / 1000 rtdiff = time.time() - self.lasteventrealtime lag = rtdiff-ptdiff if lag &lt; .3: self.lagok += 1 if self.lagok %20 == 0: print("lagy? OK: %d, fail: %d" %(self.lagok, self.lagfail)) return True else: self.lagfail += 1 return False </code></pre>
0
2016-10-05T10:01:21Z
[ "python", "events", "tkinter" ]
Dummy creation in pipeline with different levels in train and test set
39,804,733
<p>I'm currently exploring the scikit learn pipelines. I also want to preprocess the data with a pipeline. However, my train and test data have different levels of the categorical variable. Example: Consider:</p> <pre><code>import pandas as pd train = pd.Series(list('abbaa')) test = pd.Series(list('abcd')) </code></pre> <p>I wrote a TransformerMixinClass using pandas</p> <pre><code>class CreateDummies(TransformerMixin): def transform(self, X, **transformparams): return pd.get_dummies(X).copy() def fit(self, X, y=None, **fitparams): return self </code></pre> <p>fit_transform yields for the train data 2 columns and for the test data 4 columns. So no surprise here, but not suitable for a pipeline</p> <p>Similary, I tried to import the label encoder (and OneHotEncoder for the potential next steps):</p> <pre><code>from sklearn.preprocessing import LabelEncoder, OneHotEncoder le = LabelEncoder() le.fit_transform(train) le.transform(test) </code></pre> <p>which yields, not surprisingly, an error.</p> <p>So the problem here is that I need some information contained in the test set. Is there a good way to include this in a pipeline?</p>
2
2016-10-01T08:53:53Z
39,805,740
<p>You can use categoricals as explained in <a href="http://stackoverflow.com/a/37451867/2285236">this answer</a>:</p> <pre><code>categories = np.union1d(train, test) train = train.astype('category', categories=categories) test = test.astype('category', categories=categories) pd.get_dummies(train) Out: a b c d 0 1 0 0 0 1 0 1 0 0 2 0 1 0 0 3 1 0 0 0 4 1 0 0 0 pd.get_dummies(test) Out: a b c d 0 1 0 0 0 1 0 1 0 0 2 0 0 1 0 3 0 0 0 1 </code></pre>
2
2016-10-01T10:53:54Z
[ "python", "pandas", "scikit-learn" ]
Turning 4 metric coordinates of Vector into a Vector field
39,804,757
<p>I have four 3*3 matrices:</p> <pre><code>X1=[[2.276840271621883, 2.329662596474333, 2.3633290819729527], [2.276840271621883, 2.329662596474333, 2.3633290819729527], [2.276840271621883, 2.329662596474333, 2.3633290819729527]] X2=[[2.2698145746531786, 2.3308266405107805, 2.3594316100497643], [2.2698145746531786, 2.3308266405107805, 2.3594316100497643], [2.2698145746531786, 2.3308266405107805, 2.3594316100497643]] Y1=[[48.832151066337865, 48.84935494957576, 48.86990145209316], [48.832151066337865, 48.84935494957576, 48.86990145209316], [48.832151066337865, 48.84935494957576, 48.86990145209316]] Y2=[[48.83251302946139, 48.85024866127781, 48.86928223168673], [48.83251302946139, 48.85024866127781, 48.86928223168673], [48.83251302946139, 48.85024866127781, 48.86928223168673]] </code></pre> <p>I would like to create a vector field containing 9 vectors going from</p> <pre><code>(X1[i][j],Y1[i][j]) to (X2[i][j],Y2[i][j]) these are coordinates </code></pre> <p>I have tried using quiver, but I have a dimension problem.</p>
0
2016-10-01T08:57:25Z
39,807,867
<p>When you want to plot a set of arrows using matplotlib's <code>quiver</code> function, that start at points <code>Pi = (X1i, Y1i)</code> and "end" at points <code>Qi = (X2i, Y2i)</code>, you call <code>quiver</code> like this:</p> <pre><code># creating demo data X1, X2, Y1, Y2 = [ np.random.random_integers(0, 9, (2,2)) for _ in range(4) ] plt.quiver(X1, Y1, (X2 - X1), (Y2 - Y1), angles='xy', scale=1, scale_units='xy') </code></pre> <p>Notice the added arguments in the call to <code>quiver</code>. These ensure that the arrows start and end in the provided data coordinates. The shape for <code>X1</code> and the other 3 variables defined here is <code>(2, 2)</code>, which was done only to illustrate that <code>quiver</code> can work with 2-D arrays. You could make the shape <code>(3, 3)</code> to suit your example.</p> <p>For visualisation purposes and to make the point more clear, I've added some markers to the start and end coordinates:</p> <pre><code>plt.plot(X1.ravel(), Y1.ravel(), 'ro ') plt.plot(X2.ravel(), Y2.ravel(), 'bx ') </code></pre> <p>which results in this figure:</p> <p><a href="http://i.stack.imgur.com/KtDuh.png" rel="nofollow"><img src="http://i.stack.imgur.com/KtDuh.png" alt="quiver arrows from begin to end coordinates"></a></p>
0
2016-10-01T14:39:52Z
[ "python", "matplotlib", "arrow" ]
Stuck implementing simple neural network
39,804,774
<p>I've been bashing my head against this brick wall for what seems like an eternity, and I just can't seem to wrap my head around it. I'm trying to implement an autoencoder using only numpy and matrix multiplication. No theano or keras tricks allowed.</p> <p>I'll describe the problem and all its details. It is a bit complex at first since there are a lot of variables, but it really is quite straightforward.</p> <p><strong>What we know</strong></p> <p>1) <code>X</code> is an <code>m</code> by <code>n</code> matrix which is our inputs. The inputs are rows of this matrix. Each input is an <code>n</code> dimensional row vector, and we have <code>m</code> of them.</p> <p>2)The number of neurons in our (single) hidden layer, which is <code>k</code>.</p> <p>3) The activation function of our neurons (sigmoid, will be denoted as <code>g(x)</code>) and its derivative <code>g'(x)</code></p> <p><strong>What we don't know and want to find</strong></p> <p>Overall our goal is to find 6 matrices: <code>w1</code> which is <code>n</code> by <code>k</code>, <code>b1</code> which is <code>m</code> by <code>k</code>, <code>w2</code> which is <code>k</code> by <code>n</code>, b2 which is <code>m</code> by <code>n</code>, <code>w3</code> which is <code>n</code> by <code>n</code> and <code>b3</code> which is <code>m</code> by <code>n</code>.</p> <p>They are initallized randomly and we find the best solution using gradient descent.</p> <p><strong>The process</strong></p> <p>The entire process looks something like this <a href="http://i.stack.imgur.com/OQl3g.jpg"><img src="http://i.stack.imgur.com/OQl3g.jpg" alt="enter image description here"></a></p> <p>First we compute <code>z1 = Xw1+b1</code>. It is <code>m</code> by <code>k</code> and is the input to our hidden layer. We then compute <code>h1 = g(z1)</code>, which is simply applying the sigmoid function to all elements of <code>z1</code>. naturally it is also <code>m</code> by <code>k</code> and is the output of our hidden layer.</p> <p>We then compute <code>z2 = h1w2+b2</code> which is <code>m</code> by <code>n</code> and is the input to the output layer of our neural network. Then we compute <code>h2 = g(z2)</code> which again is naturally also <code>m</code> by <code>n</code> and is the output of our neural network.</p> <p>Finally, we take this output and perform some linear operator on it: <code>Xhat = h2w3+b3</code> which is also <code>m</code> by <code>n</code> and is our final result.</p> <p><strong>Where I am stuck</strong></p> <p>The cost function I want to minimize is the mean squared error. I already implemented it in numpy code</p> <pre><code>def cost(x, xhat): return (1.0/(2 * m)) * np.trace(np.dot(x-xhat,(x-xhat).T)) </code></pre> <p>The problem is finding the derivatives of cost with respect to <code>w1,b1,w2,b2,w3,b3</code>. Let's call the cost <code>S</code>.</p> <p>After deriving myself <strong>and checking myself numerically</strong>, I have established the following facts:</p> <p>1) <code>dSdxhat = (1/m) * np.dot(xhat-x)</code></p> <p>2) <code>dSdw3 = np.dot(h2.T,dSdxhat)</code></p> <p>3) <code>dSdb3 = dSdxhat</code></p> <p>4) <code>dSdh2 = np.dot(dSdxhat, w3.T)</code></p> <p>But I can't for the life of me figure out dSdz2. It's a brick wall.</p> <p>From chain-rule, it should be that dSdz2 = dSdh2 * dh2dz2 but the dimensions don't match. </p> <p>What is the formula to compute the derivative of S with respect to z2?</p> <p><strong>Edit</strong> - This is my code for the entire feed forward operation of the autoencoder.</p> <pre><code>import numpy as np def g(x): #sigmoid activation functions return 1/(1+np.exp(-x)) #same shape as x! def gGradient(x): #gradient of sigmoid return g(x)*(1-g(x)) #same shape as x! def cost(x, xhat): #mean squared error between x the data and xhat the output of the machine return (1.0/(2 * m)) * np.trace(np.dot(x-xhat,(x-xhat).T)) #Just small random numbers so we can test that it's working small scale m = 5 #num of examples n = 2 #num of features in each example k = 2 #num of neurons in the hidden layer of the autoencoder x = np.random.rand(m, n) #the data, shape (m, n) w1 = np.random.rand(n, k) #weights from input layer to hidden layer, shape (n, k) b1 = np.random.rand(m, k) #bias term from input layer to hidden layer (m, k) z1 = np.dot(x,w1)+b1 #output of the input layer, shape (m, k) h1 = g(z1) #input of hidden layer, shape (m, k) w2 = np.random.rand(k, n) #weights from hidden layer to output layer of the autoencoder, shape (k, n) b2 = np.random.rand(m, n) #bias term from hidden layer to output layer of autoencoder, shape (m, n) z2 = np.dot(h1, w2)+b2 #output of the hidden layer, shape (m, n) h2 = g(z2) #Output of the entire autoencoder. The output layer of the autoencoder. shape (m, n) w3 = np.random.rand(n, n) #weights from output layer of autoencoder to entire output of the machine, shape (n, n) b3 = np.random.rand(m, n) #bias term from output layer of autoencoder to entire output of the machine, shape (m, n) xhat = np.dot(h2, w3)+b3 #the output of the machine, which hopefully resembles the original data x, shape (m, n) </code></pre>
13
2016-10-01T08:59:04Z
39,921,537
<p>OK, here's a suggestion. In the vector case, if you have <em>x</em> as a vector of length <code>n</code>, then <code>g(x)</code> is also a vector of length <code>n</code>. However, <code>g'(x)</code> is not a vector, it's the <a href="https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant" rel="nofollow">Jacobian matrix</a>, and will be of size <code>n X n</code>. Similarly, in the minibatch case, where <em>X</em> is a matrix of size <code>m X n</code>, <code>g(X)</code> is <code>m X n</code> but <code>g'(X)</code> is <code>n X n</code>. Try:</p> <pre><code>def gGradient(x): #gradient of sigmoid return np.dot(g(x).T, 1 - g(x)) </code></pre> <p>@Paul is right that the bias terms should be vectors, not matrices. You should have:</p> <pre><code>b1 = np.random.rand(k) #bias term from input layer to hidden layer (k,) b2 = np.random.rand(n) #bias term from hidden layer to output layer of autoencoder, shape (n,) b3 = np.random.rand(n) #bias term from output layer of autoencoder to entire output of the machine, shape (n,) </code></pre> <p>Numpy's broadcasting means that you don't have to change your calculation of <code>xhat</code>.</p> <p>Then (I think!) you can compute the derivatives like this:</p> <pre><code>dSdxhat = (1/float(m)) * (xhat-x) dSdw3 = np.dot(h2.T,dSdxhat) dSdb3 = dSdxhat.mean(axis=0) dSdh2 = np.dot(dSdxhat, w3.T) dSdz2 = np.dot(dSdh2, gGradient(z2)) dSdb2 = dSdz2.mean(axis=0) dSdw2 = np.dot(h1.T,dSdz2) dSdh1 = np.dot(dSdz2, w2.T) dSdz1 = np.dot(dSdh1, gGradient(z1)) dSdb1 = dSdz1.mean(axis=0) dSdw1 = np.dot(x.T,dSdz1) </code></pre> <p>Does this work for you?</p> <p><strong>Edit</strong></p> <p>I've decided that I'm not at all sure that <code>gGradient</code> is supposed to be a matrix. How about:</p> <pre><code>dSdxhat = (xhat-x) / m dSdw3 = np.dot(h2.T,dSdxhat) dSdb3 = dSdxhat.sum(axis=0) dSdh2 = np.dot(dSdxhat, w3.T) dSdz2 = h2 * (1-h2) * dSdh2 dSdb2 = dSdz2.sum(axis=0) dSdw2 = np.dot(h1.T,dSdz2) dSdh1 = np.dot(dSdz2, w2.T) dSdz1 = h1 * (1-h1) * dSdh1 dSdb1 = dSdz1.sum(axis=0) dSdw1 = np.dot(x.T,dSdz1) </code></pre>
4
2016-10-07T16:04:28Z
[ "python", "algorithm", "numpy", "matrix", "derivative" ]
switch variable and write problems,python
39,804,800
<pre><code>import csv import sys def switch(): file1=open('enjoysport.csv','r') for line in file1: line.split(",")[0],line.split(",")[-1]=line.split(",")[-1],line.split(",")[0] file1.close() origin=sys.stdout fil2=open("test.csv","w") sys.stdout=fil2 print(file1) sys.stdout = origin fil2.close() switch() </code></pre> <p>I want to switch the first column and last column ,but it didn't work,what's more,the file after switching cannot be written into the new csv.file?</p> <p>like this:</p> <pre><code>&lt;_io.TextIOWrapper name='agaricus_lepiota.csv' mode='r' encoding='cp1252'&gt; </code></pre> <p>what's wrong?Thank you in advance:)</p>
0
2016-10-01T09:03:03Z
39,804,875
<p>You need to actually write the updated row to the file, you can also use the <em>csv</em> lib to read and write your file content:</p> <pre><code>def switch(): with open('enjoysport.csv') as f, open("test.csv", "w") as out: wr = csv.writer(out) for row in csv.reader(f): row[0], row[-1] = row[-1], row[0] wr.writerow(row) # actually write it to test.csv </code></pre> <p>In your own code all you are doing is shifting elements in each row, you never write the result so it is a pointless exercise. </p> <p>Why you see <code>&lt;_io.TextIOWrapper name='agaricus_lepiota.csv' mode='r' encoding='cp1252'&gt;</code> is because <code>sys.stdout = fil2</code> <em>redirects stdout</em> to <em>file2</em>, then you print the reference to the <code>file1</code> i.e the file object so that gets written/redirected to your file.</p>
2
2016-10-01T09:13:49Z
[ "python", "output" ]
switch variable and write problems,python
39,804,800
<pre><code>import csv import sys def switch(): file1=open('enjoysport.csv','r') for line in file1: line.split(",")[0],line.split(",")[-1]=line.split(",")[-1],line.split(",")[0] file1.close() origin=sys.stdout fil2=open("test.csv","w") sys.stdout=fil2 print(file1) sys.stdout = origin fil2.close() switch() </code></pre> <p>I want to switch the first column and last column ,but it didn't work,what's more,the file after switching cannot be written into the new csv.file?</p> <p>like this:</p> <pre><code>&lt;_io.TextIOWrapper name='agaricus_lepiota.csv' mode='r' encoding='cp1252'&gt; </code></pre> <p>what's wrong?Thank you in advance:)</p>
0
2016-10-01T09:03:03Z
39,804,911
<p>The problem is with this line</p> <pre><code> line.split(",")[0],line.split(",")[-1]=line.split(",")[-1],line.split(",")[0] </code></pre> <p>You create four temporary lists by split, which are discarded after that line directly because they are not assigned to any variable.</p> <p>You have to process one line and write it directly to the new file:</p> <pre><code>file1=open('enjoysport.csv','r') fil2=open("test.csv","w") for line in file1: parts = line.rstrip().split(',') parts[0],parts[-1] = parts[-1], parts[0] file2.write(','.join(parts) + '\n') file1.close() file2.close() </code></pre>
1
2016-10-01T09:17:28Z
[ "python", "output" ]
Find nodes defined in corrupted namespace
39,804,844
<p>I've downloaded <a href="http://udcdata.info/udcsummary-skos.zip" rel="nofollow">this</a> XML file.</p> <p>I'm trying to get <code>includingNote</code> as follows:</p> <pre><code>... namespaces = { "skos" : "http://www.w3.org/2004/02/skos/core#", "xml" : "http://www.w3.org/XML/1998/namespace", "udc" : "http://udcdata.info/udc-schema#" } ... includingNote = child.find("udc:includingNote[@xml:lang='en']", namespaces) if includingNote: print includingNote.text.encode("utf8") </code></pre> <p>The scheme is located <a href="http://udcdata.info/udc-scheme" rel="nofollow">here</a> and seems to be corrupted.</p> <p>Is there a way I can print <code>includingNote</code> for each child node.</p>
0
2016-10-01T09:08:11Z
39,805,230
<p>It is true that the <code>skos</code> prefix is not declared in udc-scheme, but searching the XML document is not a problem. </p> <p>The following program extracts 639 <code>includingNote</code> elements:</p> <pre><code>from xml.etree import cElementTree as ET namespaces = {"udc" : "http://udcdata.info/udc-schema#", "xml" : "http://www.w3.org/XML/1998/namespace"} doc = ET.parse("udcsummary-skos.rdf") includingNotes = doc.findall(".//udc:includingNote[@xml:lang='en']", namespaces) print len(includingNotes) # 639 for i in includingNotes: print i.text </code></pre> <p>Note the use of <code>findall()</code> and <code>.//</code> in front of the element name in order to search the whole document.</p> <hr> <p>Here is a variant that returns the same information by first finding all <code>Concept</code> elements:</p> <pre><code>from xml.etree import cElementTree as ET namespaces = {"udc" : "http://udcdata.info/udc-schema#", "skos" : "http://www.w3.org/2004/02/skos/core#", "xml" : "http://www.w3.org/XML/1998/namespace"} doc = ET.parse("udcsummary-skos.rdf") concepts = doc.findall(".//skos:Concept", namespaces) for c in concepts: includingNote = c.find("udc:includingNote[@xml:lang='en']", namespaces) if includingNote is not None: print includingNote.text </code></pre> <p>Note the use of <code>is not None</code>. Without that, it does not work. This seems to be a peculiarity of ElementTree. See <a href="http://stackoverflow.com/q/20129996/407651">Why does bool(xml.etree.ElementTree.Element) evaluate to False?</a>.</p>
1
2016-10-01T09:56:14Z
[ "python", "xml", "xml-namespaces", "elementtree" ]
How do I iterate over the product of different lists?
39,804,860
<p>I have the following problem:</p> <p>I have a list <code>l1</code> and I want to iterate over the product with the function <code>itertools.product</code>, I also want to include the second list <code>l2</code> in the same way.</p> <p>For example:</p> <pre><code>l1 = [1, 2, 3, 4] l2 = ['a', 'b', 'c', 'd'] for i in list(itertools.product(l1, repeat = 2)): print(i) </code></pre> <p>The output is:</p> <pre><code>(1, 1) (1, 2) ... </code></pre> <p>I think this is very clear. But how can I manage to include the second list and get an output like this:</p> <pre><code>(1, a),(1, a) (1, a),(2, b) (1, a),(3, c) (1, a),(4, d) (2, b),(1, a) (2, b),(2, b) (2, b),(3, c) (2, b),(4, d) (3, c),(1, a) (3, c),(2, b) (3, c),(3, c) (3, c),(4, d) (4, d),(1, a) (4, d),(2, b) (4, d),(3, c) (4, d),(4, d) </code></pre> <p>I know that a proper solution would be to combine for-loops. But that doesn't fit for me as I want to increase the <code>repeat</code>-counter.</p>
2
2016-10-01T09:10:43Z
39,804,868
<p>By providing a <code>zip</code> of the lists to <code>product</code>:</p> <pre><code>for i in product(zip(l1,l2), repeat = 2): print(i) </code></pre> <p>Wrapping in a <code>list</code> isn't required, the for loop takes care of calling <code>next</code> on the iterator for you.</p> <p>If you want a new-line for every 4 combinations, use <code>enumerate</code> (starting from <code>1</code>) and add a <code>\n</code> when <code>c % 4</code> is <code>0</code>:</p> <pre><code>for c, i in enumerate(product(zip(l1,l2), repeat = 2), 1): print(i, '\n' if c % 4 == 0 else '') </code></pre> <p>Output:</p> <pre><code>((1, 'a'), (1, 'a')) ((1, 'a'), (2, 'b')) ((1, 'a'), (3, 'c')) ((1, 'a'), (4, 'd')) ((2, 'b'), (1, 'a')) ((2, 'b'), (2, 'b')) ((2, 'b'), (3, 'c')) ((2, 'b'), (4, 'd')) ((3, 'c'), (1, 'a')) ((3, 'c'), (2, 'b')) ((3, 'c'), (3, 'c')) ((3, 'c'), (4, 'd')) ((4, 'd'), (1, 'a')) ((4, 'd'), (2, 'b')) ((4, 'd'), (3, 'c')) ((4, 'd'), (4, 'd')) </code></pre>
3
2016-10-01T09:12:36Z
[ "python", "list", "python-3.x", "for-loop", "itertools" ]
Which is the better location to compress images ? In the browswer or on the server?
39,805,033
<p>I have a Django project and i allow users to upload images. I don't want to limit image upload size for users. But want to compress the image after they select and store them. I want to understand which is better:</p> <ol> <li>Compress using java-script on the browser.</li> <li>Back end server using python libraries.</li> </ol> <p>Also it will be helpful if links can be provided to implement the better approach.</p>
0
2016-10-01T09:32:14Z
39,805,099
<p>I advice you to compress on the browser in order to :</p> <ul> <li>avoid loading the server with many CPU and RAM heavy consuming calculations (as numerous as number of clients)</li> <li>dwindle bandwith needed when transfert image threw the network</li> </ul>
1
2016-10-01T09:40:12Z
[ "javascript", "python", "html", "django", "image-compression" ]
Which is the better location to compress images ? In the browswer or on the server?
39,805,033
<p>I have a Django project and i allow users to upload images. I don't want to limit image upload size for users. But want to compress the image after they select and store them. I want to understand which is better:</p> <ol> <li>Compress using java-script on the browser.</li> <li>Back end server using python libraries.</li> </ol> <p>Also it will be helpful if links can be provided to implement the better approach.</p>
0
2016-10-01T09:32:14Z
39,805,180
<p>I would compress in nginx (or apache) since this is the right place to do it. no need for python libraries to do this</p> <p>small example: </p> <pre><code>gzip on; gzip_static on; gzip_comp_level 9; gzip_min_length 1400; gzip_types image/png image/gif image/jpeg </code></pre> <p>more on it --> <a href="https://www.nginx.com/resources/admin-guide/compression-and-decompression/" rel="nofollow">in the nginx docs</a></p>
1
2016-10-01T09:49:54Z
[ "javascript", "python", "html", "django", "image-compression" ]
RabbitMQ unacked messages
39,805,088
<p>I'm creating Tasks at a rate of 5 Tasks per second. I can see in RabbitMQ Message rates incoming an average of 5.2/s, I have 240 consumers distributed in 4 Virtual machines (60 per VM), each worker process a Task that last 20 seconds. In theory I'm supposed to handle 100K task without queuing.</p> <p>I see a large number of <strong>Unacked</strong> messages. How to get rid of Unacked messages or add a timer to kill them, does that point to be a problem in my worker side?</p> <p><a href="http://stackoverflow.com/questions/7063224/how-can-i-recover-unacknowledged-amqp-messages-from-other-channels-than-my-conne">How can I recover unacknowledged AMQP messages from other channels than my connection&#39;s own?</a></p> <p><strong>Queues</strong> tab </p> <p>Ready Unacked Total incoming deliver / get ack</p> <p>21,884 960 22,844 5.0/s 0.40/s 0.40/s</p> <p><a href="http://i.stack.imgur.com/aJbuZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/aJbuZ.png" alt="enter image description here"></a> <strong>Exchange</strong> tab: stackoverflow direct D 5.0/s 5.0/s</p> <p>This is my celeryconfig file.</p> <pre><code>CELERYD_CHDIR = settings.filepath CELERY_ENABLE_UTC = True CELERY_TIMEZONE = "US/Eastern" CELERY_ACCEPT_CONTENT = ['json', 'pickle', 'yaml'] CELERY_IGNORE_RESULT = True CELERY_RESULT_BACKEND = "amqp" CELERY_RESULT_PERSISTENT = True BROKER_URL = 'amqp://stackoverflow:stackoverflow@rabbitmq:5672' BROKER_CONNECTION_TIMEOUT = 15 BROKER_CONNECTION_MAX_RETRIES = 5 CELERY_DISABLE_RATE_LIMITS = True CELERY_TASK_RESULT_EXPIRES = 7200 CELERY_IMPORTS = ("cc.modules.stackoverflow") CELERY_DEFAULT_QUEUE = "default" CELERY_QUEUES = ( Queue('default', Exchange('default'), routing_key='default'), Queue('gold', Exchange('stackoverflow'), routing_key='stackoverflow.gold'), Queue('silver', Exchange('stackoverflow'), routing_key='stackoverflow.silver'), Queue('bronze', Exchange('stackoverflow'), routing_key='stackoverflow.bronze'), ) CELERY_DEFAULT_EXCHANGE = "stackoverflow" CELERY_DEFAULT_EXCHANGE_TYPE = "topic" CELERY_DEFAULT_ROUTING_KEY = "default" CELERY_TRACK_STARTED = True CELERY_ROUTES = { 'process_call' : {'queue': 'gold', 'routing_key': 'stackoverflow.gold', 'exchange': 'stackoverflow',}, 'process_recording': {'queue': 'silver', 'routing_key': 'stackoverflow.silver', 'exchange': 'stackoverflow',}, 'process_campaign' : {'queue': 'bronze', 'routing_key': 'stackoverflow.bronze', 'exchange': 'stackoverflow',} } </code></pre>
0
2016-10-01T09:39:14Z
39,816,273
<p>Message acknowledgement acts like transaction in SQL like commit you have to acknowledge the message received from RabbitMq. This function help to avoid the message loss in your system.</p> <p>Navigate to <strong>Message acknowledgment</strong> title <a href="https://www.rabbitmq.com/tutorials/tutorial-two-python.html" rel="nofollow">https://www.rabbitmq.com/tutorials/tutorial-two-python.html</a></p>
1
2016-10-02T10:57:24Z
[ "python", "rabbitmq", "celery" ]
In a list of lists how to get all the items except the last one for each list?
39,805,098
<p>So I have this list of lists. Each nested list has <code>n+1</code> element where the first element are floats and the last one is an integer. I need to get , for each nested list, all the floats (so n elements out of <code>n+1</code>). Which is the best way to achieve that?</p> <p>For example:</p> <pre><code>x = [[0.1, 0.2, 1], [0.4, 0.05, 16], [0.3, 0.3, 5]] output = [[0.1, 0.2], [0.4, 0.05], [0.3, 0.3]] </code></pre>
0
2016-10-01T09:40:08Z
39,805,133
<p>If you are <em>certain</em> the <code>int</code> will always be last, slicing is an option whereby you trim off the last element from every sub-list <code>sub</code> in <code>x</code> with <code>sub[:-1]</code> (<code>[:-1]</code> means grab all except the last element):</p> <pre><code>out = [sub[:-1] for sub in x] # or sub[:2] if sub is always 3 elements long print(out) [[0.1, 0.2], [0.4, 0.05], [0.3, 0.3]] </code></pre> <p>Alternatively, you can do this by iterating through the elements of <code>x</code>, iterating through each sub-element and evaluating if it is an instance of a <code>float</code>, i.e:</p> <pre><code>out = [[i for i in sub if isinstance(i, float)] for sub in x] </code></pre> <p>This filters out any element the list <code>sub</code> which is a sub-list in <code>x</code> that isn't an instance of the <code>float</code> type. This operates <em>irregardless of positioning</em> so you could use it if the position of the <code>int</code> isn't always last:</p> <pre><code>print(out) [[0.1, 0.2], [0.4, 0.05], [0.3, 0.3]] </code></pre> <p>Finally, for an <em>in-place</em> approach, <code>for</code> looping and <code>pop</code>ing is a viable option:</p> <pre><code>for s in x: _ = s.pop() </code></pre> <p>Now <code>x</code> is mutated to:</p> <pre><code>print(x) [[0.1, 0.2], [0.4, 0.05], [0.3, 0.3]] </code></pre>
2
2016-10-01T09:44:18Z
[ "python", "list", "python-3.x" ]
In a list of lists how to get all the items except the last one for each list?
39,805,098
<p>So I have this list of lists. Each nested list has <code>n+1</code> element where the first element are floats and the last one is an integer. I need to get , for each nested list, all the floats (so n elements out of <code>n+1</code>). Which is the best way to achieve that?</p> <p>For example:</p> <pre><code>x = [[0.1, 0.2, 1], [0.4, 0.05, 16], [0.3, 0.3, 5]] output = [[0.1, 0.2], [0.4, 0.05], [0.3, 0.3]] </code></pre>
0
2016-10-01T09:40:08Z
39,805,134
<p>This is the shortest and easiest way:</p> <pre><code>output = [l[:-1] for l in x] </code></pre> <p>It is called a <a href="https://docs.python.org/3.6/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension </a>.</p>
4
2016-10-01T09:44:23Z
[ "python", "list", "python-3.x" ]
Jupyter Notebook: How to output chinese?
39,805,113
<p>The coloumn ['douban_info'] in my dataset is info about movies in Chinese which stored in JSON, so when I do <code>df['douban_info'][0]</code>, it returns</p> <p><a href="http://i.stack.imgur.com/6WCkU.png" rel="nofollow"><img src="http://i.stack.imgur.com/6WCkU.png" alt="enter image description here"></a></p> <p>The chinese are all changed into things like <code>\u7834\u6653\u8005</code>, which I can't read with ease. Is it possible to make python to turn them into the originall chinese when outputing?</p> <p>I'm on Python 2.7.</p>
0
2016-10-01T09:42:29Z
39,805,228
<p>Call <code>json.dump</code> or <code>json.dumps</code> with <code>ensure_ascii=False</code> options, then you will get raw utf-8 encoded string.</p> <p>referenced by <a href="https://docs.python.org/2/library/json.html" rel="nofollow">https://docs.python.org/2/library/json.html</a></p> <p><code>json.dump(obj, fp, skipkeys=False, **ensure_ascii=True**, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)</code>¶</p> <p>you can try </p> <p><code>df['douban_info'][0].to_json(ensure_ascii=False)</code></p> <p>to get attribute values displayed with chinese character.</p>
-1
2016-10-01T09:56:13Z
[ "python", "unicode", "jupyter-notebook" ]
Jupyter Notebook: How to output chinese?
39,805,113
<p>The coloumn ['douban_info'] in my dataset is info about movies in Chinese which stored in JSON, so when I do <code>df['douban_info'][0]</code>, it returns</p> <p><a href="http://i.stack.imgur.com/6WCkU.png" rel="nofollow"><img src="http://i.stack.imgur.com/6WCkU.png" alt="enter image description here"></a></p> <p>The chinese are all changed into things like <code>\u7834\u6653\u8005</code>, which I can't read with ease. Is it possible to make python to turn them into the originall chinese when outputing?</p> <p>I'm on Python 2.7.</p>
0
2016-10-01T09:42:29Z
39,812,356
<p>This is how Python 2 works. It by default displays the <code>repr()</code> when generating display strings for lists and strings. You have to <code>print</code> strings to see the Unicode characters:</p> <pre><code>&gt;&gt;&gt; D = {u'aka': [u'2019\u730e\u8840\u90fd\u5e02(\u6e2f)', u'\u9ece\u660e\u65f6\u5206']} &gt;&gt;&gt; D[u'aka'][0] u'2019\u730e\u8840\u90fd\u5e02(\u6e2f)' &gt;&gt;&gt; print D[u'aka'][0] 2019猎血都市(港) </code></pre> <p>If you can't move to Python 3, you'll have to make your own display routine if you don't like the default <code>repr()</code> display. Something like:</p> <pre><code>D = {u'aka':[u'2019\u730e\u8840\u90fd\u5e02(\u6e2f)',u'\u9ece\u660e\u65f6\u5206']} def dump(item): L = [] if isinstance(item,dict): for k,v in item.items(): L.append(dump(k) + ':') L.append(dump(v)) return '{' + ', '.join(L) + '}' elif isinstance(item,list): for i in item: L.append(dump(i)) return '[' + ', '.join(L) + ']' else: return "u'" + item + "'" print dump(D) </code></pre> <p>Output:</p> <pre><code>{u'aka':, [u'2019猎血都市(港)', u'黎明时分']} </code></pre> <p>Note this is by no means complete as a generic dumping utility.</p> <p>In Python 3 <code>repr()</code> has been updated:</p> <pre><code>&gt;&gt;&gt; print(D) {'aka': ['2019猎血都市(港)', '黎明时分']} </code></pre>
1
2016-10-01T23:15:47Z
[ "python", "unicode", "jupyter-notebook" ]
How to go about incremental scraping large sites near-realtime
39,805,237
<p>I want to scrape a lot (a few hundred) of sites, which are basically like bulletin boards. Some of these are very large (up to 1.5 million) and also growing very quickly. What I want to achieve is:</p> <ul> <li>scrape all the existing entries</li> <li>scrape all the new entries near real-time (ideally around 1 hour intervals or less)</li> </ul> <p>For this we are using scrapy and save the items in a postresql database. The problem right now is, how can I make sure I got all the records without scraping the complete site every time? (Which would not be very agressive traffic-wise, but also not possible to complete within 1 hour.)</p> <p>For example: I have a site with 100 pages and 10 records each. So I scrape page 1, and then go to page 2. But on fast growing sites, at the time I do the request for page 2, there might be 10 new records, so I would get the same items again. Nevertheless I would get all items in the end. <strong>BUT</strong> next time scraping this site, how would I know where to stop? I can't stop at the first record I already have in my database, because this might be suddenly on the first page, because there a new reply was made.</p> <p>I am not sure if I got my point accross, but tl;dr: How to fetch fast growing BBS in an incremental way? So with getting all the records, but only fetching new records each time. I looked at scrapy's resume function and also at scrapinghubs deltafetch middleware, but I don't know if (and how) they can help to overcome this problem.</p>
-1
2016-10-01T09:56:48Z
39,805,342
<blockquote> <p>For example: I have a site with 100 pages and 10 records each. So I scrape page 1, and then go to page 2. But on fast growing sites, at the time I do the request for page 2, there might be 10 new records, so I would get the same items again. Nevertheless I would get all items in the end. BUT next time scraping this site, how would I know where to stop? I can't stop at the first record I already have in my database, because this might be suddenly on the first page, because there a new reply was made.</p> </blockquote> <p>Usually each record has a unique link (permalink) e.g. the above question can be accessed by just entering <code>https://stackoverflow.com/questions/39805237/</code> &amp; ignoring the text beyond that. You'll have to store the unique URL for each record and when you scrape next time, ignore the ones that you already have. </p> <p>If you take the example of tag <code>python</code> on Stackoverflow, you can view the questions here : <code>https://stackoverflow.com/questions/tagged/python</code> but the sorting order can't be relied upon for ensuring unique entries. One way to scrape would be to sort by newest questions and keep ignoring duplicate ones by their URL. </p> <p>You can have an algorithm that scrapes first 'n' pages every 'x' minutes until it hits an existing record. The whole flow is a bit site specific, but as you scrape more sites, your algorithm will become more generic and robust to handle edge cases and new sites.</p> <p>Another approach is to not run scrapy yourself, but use a distributed spider service. They generally have multiple IPs and can spider large sites within minutes. Just make sure you respect the site's robots.txt file and don't accidentally DDoS them.</p>
1
2016-10-01T10:08:50Z
[ "python", "postgresql", "web-scraping", "scrapy" ]
plot 2d lines by line equation in Python using Matplotlib
39,805,258
<p>Lets say I have 2d line equations (y = Ax + B) , i.e: </p> <pre><code>[[A_1, B_1] , [A_2, B_2], .. ] </code></pre> <p>and I want to plot the lines in 2d range, for example from point (-100,-100) to point (100,100).</p> <p>as I understand the range limit can achieved with <code>xlim</code> and <code>ylim</code>, but I don't understand how to draw line according to its equation. I know that one way could be to find 2 points according the equation, but I don't understand how <code>plot</code> function works for my problem, Thanks.</p>
2
2016-10-01T09:59:25Z
39,805,466
<p>To plot two straight lines within some specified range in x and y, you would do something like this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt A1,B1 = 1.,1. A2,B2 = 2.,2. x = np.linspace(-100.,100.) fig,ax = plt.subplots() ax.plot(x,A1*x+B1) ax.plot(x,A2*x+B2) ax.set_xlim((-100.,100.)) ax.set_ylim((-100.,100.)) plt.show() </code></pre> <p>Given that you phrased the question in terms of <code>[[A_1, B_1] , [A_2, B_2], .. ]</code>, suggesting an array of different lines you'd like to plot, then you can plot using a <code>for</code> loop like this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt AB = np.random.randn(100,2) #create a random array of [[A1,B1],[A2,B2],...] as example x = np.linspace(-100.,100.) fig,ax = plt.subplots() for ABi in AB: A,B = ABi ax.plot(x, A*x+B ) ax.set_xlim((-100.,100.)) ax.set_ylim((-100.,100.)) plt.show() </code></pre>
3
2016-10-01T10:22:36Z
[ "python", "matplotlib" ]
Intersection and Difference of two dictionaries
39,805,266
<p>Given two dictionaries, I want to look at their intersction and difference and perform f function on the elements that intersect and perform g on the unique elements, Here's how I found out what the unique and intersecting elements are where d1 and d2 are two dictionaries, How do i print out the d_intersection and d_difference as dictionaries inside a tuple? The output should look something like this ({intersecting keys,values}, {difference keys,values}) for example: given </p> <pre><code>d1 = {1:30, 2:20, 3:30, 5:80} d2 = {1:40, 2:50, 3:60, 4:70, 6:90} </code></pre> <p>The output should be <code>({1: 70, 2: 70, 3: 90}, {4: 70, 5: 80, 6: 90})</code></p> <pre><code>dic = {} d_intersect = set(d1) &amp; set(d2) d_difference = set(d1) ^ set(d2) for i in d_intersect: dic.update({i : f(d1[i],d2[i])}) for j in d_difference: dic.update({j : g(d1[j],d2[j])}) </code></pre> <p>Can someone tell me where I was going wrong and why does my code give key error 4?</p>
0
2016-10-01T10:00:22Z
39,805,458
<p>Here's one way of doing it, though there may be a more efficient method.</p> <pre><code>d1 = {1:30, 2:20, 3:30, 5:80} d2 = {1:40, 2:50, 3:60, 4:70, 6:90} d_intersect = {} # Keys that appear in both dictionaries. d_difference = {} # Unique keys that appear in only one dictionary. # Get all keys from both dictionaries. # Convert it into a set so that we don't loop through duplicate keys. all_keys = set(d1.keys() + d2.keys()) # Python2.7 #all_keys = set(list(d1.keys()) + list(d2.keys())) # Python3.3 for key in all_keys: if key in d1 and key in d2: # If the key appears in both dictionaries, add both values # together and place it in intersect. d_intersect[key] = d1[key] + d2[key] else: # Otherwise find out the dictionary it comes from and place # it in difference. if key in d1: d_difference[key] = d1[key] else: d_difference[key] = d2[key] </code></pre> <blockquote> <p>Output:</p> <p>{1: 70, 2: 70, 3: 90}</p> <p>{4: 70, 5: 80, 6: 90}</p> </blockquote>
0
2016-10-01T10:21:57Z
[ "python", "dictionary" ]
Intersection and Difference of two dictionaries
39,805,266
<p>Given two dictionaries, I want to look at their intersction and difference and perform f function on the elements that intersect and perform g on the unique elements, Here's how I found out what the unique and intersecting elements are where d1 and d2 are two dictionaries, How do i print out the d_intersection and d_difference as dictionaries inside a tuple? The output should look something like this ({intersecting keys,values}, {difference keys,values}) for example: given </p> <pre><code>d1 = {1:30, 2:20, 3:30, 5:80} d2 = {1:40, 2:50, 3:60, 4:70, 6:90} </code></pre> <p>The output should be <code>({1: 70, 2: 70, 3: 90}, {4: 70, 5: 80, 6: 90})</code></p> <pre><code>dic = {} d_intersect = set(d1) &amp; set(d2) d_difference = set(d1) ^ set(d2) for i in d_intersect: dic.update({i : f(d1[i],d2[i])}) for j in d_difference: dic.update({j : g(d1[j],d2[j])}) </code></pre> <p>Can someone tell me where I was going wrong and why does my code give key error 4?</p>
0
2016-10-01T10:00:22Z
39,805,600
<p>You get a <em>KeyError</em> for <em>4</em> as <code>^</code> looks for the <em>symmetric difference</em> which means keys <em>unique to either</em>, the keys are <em>not in</em> both. You also don't need to create sets, you can use the <a href="https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects" rel="nofollow">view object</a> returned from calling .keys</p> <pre><code>d1 = {1: 30, 2: 20, 3: 30, 5: 80} d2 = {1: 40, 2: 50, 3: 60, 4: 70, 6: 90} # d1.keys() ^ d2 -&gt; {4, 5, 6}, 4, 6 unique to d2, 5 unique to d1. symm = {k: d1.get(k, d2.get(k)) for k in d1.keys() ^ d2} inter = {k: d2[k] + d1[k] for k in d1.keys() &amp; d2} </code></pre> <p><code>d1.get(k, d2.get(k))</code> works for the <em>symmetric difference</em> as it catches when we get a unique key from <code>d2</code>.</p> <p>The code for python2 is slightly different, you would need to replace <code>.keys</code> with <code>.viewkeys</code> to get a <a href="https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects" rel="nofollow"><em>view object</em>:</a></p> <pre><code> {k: d1.get(k, d2.get(k)) for k in d1.viewkeys() ^ d2} {k: d2[k] + d1[k] for k in d1.viewkeys() &amp; d2} </code></pre> <p>To get the just the difference between two sets i.e what is in a but not in b, you need <code>-</code>:</p> <pre><code>In [1]: d1 = {1: 30, 2: 20, 3: 30, 5: 80} In [2]: d2 = {1: 40, 2: 50, 3: 60, 4: 70, 6: 90} In [3]: {k: d2[k] for k in d2.keys() - d1} Out[3]: {4: 70, 6: 90} In [4]: {k: d1[k] for k in d1.keys() - d2} Out[4]: {5: 80} In [5]: d2.keys() - d1 # in d2 not in d1 Out[5]: {4, 6} In [6]: d1.keys() - d2 # in d1 not in d2 Out[6]: {5} In [7]: d1.keys() ^ d2 # unique to either Out[7]: {4, 5, 6} </code></pre> <p>The symmetric difference is like doing the union of the differences:</p> <pre><code>In [12]: d1.keys() - d2 | d2.keys() - d1 Out[12]: {4, 5, 6} </code></pre> <p>All the operators are discussed in the python <a href="https://docs.python.org/2/library/sets.html#set-objects" rel="nofollow">docs</a>, also the wiki page on <a href="https://en.wikipedia.org/wiki/Set_(mathematics)" rel="nofollow">Set_(mathematics)</a> gives you a good overview.</p>
1
2016-10-01T10:38:19Z
[ "python", "dictionary" ]
selecting correct form while iterating all forms
39,805,391
<p>I want to submit forms in multiple websites with mechanize. Usually I can't exactly know the form name or form id, but I know the input name that I want to submit.</p> <p>Let's say there is a website which has couple of forms inside it. My code should check all of the forms, if one of them has a input value named "email" it will submit that form. If multiple forms has it, it will submit them all.</p> <p>The website which I'm testing has two forms. One of them is login form, the other is subscribe form. Both of them has "email" input value. So my code should submit both forms.</p> <p>I'm trying to achieve it with this code block:</p> <pre><code>for forms in br.forms(): if not forms.find_control(name="email"): continue br.select_form(nr=0) br.form["email"] = email br.submit() print "Success: ", link </code></pre> <p>This code prints two success messages, however it's not subscribes. Following code works with submitting subscription form because I set the form name:</p> <pre><code>br = mechanize.Browser() br.set_handle_robots(False) br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6')] br.open("http://example.com") br.select_form("subscribe") br.form["email"] = email br.submit() </code></pre> <p>So what's wrong with the first code? How can I select both forms and submit the value? Probably the problem is with that form selection part:</p> <pre><code>br.select_form(nr=0) </code></pre> <p>Edit: I checked it's POST requests with Wireshark. It seems it fills the first form for 2 times. When I change <code>nr=0</code> with <code>nr=1</code> it works because the correct form is the second form.</p>
7
2016-10-01T10:15:06Z
39,816,690
<p>Your problem is that you aren't storing what form you are working on. I would simply assign 0 into a variable and add 1 to it after every iteration. So your code should be:</p> <pre><code>currentForm = 0 for form in br.forms(): if not forms.find_control(name = "email"): currentForm += 1 continue print "Selecting form number %i..." % currentForm br.select_form(nr = currentForm) br.form["email"] = email br.submit() currentForm += 1 print "Success: ", link </code></pre> <p>Note: <code>x += y</code> is equal to <code>x = x + y</code></p> <p>Edit: You should fix your indenting too, you don't need to press tab twice, one press works too!</p>
0
2016-10-02T11:49:33Z
[ "python", "mechanize" ]
selecting correct form while iterating all forms
39,805,391
<p>I want to submit forms in multiple websites with mechanize. Usually I can't exactly know the form name or form id, but I know the input name that I want to submit.</p> <p>Let's say there is a website which has couple of forms inside it. My code should check all of the forms, if one of them has a input value named "email" it will submit that form. If multiple forms has it, it will submit them all.</p> <p>The website which I'm testing has two forms. One of them is login form, the other is subscribe form. Both of them has "email" input value. So my code should submit both forms.</p> <p>I'm trying to achieve it with this code block:</p> <pre><code>for forms in br.forms(): if not forms.find_control(name="email"): continue br.select_form(nr=0) br.form["email"] = email br.submit() print "Success: ", link </code></pre> <p>This code prints two success messages, however it's not subscribes. Following code works with submitting subscription form because I set the form name:</p> <pre><code>br = mechanize.Browser() br.set_handle_robots(False) br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6')] br.open("http://example.com") br.select_form("subscribe") br.form["email"] = email br.submit() </code></pre> <p>So what's wrong with the first code? How can I select both forms and submit the value? Probably the problem is with that form selection part:</p> <pre><code>br.select_form(nr=0) </code></pre> <p>Edit: I checked it's POST requests with Wireshark. It seems it fills the first form for 2 times. When I change <code>nr=0</code> with <code>nr=1</code> it works because the correct form is the second form.</p>
7
2016-10-01T10:15:06Z
39,948,965
<p>One solution would be to select the form by passing list form into br.form without using br.select_form. </p> <p>Contents of test.html:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Stuff&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="POST" &gt; &lt;input type="text" name="email"&gt; &lt;/form&gt; &lt;form method="POST"&gt; &lt;input type="text" name="email"&gt; &lt;/form&gt; &lt;form method="POST"&gt; &lt;input type="text" name="notemail"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and the modified python script:</p> <pre><code>import mechanize import sys br = mechanize.Browser() br.open("http://localhost/test.html") email = "the@email.com" for form in br.forms(): br.form = form try: textctrl = br.form.find_control(name="email") textctrl.value = email response = br.submit() print "Found email input, Submitted", response except mechanize.ControlNotFoundError: print "No Email control" except: print "Unexpected error:", sys.exc_info()[0] </code></pre> <p>This submits form 1 and 2 but not 3. Hope I understood the problem correctly.</p>
0
2016-10-09T21:58:54Z
[ "python", "mechanize" ]
Python ignore character and print next character from list in for loop
39,805,409
<p>I am using BeautifulSoup4 and requests to scrape information from a website.</p> <p>I then store the required information in lists, there are two lists for two different types of information I scraped from the page.</p> <pre><code> try: for i in range(0,1000): location = dive_data1[((9*i)-7)].text locations.append(location) location = dive_data2[((9*i)-7)] locations.append(location) depth = dive_data1[((9*i)-6)].text depths.append(depth) depth = dive_data2[((9*i)-6)].text depths.append(depth) except: pass </code></pre> <p>After that I try to pass these lists into another for loop to write the contents into a CSV file.</p> <pre><code> try: writer = csv.writer(dive_log) writer.writerow( ("Locations and depths") ) writer.writerow( ("Sourced from:", str(url_page)) ) writer.writerow( ("Location", "Depth") ) for i in range(len(locations)): writer.writerow( (locations[i], depths[i]) ) </code></pre> <p>when i run the script i recieve this error:</p> <pre><code>writer.writerow( (locations[i], depths[i]) ) UnicodeEncodeError: 'ascii' codec can't encode characters in position 65-66: ordinal not in range(128) </code></pre> <p>I tried this to pass characters it cannot encode:</p> <pre><code> writer = csv.writer(dive_log) writer.writerow( ("Locations and depths") ) writer.writerow( ("Sourced from:", str(url_page)) ) writer.writerow( ("Location", "Depth") ) for i in range(len(locations)): try: writer.writerow( (locations[i], depths[i]) ) except: pass </code></pre> <p>When I run this, only the lines prior to the for loop are excecuted and it completely passes the repeat of the for loop.</p> <p>The entirety of the code in my script is copied below in case it is related to something that I had not seen in the rest.</p> <pre><code>import csv from bs4 import BeautifulSoup import requests dive_log = open("divelog.csv", "wt") url_page = "https://en.divelogs.de/log/Mark_Gosling" r = requests.get(url_page) soup = BeautifulSoup(r.content) dive_data1 = soup.find_all("tr", {"class": "td2"}) dive_data2 = soup.find_all("td", {"class": "td"}) locations = [] depths = [] try: for i in range(0,1000): location = dive_data1[((9*i)-7)].text locations.append(location) location = dive_data2[((9*i)-7)] locations.append(location) depth = dive_data1[((9*i)-6)].text depths.append(depth) depth = dive_data2[((9*i)-6)].text depths.append(depth) except: pass try: writer = csv.writer(dive_log) writer.writerow( ("Locations and depths") ) writer.writerow( ("Sourced from:", str(url_page)) ) writer.writerow( ("Location", "Depth") ) for i in range(len(locations)): try: writer.writerow( (locations[i], depths[i]) ) except: pass finally: dive_log.close() print open("divelog.csv", "rt").read() print "\n\n" print locations </code></pre>
1
2016-10-01T10:16:51Z
39,805,531
<p>Like @yedpodtriztko noted. You can just leave the characters that it cannot decode with following:</p> <p>instead of doing:</p> <pre><code>soup = BeautifulSoup(r.content) </code></pre> <p>you could use this:</p> <pre><code>soup = BeautifulSoup(r.content.decode('utf-8', 'ignore')) </code></pre>
-1
2016-10-01T10:30:54Z
[ "python", "beautifulsoup", "export-to-csv" ]
Python ignore character and print next character from list in for loop
39,805,409
<p>I am using BeautifulSoup4 and requests to scrape information from a website.</p> <p>I then store the required information in lists, there are two lists for two different types of information I scraped from the page.</p> <pre><code> try: for i in range(0,1000): location = dive_data1[((9*i)-7)].text locations.append(location) location = dive_data2[((9*i)-7)] locations.append(location) depth = dive_data1[((9*i)-6)].text depths.append(depth) depth = dive_data2[((9*i)-6)].text depths.append(depth) except: pass </code></pre> <p>After that I try to pass these lists into another for loop to write the contents into a CSV file.</p> <pre><code> try: writer = csv.writer(dive_log) writer.writerow( ("Locations and depths") ) writer.writerow( ("Sourced from:", str(url_page)) ) writer.writerow( ("Location", "Depth") ) for i in range(len(locations)): writer.writerow( (locations[i], depths[i]) ) </code></pre> <p>when i run the script i recieve this error:</p> <pre><code>writer.writerow( (locations[i], depths[i]) ) UnicodeEncodeError: 'ascii' codec can't encode characters in position 65-66: ordinal not in range(128) </code></pre> <p>I tried this to pass characters it cannot encode:</p> <pre><code> writer = csv.writer(dive_log) writer.writerow( ("Locations and depths") ) writer.writerow( ("Sourced from:", str(url_page)) ) writer.writerow( ("Location", "Depth") ) for i in range(len(locations)): try: writer.writerow( (locations[i], depths[i]) ) except: pass </code></pre> <p>When I run this, only the lines prior to the for loop are excecuted and it completely passes the repeat of the for loop.</p> <p>The entirety of the code in my script is copied below in case it is related to something that I had not seen in the rest.</p> <pre><code>import csv from bs4 import BeautifulSoup import requests dive_log = open("divelog.csv", "wt") url_page = "https://en.divelogs.de/log/Mark_Gosling" r = requests.get(url_page) soup = BeautifulSoup(r.content) dive_data1 = soup.find_all("tr", {"class": "td2"}) dive_data2 = soup.find_all("td", {"class": "td"}) locations = [] depths = [] try: for i in range(0,1000): location = dive_data1[((9*i)-7)].text locations.append(location) location = dive_data2[((9*i)-7)] locations.append(location) depth = dive_data1[((9*i)-6)].text depths.append(depth) depth = dive_data2[((9*i)-6)].text depths.append(depth) except: pass try: writer = csv.writer(dive_log) writer.writerow( ("Locations and depths") ) writer.writerow( ("Sourced from:", str(url_page)) ) writer.writerow( ("Location", "Depth") ) for i in range(len(locations)): try: writer.writerow( (locations[i], depths[i]) ) except: pass finally: dive_log.close() print open("divelog.csv", "rt").read() print "\n\n" print locations </code></pre>
1
2016-10-01T10:16:51Z
39,805,872
<p>You need to encode to <em>utf-8</em> in the loop when you write:</p> <pre><code>for i in range(len(locations)): writer.writerow((locations[i].encode("utf-8"), depths[i].encode("utf-8")) ) </code></pre>
0
2016-10-01T11:09:55Z
[ "python", "beautifulsoup", "export-to-csv" ]
Dealing with timezone dates in MongoDB and pymongo
39,805,453
<p>I do not seem to be able to query records and get what I expect. For example I am searching </p> <pre><code>today = datetime.datetime.today() past = today + timedelta(days=-200) results = mongo.stuff.find({"date_added": {"gt": past}}, {"id":1}) </code></pre> <p>I have the following date specified in MongoDB:</p> <pre><code>"date_added": { "$date": "2016-04-19T18:47:54.101Z" }, </code></pre> <p>But I get no results! Is this down to the timezone which appears in the MongoDB date which is screwing things up.</p>
0
2016-10-01T10:21:19Z
39,805,496
<p>Use an aware datetime object (with timezone info). </p> <pre><code># E.g. with UTC timezone : import pytz import datetime today = datetime.datetime.today() past = today + timedelta(days=-200) pytc.utc.localize(past) results = mongo.stuff.find({"date_added": {"gt": past}}, {"id":1}) </code></pre> <p>To use a different timezone to localize, try something like <code>pytz.timezone('US/Mountain')</code> </p> <p>P.S. you'll need <code>pip install pytz</code></p>
1
2016-10-01T10:25:53Z
[ "python", "mongodb", "pymongo" ]
Dealing with timezone dates in MongoDB and pymongo
39,805,453
<p>I do not seem to be able to query records and get what I expect. For example I am searching </p> <pre><code>today = datetime.datetime.today() past = today + timedelta(days=-200) results = mongo.stuff.find({"date_added": {"gt": past}}, {"id":1}) </code></pre> <p>I have the following date specified in MongoDB:</p> <pre><code>"date_added": { "$date": "2016-04-19T18:47:54.101Z" }, </code></pre> <p>But I get no results! Is this down to the timezone which appears in the MongoDB date which is screwing things up.</p>
0
2016-10-01T10:21:19Z
39,826,995
<p>This is just a typing error:</p> <p>Try with the following code:</p> <pre><code>results = mongo.stuff.find({"date_added": {"$gt": past}}, {"id":1}) </code></pre> <p>You forgot about the $ sign in $gt.</p>
1
2016-10-03T08:04:08Z
[ "python", "mongodb", "pymongo" ]
Εxtract data in between paratheses and append at the end of the line
39,805,590
<p>File.txt:</p> <pre><code>first_name NVARCHAR2(15) NOT NULL, middle_name NVARCHAR2(20) NOT NULL, last_name NVARCHAR2(11) NOT NULL, output i need:-&gt;output.txt first_name NVARCHAR2(15) NOT NULL,15 middle_name NVARCHAR2(20) NOT NULL,20 last_name NVARCHAR2(11) NOT NULL,11 </code></pre> <p>How can I extract data in <code>File.txt</code> between paratheses and append at the end of the line?</p>
-2
2016-10-01T10:36:46Z
39,810,895
<p>Use regex - something like:</p> <pre><code>import re for line in input: m=re.search('\((\d+)\)',line) output.write(line.rstrip('\n')+m.group(1)+'\n') </code></pre> <p>The search content should match what you are looking for (<code>\d+</code> in my example - matches any number). If you expect more then one parentheses in a sentence then you should give some more info. But in general, to extract a part of a match to your regex, use parentheses around what you wish to extract, and use <code>group(index)</code> on the retrieved "match item" (<code>m</code> in the example) - where <code>index</code> is the index of the parentheses you put in your regex that their content you wish to retrieve (and 0 means the entire match).</p> <p>For example:</p> <pre><code>m=re.search('a(.)c(.)e','abcde') m.group(0) 'abcde' m.group(1) 'b' m.group(2) 'd' </code></pre>
-1
2016-10-01T19:56:39Z
[ "python", "python-3.x" ]
Django /admin/ Page not found (404)
39,805,624
<p>I have the following error:</p> <pre><code>Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Raised by: nw.views.post_detail </code></pre> <p>But I can enter in example to <a href="http://127.0.0.1:8000/admin/nw/" rel="nofollow">http://127.0.0.1:8000/admin/nw/</a></p> <p>And if I remove all post_detail functions/parts of the code then I can enter to <a href="http://127.0.0.1:8000/admin/" rel="nofollow">http://127.0.0.1:8000/admin/</a> and it works, so something with this post_detail is wrong.</p> <p><strong>nw.views.post_detail:</strong></p> <pre><code>def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) context = { "instance": instance, } return render(request, "post_detail.html", context) </code></pre> <p><strong>urls.py:</strong></p> <pre><code>urlpatterns = [ url(r'', include('nw.urls', namespace='posts')), url(r'^admin/', admin.site.urls), ] </code></pre> <p>and</p> <pre><code>urlpatterns = [ url(r'^$', post_list, name='list'), url(r'^create/$', post_create), url(r'^(?P&lt;slug&gt;[\w-]+)/$', post_detail, name='detail'), url(r'^(?P&lt;slug&gt;[\w-]+)/edit/$', post_update, name='update'), url(r'^(?P&lt;slug&gt;[\w-]+)/delete/$', post_delete), ] </code></pre> <p><strong>post_detail.html:</strong></p> <pre><code>{% extends 'base.html' %} {% block head_title %}{{ instance.title }} | {{ block.super }}{% endblock head_title %} {% block content %} &lt;div class="instance"&gt; &lt;h1&gt;{{ instance.title }}&lt;/h1&gt; &lt;div class="date"&gt;{{ instance.published }}&lt;/div&gt; &lt;p&gt;{{ instance.text|linebreaksbr }}&lt;/p&gt; &lt;a href="https://www.facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}"&gt; Facebook &lt;/a&gt; &lt;a href="https://twitter.com/home?status={{ share_string }}%20{{ request.build_absolute_uri }}"&gt; Twitter &lt;/a&gt; &lt;a href='https://plus.google.com/share?url={{ request.build_absolute_uri }}'&gt;google&lt;/a&gt; &lt;a href="https://www.linkedin.com/shareArticle?mini=true&amp;url={{ request.build_absolute_uri }}&amp;title={{ instance.title }}&amp;summary={{ share_string }}&amp;source={{ request.build_absolute_uri }}"&gt; Linkedin &lt;/a&gt; &lt;a href="http://www.reddit.com/submit?url={{ request.build_absolute_uri }}&amp;title={{ share_string }}."&gt;Reddit&lt;/a&gt; &lt;/div&gt; {% endblock %} </code></pre> <p><strong>models.py:</strong></p> <pre><code>class Post(models.Model): author = models.ForeignKey('auth.User', default=1) title = models.CharField(max_length=200) slug = models.SlugField(unique=True) text = models.TextField() published = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"slug": self.slug}) class Meta: ordering = ["-published"] def create_slug(instance, new_slug=None): slug = slugify(instance.title) if new_slug is not None: slug = new_slug qs = Post.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" %(slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_post_receiver, sender=Post) </code></pre>
0
2016-10-01T10:40:28Z
39,805,687
<p>The <code>admin</code> <em>url</em> should come first:</p> <pre><code>urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('nw.urls', namespace='posts')), ] </code></pre> <p>Or else, it will be intercepted by another matching regex in your posts app <code>urlpatterns</code>, viz.:</p> <pre><code>url(r'^(?P&lt;slug&gt;[\w-]+)/$', post_detail, name='detail'), </code></pre> <p>As a rule of thumb, always keep the admin url at the top of the project's <code>urlpatterns</code></p>
1
2016-10-01T10:47:37Z
[ "python", "django" ]
Django /admin/ Page not found (404)
39,805,624
<p>I have the following error:</p> <pre><code>Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Raised by: nw.views.post_detail </code></pre> <p>But I can enter in example to <a href="http://127.0.0.1:8000/admin/nw/" rel="nofollow">http://127.0.0.1:8000/admin/nw/</a></p> <p>And if I remove all post_detail functions/parts of the code then I can enter to <a href="http://127.0.0.1:8000/admin/" rel="nofollow">http://127.0.0.1:8000/admin/</a> and it works, so something with this post_detail is wrong.</p> <p><strong>nw.views.post_detail:</strong></p> <pre><code>def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) context = { "instance": instance, } return render(request, "post_detail.html", context) </code></pre> <p><strong>urls.py:</strong></p> <pre><code>urlpatterns = [ url(r'', include('nw.urls', namespace='posts')), url(r'^admin/', admin.site.urls), ] </code></pre> <p>and</p> <pre><code>urlpatterns = [ url(r'^$', post_list, name='list'), url(r'^create/$', post_create), url(r'^(?P&lt;slug&gt;[\w-]+)/$', post_detail, name='detail'), url(r'^(?P&lt;slug&gt;[\w-]+)/edit/$', post_update, name='update'), url(r'^(?P&lt;slug&gt;[\w-]+)/delete/$', post_delete), ] </code></pre> <p><strong>post_detail.html:</strong></p> <pre><code>{% extends 'base.html' %} {% block head_title %}{{ instance.title }} | {{ block.super }}{% endblock head_title %} {% block content %} &lt;div class="instance"&gt; &lt;h1&gt;{{ instance.title }}&lt;/h1&gt; &lt;div class="date"&gt;{{ instance.published }}&lt;/div&gt; &lt;p&gt;{{ instance.text|linebreaksbr }}&lt;/p&gt; &lt;a href="https://www.facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}"&gt; Facebook &lt;/a&gt; &lt;a href="https://twitter.com/home?status={{ share_string }}%20{{ request.build_absolute_uri }}"&gt; Twitter &lt;/a&gt; &lt;a href='https://plus.google.com/share?url={{ request.build_absolute_uri }}'&gt;google&lt;/a&gt; &lt;a href="https://www.linkedin.com/shareArticle?mini=true&amp;url={{ request.build_absolute_uri }}&amp;title={{ instance.title }}&amp;summary={{ share_string }}&amp;source={{ request.build_absolute_uri }}"&gt; Linkedin &lt;/a&gt; &lt;a href="http://www.reddit.com/submit?url={{ request.build_absolute_uri }}&amp;title={{ share_string }}."&gt;Reddit&lt;/a&gt; &lt;/div&gt; {% endblock %} </code></pre> <p><strong>models.py:</strong></p> <pre><code>class Post(models.Model): author = models.ForeignKey('auth.User', default=1) title = models.CharField(max_length=200) slug = models.SlugField(unique=True) text = models.TextField() published = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"slug": self.slug}) class Meta: ordering = ["-published"] def create_slug(instance, new_slug=None): slug = slugify(instance.title) if new_slug is not None: slug = new_slug qs = Post.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" %(slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_post_receiver, sender=Post) </code></pre>
0
2016-10-01T10:40:28Z
39,805,748
<p>In your case this route working <code>url(r'^(?P&lt;slug&gt;[\w-]+)/$', post_detail, name='detail'),</code> and this function called <code>instance = get_object_or_404(Post, slug=slug)</code></p> <p>You can replace route like this</p> <pre><code>urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('nw.urls', namespace='posts')), ] </code></pre> <p><strong>The order of route is important</strong></p>
1
2016-10-01T10:55:26Z
[ "python", "django" ]
ValueError: Could not find a default download directory of nltk
39,805,675
<p>I have problem on import nltk. I configured apache and run some sample python code, it worked well on the browser. The URL is : /localhost/cgi-bin/test.py. When I import the nltk in test.py its not running. The execution not continue after the "import nltk" line.And it gives me that error ValueError: Could not find a default download directory But when I run in the command prompt its working perfect. how to remove this error?</p>
1
2016-10-01T10:46:11Z
39,805,804
<p>The environment in which your CGI script is executed is not the same as when you run it in from a terminal or similar. Specifically, environment variables like <code>$PYTHONPATH</code> might not be set to what you need.</p> <p>An ugly but safe work-around is adding the needed directories inside the script, before any third-party import statements:</p> <pre><code>import sys sys.path.append('path/to/package-parent') # change this to what you actually need import nltk </code></pre> <p>To find the location of NLTK or whatever causes trouble, import it in an interactive session. Then, typing the module/package name will print the location:</p> <pre><code>&gt;&gt;&gt; import nltk &gt;&gt;&gt; nltk &lt;module 'nltk' from '/usr/local/lib/python3.4/dist-packages/nltk/__init__.py'&gt; </code></pre> <p>So, you would append '/usr/local/lib/python3.4/dist-packages' to <code>sys.path</code> in this case.</p> <p>I'm not entirely sure if this also applies to the "default download directory", but you can give it a try.</p>
0
2016-10-01T11:02:00Z
[ "python", "nltk" ]
ValueError: Could not find a default download directory of nltk
39,805,675
<p>I have problem on import nltk. I configured apache and run some sample python code, it worked well on the browser. The URL is : /localhost/cgi-bin/test.py. When I import the nltk in test.py its not running. The execution not continue after the "import nltk" line.And it gives me that error ValueError: Could not find a default download directory But when I run in the command prompt its working perfect. how to remove this error?</p>
1
2016-10-01T10:46:11Z
39,807,691
<p>The problem is that on being imported, the <code>nltk</code> tries to initialize a <code>Downloader</code> object (even though you have not tried to download any resources), and fails to identify a usable download location. The easiest way to make it happy is to define <code>NLTK_DATA</code> in the environment, initialized to a folder that (a) exists, and (b) your server has write access to. </p> <p>In case that's not possible for some reason, let's take a look at the code that throws the error. The function <code>default_download_dir()</code> in <code>nltk\downloader.py</code> first looks for writeable locations in <code>nltk.data.path</code> (initialized from <code>NLTK_DATA</code>). If it fails to find any, it makes one last try: it tries for a folder <code>nltk_data</code> in your HOME directory (except on Windows). Evidently, your environment settings prevent Python from resolving <code>~/</code> to your HOME directory, leading to the error.</p> <pre><code># On Windows, use %APPDATA% if sys.platform == 'win32' and 'APPDATA' in os.environ: homedir = os.environ['APPDATA'] # Otherwise, install in the user's home directory. else: homedir = os.path.expanduser('~/') if homedir == '~/': raise ValueError("Could not find a default download directory") </code></pre> <p>So figure out what you can do to your environment to make this function happy.</p>
0
2016-10-01T14:19:06Z
[ "python", "nltk" ]
ValueError: Could not find a default download directory of nltk
39,805,675
<p>I have problem on import nltk. I configured apache and run some sample python code, it worked well on the browser. The URL is : /localhost/cgi-bin/test.py. When I import the nltk in test.py its not running. The execution not continue after the "import nltk" line.And it gives me that error ValueError: Could not find a default download directory But when I run in the command prompt its working perfect. how to remove this error?</p>
1
2016-10-01T10:46:11Z
39,810,288
<p>The Problem is raised probably because you don't have a default directory created for your ntlk downloads. If you are on a Windows Platform, All you need to do is to create a directory named "nltk_data" in any of your root directory and grant write permissions to that directory. The Natural Language Tool Kit initially searches for the destination named "nltk_data" in all of the root directories.</p> <p>For Instance: Create a folder in your C:\ drive named "nltk_data"</p> <p>After Making sure everything is done fine, execute your script to get rid of this error.</p> <p>Hope this helps. </p> <p>Regards.</p>
-1
2016-10-01T18:47:43Z
[ "python", "nltk" ]
Write values to a particular cell in a sheet in pandas in python
39,805,677
<p>I have an excel sheet, which already has some values in some cells.</p> <p>For ex :- </p> <pre><code> A B C D 1 val1 val2 val3 2 valx valy </code></pre> <p><strong>I want pandas to write to specific cells without touching any other cells,sheet etc</strong></p> <p>This is the code i tried.</p> <pre><code>import pandas as pd from openpyxl import load_workbook df2 = pd.DataFrame({'Data': [13, 24, 35, 46]}) book = load_workbook('b.xlsx') writer = pd.ExcelWriter('b.xlsx', engine='openpyxl') df2.to_excel(writer, "Sheet1", startcol=7,startrow=6) writer.save() </code></pre> <p>However this code deletes the older cell values.</p> <p>I have reffered to :- <a href="http://stackoverflow.com/questions/20219254/how-to-write-to-an-existing-excel-file-without-overwriting-data-using-pandas">How to write to an existing excel file without overwriting data (using pandas)?</a> but this solution does not work.</p>
2
2016-10-01T10:46:17Z
39,806,879
<p><strong>UPDATE2:</strong> appending data to existing Excel sheet, preserving other (old) sheets:</p> <pre><code>import pandas as pd from openpyxl import load_workbook fn = r'C:\Temp\.data\doc.xlsx' df = pd.read_excel(fn, header=None) df2 = pd.DataFrame({'Data': [13, 24, 35, 46]}) writer = pd.ExcelWriter(fn, engine='openpyxl') book = load_workbook(fn) writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) df.to_excel(writer, sheet_name='Sheet1', header=None, index=False) df2.to_excel(writer, sheet_name='Sheet1', header=None, index=False, startcol=7,startrow=6) writer.save() </code></pre> <p><strong>UPDATE:</strong> your Excel file doesn't have a header, so you should process it accordingly:</p> <pre><code>In [57]: df = pd.read_excel(fn, header=None) In [58]: df Out[58]: 0 1 0 abc def 1 ghi lmn In [59]: df2 Out[59]: Data 0 13 1 24 2 35 3 46 In [60]: writer = pd.ExcelWriter(fn) In [61]: df.to_excel(writer, header=None, index=False) In [62]: df2.to_excel(writer, startcol=7,startrow=6, header=None, index=False) In [63]: writer.save() </code></pre> <p><a href="http://i.stack.imgur.com/CyFhx.png" rel="nofollow"><img src="http://i.stack.imgur.com/CyFhx.png" alt="enter image description here"></a></p> <p><strong>OLD answer:</strong></p> <p>You can use the following trick:</p> <p>first read the existing contents of the excel file into a new DF:</p> <pre><code>In [17]: fn = r'C:\Temp\b.xlsx' In [18]: df = pd.read_excel(fn) In [19]: df Out[19]: A B C D 0 val1 NaN val3 val4 1 val11 val22 NaN val33 </code></pre> <p>now we can write it back and append a new DF2:</p> <pre><code>In [20]: writer = pd.ExcelWriter(fn) In [21]: df.to_excel(writer, index=False) In [22]: df2.to_excel(writer, startcol=7,startrow=6, header=None) In [23]: writer.save() </code></pre> <p><a href="http://i.stack.imgur.com/edAZY.png" rel="nofollow"><img src="http://i.stack.imgur.com/edAZY.png" alt="enter image description here"></a></p>
1
2016-10-01T12:58:18Z
[ "python", "excel", "pandas" ]
Write values to a particular cell in a sheet in pandas in python
39,805,677
<p>I have an excel sheet, which already has some values in some cells.</p> <p>For ex :- </p> <pre><code> A B C D 1 val1 val2 val3 2 valx valy </code></pre> <p><strong>I want pandas to write to specific cells without touching any other cells,sheet etc</strong></p> <p>This is the code i tried.</p> <pre><code>import pandas as pd from openpyxl import load_workbook df2 = pd.DataFrame({'Data': [13, 24, 35, 46]}) book = load_workbook('b.xlsx') writer = pd.ExcelWriter('b.xlsx', engine='openpyxl') df2.to_excel(writer, "Sheet1", startcol=7,startrow=6) writer.save() </code></pre> <p>However this code deletes the older cell values.</p> <p>I have reffered to :- <a href="http://stackoverflow.com/questions/20219254/how-to-write-to-an-existing-excel-file-without-overwriting-data-using-pandas">How to write to an existing excel file without overwriting data (using pandas)?</a> but this solution does not work.</p>
2
2016-10-01T10:46:17Z
40,060,480
<p>I was not able to do what was asked by me in the question by using pandas, but was able to solve it by using <code>Openpyxl</code>. </p> <p>I will write few code snippets which would help in achieving what was asked.</p> <pre><code>import openpyxl srcfile = openpyxl.load_workbook('docname.xlsx',read_only=False, keep_vba= True)#to open the excel sheet and if it has macros sheetname = srcfile.get_sheet_by_name('sheetname')#get sheetname from the file sheetname['B2']= str('write something') #write something in B2 cell of the supplied sheet sheetname.cell(row=1,column=1).value = "something" #write to row 1,col 1 explicitly, this type of writing is useful to write something in loops srcfile.save('newfile.xlsm')#save it as a new file, the original file is untouched and here I am saving it as xlsm(m here denotes macros). </code></pre> <p><strong>So Openpyxl writes to a purticular cell, without touching the other sheets,cells etc. It basically writes to a new file respecting the properties of the original file</strong></p>
0
2016-10-15T14:51:41Z
[ "python", "excel", "pandas" ]
For loop computing recurrence relation takes very long
39,805,705
<pre><code>Q(x)=[Q(x−1)+Q(x−2)]^2 Q(0)=0, Q(1)=1 </code></pre> <p>I need to find Q(29). I wrote a code in python but it is taking too long. How to get the output (any language would be fine)?</p> <p>Here is the code I wrote:</p> <pre><code>a=0 b=1 for i in range(28): c=(a+b)*(a+b) a=b b=c print(b) </code></pre>
0
2016-10-01T10:49:35Z
39,806,165
<p>This WILL take too long, since is a kind of geometric progression which tends to infinity.</p> <p>Example:</p> <pre><code>a=0 b=1 c=1*1 = 1 a=1 b=1 c=2*2 = 4 a=1 b=4 c=5*5 = 25 a=4 b=25 c= 29*29 = 841 a=25 b=841 . . . </code></pre>
0
2016-10-01T11:39:13Z
[ "python", "loops", "recurrence" ]
For loop computing recurrence relation takes very long
39,805,705
<pre><code>Q(x)=[Q(x−1)+Q(x−2)]^2 Q(0)=0, Q(1)=1 </code></pre> <p>I need to find Q(29). I wrote a code in python but it is taking too long. How to get the output (any language would be fine)?</p> <p>Here is the code I wrote:</p> <pre><code>a=0 b=1 for i in range(28): c=(a+b)*(a+b) a=b b=c print(b) </code></pre>
0
2016-10-01T10:49:35Z
39,806,258
<p>You can check if c%10==0 and then divide it, and in the end multiplyit number of times you divided it but in the end it'll be the same large number. If you really need to do this calculation try using C++ it should run it faster than Python.</p> <hr> <p>Here's your code written in C++</p> <pre><code>#include &lt;cstdlib&gt; #include &lt;iostream&gt; using namespace std; int main(int argc, char *argv[]) { long long int a=0; long long int b=1; long long int c=0; for(int i=0;i&lt;28;i++){ c=(a+b)*(a+b); a=b; b=c; } cout &lt;&lt; c; return 0; } </code></pre>
0
2016-10-01T11:47:23Z
[ "python", "loops", "recurrence" ]
For loop computing recurrence relation takes very long
39,805,705
<pre><code>Q(x)=[Q(x−1)+Q(x−2)]^2 Q(0)=0, Q(1)=1 </code></pre> <p>I need to find Q(29). I wrote a code in python but it is taking too long. How to get the output (any language would be fine)?</p> <p>Here is the code I wrote:</p> <pre><code>a=0 b=1 for i in range(28): c=(a+b)*(a+b) a=b b=c print(b) </code></pre>
0
2016-10-01T10:49:35Z
39,807,447
<p>I don't think this is a tractable problem with programming. The reason why your code is slow is that the numbers within grow <em>very</em> rapidly, and python uses infinite-precision integers, so it takes its time computing the result.</p> <p>Try your code with double-precision floats:</p> <pre><code>a=0.0 b=1.0 for i in range(28): c=(a+b)*(a+b) a=b b=c print(b) </code></pre> <p>The answer is <code>inf</code>. This is because the answer is much much larger than the largest representable double-precision number, which is <a href="http://stackoverflow.com/a/3477332/5067311">rougly 10^308</a>. You could try using finite-precision integers, but those will have an even smaller representable maximum. Note that using doubles will lead to loss of precision, but surely you don't want to know every single digit of your huuuge number (side note: <a href="http://math.stackexchange.com/questions/1948492/sum-of-digits-of-p29-the-sum-of-two-recurrence-series">I happen to know that you do</a>, making your job even harder).</p> <p>So here's some math background for my skepticism: Your recurrence relation goes</p> <pre><code>Q[k] = (Q[k-2] + Q[k-1])^2 </code></pre> <p>You can formulate a more tractable sequence from the square root of this sequence:</p> <pre><code>P[k] = sqrt(Q[k]) P[k] = P[k-2]^2 + P[k-1]^2 </code></pre> <p>If you can solve for <code>P</code>, you'll know <code>Q = P^2</code>.</p> <p>Now, consider this sequence:</p> <pre><code>R[k] = R[k-1]^2 </code></pre> <p>Starting from the same initial values, this will always be smaller than <code>P[k]</code>, since</p> <pre><code>P[k] = P[k-2]^2 + P[k-1]^2 &gt;= P[k-1]^2 </code></pre> <p>(but this will be a "pretty close" lower bound as the first term will always be insignificant compared to the second). We can construct this sequence:</p> <pre><code>R[k] = R[k-1]^2 = R[k-2]^4 = R[k-3]^6 = R[k-m]^(2^m) = R[0]^(2^k) </code></pre> <p>Since <code>P[1 give or take]</code> starts with value 2, we should consider</p> <pre><code>R[k] = 2^(2^k) </code></pre> <p>as a lower bound for <code>P[k]</code>, give or take a few exponents of 2. For <code>k=28</code> this is</p> <pre><code>P[28] &gt; 2^(2^28) = 2^(268435456) = 10^(log10(2)*2^28) ~ 10^80807124 </code></pre> <p>That's at least <code>80807124</code> digits for the final value of <code>P</code>, which is the square root of the number you're looking for. That makes <code>Q[28]</code> larger than <code>10^1.6e8</code>. If you printed that number into a text file, it would take more than 150 megabytes.</p> <p>If you imagine you're trying to handle these integers exactly, you'll see why it takes so long, and why you should reconsider your approach. What if you could compute that huge number? What would you do with it? How long would it take python to print that number on your screen? None of this is trivial, so I suggest that you try to solve your problem on paper, or find a way around it.</p> <hr> <p>Note that you can use a symbolic math package such as <code>sympy</code> in python to get a feeling of how hard your problem is:</p> <pre><code>import sympy as sym a,b,c,b0 = sym.symbols('a,b,c,b0') a = 0 b = b0 for k in range(28): c = (a+b)**2 a = b b = c print(c) </code></pre> <p>This will take a while, but it will fill your screen with the explicit expression for <code>Q[k]</code> with only <code>b0</code> as parameter. You would "only" have to substitute your values into that monster to obtain the exact result. You could also try <code>sym.simplify</code> on the expression, but I couldn't wait for that to return anything meaningful.</p> <hr> <p>During lunch time I let your loop run, and it finished. The result has</p> <pre><code>&gt;&gt;&gt; import math &gt;&gt;&gt; print(math.log10(c)) 49287457.71120789 </code></pre> <p>So my lower bound for <code>k=28</code> is a bit large, probably due to off-by-one errors in the exponent. The memory needed to store this integer is</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.getsizeof(c) 21830612 </code></pre> <p>that is roughly 20 MB.</p>
2
2016-10-01T13:53:52Z
[ "python", "loops", "recurrence" ]
For loop computing recurrence relation takes very long
39,805,705
<pre><code>Q(x)=[Q(x−1)+Q(x−2)]^2 Q(0)=0, Q(1)=1 </code></pre> <p>I need to find Q(29). I wrote a code in python but it is taking too long. How to get the output (any language would be fine)?</p> <p>Here is the code I wrote:</p> <pre><code>a=0 b=1 for i in range(28): c=(a+b)*(a+b) a=b b=c print(b) </code></pre>
0
2016-10-01T10:49:35Z
39,823,636
<p>This can be solved with brute force but it is still an interesting problem since it uses two different "slow" operations and there are trade-offs in choosing the correct approach.</p> <p>There are two places where the native Python implementation of algorithm is slow: the multiplication of large numbers and the conversion of large numbers to a string. </p> <p>Python uses the Karatsuba algorithm for multiplication. It has a running time of O(n^1.585) where n is the length of the numbers. It does get slower as the numbers get larger but you can compute Q(29). </p> <p>The algorithm for converting a Python integer to its decimal representation is much slower. It has running time of O(n^2). For large numbers, it is much slower than multiplication.</p> <p><strong><em>Note: the times for conversion to a string also include the actual calculation time.</em></strong></p> <p>On my computer, computing Q(25) requires ~2.5 seconds but conversion to a string requires ~3 minutes 9 seconds. Computing Q(26) requires ~7.5 seconds but conversion to a string requires ~12 minutes 36 seconds. As the size of the number doubles, multiplication time increases by a factor of 3 and the running time of string conversion increases by a factor of 4. The running time of the conversion to string dominates. Computing Q(29) takes about 3 minutes and 20 seconds but conversion to a string will take more than 12 hours (I didn't actually wait that long).</p> <p>One option is the <a href="https://pypi.python.org/pypi/gmpy2" rel="nofollow">gmpy2</a> module that provides access the very fast <a href="https://gmplib.org/" rel="nofollow">GMP</a> library. With <code>gmpy2</code>, Q(26) can be calculated in ~0.2 seconds and converted into a string in ~1.2 seconds. Q(29) can be calculated in ~1.7 seconds and converted into a string in ~15 seconds. Multiplication in GMP is O(n*ln(n)). Conversion to decimal is faster that Python's O(n^2) algorithm but still slower than multiplication.</p> <p>The fastest option is Python's <code>decimal</code> module. Instead of using a radix-2, or binary, internal representation, it uses a radix-10 (actually of power of 10) internal representation. Calculations are slightly slower but conversion to a string is very fast; it is just O(n). Calculating Q(29) requires ~9.2 seconds but calculating and conversion together only requires ~9.5 seconds. The time for conversion to string is only ~0.3 seconds.</p> <p>Here is an example program using <code>decimal</code>. It also sums the individual digits of the final value.</p> <pre><code>import decimal decimal.getcontext().prec = 200000000 decimal.getcontext().Emax = 200000000 decimal.getcontext().Emin = -200000000 def sum_of_digits(x): return sum(map(int, (t for t in str(x)))) a = decimal.Decimal(0) b = decimal.Decimal(1) for i in range(28): c = (a + b) * (a + b) a = b b = c temp = str(b) print(i, len(temp), sum_of_digits(temp)) </code></pre> <p>I didn't include the time for converting the millions of digits into strings and adding them in the discussion above. That time should be the same for each version.</p>
1
2016-10-03T02:00:20Z
[ "python", "loops", "recurrence" ]
PIL crop image give incorrect height result
39,805,750
<pre><code>import PIL from PIL import Image img = Image.open('0009_jpg.jpg') width, height = img.size #height is 720 and width is 480 if height &gt; width: rm_height = abs(height - width) # rm_height = 240 x_offset = 0 y_offset = rm_height/2 # y_offset = 120 tall = height-rm_height # tall = 480 img_crop = img.crop((x_offset, y_offset, width, tall)) img_crop.save('crop_jpg.jpg') </code></pre> <p>output image is 480x360 resulution not 480x480</p> <p>but when i change this line to</p> <pre><code>tall = height-rm_height/2 # tall = 600 </code></pre> <p>output image is square 480x480</p> <p>it's not make sense. what i do wrong. thanks</p>
1
2016-10-01T10:55:58Z
39,805,788
<p>OK after i search for more. Now i get it from this <a href="http://labb.in/s/ZCwU" rel="nofollow">post</a></p> <p>Chris Clarke's (<a href="http://labb.in/s/ZCqu" rel="nofollow">edited</a> by San4ez) answer:</p> <pre><code>import Image im = Image.open(&lt;your image&gt;) width, height = im.size # Get dimensions left = (width - new_width)/2 top = (height - new_height)/2 right = (width + new_width)/2 bottom = (height + new_height)/2 im.crop((left, top, right, bottom)) </code></pre> <p>it's not tall. it is bottom</p>
-1
2016-10-01T11:00:13Z
[ "python", "python-2.7", "python-imaging-library" ]
The difference of gevent and multiprocess
39,805,780
<p>I am learning how to make my script run faster. I think parallel is a good way. So I try gevent and multiprocessing. But I am confused by it's different result. Let me show two examples I met,</p> <p>ex 1:</p> <pre><code>a=np.zeros([3]) def f(i): a[i]=1 print a def f_para(): p=multiprocessing.Pool() p.map(f, range(3)) def f_asy(): threads = [gevent.spawn(f, i) for i in xrange(3)] gevent.joinall(threads) f_para() [ 0. 1. 0.] [ 0. 0. 1.] [ 1. 0. 0.] f_asy() [ 1. 0. 0.] [ 1. 1. 0.] [ 1. 1. 1.] </code></pre> <p>I find that using multiprocessing, the global object <code>a</code> never change in fat, and after running <code>f_para()</code>, <code>a</code> is still the original array. While running <code>f_asy()</code>, it's different, <code>a</code> changed.</p> <p>ex 2:</p> <pre><code>def f2(i): subprocess.call(['./a.out', str(i)]) time.sleep(0.2) def f2_loop(): for i in xrange(20): f2(i) def f2_para(): p=multiprocessing.Pool() p.map(f2, range(20)) def f2_asy(): threads = [gevent.spawn(f2, i) for i in xrange(20)] gevent.joinall(threads) %timeit -n1 f2_loop() 1 loop, best of 3: 4.22 s per loop %timeit -n1 f2_asy() 1 loop, best of 3: 4.22 s per loop %timeit -n1 f2_para() 1 loop, best of 3: 657 ms per loop </code></pre> <p>I find that <code>f2_asy()</code> don't decrease run time. And the output of <code>f2_asy()</code> is one by one, just as <code>f2_loop()</code>, so there is no parallel in <code>f2_asy()</code> I think. </p> <p>The <code>a.out</code> is a simple c++ code:</p> <pre><code> #include &lt;iostream&gt; int main(int argc, char* argv[]) { std::cout&lt;&lt;argv[1]&lt;&lt;std::endl; return 0; } </code></pre> <p>So my question is that:</p> <ol> <li><p>why in ex 1, <code>f_para</code> can change the value of global array <code>a</code> ?</p></li> <li><p>why in ex 2, <code>f2_asy</code> can't do parallel?</p></li> </ol> <p>Dose any knows the difference between gevent and multiprocessing? I am very grateful if you are willing to explain it.</p>
2
2016-10-01T10:59:05Z
39,805,884
<p>ex1:</p> <p>when you use multiprocess each process has separate memory(unlike threads)</p> <p>ex2:</p> <p>gevent does not create threads, it creates Greenlets(coroutines)!</p> <blockquote> <p>Greenlets all run inside of the OS process for the main program but are scheduled cooperatively.</p> <p><strong>Only one greenlet is ever running at any given time.</strong></p> <p>This differs from any of the real parallelism constructs provided by multiprocessing or threading libraries which do spin processes and POSIX threads which are scheduled by the operating system and are truly parallel.</p> </blockquote>
1
2016-10-01T11:11:56Z
[ "python", "python-2.7", "parallel-processing", "multiprocessing", "gevent" ]
keep on getting str object has no attribute 'punctuation'
39,805,837
<p>Im trying to make a code that identifies punctuation in a word this is all I got up to:</p> <pre><code>word=input('enter a word: ') punctuation=set(word.punctuation) for each in word: if each==punctuation: print('yes') </code></pre> <p>but it keeps on saying 'str' object has no attribute 'punctuation' how do I solve this???</p>
-2
2016-10-01T11:06:32Z
39,805,864
<p><code>str</code> objects do not have a punctuation attribute. You can instead use <a href="https://docs.python.org/2/library/string.html#string.punctuation" rel="nofollow"><code>string.punctuation</code></a> to check for any punctuation in your word:</p> <pre><code>import string # string.punctuation '!"#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\\]^_`{|}~' for each in word: if each in string.punctuation: print('yes') </code></pre>
5
2016-10-01T11:08:59Z
[ "python" ]
Refer a global variable that has same name as the local variable in Python
39,805,893
<p>I am new to python, how can we refer a global variable that has the same name as local one. </p> <pre><code>spam = 'global spam' def scope_test(): spam = 'local spam' print(spam) # access global spam and print or assign to the local spam # print(global.spam) # local.spam = global.spam (something like this) scope_test() </code></pre>
0
2016-10-01T11:13:02Z
39,808,103
<p>It's something not recommended, I am answering it for the sake if you're curious to ask/do it:</p> <pre><code>Python 3.5.2 &gt;&gt;&gt; spam = 'global spam' &gt;&gt;&gt; def scope_test(): .. spam = 'local spam' .. print(spam) .. # access global spam and print or assign to the local spam .. print(globals()['spam']) .. spam = globals()['spam'] .. print(spam) .. &gt;&gt;&gt; scope_test() </code></pre> <p>The output:</p> <pre><code>local spam global spam global spam </code></pre>
1
2016-10-01T15:03:22Z
[ "python" ]
pandas remove seconds from datetime index
39,805,961
<p>I have a pandas dataFrame called 'df' as follows</p> <pre><code> value 2015-09-27 03:58:30 1.0 2015-09-27 03:59:30 1.0 2015-09-27 04:00:30 1.0 2015-09-27 04:01:30 1.0 </code></pre> <p>I just want to strip out the seconds to get this</p> <pre><code> value 2015-09-27 03:58:00 1.0 2015-09-27 03:59:00 1.0 2015-09-27 04:00:00 1.0 2015-09-27 04:01:00 1.0 </code></pre> <p>How can i do this?</p> <p>ive tried things like</p> <pre><code>df.index.to_series().apply(datetime.replace(second=0, microsecond=0)) </code></pre> <p>but i always get errors </p> <pre><code>TypeError: descriptor 'replace' of 'datetime.datetime' object needs an argument </code></pre>
0
2016-10-01T11:19:45Z
39,806,178
<p>You could use <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.replace" rel="nofollow"><code>datetime.replace</code></a> to alter the second's attribute as shown:</p> <pre><code>df.index = df.index.map(lambda x: x.replace(second=0)) </code></pre> <p><a href="http://i.stack.imgur.com/xO9gu.png" rel="nofollow"><img src="http://i.stack.imgur.com/xO9gu.png" alt="Image"></a></p>
3
2016-10-01T11:40:22Z
[ "python", "pandas", "indexing", "seconds" ]
Open a file inside the package directory instead of opening from current directory
39,806,088
<p>I have created a Python package and installed locally. With using the command <code>pip install .</code> .In my package it's necessary to open a file like this.</p> <pre><code>open('abc.txt','r+') </code></pre> <p>But my problem is it's try to open the file in the working directory instead of package installed directory.I think absolute path not going to solve my problem. </p> <p>So my question is, How open a file inside the package ? </p> <p><strong>NB</strong>: While i searched about it saw that <code>os.sys.path</code> may help. But i didn't get any clear solution.</p> <p>Thank you,</p>
0
2016-10-01T11:31:21Z
39,806,187
<p>Try: </p> <pre><code>import os import inspect def open_file(filename): pkg_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) return open(pkg_dir + "/" + filename,'r+') </code></pre>
1
2016-10-01T11:41:10Z
[ "python", "python-packaging" ]
Python: Converting word to list of letters, then returning indexes of the letters against lower case alphabet
39,806,097
<p>I have already completed the task but in its most basic form looking for help shortening it and so it can apply to any word not just one with eight letters, here's what I've got so far (bit long for what it does):</p> <pre><code>alpha = map(chr, range(97, 123)) word = "computer" word_list = list(word) one = word[0] two = word[1] three = word[2] four = word[3] five = word[4] six = word[5] seven = word[6] eight = word[7] one_index = str(alpha.index(one)) two_index = str(alpha.index(two)) three_index = str(alpha.index(three)) four_index = str(alpha.index(four)) five_index = str(alpha.index(five)) six_index = str(alpha.index(six)) seven_index = str(alpha.index(seven)) eight_index = str(alpha.index(eight)) print (one + "=" + one_index) print (two + "=" + two_index) print (three + "=" + three_index) print (four + "=" + four_index) print (five + "=" + five_index) print (six + "=" + six_index) print (seven + "=" + seven_index) print (eight + "=" + eight_index) </code></pre>
0
2016-10-01T11:32:04Z
39,806,237
<p>What you are probably looking for is a <strong>for-loop</strong>.</p> <p>Using a for-loop your code could look like this:</p> <pre><code>word = "computer" for letter in word: index = ord(letter)-97 if (index&lt;0) or (index&gt;25): print ("'{}' is not in the lowercase alphabet.".format(letter)) else: print ("{}={}".format(letter, str(index+1))) # +1 to make a=1 </code></pre> <p>If you use</p> <pre><code>for letter in word: #code </code></pre> <p>the following code will be executed for every letter in the word (or element in word if word is a list for example).</p> <p>A good start to learn more about loops is here: <a href="https://en.wikibooks.org/wiki/Python_Programming/Loops" rel="nofollow">https://en.wikibooks.org/wiki/Python_Programming/Loops</a></p> <p>You can find tons of ressources in the internet covering this topic.</p>
2
2016-10-01T11:45:21Z
[ "python", "string", "list" ]
Python: Converting word to list of letters, then returning indexes of the letters against lower case alphabet
39,806,097
<p>I have already completed the task but in its most basic form looking for help shortening it and so it can apply to any word not just one with eight letters, here's what I've got so far (bit long for what it does):</p> <pre><code>alpha = map(chr, range(97, 123)) word = "computer" word_list = list(word) one = word[0] two = word[1] three = word[2] four = word[3] five = word[4] six = word[5] seven = word[6] eight = word[7] one_index = str(alpha.index(one)) two_index = str(alpha.index(two)) three_index = str(alpha.index(three)) four_index = str(alpha.index(four)) five_index = str(alpha.index(five)) six_index = str(alpha.index(six)) seven_index = str(alpha.index(seven)) eight_index = str(alpha.index(eight)) print (one + "=" + one_index) print (two + "=" + two_index) print (three + "=" + three_index) print (four + "=" + four_index) print (five + "=" + five_index) print (six + "=" + six_index) print (seven + "=" + seven_index) print (eight + "=" + eight_index) </code></pre>
0
2016-10-01T11:32:04Z
39,806,314
<p>Use for loop for loop,</p> <pre><code>alpha = map(chr, range(97, 123)) word = "computer" for l in word: print '{} = {}'.format(l,alpha.index(l.lower())) </code></pre> <p><strong>Result</strong></p> <pre><code>c = 2 o = 14 m = 12 p = 15 u = 20 t = 19 e = 4 r = 17 </code></pre>
0
2016-10-01T11:53:54Z
[ "python", "string", "list" ]
Python: Converting word to list of letters, then returning indexes of the letters against lower case alphabet
39,806,097
<p>I have already completed the task but in its most basic form looking for help shortening it and so it can apply to any word not just one with eight letters, here's what I've got so far (bit long for what it does):</p> <pre><code>alpha = map(chr, range(97, 123)) word = "computer" word_list = list(word) one = word[0] two = word[1] three = word[2] four = word[3] five = word[4] six = word[5] seven = word[6] eight = word[7] one_index = str(alpha.index(one)) two_index = str(alpha.index(two)) three_index = str(alpha.index(three)) four_index = str(alpha.index(four)) five_index = str(alpha.index(five)) six_index = str(alpha.index(six)) seven_index = str(alpha.index(seven)) eight_index = str(alpha.index(eight)) print (one + "=" + one_index) print (two + "=" + two_index) print (three + "=" + three_index) print (four + "=" + four_index) print (five + "=" + five_index) print (six + "=" + six_index) print (seven + "=" + seven_index) print (eight + "=" + eight_index) </code></pre>
0
2016-10-01T11:32:04Z
39,806,396
<p>Start with a <code>dict</code> that maps each letter to its number.</p> <pre><code>import string d = dict((c, ord(c)-ord('a')) for c in string.lowercase) </code></pre> <p>Then pair each letter of your string to the appropriate index.</p> <pre><code>result = [(c, d[c]) for c in word] </code></pre>
0
2016-10-01T12:02:42Z
[ "python", "string", "list" ]
Python: Converting word to list of letters, then returning indexes of the letters against lower case alphabet
39,806,097
<p>I have already completed the task but in its most basic form looking for help shortening it and so it can apply to any word not just one with eight letters, here's what I've got so far (bit long for what it does):</p> <pre><code>alpha = map(chr, range(97, 123)) word = "computer" word_list = list(word) one = word[0] two = word[1] three = word[2] four = word[3] five = word[4] six = word[5] seven = word[6] eight = word[7] one_index = str(alpha.index(one)) two_index = str(alpha.index(two)) three_index = str(alpha.index(three)) four_index = str(alpha.index(four)) five_index = str(alpha.index(five)) six_index = str(alpha.index(six)) seven_index = str(alpha.index(seven)) eight_index = str(alpha.index(eight)) print (one + "=" + one_index) print (two + "=" + two_index) print (three + "=" + three_index) print (four + "=" + four_index) print (five + "=" + five_index) print (six + "=" + six_index) print (seven + "=" + seven_index) print (eight + "=" + eight_index) </code></pre>
0
2016-10-01T11:32:04Z
39,806,691
<p>thanks for the help managed to solve it myself in a different way using a function and a while loop, not as short but will work for all lower case words:</p> <pre><code>alpha = map(chr, range (97,123)) word = "computer" count = 0 y = 0 def indexfinder (number): o = word[number] i = str(alpha.index(o)) print (o + "=" + i) while count &lt; len(word): count = count + 1 indexfinder (y) y = y+1 </code></pre>
0
2016-10-01T12:39:20Z
[ "python", "string", "list" ]
Python: Converting word to list of letters, then returning indexes of the letters against lower case alphabet
39,806,097
<p>I have already completed the task but in its most basic form looking for help shortening it and so it can apply to any word not just one with eight letters, here's what I've got so far (bit long for what it does):</p> <pre><code>alpha = map(chr, range(97, 123)) word = "computer" word_list = list(word) one = word[0] two = word[1] three = word[2] four = word[3] five = word[4] six = word[5] seven = word[6] eight = word[7] one_index = str(alpha.index(one)) two_index = str(alpha.index(two)) three_index = str(alpha.index(three)) four_index = str(alpha.index(four)) five_index = str(alpha.index(five)) six_index = str(alpha.index(six)) seven_index = str(alpha.index(seven)) eight_index = str(alpha.index(eight)) print (one + "=" + one_index) print (two + "=" + two_index) print (three + "=" + three_index) print (four + "=" + four_index) print (five + "=" + five_index) print (six + "=" + six_index) print (seven + "=" + seven_index) print (eight + "=" + eight_index) </code></pre>
0
2016-10-01T11:32:04Z
39,806,942
<p>Just an alternative way:</p> <pre><code>for w in word: print (w+" = "+str((ord(w.lower())-96))) if w not in '., !' else "" </code></pre> <p>This way is not case sensitive, for example for <code>Computer</code> you will get the same results as with <code>computer</code>, but the output is case sensitive (I mean even if the index remains the same for capitals and lowers the letters printed in the output will be as in the word) .</p>
0
2016-10-01T13:03:40Z
[ "python", "string", "list" ]
Python - multiprocessing while writing to a single result file
39,806,110
<p>I am really new to the multiprocessing package and I am failing to get the task done.</p> <p>I have lots of calculations to do on a list of objects. </p> <p>The results I need to write down are saved in those objects, too.</p> <p>The results should be written in a single file as soon as the process finished the calculations (the way I got it at least working, waits until all calculations are done).</p> <pre><code>import multiprocessing import time import csv class simpl(): def __init__(self, name, val): self.name = name self.val = val def pot_val(inpt): print("Process %s\t ..." % (inpt.name)) old_v = inpt.val inpt.val *= inpt.val if old_v != 8: time.sleep(old_v) print("Process %s\t ... Done" % (inpt.name)) def mp_worker(inpt): pot_val(inpt) return inpt def mp_handler(data_list): p = multiprocessing.Pool(4) with open('results.csv', 'a') as f: res = p.map_async(mp_worker, data_list) results = (res.get()) for result in results: print("Writing result for ",result.name) writer= csv.writer(f, lineterminator = '\n', delimiter=";") writer.writerow((result.name, result.val)) if __name__=='__main__': data = [] counter=0 for i in range(10): data.append(simpl("name"+str(counter),counter)) counter += 1 for d in data: print(d.name, d.val) mp_handler(data) </code></pre> <p>How to write the results from the calculations simultaneously to one single file, without having to wait for all processes to finish?</p>
0
2016-10-01T11:33:29Z
39,806,402
<p>You can use <a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.imap_unordered" rel="nofollow">imap_unordered</a></p> <pre><code>def mp_handler(data_list): p = multiprocessing.Pool(4) with open('results.csv', 'a') as f: writer= csv.writer(f, lineterminator = '\n', delimiter=";") for result in p.imap_unordered(mp_worker, data_list): print("Writing result for ",result.name) writer.writerow((result.name, result.val)) </code></pre> <p>With Python 3.3+ better do</p> <pre><code>def mp_handler(data_list): with multiprocessing.Pool(4) as p: with open('results.csv', 'a') as f: writer= csv.writer(f, lineterminator = '\n', delimiter=";") for result in p.imap_unordered(mp_worker, data_list): print("Writing result for ",result.name) writer.writerow((result.name, result.val)) </code></pre>
3
2016-10-01T12:03:34Z
[ "python", "multiprocessing" ]
Scrapy not going to next page (follow links) when the url is constructed from a csv file
39,806,177
<p>Hi I have this simple scrapy file. As you can see, I am adding ship imo number to the response.url(). But when i run the programme i do not get any results (no error messages as well). I have set the USER AGENT in settings.py.</p> <pre><code>import re import csv import scrapy from mcdetails.items import McdetailsItem class GetVesselDetails(scrapy.Spider): name = "mconnector" allowed_domains = ["http://maritime-connector.com/"] start_urls = [ 'http://maritime-connector.com/ship/', ] def parse(self, response): with open('output.csv', "r") as f: mclist = csv.reader(f, delimiter=',') next(f) for l in mclist: if not l[1] in (None, ""): # eg. 'http://maritime-connector.com/ship' + '849949' mcurl = response.urljoin(l[1]) yield scrapy.Request(mcurl, callback=self.parse_ships_details) def parse_ships_details(self,response): item = McdetailsItem() # item = resonse.meta['item'] item['v_name'] = response.xpath('//title/text()').extract_first() yield {'vessell name': item['v_name']} </code></pre> <p>and this the output.</p> <pre><code>2016-10-01 15:37:52 [scrapy] INFO: Enabled item pipelines: [] 2016-10-01 15:37:52 [scrapy] INFO: Spider opened 2016-10-01 15:37:52 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2016-10-01 15:37:52 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6024 2016-10-01 15:37:53 [scrapy] DEBUG: Redirecting (301) to &lt;GET http://maritime-connector.com/robots.txt/&gt; from &lt;GET http://maritime-connector.com/robots.txt&gt; 2016-10-01 15:37:53 [scrapy] DEBUG: Crawled (404) &lt;GET http://maritime-connector.com/robots.txt/&gt; (referer: None) 2016-10-01 15:37:53 [scrapy] DEBUG: Crawled (200) &lt;GET http://maritime-connector.com/ship/&gt; (referer: None) 2016-10-01 15:37:53 [scrapy] DEBUG: Filtered offsite request to 'maritime-connector.com': &lt;GET http://maritime-connector.com/ship/8986080&gt; 2016-10-01 15:37:54 [scrapy] INFO: Closing spider (finished) 2016-10-01 15:37:54 [scrapy] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 1109, 'downloader/request_count': 3, 'downloader/request_method_count/GET': 3, 'downloader/response_bytes': 25884, 'downloader/response_count': 3, 'downloader/response_status_count/200': 1, 'downloader/response_status_count/301': 1, 'downloader/response_status_count/404': 1, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2016, 10, 1, 11, 37, 54, 36472), 'log_count/DEBUG': 5, 'log_count/INFO': 7, 'offsite/domains': 1, 'offsite/filtered': 913, 'request_depth_max': 1, 'response_received_count': 2, 'scheduler/dequeued': 1, 'scheduler/dequeued/memory': 1, 'scheduler/enqueued': 1, 'scheduler/enqueued/memory': 1, 'start_time': datetime.datetime(2016, 10, 1, 11, 37, 52, 641119)} </code></pre>
0
2016-10-01T11:40:10Z
39,808,074
<p>The traceback speaks for itself:</p> <pre><code>2016-10-01 15:37:53 [scrapy] DEBUG: Filtered offsite request to 'maritime-connector.com': &lt;GET http://maritime-connector.com/ship/8986080&gt; </code></pre> <p>Your <code>allowed_domains</code> are wrong. You should use:</p> <pre><code>allowed_domains = ["maritime-connector.com"] </code></pre> <p>The <code>http://</code> does not play a part in the domain.</p>
1
2016-10-01T15:00:35Z
[ "python", "scrapy" ]
Convert List of List of Tuples Into 2d Numpy Array
39,806,259
<p>I have a list of list of tuples:</p> <pre><code>X = [[(0.5, 0.5, 0.5), (1.0, 1.0, 1.0)], [(0.5, 0.5, 0.52), (1.0, 1.0, 1.0)], [(0.5, 0.52, 0.52), (1.0, 1.0, 1.0)], [(0.52, 0.52, 0.52), (1.0, 1.0, 1.0)], [(0.52, 0.52, 0.52), (1.0, 1.0, 1.0)]] </code></pre> <p>and would like to convert it to a 2D numpy array. I tried the following but didn't work. I just want to make sure the new transformed 2D keeps the same shape and structure of X. Please help me , thanks a lot.</p> <pre><code>import numpy as np X = [[(0.5, 0.5, 0.5), (1.0, 1.0, 1.0)], [(0.5, 0.5, 0.52), (1.0, 1.0, 1.0)], [(0.5, 0.52, 0.52), (1.0, 1.0, 1.0)], [(0.52, 0.52, 0.52), (1.0, 1.0, 1.0)], [(0.52, 0.52, 0.52), (1.0, 1.0, 1.0)]] np.asarray([sublist for sublist in X]) </code></pre> <p>Expected result would be:</p> <pre><code>[[ 0.5 , 0.5 , 0.5 ], [ 1. , 1. , 1. ]], [[ 0.5 , 0.5 , 0.52], [ 1. , 1. , 1. ]], [[ 0.5 , 0.52, 0.52], [ 1. , 1. , 1. ]], [[ 0.52, 0.52, 0.52], [ 1. , 1. , 1. ]], [[ 0.52, 0.52, 0.52], [ 1. , 1. , 1. ]] </code></pre>
0
2016-10-01T11:47:28Z
39,806,711
<p>Dont know if you are working on python 2.x or 3.x but in 3.x you could try:</p> <pre><code>&gt;&gt; import numpy as np &gt;&gt; X = [(....)] # Your list &gt;&gt; array = np.array([*X]) &gt;&gt; print(array) array([[[ 0.5 , 0.5 , 0.5 ], [ 1. , 1. , 1. ]], [[ 0.5 , 0.5 , 0.52], [ 1. , 1. , 1. ]], [[ 0.5 , 0.52, 0.52], [ 1. , 1. , 1. ]], [[ 0.52, 0.52, 0.52], [ 1. , 1. , 1. ]], [[ 0.52, 0.52, 0.52], [ 1. , 1. , 1. ]]]) </code></pre> <p>Dont know if this is what you want to achieve.</p>
0
2016-10-01T12:41:30Z
[ "python", "numpy" ]
Convert List of List of Tuples Into 2d Numpy Array
39,806,259
<p>I have a list of list of tuples:</p> <pre><code>X = [[(0.5, 0.5, 0.5), (1.0, 1.0, 1.0)], [(0.5, 0.5, 0.52), (1.0, 1.0, 1.0)], [(0.5, 0.52, 0.52), (1.0, 1.0, 1.0)], [(0.52, 0.52, 0.52), (1.0, 1.0, 1.0)], [(0.52, 0.52, 0.52), (1.0, 1.0, 1.0)]] </code></pre> <p>and would like to convert it to a 2D numpy array. I tried the following but didn't work. I just want to make sure the new transformed 2D keeps the same shape and structure of X. Please help me , thanks a lot.</p> <pre><code>import numpy as np X = [[(0.5, 0.5, 0.5), (1.0, 1.0, 1.0)], [(0.5, 0.5, 0.52), (1.0, 1.0, 1.0)], [(0.5, 0.52, 0.52), (1.0, 1.0, 1.0)], [(0.52, 0.52, 0.52), (1.0, 1.0, 1.0)], [(0.52, 0.52, 0.52), (1.0, 1.0, 1.0)]] np.asarray([sublist for sublist in X]) </code></pre> <p>Expected result would be:</p> <pre><code>[[ 0.5 , 0.5 , 0.5 ], [ 1. , 1. , 1. ]], [[ 0.5 , 0.5 , 0.52], [ 1. , 1. , 1. ]], [[ 0.5 , 0.52, 0.52], [ 1. , 1. , 1. ]], [[ 0.52, 0.52, 0.52], [ 1. , 1. , 1. ]], [[ 0.52, 0.52, 0.52], [ 1. , 1. , 1. ]] </code></pre>
0
2016-10-01T11:47:28Z
39,808,449
<p>If I do the normal thing to your list I get a 3d array:</p> <pre><code>In [38]: np.array(X) Out[38]: array([[[ 0.5 , 0.5 , 0.5 ], [ 1. , 1. , 1. ]], [[ 0.5 , 0.5 , 0.52], [ 1. , 1. , 1. ]], [[ 0.5 , 0.52, 0.52], [ 1. , 1. , 1. ]], [[ 0.52, 0.52, 0.52], [ 1. , 1. , 1. ]], [[ 0.52, 0.52, 0.52], [ 1. , 1. , 1. ]]]) In [39]: _.shape Out[39]: (5, 2, 3) </code></pre> <p>The <code>print</code> (str) display looks a lot like your desired result - except for the extra set of [] to enclose the whole thing:</p> <pre><code>In [40]: print(__) [[[ 0.5 0.5 0.5 ] [ 1. 1. 1. ]] [[ 0.5 0.5 0.52] [ 1. 1. 1. ]] [[ 0.5 0.52 0.52] [ 1. 1. 1. ]] [[ 0.52 0.52 0.52] [ 1. 1. 1. ]] [[ 0.52 0.52 0.52] [ 1. 1. 1. ]]] </code></pre> <p>I could split it into a list of 5 2d arrays, but the display is rather different:</p> <pre><code>In [43]: np.split(np.array(X),5) Out[43]: [array([[[ 0.5, 0.5, 0.5], [ 1. , 1. , 1. ]]]), array([[[ 0.5 , 0.5 , 0.52], [ 1. , 1. , 1. ]]]), array([[[ 0.5 , 0.52, 0.52], ...] </code></pre> <p>A list comprehension turning each sublist into an array does the same thing, <code>[np.array(x) for x in X]</code></p> <p>I could also reshape the <code>(5,2,3)</code> array into 2d arrays, (10,3) or (5,6) for example, but they won't look like your target. </p> <p>Is the <code>tuple</code> layer important (as opposed to being a list)? I could preserve it (appearance wise) with a structured array: <code>np.array(X, dtype=('f,f,f'))</code>.</p>
0
2016-10-01T15:37:50Z
[ "python", "numpy" ]
convert a fasta file to a tab-delimited file using python script
39,806,301
<p>I am student currently learning how to write scripts in python. I have been giving the following exercise. I have to convert a fasta file in the following format: </p> <pre><code>&gt;header 1 AATCTGTGTGATAT ATATA AT &gt;header 2 AATCCTCT </code></pre> <p>into this: </p> <pre><code>&gt;header 1 AATCTGTGTGATATATATAAT &gt;header 2 AATCCTCT </code></pre> <p>I am having some difficulty getting rid of the white space (using line.strip()?) Any help would be very much appreciated...</p>
0
2016-10-01T11:52:18Z
39,806,591
<p>This creates a new string based on the <code>&gt;</code> character and combines the string until the next <code>&gt;</code>. It then appends to a running list.</p> <pre><code># open file and iterate through the lines, composing each single line as we go out_lines = [] temp_line = '' with open('path/to/file','r') as fp: for line in fp: if line.startswith('&gt;'): out_lines.append(temp_line) temp_line = line.strip() + '\t' else: temp_line += line.strip() with open('path/to/new_file', 'w') as fp_out: fp_out.write('\n'.join(out_lines)) </code></pre>
0
2016-10-01T12:26:26Z
[ "python", "parsing" ]
convert a fasta file to a tab-delimited file using python script
39,806,301
<p>I am student currently learning how to write scripts in python. I have been giving the following exercise. I have to convert a fasta file in the following format: </p> <pre><code>&gt;header 1 AATCTGTGTGATAT ATATA AT &gt;header 2 AATCCTCT </code></pre> <p>into this: </p> <pre><code>&gt;header 1 AATCTGTGTGATATATATAAT &gt;header 2 AATCCTCT </code></pre> <p>I am having some difficulty getting rid of the white space (using line.strip()?) Any help would be very much appreciated...</p>
0
2016-10-01T11:52:18Z
39,807,390
<p>I am trying to understand the script posted above, line by line. I have posted what I think it is doing below: </p> <pre><code># open file and iterate through the lines, composing each single line as we go. out_lines = [] temp_line = '' with open('sequences.fa','r') as fp: for line in fp: if line.startswith('&gt;'): out_lines.append(temp_line) # if line starts with '&gt;', add temp_line to end of out_lines temp_line = line.strip() + '\t' # remove white_space from line and make tab_delimited else: temp_line += line.strip() # temp_line = temp_line + line.strip - i.e. go to next line after header (sequences) and remove white space. add to temp_line, appended to out_lines. with open('output.fa', 'w') as fp_out: fp_out.write('\n'.join(out_lines)) # print out_lines, such that out_lines is a single string with space between. </code></pre>
0
2016-10-01T13:47:43Z
[ "python", "parsing" ]
Why does a python program not interrupt with Ctlr+d or Ctrl+c?
39,806,392
<p>This is a client code from my server-client chat program but when i'm trying to close this program with sending a letter <em>q</em>, it simply doesn't work. It stucks in the terminal and waits for something.</p> <p>What did i do wrong here?</p> <pre><code>import socket import threading import time receiving = False lock = threading.Lock() def receive(name, sock): receiving = True while receiving: try: lock.acquire() while True: data, address = sock.recvfrom(1024) print str(data) except: pass finally: lock.release() host = 'localhost' port = 0 server = ('localhost', 7787) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((host, port)) s.setblocking(0) receiveThread = threading.Thread(target=receive, args=("receiveThread", s)) receiveThread.start() username = raw_input("Name: ") message = raw_input(username + "-&gt; ") while True: if message == 'q': receiving = False receiveThread.join() s.close() break if message != '': s.sendto(username + ": " + message, server) lock.acquire() message = raw_input(username + "-&gt; ") lock.release() time.sleep(0.2) </code></pre> <p>In case you are interested in seeing the server code, here it is:</p> <pre><code>import socket import threading import time host = 'localhost' port = 7787 running = False MAX_PACKET_SIZE = 1024 clients = [] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((host, port)) s.setblocking(0) running = True print "server started..." while running: try: data, address = s.recvfrom(MAX_PACKET_SIZE) if 'quit' in str(data): running = False print 'server stopped...' if address not in clients: clients.append(address) print time.ctime(time.time()) + str(address) + ": :" + str(data) for client in clients: s.sendto(data, client) except: pass running = False s.close() </code></pre>
0
2016-10-01T12:02:10Z
39,806,416
<p>Because you have a exception block that excepts on everything. In this case it also catches keyboard interrupt and overrides your termination call.</p> <p>You should probably add a separate catch block for the KeyboardInterrupt:</p> <pre><code>except KeyboardInterrupt: raise </code></pre>
3
2016-10-01T12:05:16Z
[ "python" ]
Why does a python program not interrupt with Ctlr+d or Ctrl+c?
39,806,392
<p>This is a client code from my server-client chat program but when i'm trying to close this program with sending a letter <em>q</em>, it simply doesn't work. It stucks in the terminal and waits for something.</p> <p>What did i do wrong here?</p> <pre><code>import socket import threading import time receiving = False lock = threading.Lock() def receive(name, sock): receiving = True while receiving: try: lock.acquire() while True: data, address = sock.recvfrom(1024) print str(data) except: pass finally: lock.release() host = 'localhost' port = 0 server = ('localhost', 7787) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((host, port)) s.setblocking(0) receiveThread = threading.Thread(target=receive, args=("receiveThread", s)) receiveThread.start() username = raw_input("Name: ") message = raw_input(username + "-&gt; ") while True: if message == 'q': receiving = False receiveThread.join() s.close() break if message != '': s.sendto(username + ": " + message, server) lock.acquire() message = raw_input(username + "-&gt; ") lock.release() time.sleep(0.2) </code></pre> <p>In case you are interested in seeing the server code, here it is:</p> <pre><code>import socket import threading import time host = 'localhost' port = 7787 running = False MAX_PACKET_SIZE = 1024 clients = [] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((host, port)) s.setblocking(0) running = True print "server started..." while running: try: data, address = s.recvfrom(MAX_PACKET_SIZE) if 'quit' in str(data): running = False print 'server stopped...' if address not in clients: clients.append(address) print time.ctime(time.time()) + str(address) + ": :" + str(data) for client in clients: s.sendto(data, client) except: pass running = False s.close() </code></pre>
0
2016-10-01T12:02:10Z
39,806,418
<p>Because in python ctrl+C triggers KeyboardInterrupt exception to be thrown. This allows you to gracefully shut down your program. And you catch this exception with </p> <pre><code> except: pass </code></pre>
0
2016-10-01T12:05:28Z
[ "python" ]
Comparing items of case-insensitive list
39,806,410
<p>So I have two lists, with items in varying cases. Some of the items are the same but are lowercase/uppercase. How can I create a loop to run through all the items and do something with each item, that also ignores what case the item may have?</p> <pre><code>fruits = ['Apple','banana','Kiwi','melon'] fruits_add = ['apple','Banana','KIWI','strawberry'] </code></pre> <p>I want to create a loop that goes through each item in <code>fruits_add</code> and adds it to <code>fruits</code>, if the item is not already in <code>fruits</code>. However an item like <code>'apple'</code> and <code>'Apple'</code> need to count as the same item.</p> <p>I understand how to convert individual items to different cases and how to check if one specific item is identical to another (disregarding case). I don't know how to create a loop that just does this for all items.</p> <p>Found answers to similar questions for other languages, but not for Python 3.</p> <p>My attempt:</p> <pre><code>for fruit.lower() in fruits_add: if fruit in fruits: print("already in list") </code></pre> <p>This gives me an error: </p> <pre><code>SyntaxError: can't assign to function call </code></pre> <p>I've also tried converting every item in each list to lowercase before comparing the lists, but that doesn't work either.</p>
2
2016-10-01T12:04:15Z
39,806,435
<p>I wouldn't use the lower() function there. Use lower like this:</p> <pre><code>for fruit in fruits_add: if fruit.lower() in fruits: print("already in list") </code></pre>
-1
2016-10-01T12:07:18Z
[ "python", "list", "python-3.x", "compare", "case-insensitive" ]
Comparing items of case-insensitive list
39,806,410
<p>So I have two lists, with items in varying cases. Some of the items are the same but are lowercase/uppercase. How can I create a loop to run through all the items and do something with each item, that also ignores what case the item may have?</p> <pre><code>fruits = ['Apple','banana','Kiwi','melon'] fruits_add = ['apple','Banana','KIWI','strawberry'] </code></pre> <p>I want to create a loop that goes through each item in <code>fruits_add</code> and adds it to <code>fruits</code>, if the item is not already in <code>fruits</code>. However an item like <code>'apple'</code> and <code>'Apple'</code> need to count as the same item.</p> <p>I understand how to convert individual items to different cases and how to check if one specific item is identical to another (disregarding case). I don't know how to create a loop that just does this for all items.</p> <p>Found answers to similar questions for other languages, but not for Python 3.</p> <p>My attempt:</p> <pre><code>for fruit.lower() in fruits_add: if fruit in fruits: print("already in list") </code></pre> <p>This gives me an error: </p> <pre><code>SyntaxError: can't assign to function call </code></pre> <p>I've also tried converting every item in each list to lowercase before comparing the lists, but that doesn't work either.</p>
2
2016-10-01T12:04:15Z
39,806,444
<p><code>fruit.lower()</code> in the for loop won't work as the error message implies, you can't assign to a function call..</p> <p>What you could do is create an auxiliary structure (<code>set</code> here) that holds the lowercase items of the existing fruits in <code>fruits</code>, and, <code>append</code> to <code>fruits</code> if a <code>fruit.lower()</code> in <code>fruit_add</code> isn't in the <code>t</code> set (containing the lowercase fruits from <code>fruits</code>):</p> <pre><code>t = {i.lower() for i in fruits} for fruit in fruits_add: if fruit.lower() not in t: fruits.append(fruit) </code></pre> <p>With <code>fruits</code> now being:</p> <pre><code>print(fruits) ['Apple', 'banana', 'Kiwi', 'melon', 'strawberry'] </code></pre>
1
2016-10-01T12:08:36Z
[ "python", "list", "python-3.x", "compare", "case-insensitive" ]
Why does this Python Tkinter stopwatch script crash?
39,806,420
<p>I have this script I wrote as a timer, but it crashes whenever I press the start button. (Sorry, I'm very much so of a noob) <a href="http://pastebin.com/BWDaRTYv" rel="nofollow">http://pastebin.com/BWDaRTYv</a> Thanks, Sam</p>
-4
2016-10-01T12:05:37Z
39,835,322
<p>I can't see your code but I am willing to bet that you are using time.sleep to delay your time. DONT. Use the Tkinter .after method to schedule a function to be called periodically to update your timer.</p> <p><a href="http://effbot.org/tkinterbook/widget.htm" rel="nofollow">See here</a> or <a href="http://stackoverflow.com/questions/25753632/tkinter-how-to-use-after-method">here</a></p>
0
2016-10-03T15:36:54Z
[ "python", "button", "timer", "tkinter", "crash" ]
Flask: differences between request.form["xxxxx"], request.form.get("xxxxxx") and request.args.get("xxxxx")?
39,806,433
<p>What are the differences between <code>flask.request.form["xxx"]</code> , <code>flask.request.form.get("xxx")</code> and <code>flask.request.args.get("xxx")</code> ? </p> <p>I have this question because I am using flask-login to handle authentication.<br> In particular in the following code (taken from the flask-login github page), I don't understand why with <code>req.form.get("email")</code>, email is <code>None</code>, while with <code>req.form["email"]</code>, email hasn't a value. Here's the code. </p> <pre><code>@login_manager.request_loader def request_loader(req): email = req.form.get('email') if email not in users: return user = User() user.id = email # DO NOT ever store passwords in plaintext and always compare password # hashes using constant-time comparison! user.is_authenticated = req.form['pw'] == users[email]['pw'] return user </code></pre>
0
2016-10-01T12:06:51Z
39,807,501
<p>The proper use-case get() is to return a default value when the key you are looking for doesn't exist in a dictionary.</p> <p>For example, if you have a dictionary d such that :</p> <pre><code>d = {'foo': 'bar'} </code></pre> <p>Doing the following will return None:</p> <pre><code>d.get('baz', None) </code></pre> <p>While doing the following will throw an exception:</p> <pre><code>d['baz'] </code></pre>
0
2016-10-01T13:59:12Z
[ "python", "flask", "flask-login" ]
How do I return the value from each iteration of a loop to the function it is running within?
39,806,486
<p>I'm making a program that scrapes local bus times from a real time information server and prints them. In order to return all the bus times, it does this:</p> <pre><code>while i &lt; len(info["results"]): print "Route Number:" + " " + info['results'][i]['route'] print "Due in" + " " + info["results"][i]["duetime"] + " " + "minutes." + "\n" i = i + 1 </code></pre> <p>This works fine, and returns all of the results, one by one like so:</p> <p>Route Number: 83 Due in 12 minutes.</p> <p>Route Number: 83 Due in 25 minutes.</p> <p>Route Number: 83A Due in 39 minutes.</p> <p>Route Number: 83 Due in 55 minutes.</p> <p>However, as I'm using this feature within another script, I turned the code to fetch times and return them into a function:</p> <pre><code>def fetchtime(stopnum): data = "?stopid={}".format(stopnum)+"&amp;format=json" content = "https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation" req = urllib2.urlopen(content + data + "?") i = 0 info = json.load(req) if len(info["results"]) == 0: return "Sorry, there's no real time info for this stop!" while i &lt; len(info["results"]): return "Route Number:" + " " + str(info['results'][i]['route']) + "\n" + "Due in" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n" i = i + 1 </code></pre> <p>This works, however it only returns the first bus from the list given by the server, instead of however many buses there may be. How do I get the printed result of the function to return the info supplied in each iteration of the loop?</p>
0
2016-10-01T12:14:06Z
39,806,531
<p>Can you not just make a list and return the list? </p> <pre><code>businfo = list() while i &lt; len(info["results"]): businfo.append("Route Number:" + " " + str(info['results'][i]['route']) + "\n" + "Due in" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n") i = i + 1 return businfo </code></pre> <p>You will have to edit the printing commands that this function returns to. </p>
3
2016-10-01T12:20:43Z
[ "python", "json", "function", "loops" ]
How do I return the value from each iteration of a loop to the function it is running within?
39,806,486
<p>I'm making a program that scrapes local bus times from a real time information server and prints them. In order to return all the bus times, it does this:</p> <pre><code>while i &lt; len(info["results"]): print "Route Number:" + " " + info['results'][i]['route'] print "Due in" + " " + info["results"][i]["duetime"] + " " + "minutes." + "\n" i = i + 1 </code></pre> <p>This works fine, and returns all of the results, one by one like so:</p> <p>Route Number: 83 Due in 12 minutes.</p> <p>Route Number: 83 Due in 25 minutes.</p> <p>Route Number: 83A Due in 39 minutes.</p> <p>Route Number: 83 Due in 55 minutes.</p> <p>However, as I'm using this feature within another script, I turned the code to fetch times and return them into a function:</p> <pre><code>def fetchtime(stopnum): data = "?stopid={}".format(stopnum)+"&amp;format=json" content = "https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation" req = urllib2.urlopen(content + data + "?") i = 0 info = json.load(req) if len(info["results"]) == 0: return "Sorry, there's no real time info for this stop!" while i &lt; len(info["results"]): return "Route Number:" + " " + str(info['results'][i]['route']) + "\n" + "Due in" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n" i = i + 1 </code></pre> <p>This works, however it only returns the first bus from the list given by the server, instead of however many buses there may be. How do I get the printed result of the function to return the info supplied in each iteration of the loop?</p>
0
2016-10-01T12:14:06Z
39,806,577
<p>I would suggest you to use the yield statement instead return in fetchtime function.</p> <p>Something like:</p> <pre><code>def fetchtime(stopnum): data = "?stopid={}".format(stopnum)+"&amp;format=json" content = "https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation" req = urllib2.urlopen(content + data + "?") i = 0 info = json.load(req) if len(info["results"]) == 0: yield "Sorry, there's no real time info for this stop!" while i &lt; len(info["results"]): yield "Route Number:" + " " + str(info['results'][i]['route']) + "\n" + "Due in" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n" i = i + 1 </code></pre> <p>It would allow you to pick one data at a time and proceed.</p> <p>Lets say that info["results"] is a list of length 2, then you could do:</p> <pre><code>&gt;&gt; a = fetchtime(data) &gt;&gt; next(a) Route Number: 83 Due in 25 minutes. &gt;&gt; next(a) Route Number: 42 Due in 33 minutes. &gt;&gt; next(a) StopIteration Error or simple do: &gt;&gt; for each in a: print(each) Route Number: 83 Due in 25 minutes. Route Number: 42 Due in 33 minutes. # In case if there would be no results (list would be empty), iterating # over "a" would result in: &gt;&gt; for each in a: print(each) Sorry, there's no real time info for this stop! </code></pre>
1
2016-10-01T12:24:54Z
[ "python", "json", "function", "loops" ]
How do I draw a table of squares on tkinter canvas based on a table (list of lists)?
39,806,552
<p>it's me again :) I'm carrying on on my game project. I'm stuck (as the beginner I am) on this thing: I have a table (list of 4 lists of 4 elements each. The length is flexible though, this is only a simple example for the question). so here is my code:</p> <pre><code>from tkinter import* l=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] n=len(l) #this is the length of the list l lngt=400/len(l) #this is the dimension of the squares that I want fen=Tk() fen.geometry("600x400") #I would like to create a table of 4 rows on canvas #each row should contain 4 squares can=Canvas(fen,width=450,height=400,bg="lightblue") can.pack(side=LEFT) for i in range(n): can.create_rectangle(n, i*(lngt) ,n+lngt, i*n+(i+1)*lngt, fill="red") f=Frame(fen,width=150,height=400,bg="lightcoral") f.pack(side=LEFT) fen.mainloop() </code></pre> <p>As of now, I only get a column of 4 squares on the left side of the canvas. All my trials have failed to create the 12 other squares.</p> <p>Thank you awesome people!!</p>
0
2016-10-01T12:22:03Z
39,806,855
<p>Here's how to draw a square grid of squares on a Canvas.</p> <pre><code>import tkinter as tk l = [[0,0,0,0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] n = len(l) #this is the length of the list l lngt = 400 // n #this is the dimension of the squares that I want fen = tk.Tk() fen.geometry("600x400") #I would like to create a table of 4 rows on canvas #each row should contain 4 squares can = tk.Canvas(fen, width=450, height=400, bg="lightblue") can.pack(side=tk.LEFT) for i in range(n): y = i * lngt for j in range(n): x = j * lngt can.create_rectangle(x, y, x+lngt, y+lngt, fill="red") f = tk.Frame(fen, width=150, height=400, bg="lightcoral") f.pack(side=tk.LEFT) fen.mainloop() </code></pre>
1
2016-10-01T12:55:30Z
[ "python", "list", "canvas", "tkinter", "tkinter-canvas" ]
how to have "city" fields depending on "country" field in Django models, without creating their tables
39,806,588
<p>I know there are several questions asked like this (such as <a href="http://stackoverflow.com/questions/25706639/django-dependent-select">this one</a>), but non of them could help me with my problem.</p> <p>I wanna have a City and a Country field in my models, which the City choices is depended on Country; BUT I do not want to define City and Country as models classes. here is my code :</p> <pre><code>from django.contrib.auth.models import User from django.db import models from django.forms import ChoiceField from django_countries.fields import CountryField class UserProfile(models.Model): user = models.OneToOneField(User, related_name="UserProfile") name = models.CharField(max_length=30, null=False, blank=False) picture = models.ImageField(upload_to='userProfiles/', null=False, blank=False) date_of_birth = models.DateTimeField(null=False, blank=False) country = CountryField() # city = ?? national_code = models.IntegerField(max_length=10, null=False, blank=False) email = models.EmailField() def __str__(self): return '{}'.format(self.user.username) def __unicode__(self): return self.user.username </code></pre> <p>just like field "country" which is <code>country = CountryField()</code>, I wonder if there is a way that I could do the mission without defining the <code>class Country(models.Model)</code> or <code>class City(models.Model)</code></p>
0
2016-10-01T12:25:55Z
39,807,298
<p>the only way for it would be to define choices in your model: </p> <pre><code>class UserProfile(models.Model): CITIES = ( ('ny', 'New York'), ('sm', 'Santa Monica') # .. etc ) city = models.CharField(max_length=5, choices=CITIES, blank=True) </code></pre> <p><a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.Field.choices" rel="nofollow">more in the docs</a></p>
0
2016-10-01T13:37:10Z
[ "python", "django", "django-countries" ]
how to have "city" fields depending on "country" field in Django models, without creating their tables
39,806,588
<p>I know there are several questions asked like this (such as <a href="http://stackoverflow.com/questions/25706639/django-dependent-select">this one</a>), but non of them could help me with my problem.</p> <p>I wanna have a City and a Country field in my models, which the City choices is depended on Country; BUT I do not want to define City and Country as models classes. here is my code :</p> <pre><code>from django.contrib.auth.models import User from django.db import models from django.forms import ChoiceField from django_countries.fields import CountryField class UserProfile(models.Model): user = models.OneToOneField(User, related_name="UserProfile") name = models.CharField(max_length=30, null=False, blank=False) picture = models.ImageField(upload_to='userProfiles/', null=False, blank=False) date_of_birth = models.DateTimeField(null=False, blank=False) country = CountryField() # city = ?? national_code = models.IntegerField(max_length=10, null=False, blank=False) email = models.EmailField() def __str__(self): return '{}'.format(self.user.username) def __unicode__(self): return self.user.username </code></pre> <p>just like field "country" which is <code>country = CountryField()</code>, I wonder if there is a way that I could do the mission without defining the <code>class Country(models.Model)</code> or <code>class City(models.Model)</code></p>
0
2016-10-01T12:25:55Z
39,807,588
<p>In order to do this you can use <a href="https://github.com/coderholic/django-cities" rel="nofollow">django-cities</a>. </p> <p>However, this will not resolve the issue with the input logic - if you need something like filtering the cities after selecting a country in your forms. You could use <a href="https://github.com/digi604/django-smart-selects" rel="nofollow">django-smart-selects</a> for this but I am not sure how easy it is to implement the complex model structure of django-cities.</p>
0
2016-10-01T14:08:45Z
[ "python", "django", "django-countries" ]
Ignore or sidestep a name error
39,806,706
<p>I feel like I'm turning a molehill into a mountain here but I can't think of or don't know of a better way to do this. </p> <p>In short, <strong>I have</strong> a list of lists that looks like: </p> <p><code>[ [4.54323, 5.4325], [7.235, 3.67543], [9.342543, 1.65323] ]</code></p> <p>And <strong>I need</strong> a list that looks like the following:</p> <p><code>[ {lat: 4.54323, lng: 5.4325}, {lat: 7.235, lng: 3.67543}, {lat: 9.342543, lng: 1.65323} ]</code></p> <p>I've done some things I'm not proud of and have ended up with:</p> <p><code>[ '{lat: 4.54323, lng: 5.4325}', '{lat: 7.235, lng: 3.67543}', '{lat: 9.342543, lng: 1.65323}' ]</code></p> <p>Yup, some string manipulation and now I'm <em>stuck</em> with a list of strings. I then tried to evaluate each element in said list but got a <code>NameError: name 'lat' is not defined.</code> unsurprisingly. </p> <p>So this more of a multi-part question. Is there a way to get what I want without turning elements into strings and replacing characters? Or alternatively, can I evaluate or turn these strings into whatever data type they should be (I think sets). This variable is only going to be sent to a HTML file to replace a variable by using Jinja. So it doesn't really need to be understood by python, (I'm using 2.7.x).</p> <p><strong>EDIT:</strong> This is the method I'm working with, I'm actively trying not to share that much code because of work reasons, sorry. There's also a lot of different attempts been made in the lifetime of the method. So some lines may look weird.</p> <pre><code>evalledCoords = [] def make_points(coords): if(coords): for x in range(0, len(coords)): # remove first element, not needed. coords[x].pop(0) coords[x] = str(coords[x]).replace("[", "{lat: ").replace(",", ", lng:").replace("]", "}") # See outputs print '\n', coords[x] print 'evalled coords', evalledCoords.append(eval(coords[x])) return coords </code></pre>
0
2016-10-01T12:41:04Z
39,806,810
<p>If you want to solve "i have this and i want this" it can simply be done with <a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow"><code>map</code></a></p> <pre><code>&gt;&gt;&gt; a = [ [4.54323, 5.4325], [7.235, 3.67543], [9.342543, 1.65323] ] &gt;&gt;&gt; map(lambda x: {'lat': x[0], 'lng': x[1]}, a) [{'lat': 4.54323, 'lng': 5.4325}, {'lat': 7.235, 'lng': 3.67543}, {'lat': 9.342543, 'lng': 1.65323}] </code></pre> <p><strong>UPDATE</strong></p> <p>To make your function to work</p> <pre><code>def make_points(coords): return map(lambda x: {'lat': x[0], 'lng': x[1]}, coords) </code></pre>
0
2016-10-01T12:51:00Z
[ "python", "string", "list", "set", "jinja2" ]
Ignore or sidestep a name error
39,806,706
<p>I feel like I'm turning a molehill into a mountain here but I can't think of or don't know of a better way to do this. </p> <p>In short, <strong>I have</strong> a list of lists that looks like: </p> <p><code>[ [4.54323, 5.4325], [7.235, 3.67543], [9.342543, 1.65323] ]</code></p> <p>And <strong>I need</strong> a list that looks like the following:</p> <p><code>[ {lat: 4.54323, lng: 5.4325}, {lat: 7.235, lng: 3.67543}, {lat: 9.342543, lng: 1.65323} ]</code></p> <p>I've done some things I'm not proud of and have ended up with:</p> <p><code>[ '{lat: 4.54323, lng: 5.4325}', '{lat: 7.235, lng: 3.67543}', '{lat: 9.342543, lng: 1.65323}' ]</code></p> <p>Yup, some string manipulation and now I'm <em>stuck</em> with a list of strings. I then tried to evaluate each element in said list but got a <code>NameError: name 'lat' is not defined.</code> unsurprisingly. </p> <p>So this more of a multi-part question. Is there a way to get what I want without turning elements into strings and replacing characters? Or alternatively, can I evaluate or turn these strings into whatever data type they should be (I think sets). This variable is only going to be sent to a HTML file to replace a variable by using Jinja. So it doesn't really need to be understood by python, (I'm using 2.7.x).</p> <p><strong>EDIT:</strong> This is the method I'm working with, I'm actively trying not to share that much code because of work reasons, sorry. There's also a lot of different attempts been made in the lifetime of the method. So some lines may look weird.</p> <pre><code>evalledCoords = [] def make_points(coords): if(coords): for x in range(0, len(coords)): # remove first element, not needed. coords[x].pop(0) coords[x] = str(coords[x]).replace("[", "{lat: ").replace(",", ", lng:").replace("]", "}") # See outputs print '\n', coords[x] print 'evalled coords', evalledCoords.append(eval(coords[x])) return coords </code></pre>
0
2016-10-01T12:41:04Z
39,806,815
<p>Based on the provided data structures and what expected output you are looking to achieve, this can be done through a simple loop over your existing data structure and creating a new list of dictionaries:</p> <pre><code>coords = [ [4.54323, 5.4325], [7.235, 3.67543], [9.342543, 1.65323] ] new_list = [] for data in coords: new_list.append({ 'lat': data[0], 'lng': data[1] }) print(new_list) # [{'lng': 5.4325, 'lat': 4.54323}, {'lng': 3.67543, 'lat': 7.235}, {'lng': 1.65323, 'lat': 9.342543}] </code></pre> <p>Or, simply as a list comprehension:</p> <pre><code>new_list = [{'lat': d[0], 'lng': d[1]} for d in coords] print(new_list) # [{'lng': 5.4325, 'lat': 4.54323}, {'lng': 3.67543, 'lat': 7.235}, {'lng': 1.65323, 'lat': 9.342543}] </code></pre>
1
2016-10-01T12:51:14Z
[ "python", "string", "list", "set", "jinja2" ]
Ignore or sidestep a name error
39,806,706
<p>I feel like I'm turning a molehill into a mountain here but I can't think of or don't know of a better way to do this. </p> <p>In short, <strong>I have</strong> a list of lists that looks like: </p> <p><code>[ [4.54323, 5.4325], [7.235, 3.67543], [9.342543, 1.65323] ]</code></p> <p>And <strong>I need</strong> a list that looks like the following:</p> <p><code>[ {lat: 4.54323, lng: 5.4325}, {lat: 7.235, lng: 3.67543}, {lat: 9.342543, lng: 1.65323} ]</code></p> <p>I've done some things I'm not proud of and have ended up with:</p> <p><code>[ '{lat: 4.54323, lng: 5.4325}', '{lat: 7.235, lng: 3.67543}', '{lat: 9.342543, lng: 1.65323}' ]</code></p> <p>Yup, some string manipulation and now I'm <em>stuck</em> with a list of strings. I then tried to evaluate each element in said list but got a <code>NameError: name 'lat' is not defined.</code> unsurprisingly. </p> <p>So this more of a multi-part question. Is there a way to get what I want without turning elements into strings and replacing characters? Or alternatively, can I evaluate or turn these strings into whatever data type they should be (I think sets). This variable is only going to be sent to a HTML file to replace a variable by using Jinja. So it doesn't really need to be understood by python, (I'm using 2.7.x).</p> <p><strong>EDIT:</strong> This is the method I'm working with, I'm actively trying not to share that much code because of work reasons, sorry. There's also a lot of different attempts been made in the lifetime of the method. So some lines may look weird.</p> <pre><code>evalledCoords = [] def make_points(coords): if(coords): for x in range(0, len(coords)): # remove first element, not needed. coords[x].pop(0) coords[x] = str(coords[x]).replace("[", "{lat: ").replace(",", ", lng:").replace("]", "}") # See outputs print '\n', coords[x] print 'evalled coords', evalledCoords.append(eval(coords[x])) return coords </code></pre>
0
2016-10-01T12:41:04Z
39,807,063
<p>As an alternative to using dictionaries, consider using namedtuples to store your position data. They use less RAM, and the components can be accessed either by index or as attributes. Since namedtuples are a type of tuple they are immutable, but it generally make sense for (latitude, longitude) info of a place to be stored in an immutable data structure. :) </p> <p>Here's a short demo.</p> <pre><code>from collections import namedtuple Pos = namedtuple('Pos', ('lat', 'lng')) a = Pos(30, 150) print(a) print(a[0], a.lng) coords = [ [4.54323, 5.4325], [7.235, 3.67543], [9.342543, 1.65323], ] locations = [Pos(*u) for u in coords] print(locations) </code></pre> <p><strong>output</strong></p> <pre><code>Pos(lat=30, lng=150) 30 150 [Pos(lat=4.54323, lng=5.4325), Pos(lat=7.235, lng=3.67543), Pos(lat=9.342543, lng=1.65323)] </code></pre>
1
2016-10-01T13:14:03Z
[ "python", "string", "list", "set", "jinja2" ]
Using BeautifulSoup with multiple tags with the same name
39,806,817
<p>I have the below html</p> <pre><code>&lt;g class="1581 sqw_sv5" style="cursor: pointer;"&gt; &lt;path d="M397.696,126.554C397.696,126.554,404.57504,140.2417375,404.57504,140.2417375" stroke="#ffffff" style="stroke-width: 3.6; stroke-opacity: 0.5; stroke-linecap: round; fill-opacity: 0;"&gt; &lt;/path&gt; &lt;path d="M397.696,126.554C397.696,126.554,404.57504,140.2417375,404.57504,140.2417375" stroke="#f95a0b" style="stroke-width: 1.2; stroke-linecap: round; fill-opacity: 0;"&gt; &lt;/path&gt; </code></pre> <p>I need to obtain the value of the 'stroke' in the second <em>path</em>. My current code is only pulling the value from the first <em>path</em>.</p> <p>I am currently using</p> <pre><code>shots = soup.find_all('g') for shot in shots: print(shot.path['stroke']) </code></pre> <p>which returns #ffffff. I need it to return #f95a0b</p>
0
2016-10-01T12:51:21Z
39,806,925
<p>You need to use find_all to first find all the <em>path's</em> and then extract the last one:</p> <pre><code>h = """&lt;g class="1581 sqw_sv5" style="cursor: pointer;"&gt; &lt;path d="M397.696,126.554C397.696,126.554,404.57504,140.2417375,404.57504,140.2417375" stroke="#ffffff" style="stroke-width: 3.6; stroke-opacity: 0.5; stroke-linecap: round; fill-opacity: 0;"&gt; &lt;/path&gt; &lt;path d="M397.696,126.554C397.696,126.554,404.57504,140.2417375,404.57504,140.2417375" stroke="#f95a0b" style="stroke-width: 1.2; stroke-linecap: round; fill-opacity: 0;"&gt; &lt;/path&gt;""" soup = BeautifulSoup(h) shots = soup.find_all('g') for shot in shots: print(shot.find_all("path", stroke=True)[-1]["stroke"] </code></pre> <p>Using <code>shot.path['stroke']</code> is equivalent to using <code>shot.find("path")['stroke']</code> which would only return the first path.</p> <p>Or using <em>nth-of-type</em> may also work depending on the structure of the html:</p> <pre><code>soup = BeautifulSoup(h) shots = soup.find_all('g') for shot in shots: print(shot.select_one("path:nth-of-type(2)")["stroke"]) </code></pre>
2
2016-10-01T13:02:09Z
[ "python", "beautifulsoup" ]
Using BeautifulSoup with multiple tags with the same name
39,806,817
<p>I have the below html</p> <pre><code>&lt;g class="1581 sqw_sv5" style="cursor: pointer;"&gt; &lt;path d="M397.696,126.554C397.696,126.554,404.57504,140.2417375,404.57504,140.2417375" stroke="#ffffff" style="stroke-width: 3.6; stroke-opacity: 0.5; stroke-linecap: round; fill-opacity: 0;"&gt; &lt;/path&gt; &lt;path d="M397.696,126.554C397.696,126.554,404.57504,140.2417375,404.57504,140.2417375" stroke="#f95a0b" style="stroke-width: 1.2; stroke-linecap: round; fill-opacity: 0;"&gt; &lt;/path&gt; </code></pre> <p>I need to obtain the value of the 'stroke' in the second <em>path</em>. My current code is only pulling the value from the first <em>path</em>.</p> <p>I am currently using</p> <pre><code>shots = soup.find_all('g') for shot in shots: print(shot.path['stroke']) </code></pre> <p>which returns #ffffff. I need it to return #f95a0b</p>
0
2016-10-01T12:51:21Z
39,807,113
<p>Here's my solution to your question. My issue with my answer is that it may be overly specific. This will only work if the value of <code>style</code> is always <code>"stroke-width: 1.2; stroke-linecap: round; fill-opacity: 0;"</code> and if only one such <code>path</code> element is present in the entire document.</p> <p>The idea behind this solution is to quickly narrow down the elements by looking for what's unique to the desired element containing the desired attribute.</p> <pre><code>` from bs4 import BeautifulSoup html = """"&lt;g class="1581 sqw_sv5" style="cursor: pointer;"&gt; &lt;path d="M397.696,126.554C397.696,126.554,404.57504,140.2417375,404.57504,140.2417375" stroke="#ffffff" style="stroke-width: 3.6; stroke-opacity: 0.5; stroke-linecap: round; fill-opacity: 0;"&gt; &lt;/path&gt; &lt;path d="M397.696,126.554C397.696,126.554,404.57504,140.2417375,404.57504,140.2417375" stroke="#f95a0b" style="stroke-width: 1.2; stroke-linecap: round; fill-opacity: 0;"&gt; &lt;/path&gt;""" soup = BeautifulSoup(html, "html.parser") # get the desired 'path' element using the 'style' that identifies it desired_element = soup.find("path", {"style" : "stroke-width: 1.2; stroke-linecap: round; fill-opacity: 0;"}) # get the attribute value from the extracted element desired_attribute = desired_element["stroke"] print (desired_attribute) # prints #f95a0b ` </code></pre> <p>If this approach is a no go, then you may have to use BeautifulSoups's <code>next_sibling</code> or <code>findNext</code> methods. Basically look for the first path element, which you are currently accomplishing with your code, then 'jump' from there to the next path element, which contains what you need.</p> <p>findNext: <a href="https://stackoverflow.com/questions/5999747/beautifulsoup-nextsibling">Beautifulsoup - nextSibling</a></p> <p>next_sibling: <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#next-sibling-and-previous-sibling" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/bs4/doc/#next-sibling-and-previous-sibling</a></p>
1
2016-10-01T13:20:05Z
[ "python", "beautifulsoup" ]
find all files matching exact name with and without an extension
39,806,895
<p>I'm using glob to scan a specified directory to find all files matching the specified name, but I can't seem to get it to work with files with no extension without finding files matching the name and then some...</p> <p>For example, here's some files:<br> - file<br> - file2<br> - file.dat</p> <p>The resulting list should be:<br> <code>[ 'file', 'file.dat' ]</code></p> <p>How can I get glob to work as expected??</p>
3
2016-10-01T12:59:36Z
39,812,454
<p>Shortly after posting this question, I thought of the answer, but gave up the phone before I could post it...</p> <p>So instead of relying on glob to find the royal all files, have it only look for files with extensions.</p> <p>Here's how to validate if glob is even needed:</p> <pre><code>path = 'subdirectory/filename' # no extension files = [ path ] # for consistancy if not os.path.exists( path ): files = glob('%s.*'%path) if not files: raise IOError("no files found") for f in files: # do whatever </code></pre> <p>This should work with most names, including weirdly formatted names.</p>
0
2016-10-01T23:31:36Z
[ "python", "glob" ]
local and global variable usage in Python
39,806,949
<p>I am testing a reverse function. My code is as follow:</p> <pre><code>def deep_reverse(L): new_list = [] for element in L: new_list += [element[::-1]] L = new_list[::-1] L = [[1, 2], [3, 4], [5, 6, 7]] deep_reverse(L) print(L) </code></pre> <p>I expect my output L can be like [[7, 6, 5], [4, 3], [2, 1]], but it only works inside my function. </p> <p>I wasn't able to change it in the global variable. How can I make it happen? Thank you</p>
-1
2016-10-01T13:04:28Z
39,807,032
<p><code>L</code> is just a local variable, and assigning a new object to it won't change the original list; all it does is point the name <code>L</code> in the function to another object. See <a href="http://nedbatchelder.com/text/names.html" rel="nofollow">Ned Batchelder's excellent explanation about Python names</a>.</p> <p>You could replace all elements <em>in</em> the list <code>L</code> references by assigning to the <code>[:]</code> identity slice instead:</p> <pre><code>L[:] = new_list[::-1] </code></pre> <p>However, mutable sequences like lists have a <a href="https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types" rel="nofollow"><code>list.reverse()</code> method</a>, so you can just reverse the list in-place with that:</p> <pre><code>L.reverse() </code></pre> <p>Do the same for each sublist:</p> <pre><code>def deep_reverse(L): """ assumes L is a list of lists whose elements are ints Mutates L such that it reverses its elements and also reverses the order of the int elements in every element of L. It does not return anything. """ for element in L: element.reverse() L.reverse() </code></pre>
1
2016-10-01T13:11:56Z
[ "python", "list", "global-variables", "reverse", "local-variables" ]
shell script not executing a python file
39,806,957
<p>I am trying to run a script which in turn should execute a basic python script. This is the shell script:</p> <pre><code>#!usr/bin/bash mv ~/Desktop/source/movable.py ~/Desktop/dest cd ~/Desktop/dest pwd ls -lah chmod +x movable.py python movable.py echo "Just ran a python file from a shell script" </code></pre> <p>This is the python script:</p> <pre><code>#!usr/bin/python import os print("movable transfered to dest") os.system("pwd") os.system("mv ~/Desktop/dest/movable.py ~/Desktop/source") print("movable transfered to dest") os.system("cd ~/Desktop/source") os.system("pwd") </code></pre> <p>Q1. The shell script is not executing the python file. What am I doing wrong? Q2. Do I need to write the first line <code>#!usr/bin/python</code> in the python script? Thank you.</p>
0
2016-10-01T13:05:15Z
39,822,085
<p>You are missing a '/' in the shebang line:</p> <pre><code>#!usr/bin/python </code></pre> <p>should be</p> <pre><code>#!/usr/bin/python </code></pre> <p>Another thing I noticed was, you are calling cd in os.system. Since that command would be executed in a sub shell, it won't change the current directory of the calling script process.</p>
0
2016-10-02T21:52:56Z
[ "python", "shell" ]
is comparison returns False with strings using same id
39,807,008
<p>I was playing around with Python <code>is</code> and <code>==</code> operator. As far as I know, is operator checks whether two objects have same id, but in my case operator returns False even if two substrings have the same id. </p> <p>Here is the code:</p> <pre><code>#! /usr/bin/python3 # coding=utf-8 string = "HelloWorld" print(id(string)) #140131089280176 print(id(string[0:5])) #140131089251048 print(id(string[-10:-5])) #140131089251048 print(string[0:5] == string[-10:-5]) #True print(string[0:5] is string[-10:-5]) #False </code></pre> <p>Substrings do not have same id with the original string as expected, but why is operator returns false with 2 substrings with the same id?</p>
3
2016-10-01T13:10:37Z
39,807,198
<p>For me both:</p> <pre><code>print(id(string[0:5])) print(id(string[-10:-5])) </code></pre> <p>have different IDs, and as such, those answers:</p> <pre><code>print(string[0:5] == string[-10:-5]) #True print(string[0:5] is string[-10:-5]) #False </code></pre> <p>Are as they should be expected.</p> <p>Are u sure u didnt make mistake here?</p> <p># I would post that as a comment, but cant yet</p>
0
2016-10-01T13:27:19Z
[ "python", "string", "comparison" ]
How to parallelize 2 loops in python
39,807,026
<p>I need to make each iteration in different thread (for each of these 2 loops). </p> <pre><code>var = 5 a = -7 b = 7 for i in range(var): for j in range(a, b): print(i, " ", j) </code></pre> <p>How can I make it?</p> <p>UPD:</p> <pre><code>var = 5 a = -7 b = 7 max = 0 for i in range(var): for j in range(a, b): print(i, " ", j) if i+j&gt;max: max=i+j print(max) </code></pre>
1
2016-10-01T13:11:43Z
39,807,254
<p>You can not run these two loops in different threads because the second loop have dependency to the data which is produced in first loop.</p> <p>One way is to run each iteration of first loop in a different thread like this:</p> <pre><code>from threading import Thread var = 5 a = -7 b = 7 def inner_loop(i): for j in range(a, b): print(i, " ", j) for i in range(var): Thread(target=inner_loop, args=[i]).start() </code></pre> <p>Another way is producer consumer pattern. First loop generate <code>i</code> value and add it to a queue and second loop read values from queue and generate <code>j</code> and print <code>i</code> and <code>j</code> like this:</p> <pre><code>from threading import Thread var = 5 a = -7 b = 7 queue = [] finished = False def inner_loop(): while not finished or len(queue) &gt; 0: if len(queue) == 0: continue i = queue.pop() for j in range(a, b): print(i, " ", j) def first_loop(): for i in range(var): queue.append(i) finished = True Thread(target=inner_loop).start() Thread(target=first_loop).start() </code></pre>
1
2016-10-01T13:33:15Z
[ "python", "multithreading" ]
How to parallelize 2 loops in python
39,807,026
<p>I need to make each iteration in different thread (for each of these 2 loops). </p> <pre><code>var = 5 a = -7 b = 7 for i in range(var): for j in range(a, b): print(i, " ", j) </code></pre> <p>How can I make it?</p> <p>UPD:</p> <pre><code>var = 5 a = -7 b = 7 max = 0 for i in range(var): for j in range(a, b): print(i, " ", j) if i+j&gt;max: max=i+j print(max) </code></pre>
1
2016-10-01T13:11:43Z
39,807,401
<p>If you want true multi-threading (which the 'threading' library doesn't do!) use the 'multiprocessing' library. The <a href="https://docs.python.org/2/library/multiprocessing.html#introduction" rel="nofollow">introduction section in the docs</a> has a good example.</p>
1
2016-10-01T13:49:10Z
[ "python", "multithreading" ]
Selenium seems not working properly with Firefox 49.0, Is anyone familiar with this?
39,807,042
<p>I have been trying to load my Firefox (Mozilla Firefox 49.0), with simple python script and with the assistance of selenium-2.53.6 on Ubuntu 16.04.1 LTS, but even <a href="https://pypi.python.org/pypi/selenium" rel="nofollow">selenium's basic example 0</a> doesn't work:</p> <blockquote> <p>from selenium import webdriver </p> <p>browser = webdriver.Firefox()</p> <p>browser.get('<a href="http://seleniumhq.org/" rel="nofollow">http://seleniumhq.org/</a>')</p> </blockquote> <p>I always get after about 5 seconds a timeout, and firefox crashes with the following message:</p> <p>"Can't load the profile. Profile Dir: /tmp/tmpl5qlfokc If you specified a log_file in the FirefoxBinary constructor, check it for details"</p> <p>so I created a specific firefox profile (profile -p), and used it, wrote:</p> <blockquote> <p>profile = webdriver.FirefoxProfile('absolute path to profile folder')</p> <p>driver = webdriver.Firefox(profile)</p> </blockquote> <p>but still it seems no matter what I do, the browser crashes after 5 seconds. </p> <p>Read the post <a href="http://stackoverflow.com/questions/6682009/selenium-firefoxprofile-exception-cant-load-the-profile">can't load profile on firefox</a> and followed the instructions but still unfortunately the same result. does anyone know how to overcome this the issue?</p> <p>Thank you all!</p>
0
2016-10-01T13:12:25Z
39,807,144
<p>For firefox 49.0 you need selenium 3(it's in beta stage, that's why you can't download it with <code>pip -U</code>) and geckodriver.</p> <p>try this:</p> <pre><code>wget https://github.com/mozilla/geckodriver/releases/download/v0.10.0/geckodriver-v0.10.0-linux64.tar.gz tar xzvf geckodriver-v0.10.0-linux64.tar.gz cp geckodriver /usr/bin/ pip install selenium==3.0.0b3 </code></pre>
3
2016-10-01T13:21:49Z
[ "python", "selenium", "firefox" ]