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 |
|---|---|---|---|---|---|---|---|---|---|
AttributeError: 'list' object has no attribute 'keys' | 37,961,174 | <p>I try to calculate word frequency and sort the frequency from big to small
but face the above list object has no attribute key problem</p>
<p>I think result is really a dic so how can it has not "key"ï¼
thanks.</p>
<pre><code>#encoding=utf-8
import os
result = {}
if os.path.exists("test.txt"):
day_file = o... | -2 | 2016-06-22T07:23:25Z | 37,961,256 | <p>The built-in function <code>sorted</code> takes an iterable as an argument and returns <strong>a list</strong></p>
<p>You'll need some further conversion to get a dict, which has an attribute <code>keys</code> to avoid that exception</p>
<pre><code>result = sorted(result.items(), key = lambda item: item[1], revers... | 1 | 2016-06-22T07:26:55Z | [
"python",
"nlp",
"text-mining"
] |
Python: Re-bind function as int | 37,961,175 | <p>I have a test class:</p>
<pre><code>class TestClass:
def someFunction(self, someInt):
self.i = someInt
return self.i
</code></pre>
<p>And was testing it with:</p>
<pre><code>x = MyClass()
x.someFunction = 3
print(x.someFunction)
x.someFunction(4)
</code></pre>
<p>However, this leads to <code>... | 1 | 2016-06-22T07:23:32Z | 37,961,490 | <p>Please execute your demo code in a python shell:</p>
<pre><code>>>> class TestClass:
... def someFunction(self, someInt):
... self.i = someInt
... return self.i
...
>>> x = TestClass()
>>> x.someFunction = 3
>>> print(x.someFunction)
3
>>> x.someFunct... | 0 | 2016-06-22T07:37:22Z | [
"python",
"python-3.x"
] |
Python: Re-bind function as int | 37,961,175 | <p>I have a test class:</p>
<pre><code>class TestClass:
def someFunction(self, someInt):
self.i = someInt
return self.i
</code></pre>
<p>And was testing it with:</p>
<pre><code>x = MyClass()
x.someFunction = 3
print(x.someFunction)
x.someFunction(4)
</code></pre>
<p>However, this leads to <code>... | 1 | 2016-06-22T07:23:32Z | 37,961,840 | <p>In python</p>
<ul>
<li>functions are threated as first-class objects</li>
<li>and variables are not typed.</li>
</ul>
<p>Or just "Everything is an object" in python. So there is just no fundamental difference of a variable containing an integer vs a variable containing a function. Both, first-class functions and u... | 0 | 2016-06-22T07:55:08Z | [
"python",
"python-3.x"
] |
Python: Re-bind function as int | 37,961,175 | <p>I have a test class:</p>
<pre><code>class TestClass:
def someFunction(self, someInt):
self.i = someInt
return self.i
</code></pre>
<p>And was testing it with:</p>
<pre><code>x = MyClass()
x.someFunction = 3
print(x.someFunction)
x.someFunction(4)
</code></pre>
<p>However, this leads to <code>... | 1 | 2016-06-22T07:23:32Z | 37,961,864 | <p>The reason you can assign anything to function variables is because they are implemented as objects. This enables you to return functions and pass functions as arguments, unlike in C. </p>
<p>The usefulness of this feature far surpasses the 'accidental errors'.</p>
<p>For example, you can do something like this:<... | 0 | 2016-06-22T07:55:49Z | [
"python",
"python-3.x"
] |
Python: Re-bind function as int | 37,961,175 | <p>I have a test class:</p>
<pre><code>class TestClass:
def someFunction(self, someInt):
self.i = someInt
return self.i
</code></pre>
<p>And was testing it with:</p>
<pre><code>x = MyClass()
x.someFunction = 3
print(x.someFunction)
x.someFunction(4)
</code></pre>
<p>However, this leads to <code>... | 1 | 2016-06-22T07:23:32Z | 37,962,084 | <p>This is allowed because of the way attribute lookup works in Python and this is by design. In Python, many things that are discouraged, forbidden or impossible in other languages, are allowed to leverage your use case (if used wisely). Of course, more power implies more responsibility.</p>
<blockquote>
<p><a href... | 1 | 2016-06-22T08:05:15Z | [
"python",
"python-3.x"
] |
How to chat with multiple clients from a chat server | 37,961,243 | <p>The issues: </p>
<ul>
<li>How to chat with any of user-clients from chat server in os console? </li>
<li>Could anybody help me a job mechanism for multiple clients ? The job mechanism is controlled by os terminal console.</li>
</ul>
<hr>
<h2>Chat with the server</h2>
<p>Start a chat server, and make chat connec... | 0 | 2016-06-22T07:26:32Z | 37,964,454 | <p>This <code>self.set_reuse_addr()</code> is generally a bad idea, but fine for development. Try to properly close your connections instead.</p>
<p>I think the problem is you end up calling <code>handle_read()</code> from ConsoleHandler twice (perhaps put a <code>print("CH read")</code>in there to check the logic of ... | 0 | 2016-06-22T09:51:10Z | [
"python",
"sockets",
"console",
"chat",
"asyncore"
] |
How to loop without getting IndexError on python? | 37,961,494 | <p>I tried to loop for <code>url_data</code>. <code>url_data</code> is an array of strings. I get an <code>IndexError</code> that reads: </p>
<pre><code>keywords[i]=urlparse.urlparse(url_data[i])
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid ... | 1 | 2016-06-22T07:37:31Z | 37,961,855 | <p>try this loop instead</p>
<pre><code>for i in xrange(0,len(url_data)):
keywords[i]=urlparse.urlparse(url_data[i])
</code></pre>
| 1 | 2016-06-22T07:55:38Z | [
"python",
"loops",
"indexing"
] |
How to loop without getting IndexError on python? | 37,961,494 | <p>I tried to loop for <code>url_data</code>. <code>url_data</code> is an array of strings. I get an <code>IndexError</code> that reads: </p>
<pre><code>keywords[i]=urlparse.urlparse(url_data[i])
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid ... | 1 | 2016-06-22T07:37:31Z | 37,961,892 | <p>You're doing it wrong. If you want both the element and index, use <a href="https://docs.python.org/2.3/whatsnew/section-enumerate.html" rel="nofollow"><code>enumerate()</code></a>. </p>
<pre><code>for idx,url in enumerate(url_data):
keywords[idx]=urlparse.urlparse(url_data[idx])
# or it could be
keywo... | 1 | 2016-06-22T07:57:07Z | [
"python",
"loops",
"indexing"
] |
How to loop without getting IndexError on python? | 37,961,494 | <p>I tried to loop for <code>url_data</code>. <code>url_data</code> is an array of strings. I get an <code>IndexError</code> that reads: </p>
<pre><code>keywords[i]=urlparse.urlparse(url_data[i])
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid ... | 1 | 2016-06-22T07:37:31Z | 37,962,816 | <p>From the looks of your code keywords should be either:</p>
<pre><code>keywords = {}
keywords = dict()
</code></pre>
<p><code>print(i)</code> to figure out what you're doing.</p>
| 0 | 2016-06-22T08:41:54Z | [
"python",
"loops",
"indexing"
] |
Losing quality of image while changing from pdf to image using PythonMagick | 37,961,535 | <p>I am working on changing pdfs to images using PythonMagick.
I am successfully changing the formats, but the quality of the image is diminished during this process.</p>
<p>This is the code that i am using.</p>
<pre><code>sample_pdf="test_pdf"
sample_image="test_image"
pdf='/home/path/'+sample_pdf+''
image='/home/p... | 0 | 2016-06-22T07:39:19Z | 37,962,121 | <p>Have you tried the <code>density</code> and <code>quality</code> methods of your instance?</p>
<pre class="lang-py prettyprint-override"><code>sample_pdf="test_pdf"
sample_image="test_image"
pdf='/home/path/{}'.format(sample_pdf)
image='/home/path/images/{}'.format(sample_image)
im = PythonMagick.Image(pdf)
im.de... | 1 | 2016-06-22T08:07:04Z | [
"python",
"image",
"pdf",
"imagemagick",
"pythonmagick"
] |
Losing quality of image while changing from pdf to image using PythonMagick | 37,961,535 | <p>I am working on changing pdfs to images using PythonMagick.
I am successfully changing the formats, but the quality of the image is diminished during this process.</p>
<p>This is the code that i am using.</p>
<pre><code>sample_pdf="test_pdf"
sample_image="test_image"
pdf='/home/path/'+sample_pdf+''
image='/home/p... | 0 | 2016-06-22T07:39:19Z | 37,988,169 | <pre><code>import PythonMagick
sample_pdf="test_pdf"
sample_image="test_image"
pdf='/home/path/'+sample_pdf+''
image='/home/path/images/'+sample_image+''
im = PythonMagick.Image()
im.density("300")
im.read(pdf)
im.quality(100)
im.write(image)
</code></pre>
<p>This worked like a charm for me.
Thanks once again Payet... | 0 | 2016-06-23T09:52:42Z | [
"python",
"image",
"pdf",
"imagemagick",
"pythonmagick"
] |
How can I recognize widgets at callback fucntion in kivy framework? | 37,961,538 | <p>Hi guys I am learning python and kivy at the same time.</p>
<p>I wonder how can i recognize the component using just single function </p>
<p>here is my code</p>
<pre><code>def build(self):
btn1.bind(on_press=self.press_callback)
btn2.bind(on_press=self.press_callback)
def press_callback(self, event):
... | 0 | 2016-06-22T07:39:25Z | 37,962,865 | <p>Well, maybe self.sender?</p>
<pre><code>def press_callback(self, event):
print self.sender
</code></pre>
| -1 | 2016-06-22T08:44:15Z | [
"python"
] |
How can I recognize widgets at callback fucntion in kivy framework? | 37,961,538 | <p>Hi guys I am learning python and kivy at the same time.</p>
<p>I wonder how can i recognize the component using just single function </p>
<p>here is my code</p>
<pre><code>def build(self):
btn1.bind(on_press=self.press_callback)
btn2.bind(on_press=self.press_callback)
def press_callback(self, event):
... | 0 | 2016-06-22T07:39:25Z | 37,963,002 | <p>Here is what happens when a function bound to <code>on_press</code> gets executed. For demonstration, I made a simple function that prints out the arguments that are passed to the function:</p>
<pre><code>from kivy.app import App
from kivy.uix.button import Button
class TestApp(App):
def press(*args):
... | 1 | 2016-06-22T08:50:21Z | [
"python"
] |
Guided filter in OpenCV and Python | 37,961,571 | <p>I wanted to use a guided filter on an image to compare bilateral and guided filters, but my guided filter code shows the error:</p>
<pre><code>AttributeError: 'module' object has no attribute 'GuidedFilter'
</code></pre>
<p>How do I fix this error? My code is as follows:</p>
<pre><code>import cv2
import numpy as ... | 1 | 2016-06-22T07:41:07Z | 37,962,027 | <p>GuidedFilter is not in core, but in the <a href="https://github.com/Itseez/opencv_contrib/tree/master/modules/ximgproc" rel="nofollow" title="ximgproc contrib module">ximgproc contrib module.</a></p>
<p>So you'll have to make sure your OpenCV installation is built with contrib modules enabled in order to use Guided... | 2 | 2016-06-22T08:02:47Z | [
"python",
"opencv"
] |
Python OSError: [Errno 2] No such file err | 37,961,679 | <p>I'm trying to use python webdriver to get html source in linux.</p>
<p>But I got below error:</p>
<pre><code>python daiwa.py 'http://asp.hotel-story.ne.jp/ver3d/planlist.asp?herehcod1=DWHQ0&sAreacode=00151&hidmode=select&mode=seek&hidSELECTARRYMD=2016/06/22&hidSELECTadult=1'Traceback (most rece... | 0 | 2016-06-22T07:46:11Z | 37,962,742 | <p>In your code Change line</p>
<pre><code>xephyr=Display(visible=1, size=(320, 240)).start()
</code></pre>
<p>to</p>
<pre><code>xephyr=Display(visible=0, size=(320, 240)).start() # visible=0
</code></pre>
<p>If backend <strong>Xephyr:</strong>:</p>
<pre><code>display = Display(visible=1, size=(320, 240)).start()... | 0 | 2016-06-22T08:38:26Z | [
"python",
"python-2.7",
"selenium"
] |
making matrix using numpy | 37,961,701 | <p>I want to make a matrix with 5 rows and 4 columns. The problem is when I run it there appears an error that "Traceback (most recent call last):
File "C:\Users\yasini\Desktop\30.py", line 21, in
['ART|Ф',0.71], ['N|Ф',0.29], ['V|Ф',0.0001], ['P|Ф',0]]).reshape(5,4)
ValueError: total size of new array must ... | -2 | 2016-06-22T07:47:29Z | 37,965,727 | <p>Omit the <code>reshape</code> step and print <code>A.shape</code>. How many items are there in <code>A</code>? If there aren't 4*5=20, then reshape to <code>(5,4)</code> will produce this error. When a step gives you an error, make sure the previous one produced what you expected.</p>
<p>My guess is that the sha... | 0 | 2016-06-22T10:45:29Z | [
"python",
"numpy",
"matrix"
] |
Sending iterable object to base template (ex: ' menus = Menu.objects.all() ') | 37,961,901 | <p>When I send </p>
<blockquote>
<p>menus = Menu.objects.all() </p>
</blockquote>
<p>through render </p>
<blockquote>
<p>render(request, 'index.html', {'menus': menus})</p>
</blockquote>
<p>it did not show me anything, just empty page
But other variables like </p>
<blockquote>
<p>info = Info.objects.last()</... | 0 | 2016-06-22T07:57:23Z | 37,961,974 | <p>If you pass:</p>
<pre><code>menus = Menu.objects.all()
</code></pre>
<p>you can use in your template:</p>
<pre><code>{% for menu in menus %}
...
{% if menu.sub_menu.exists %}
{% for submenu in menu.sub_menu.all %}
....
</code></pre>
<p>You did already call <code>.all()</code> in your view.</... | 1 | 2016-06-22T08:00:45Z | [
"python",
"django",
"html5"
] |
My selenium python code unable to locate links in the webpage | 37,962,003 | <p>My <code>selenium</code> python code is unable to locate links in the webpage. </p>
<p>I have two questions related to the following code -</p>
<ol>
<li><p>I cannot even login to the webpage if I do not mention <code>login:password</code> in the <code>self.base_url</code> (please see admin:admin).</p>
<p>It is to... | 0 | 2016-06-22T08:01:49Z | 37,962,336 | <p>If you say that the web page throws in a <strong>pop up</strong>, and if the <strong>pop up</strong> is <strong>Web Based</strong> then you would most likely need to switch between windows. It is most likely that the focus is not on the the main web page and thats the reason you are unable to find any elements withi... | 0 | 2016-06-22T08:17:45Z | [
"python",
"selenium-webdriver"
] |
not sure which testcases fails my code | 37,962,055 | <p>I have found the following code in CodeWars and have written the description too. It says my code passes 8 testcases and not the 9th one. Can someone give me an idea what is wrong or how should I proceed to this? I had only access to the four testcases I have in answer.
<a href="https://www.codewars.com/kata/555615a... | 0 | 2016-06-22T08:03:54Z | 37,962,591 | <p>The if statement is also wrong. Think about the testcase [25, 50, 100] for the sum += p mistake and the following scenario [25, 50] for the if statement mistake. With the code bellow, both issues should be fixed.</p>
<pre><code>def tickets(people):
register = {'25s': 0, '50s': 0, '100s': 0}
cash_in_register... | 1 | 2016-06-22T08:31:09Z | [
"python",
"testing",
"testcase"
] |
not sure which testcases fails my code | 37,962,055 | <p>I have found the following code in CodeWars and have written the description too. It says my code passes 8 testcases and not the 9th one. Can someone give me an idea what is wrong or how should I proceed to this? I had only access to the four testcases I have in answer.
<a href="https://www.codewars.com/kata/555615a... | 0 | 2016-06-22T08:03:54Z | 37,964,366 | <p>I think the problem is that you don't look at the actual bills you have.</p>
<p>look at the testcase [25, 25, 50, 50, 50]: It should produce a "NO", but if I understand your Code correctly, yours answers "YES".</p>
<p>After the second 50, there is 50$ in your sum, but its one 50$ Bill. So when another customer com... | 0 | 2016-06-22T09:47:41Z | [
"python",
"testing",
"testcase"
] |
Python looping and appending arrays | 37,962,158 | <p>I'm creating an application to test how many 'steps' it takes for a number to reach 1 using the colatz conjecture. Here is the code:</p>
<pre><code>import sys
import csv
def findSteps(mode):
count = 0
while mode != 1:
count = count + 1
if mode%2 == 0:
mode = mode/2
else:... | 0 | 2016-06-22T08:08:42Z | 37,962,299 | <p>Both <code>numbers</code> and <code>counts</code> have a type of <code>list</code>, based on how you defined them in your code. So you can use the method of <code>append</code> to add the data to both of them. Just remember that the indexes are zero-based.
Moreover, I agree with @Evert's comment it looks like a <cod... | 0 | 2016-06-22T08:15:43Z | [
"python",
"arrays",
"dynamic-arrays"
] |
Python looping and appending arrays | 37,962,158 | <p>I'm creating an application to test how many 'steps' it takes for a number to reach 1 using the colatz conjecture. Here is the code:</p>
<pre><code>import sys
import csv
def findSteps(mode):
count = 0
while mode != 1:
count = count + 1
if mode%2 == 0:
mode = mode/2
else:... | 0 | 2016-06-22T08:08:42Z | 37,962,304 | <p>In addition of the <code>list.append()</code> variant, you may also use</p>
<pre><code>numbers = range(1, 100)
counts = [findSteps(n) for n in numbers]
</code></pre>
<p>Or, if you like to keep it functional</p>
<pre><code>numbers = range(1, 100)
counts = map(findSteps, numbers)
</code></pre>
| 2 | 2016-06-22T08:16:00Z | [
"python",
"arrays",
"dynamic-arrays"
] |
What's wrong with my GMRES implementation? | 37,962,271 | <p>I'm trying to implement GMRES in Jupyter Notebook, which is (in case you don't know):</p>
<p><a href="http://i.stack.imgur.com/SNOz4.png" rel="nofollow"><img src="http://i.stack.imgur.com/SNOz4.png" alt="enter image description here"></a></p>
<p>This is my code:</p>
<pre><code>def GMRes(A, b, x0, e, nmax_iter, re... | 1 | 2016-06-22T08:14:31Z | 37,971,370 | <p>I think the algorithm is giving the correct result.</p>
<p>You are trying to solve Ax=b where:</p>
<p><img src="https://chart.googleapis.com/chart?cht=tx&chl=A%20%3D%20%5Cbegin%7Bbmatrix%7D%201%20%26%201%20%5C%5C%20%203%20%26%20-4%20%5Cend%7Bbmatrix%7D%2C%20b%20%3D%20%5Cbegin%7Bbmatrix%7D%203%20%5C%5C%20%202%2... | 4 | 2016-06-22T14:43:02Z | [
"python",
"numpy",
"scipy",
"numerical-methods",
"jupyter-notebook"
] |
ValueError: Extra data: Importing multiple JSON frame from JSON file in python | 37,962,288 | <p>I am trying to import multiple JSON frames stored in JSON file to pyhton.
My code is:</p>
<pre><code>import json
import array
with open("J1.json") as J:
j_Data = json.load(J)
print j_Data
</code></pre>
<p>Error :</p>
<pre><code>Traceback (most recent call last):
File "/home/abhi/Desktop/CSS HTML/Python... | 0 | 2016-06-22T08:15:18Z | 37,963,633 | <p>If you can make array of your JSON frames in JSON file:</p>
<pre><code>[{"yphthd": "123.32"} , {"yphthd": "123.32"}, ... {"yphthd": "123.32"}]
</code></pre>
<p>and then load it:</p>
<pre><code>with open("J1.json") as J:
j_Data = json.load(J)
print j_Data
</code></pre>
| 1 | 2016-06-22T09:17:11Z | [
"python",
"json",
"file"
] |
Form submit using Python lxml | 37,962,290 | <p>I have a login page which is like this</p>
<pre><code><form method="POST" name="DefaultForm" action="SOME_URL" onSubmit="return (isReady(this));" autocomplete="off">
<input name="action" type="hidden" value="SOME_VALUE">
<input name="serverTimeStamp" type="hidden" value="SOME_VALUE">
<input na... | 0 | 2016-06-22T08:15:20Z | 37,966,478 | <p>Why you see none is because the form is the <em>root</em> element:</p>
<pre><code> h = """<form method="POST" name="DefaultForm" action="SOME_URL" onSubmit="return (isReady(this));" autocomplete="off">
<input name="action" type="hidden" value="SOME_VALUE">
<input name="serverTimeStamp" type="hidd... | 0 | 2016-06-22T11:18:13Z | [
"python",
"html",
"xml",
"forms",
"lxml"
] |
Message: The browser appears to have exited before we could connect. | 37,962,685 | <p>first I sorry about path question...</p>
<p>HI</p>
<p>I know that lastest firefox doesn't open in selenium so</p>
<p>I fount <code>marionette</code> but <code>button</code> doesn't working in <code>morionette</code></p>
<p>so I decide to use old version firefox using <code>FirefoxBinary</code></p>
<p>I want sol... | 1 | 2016-06-22T08:35:52Z | 38,472,111 | <p>Try using absolute paths instead, and ensure your path spelling:</p>
<pre><code>binary = FirefoxBinary('~/Documents/firefox/firefox')
</code></pre>
| 1 | 2016-07-20T04:01:54Z | [
"python",
"selenium",
"firefox"
] |
How set values in pandas dataframe based on NaN values of another column? | 37,962,759 | <p>I have dataframe named <code>df</code> with original shape <code>(4361, 15)</code>. Some of <code>agefm</code> column`s values are NaN. Just look: </p>
<pre><code>> df[df.agefm.isnull() == True].agefm.shape
(2282,)
</code></pre>
<p>Then I create new column and set all its values to 0: </p>
<pre><code>df['neve... | 1 | 2016-06-22T08:39:20Z | 37,962,791 | <p>The best is use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>:</p>
<pre><code>df['nevermarr'] = np.where(df.agefm.isnull(), 1, 0)
print (df)
agefm nevermarr
0 NaN 1
1 5.0 0
2 6.0 0
</code></pr... | 2 | 2016-06-22T08:40:52Z | [
"python",
"python-2.7",
"pandas",
null
] |
Flask app get "IOError: [Errno 32] Broken pipe" | 37,962,925 | <p>Now I use flask to develop web app.</p>
<p>But at first it works well,after operating web page for a while,the flask back-end shows error like these:</p>
<pre><code> File "/usr/lib64/python2.6/BaseHTTPServer.py", line 329, in handle
self.handle_one_request()
File "/usr/lib/python2.6/site-packages/werkzeug/... | 6 | 2016-06-22T08:46:48Z | 38,628,780 | <p>The built-in werkzeug server is not capable of handling the remote end closing the connection while the server is still churing its content out.</p>
<p>instead of <code>app.run(debug=True,port=5000)</code></p>
<p>try</p>
<pre><code>from gevent.wsgi import WSGIServer
http_server = WSGIServer(('', 5000), app)
http_... | 7 | 2016-07-28T06:38:31Z | [
"python",
"web",
"flask",
"webserver"
] |
In python, when self can be omitted? | 37,963,018 | <p>Codes below defined <em>Duck</em> class as composited from <em>Bill</em> class and <em>Tail</em> class. My questions is that as for the method <em>about()</em> inside <em>Duck</em> class definition, why can one write <code>bill.description</code> and <code>tail.length</code>? Is <code>self</code> omitted here? If ye... | 0 | 2016-06-22T08:50:50Z | 37,963,098 | <p>You can write that because you have defined a global variable <code>bill</code> and <code>tail</code>, which is being referenced here.</p>
<pre><code>...
def about(self):
print('This duck has a', bill.description, 'bill and a', tail.length, 'tail')
# these ^^^^ ... | 1 | 2016-06-22T08:54:19Z | [
"python",
"class"
] |
In python, when self can be omitted? | 37,963,018 | <p>Codes below defined <em>Duck</em> class as composited from <em>Bill</em> class and <em>Tail</em> class. My questions is that as for the method <em>about()</em> inside <em>Duck</em> class definition, why can one write <code>bill.description</code> and <code>tail.length</code>? Is <code>self</code> omitted here? If ye... | 0 | 2016-06-22T08:50:50Z | 37,963,102 | <p>You should avoid doing that. <code>bill</code> in <code>about()</code> will refer to <code>bill</code> in the outer scope, in this case the global one. So when you change the value of that global variable, the output of <code>about()</code> is also affected:</p>
<pre><code>>>> tail = Tail('long')
>>&... | 1 | 2016-06-22T08:54:36Z | [
"python",
"class"
] |
In python, when self can be omitted? | 37,963,018 | <p>Codes below defined <em>Duck</em> class as composited from <em>Bill</em> class and <em>Tail</em> class. My questions is that as for the method <em>about()</em> inside <em>Duck</em> class definition, why can one write <code>bill.description</code> and <code>tail.length</code>? Is <code>self</code> omitted here? If ye... | 0 | 2016-06-22T08:50:50Z | 37,963,111 | <p>In Python explicit is better than implicit and <code>self</code> cannot ever be omitted when accessing member variables.</p>
<p>In your case you actually use names from global scope. To trigger an error simply assign the created objects to other names:</p>
<pre><code>tail1 = Tail('long')
bill1 = Bill('another')
du... | 4 | 2016-06-22T08:55:13Z | [
"python",
"class"
] |
In python, when self can be omitted? | 37,963,018 | <p>Codes below defined <em>Duck</em> class as composited from <em>Bill</em> class and <em>Tail</em> class. My questions is that as for the method <em>about()</em> inside <em>Duck</em> class definition, why can one write <code>bill.description</code> and <code>tail.length</code>? Is <code>self</code> omitted here? If ye... | 0 | 2016-06-22T08:50:50Z | 37,963,547 | <p>To make a long story short: you <em>MUST</em> use <code>self.</code> whenever you want to access an attribute (data attribute, property or method) of the current instance. </p>
<p>For a somewhat more detailed answer: when using <code>def</code> in a <code>class</code> statement, what you create is not a "method" bu... | 3 | 2016-06-22T09:13:23Z | [
"python",
"class"
] |
How can I convert currency symbol to code? | 37,963,045 | <p>I am trying to convert some price given in pounds and USD into EURO. Is there a Python package which can convert the symbol to code? Which can replace the following function call <code>convert_sym_to_code(currency_symbol)</code>?</p>
<pre><code>from forex_python.converter import CurrencyRates
curconv = CurrencyRate... | -1 | 2016-06-22T08:51:55Z | 37,963,983 | <p>Technically, you just need a mapping from symbol to code, so the "convert_sym_to_code" would be quite trivial - except that quite a few currencies use the same symbol (for example the "$" symbol is used by at least 25 currencies worldwide) so you can't use the symbol as a unique key (unless you're ok to have wrong r... | 1 | 2016-06-22T09:31:52Z | [
"python",
"currency"
] |
How can I convert currency symbol to code? | 37,963,045 | <p>I am trying to convert some price given in pounds and USD into EURO. Is there a Python package which can convert the symbol to code? Which can replace the following function call <code>convert_sym_to_code(currency_symbol)</code>?</p>
<pre><code>from forex_python.converter import CurrencyRates
curconv = CurrencyRate... | -1 | 2016-06-22T08:51:55Z | 37,964,210 | <p>A naive approach would be to just use a dictionary:</p>
<pre><code>CURRENCY_MAPPING = [
'$': 'USD',
'£': 'GBP',
]
def convert_sym_to_code(currency_symbol):
try:
CURRENCY_MAPPING[currency_symbol.strip()]
except KeyError:
raise ValueError('Unknown symbol "%s" % currency_symbol)
</cod... | 3 | 2016-06-22T09:41:14Z | [
"python",
"currency"
] |
Unexpected Indent Error | 37,963,084 | <pre><code>import re
import xlwt
book = xlwt.Workbook()
sheet = book.add_sheet("Run sheet")
ifile = open("invoices.txt",'r')
# Read file object to string
text = ifile.read()
m1 = re.findall(r"From(?s)(.*?)Mobile", text)
m2 = re.findall(r"Mobile :(?s)(.*)Prokure", text)
x=0;
for i in m1:
sheet.write(0,x, i)
... | -1 | 2016-06-22T08:53:48Z | 37,963,532 | <p>It could be the result of mixing tabs and spaces. You should convert indentation to either spaces only or to tabs only. Sublime text can do that for you.</p>
<p>In <strong>Notepad++</strong> : Settings->Preferences->Language Menu/Tab Settings->"Replace by space" </p>
| 0 | 2016-06-22T09:12:53Z | [
"python",
"indentation"
] |
Node.js crypto.pbkdf2Sync password does not match with python script | 37,963,116 | <p>I have a mongodb server that stores password generated by this node.js code:</p>
<pre><code>encryptPassword(password, callback) {
if (!password || !this.salt) {
return null;
}
var defaultIterations = 10000;
var defaultKeyLength = 64;
var salt = new Buffer(this.salt, 'base64');
if (!callbac... | 0 | 2016-06-22T08:55:30Z | 37,963,944 | <p>In your Node code, you have this:</p>
<pre><code>var salt = new Buffer(this.salt, 'base64');
</code></pre>
<p>This assumes that <code>this.salt</code> is a Base64 <em>encoded</em> string containing the salt. It is subsequently decoded into a <code>Buffer</code>. So, <code>salt</code> is a (binary) buffer.</p>
<p>... | 0 | 2016-06-22T09:30:04Z | [
"javascript",
"python",
"node.js",
"django",
"node-crypto"
] |
Python autoformat string containing strings of fixed length | 37,963,142 | <p>Let's say I have an arbitrary number of strings of the same length, e.g.:</p>
<pre><code>'01'
'02'
'03'
</code></pre>
<p>And I need to format them into "one line grid" (separated with spaces) with fixed length. So, I'd like to do something like this:</p>
<pre><code>>>'{some expression, 15, left}'.format(['0... | 0 | 2016-06-22T08:56:29Z | 37,963,443 | <p>This is an apt solution to your problem that uses the inbuilt function <a href="https://docs.python.org/3.1/library/string.html#formatspec" rel="nofollow">format</a>.</p>
<pre><code>list = ['01','02','03']
list1=' '.join(list)
list_right='{:>15}'.format(list1) #right
list_left='{:<15}'.format(list1) #le... | 1 | 2016-06-22T09:09:19Z | [
"python",
"string",
"python-3.x"
] |
Python autoformat string containing strings of fixed length | 37,963,142 | <p>Let's say I have an arbitrary number of strings of the same length, e.g.:</p>
<pre><code>'01'
'02'
'03'
</code></pre>
<p>And I need to format them into "one line grid" (separated with spaces) with fixed length. So, I'd like to do something like this:</p>
<pre><code>>>'{some expression, 15, left}'.format(['0... | 0 | 2016-06-22T08:56:29Z | 37,964,582 | <p>This solution employs a lambda function and is more flexible - </p>
<pre><code>list123 = ['01','02','03']
x=15 #limiting factor for str length
s123 = ' '.join(list123) #list elements become a str seperated by a space
s_space= lambda x:(x-len(s123))*' ' #stor... | 1 | 2016-06-22T09:56:04Z | [
"python",
"string",
"python-3.x"
] |
Linear regression prediction predicting input data (test data), and not test results | 37,963,235 | <p>I'm trying to <em><strong>predict</strong></em> the following:</p>
<ul>
<li><code>list( [</code> <strong><code>close price (current day)</code></strong> - <strong><code>open price (current day)</code></strong> <code>] )</code></li>
</ul>
<p>by using the following as input:</p>
<ul>
<li><code>list( [</code> <stron... | 1 | 2016-06-22T08:59:44Z | 37,966,982 | <blockquote>
<p><sub>With a hope no one would consider this impolite and/or harmfull,</sub><br><br>let me cite a lovely point of view on the underlying assumption from â<a href="http://www.quantumforquants.org/question/can-clique-analysis-tell-us-something-new-about-time-series/" rel="nofollow">Correlation <strong>... | 1 | 2016-06-22T11:40:11Z | [
"python",
"statistics",
"scikit-learn",
"statsmodels",
"algorithmic-trading"
] |
NameError: name 'ptclType' is not defined | 37,963,429 | <p>I am beginer in python.
When I try to run code below, it gives NameError.
The purpose of the code is printing out word in readline.
I searched some forums about this, but I couldn't find proper solution.
It seems that the variable doesn't appeared at outside of if statement.</p>
<pre><code>import sys
f = open("./mu... | 1 | 2016-06-22T09:08:43Z | 37,963,563 | <p><code>ptclType</code> is only defined if your conditional "if" statement is met. Thus, when you try to print it, it's not defined. Try to assign default values first:</p>
<pre><code>import sys
f = open("./multPhiCorr_741_25nsDY_cfi.py",'r')
lines = f.readlines()
ptclType = None
nameParVar = None
formula = None
if l... | 3 | 2016-06-22T09:14:04Z | [
"python"
] |
Django login page with parameters | 37,963,510 | <p>In Django application I am working on right now, user session is marked as multiple after same user login on another device, so after page reloading first user logs out and is redirected to <code>admin/login</code> page. </p>
<p>Need to show first user warning about this on <code>admin/login</code> page. The only t... | 2 | 2016-06-22T09:12:01Z | 37,971,948 | <p>Not sure if I understood correctly. Your question is, how to show a message to the user after they logged out, is that correct? </p>
<p>Django has the <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/messages/" rel="nofollow">messages framework</a> to do just that, showing messages to a user.</p>
<pre><c... | 1 | 2016-06-22T15:08:41Z | [
"python",
"django"
] |
Django login page with parameters | 37,963,510 | <p>In Django application I am working on right now, user session is marked as multiple after same user login on another device, so after page reloading first user logs out and is redirected to <code>admin/login</code> page. </p>
<p>Need to show first user warning about this on <code>admin/login</code> page. The only t... | 2 | 2016-06-22T09:12:01Z | 37,985,035 | <p>Used this custom middleware class to achieve needed behavior:</p>
<pre><code>class LogoutMiddleware(object):
def process_response(self, request, response):
if hasattr(request, 'user'):
if request.user.is_authenticated() and request.session.exists(request.session.session_key):
... | 0 | 2016-06-23T07:35:01Z | [
"python",
"django"
] |
Filtering results on page with Django and Ajax | 37,963,753 | <p>I am working on a Django project where items are displayed on the main page. I am trying to get a filter working on this page so that if I check some checkboxes it will filter the results to display on the items matching these attributes, unfortunately I do not know how to do this. </p>
<p>I think I need to use Aja... | 0 | 2016-06-22T09:21:59Z | 37,964,000 | <p>You are a bit vague in your question, but probably you are looking for something like <a href="https://github.com/carltongibson/django-filter" rel="nofollow">django-filter</a> to automate filtering of lists.</p>
<p>Filters are defined in a similar way as you define Forms or Models, so its easy to learn. Example</p>... | 0 | 2016-06-22T09:32:51Z | [
"javascript",
"python",
"ajax",
"django"
] |
Cannot attach to an existing Selenium session via geckodriver | 37,963,785 | <p>After upgrading to geckodriver I'm unable to reuse my Selenium's sessions. Here's my setup:</p>
<p>I have a <code>start_browser.py</code> script, which launches a Firefox instance and prints a port to connect to, like:</p>
<pre><code>firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionet... | 0 | 2016-06-22T09:23:07Z | 37,964,479 | <p>You can reconnect to a session by using the session id.</p>
<pre><code>firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True
browser = webdriver.Firefox(capabilities=firefox_capabilities)
print browser.service.port
wait_forever()
# get the ID and URL from the browser
url = br... | 0 | 2016-06-22T09:51:55Z | [
"python",
"session",
"selenium",
"firefox",
"geckodriver"
] |
Cannot attach to an existing Selenium session via geckodriver | 37,963,785 | <p>After upgrading to geckodriver I'm unable to reuse my Selenium's sessions. Here's my setup:</p>
<p>I have a <code>start_browser.py</code> script, which launches a Firefox instance and prints a port to connect to, like:</p>
<pre><code>firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionet... | 0 | 2016-06-22T09:23:07Z | 37,968,826 | <p>Alright, so unless anyone comes up with more elegant solution, here's a quick dirty hack:</p>
<pre><code>class SessionRemote(webdriver.Remote):
def start_session(self, desired_capabilities, browser_profile=None):
# Skip the NEW_SESSION command issued by the original driver
# and set only some re... | 0 | 2016-06-22T13:00:17Z | [
"python",
"session",
"selenium",
"firefox",
"geckodriver"
] |
How to receive data from template file using ajax in django? | 37,963,831 | <p>I have some checkbox fields in template file.All the checked values should be sent to views file.I used ajax to prevent page reloading.How to send these data to backend(views.py)?</p>
<p>My template file,</p>
<pre><code><script type="text/javascript">
$(document).ready(function() {
$("#myform").submit(fu... | 0 | 2016-06-22T09:25:20Z | 37,965,190 | <p>Try not to mix things. If you want to submit something by ajax, don't use <code>submit</code> input.</p>
<p>Use:</p>
<pre><code><input id="submit" type="button" value="Go"/>
</code></pre>
<p>instead of:</p>
<pre><code><input type="submit" value="Go"/>
</code></pre>
<p>and then in you JS:
<code>
$("#... | 0 | 2016-06-22T10:23:04Z | [
"python",
"django",
"django-views"
] |
Converting ANSI to UTF-8 with Phyton Script in Notepad++ - unicode name issues | 37,963,836 | <p>I am using this script that was written by <a href="http://stackoverflow.com/users/415555/jun-murakami">Jun Murakami</a> to convert the encode of .srt files (movie subtitles) from ANSI to UTF-8 and it is doing great and works perfect for me but there is problem. I have folders which have Unicode characters in their ... | 1 | 2016-06-22T09:25:31Z | 37,965,529 | <p>You can try this code:</p>
<pre><code>import codecs
import os
import sys
filePathSrc="C:\\222\\3" # Path to the folder with files to convert
for root, dirs, files in os.walk(unicode(filePathSrc)):
for fn in files:
if fn[-4:] == '.srt': # Specify type of the files
filename = unicode(root + ... | 0 | 2016-06-22T10:37:00Z | [
"python",
"unicode",
"utf-8",
"notepad++",
"ansi"
] |
Converting ANSI to UTF-8 with Phyton Script in Notepad++ - unicode name issues | 37,963,836 | <p>I am using this script that was written by <a href="http://stackoverflow.com/users/415555/jun-murakami">Jun Murakami</a> to convert the encode of .srt files (movie subtitles) from ANSI to UTF-8 and it is doing great and works perfect for me but there is problem. I have folders which have Unicode characters in their ... | 1 | 2016-06-22T09:25:31Z | 37,980,494 | <p>If you use a Unicode path in <code>os.walk()</code> it will return Unicode paths and filenames. Notepad isn't required to convert the files. Below is code that will work in Python 2 and Python 3 since it wasn't specified.</p>
<p>Note that strings are Unicode by default in Python 3, but the <code>from __future__</... | 0 | 2016-06-23T00:45:48Z | [
"python",
"unicode",
"utf-8",
"notepad++",
"ansi"
] |
Pandas duplicate indexes to dataframe | 37,963,967 | <p>I have a Series with duplicate indexes that i would like to convert to a multi-column DataFrame.</p>
<pre><code>In [60]: np.random.seed(123456)
In [61]: b=pd.Series(np.random.random(30), index=range(6)*5)
</code></pre>
<pre><code>In [62]: b
Out[62]:
0 0.126970
1 0.966718
2 0.260476
3 0.897237
4 ... | 1 | 2016-06-22T09:31:23Z | 37,964,122 | <p>If values <code>0</code> in index can be edges of groups, you can first create <code>DataFrame</code> from <code>Serie</code>, then <code>groups</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cumsum.html" rel="nofollow"><code>cumsum</code></a> and last <a href="http://pandas.p... | 2 | 2016-06-22T09:37:50Z | [
"python",
"pandas",
"dataframe",
"pivot"
] |
SQLite, BeautifulSoup, Table Parse -> to List -> to Sqlite Problems | 37,964,023 | <p>EDIT!: i will explain what i want to achieve. i got this code that scrap data from main search page. <a href="http://pastebin.com/c6hRN6ac" rel="nofollow">http://pastebin.com/c6hRN6ac</a> . It Searches the main page for divs with data that i want. then i assign them to var name,year,engine,mileage and other. </p>
<... | 0 | 2016-06-22T09:33:55Z | 37,965,951 | <p>If you want all the values separately, pull the values using the divs:</p>
<pre><code>from bs4 import BeautifulSoup
soup = BeautifulSoup(h)
for row in soup.select("table tr th"):
a, b = row.select_one("div.th-key"), row.select_one("div.th-value")
print a.text,b.text
</code></pre>
<p>Which gives you all t... | 0 | 2016-06-22T10:55:00Z | [
"python",
"sqlite",
"beautifulsoup",
"html-table"
] |
Creating numpy linspace out of datetime | 37,964,100 | <p>I'm writing a script that plots some data with dates on the x axis (in matplotlib). I need to create a <code>numpy.linspace</code> out of those dates in order to create a spline afterwards. Is it possible to do that?</p>
<p>What I've tried:</p>
<pre><code>import datetime
import numpy as np
dates = [
datetime... | 4 | 2016-06-22T09:36:57Z | 37,966,189 | <p>As far as I know, np.linspace does not support datetime objects. But perhaps we can make our own function which roughly simulates it:</p>
<pre><code>def date_linspace(start, end, steps):
delta = (end - start) / steps
increments = range(0, steps) * np.array([delta]*steps)
return start + increments
</code></pre... | 3 | 2016-06-22T11:06:06Z | [
"python",
"datetime",
"numpy",
"matplotlib"
] |
Creating numpy linspace out of datetime | 37,964,100 | <p>I'm writing a script that plots some data with dates on the x axis (in matplotlib). I need to create a <code>numpy.linspace</code> out of those dates in order to create a spline afterwards. Is it possible to do that?</p>
<p>What I've tried:</p>
<pre><code>import datetime
import numpy as np
dates = [
datetime... | 4 | 2016-06-22T09:36:57Z | 37,974,165 | <p>The last error is telling us that <code>np.datetime</code> objects cannot multiply. Addition has been defined - you can add <code>n</code> timesteps to a date and get another date. But it doesn't make any sense to multiply a date.</p>
<pre><code>In [1238]: x=np.array([1000],dtype='datetime64[s]')
In [1239]: x
Ou... | 0 | 2016-06-22T16:55:20Z | [
"python",
"datetime",
"numpy",
"matplotlib"
] |
Creating numpy linspace out of datetime | 37,964,100 | <p>I'm writing a script that plots some data with dates on the x axis (in matplotlib). I need to create a <code>numpy.linspace</code> out of those dates in order to create a spline afterwards. Is it possible to do that?</p>
<p>What I've tried:</p>
<pre><code>import datetime
import numpy as np
dates = [
datetime... | 4 | 2016-06-22T09:36:57Z | 37,975,295 | <p>Have you considered using <code>pandas</code>? Using an approach from <a href="http://stackoverflow.com/questions/25796030/how-can-i-use-pandas-date-range-to-obtain-a-time-series-with-n-specified-perio?rq=1">this possible duplicate question</a>, you can make use of <code>np.linspace</code> in the following way</p>
... | 3 | 2016-06-22T18:04:58Z | [
"python",
"datetime",
"numpy",
"matplotlib"
] |
Program adds empty spaces so it won't detect correctly later | 37,964,153 | <p>I'm trying to make a game with Python and Pygame and I can't get game saving to work at all.</p>
<pre><code>f event.type == pygame.KEYDOWN: ##########WRITE################
if event.key == pygame.K_w:
print("Writing File")
with open ("Saves/testListSave.txt","w") as f:
... | 0 | 2016-06-22T09:39:32Z | 37,964,347 | <p>This is probably because data5 is Type string, not an Type int.</p>
<p>Try to cast it to an int using the following:</p>
<pre><code>if int(data5) == 5:
</code></pre>
| 0 | 2016-06-22T09:46:48Z | [
"python",
"python-3.x",
"pygame"
] |
Program adds empty spaces so it won't detect correctly later | 37,964,153 | <p>I'm trying to make a game with Python and Pygame and I can't get game saving to work at all.</p>
<pre><code>f event.type == pygame.KEYDOWN: ##########WRITE################
if event.key == pygame.K_w:
print("Writing File")
with open ("Saves/testListSave.txt","w") as f:
... | 0 | 2016-06-22T09:39:32Z | 37,969,691 | <p><code>data5 = f.readline()</code> brings back <code>5\n</code> and not <code>5</code></p>
<p>If you do <code>data5 = f.readline().replace('\n','')</code> your code will work (well, you do need to check for a string <code>'5'</code>) </p>
<p>Alternatively change the if statement to: <code>if data5.replace('\n','') ... | 0 | 2016-06-22T13:33:35Z | [
"python",
"python-3.x",
"pygame"
] |
What does the SciKit FastICA return and what is the difference between FastICA and fastica (both return different values)? | 37,964,170 | <p>I'm trying to use the scikit learn module for Machine Learning exercises at school. The exercise I'm trying to reconstruct is already given as an example on the sklearn ICA documentation, The Blind Source Separation Using ICA [<a href="http://scikit-learn.org/stable/auto_examples/decomposition/plot_ica_blind_source_... | 0 | 2016-06-22T09:40:08Z | 37,967,177 | <blockquote>
<p>What exactly is does the FastICA return? For the following piece of code:
[...] What is 'ica' in this case?</p>
</blockquote>
<p>FastICA is a class, thus call to it returns an OOP wrapper over .fastica function. In other words, you get a reference to an instance of FastICA class, which stores your... | 0 | 2016-06-22T11:48:22Z | [
"python",
"machine-learning",
"scikit-learn"
] |
My python script works in IDLE but not in console | 37,964,222 | <p>The following code executes properly in IDLE but return an error in console.</p>
<pre><code>import sys, math, string, time, os
from time import *
restart0 = True
while restart0:
def addDecimal():
print(".", end="\r")
breakout0 = False
invalidcommand0 = True
while invalidcommand0:
fil... | -2 | 2016-06-22T09:41:41Z | 37,964,445 | <p>It is because of this line</p>
<pre><code>print("\nWelcome to VACSecureServersâ¢\n")
</code></pre>
<p>You have a <code>â¢</code> symbol in it. Your console probably can't display it, but IDLE supports unicode characters. Remove it and your code should work just fine.</p>
| 0 | 2016-06-22T09:50:44Z | [
"python",
"python-3.x"
] |
Using django filter and tags with angular expressions | 37,964,292 | <pre><code><img style="width: 40px; height: 39px" class="img-responsive" src="/static{{user.avatar|cut:"abc/static" }}" alt="{{ user.first_name }}">
</code></pre>
<p>The requirement of "cut" filter in the code above is because I get "abc/static/abc/uploads/profileimages/images_3.jpg" in user avatar(from django v... | 1 | 2016-06-22T09:44:37Z | 37,965,204 | <blockquote>
<p>[...] but here I receive data from angular and cannot combine django "cut" with it</p>
<p>Is it possible to use such django filters or tag in combination of angular?</p>
</blockquote>
<p>If you're thinking of passing a value from AngularJS to a Django filter that's not going to be possible, Djan... | 1 | 2016-06-22T10:23:36Z | [
"javascript",
"python",
"angularjs",
"django",
"django-templates"
] |
Accessing Revit API from outside Revit | 37,964,449 | <p>I've used RevitPythonShell and Dynamo, but would like to use my existing Python IDE (Eclipse) where I have my configuration for logging, debugging, GitHub integration, etc. </p>
<p>I'm comfortable with transactions and the overall API, and I've invested some time in reading about the Revit API and modeless connecti... | 1 | 2016-06-22T09:51:03Z | 37,969,088 | <p>You cannot call the Revit API from another process. The API is designed to be used "in-process", so you have to make a DLL which will be loaded by Revit into its own process.</p>
| 2 | 2016-06-22T13:11:00Z | [
"python",
"revit-api",
"revitpythonshell",
"pyrevit"
] |
Read GPX using lxml and xpath | 37,964,570 | <p>From this <a href="http://stackoverflow.com/questions/18071387/read-gpx-using-python-elementtree-register-namespace">post</a>, I know that I can <code>.find()</code>, <code>.findall()</code> and <code>.text()</code> to get the values nested in the tags.</p>
<p>Take the following .gpx file as example, </p>
<pre><co... | 1 | 2016-06-22T09:55:33Z | 37,965,996 | <p>You are on the right track with:</p>
<pre><code>gpx.xpath("//ele", namespaces = {'ele': "http://www.topografix.com/GPX/1/1"})
</code></pre>
<p>Because there is a default namespace in the XML, the XPath <code>//ele</code> on it's own won't find the <code>ele</code> element in the <code>http://www.topografix.com/GPX... | 1 | 2016-06-22T10:57:32Z | [
"python",
"xml",
"xpath",
"lxml",
"gpx"
] |
Running queries in parallel in sqlalchemy | 37,964,657 | <p>I have a table (say table_A) in a db A, there are two other tables in db's B and C. I am running query like :</p>
<pre><code>session.query(Table_A).filter(Table_A.date >= time1, InventoryLog.audit_date < time2)
</code></pre>
<p>I am running it in a loop, adding the rows in table_B and updating time1,time2 in... | 0 | 2016-06-22T09:58:52Z | 37,968,081 | <p>You can use threading for paralel processing. </p>
<pre><code>from threading import Thread
def fn1(arg1):
while True:
session.query(Table_A).filter(Table_A.date >= time1, InventoryLog.audit_date < time2)
# do other stuff
def fn2(arg1):
while True:
session.query(Table_B).filt... | 0 | 2016-06-22T12:30:51Z | [
"python",
"postgresql",
"sqlalchemy"
] |
sph_harm of Scipy.special , 0.16+ broken | 37,964,669 | <p>I've recently updated my scipy version from 0.13 to the newest. </p>
<p>This used to work before: </p>
<pre><code>import numpy as np
from scipy.special import sph_harm
p,t=np.meshgrid(np.linspace(-np.pi/2.,np.pi/2.,300),np.linspace(0,2*np.pi,150))
s=sph_harm(n=4,m=3,theta=t,phi=p)
</code></pre>
<p>Now it just sa... | 0 | 2016-06-22T09:59:22Z | 37,968,782 | <p>Notice that ufuncs generally don't like keyword arguments:</p>
<pre><code>In [15]: import numpy as np
In [16]: np.sin(x=np.pi)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-16-42da70543d76>... | 0 | 2016-06-22T12:58:59Z | [
"python",
"scipy"
] |
New to Python- TypeError: can only concatenate tuple (not "int") to tuple | 37,964,766 | <p>I've looked into tuple through the forums in the site and none of the answers seem to match up with the same issue I am having. I am getting this error and I am not sure why. Any help/explanations would be greatly appreciated! I am guessing my code is unnecessarily complicated?</p>
<pre><code>import time
print "Wel... | -1 | 2016-06-22T10:03:05Z | 37,965,028 | <p>Calling <code>str</code> on string literals isn't necessary. </p>
<p><code>curYear</code> returns a time tuple which cannot be added to an <code>int</code>. You should have this instead:</p>
<pre><code>curYear = time.localtime(time.time()).tm_year
# ^
</code></pre>
<p>The <c... | 0 | 2016-06-22T10:14:47Z | [
"python",
"python-2.7"
] |
New to Python- TypeError: can only concatenate tuple (not "int") to tuple | 37,964,766 | <p>I've looked into tuple through the forums in the site and none of the answers seem to match up with the same issue I am having. I am getting this error and I am not sure why. Any help/explanations would be greatly appreciated! I am guessing my code is unnecessarily complicated?</p>
<pre><code>import time
print "Wel... | -1 | 2016-06-22T10:03:05Z | 37,965,147 | <p>You cast everything into string except the year... when i tried your code, that's the only error i got.</p>
<p>If you write <code>str(curYear + (int(100) - age))</code> instead of <code>(curYear + (int(100) - age))</code> in both assignement it should be ok.</p>
<p>However, i would recommend that you do the calcul... | 0 | 2016-06-22T10:20:46Z | [
"python",
"python-2.7"
] |
MySQLdb is not filling rows in DB with data, but feildes are auto-incremented | 37,964,915 | <p>I am using MySQlDb to connect and populate my DB with a python script.
Data from a BGP stream (dump) is going in to the DB. But when I try to
execute(insert data) with SQL on line 65 in the bottom of the code, the DB is not affected, besides that the row does auto-increment on one of itâs fields. Is this a encod... | 1 | 2016-06-22T10:09:30Z | 37,965,019 | <p>Check validity of last_record_id that might be passed as non-number which mysql will reject, same sa element_time. </p>
| 0 | 2016-06-22T10:14:26Z | [
"python",
"mysql",
"mysql-python"
] |
MySQLdb is not filling rows in DB with data, but feildes are auto-incremented | 37,964,915 | <p>I am using MySQlDb to connect and populate my DB with a python script.
Data from a BGP stream (dump) is going in to the DB. But when I try to
execute(insert data) with SQL on line 65 in the bottom of the code, the DB is not affected, besides that the row does auto-increment on one of itâs fields. Is this a encod... | 1 | 2016-06-22T10:09:30Z | 37,979,152 | <p>I'm not experienced with DBs in python, but could it be that it is necessary to run db.commit() after you run the cursor.execute() function. </p>
| 0 | 2016-06-22T22:15:46Z | [
"python",
"mysql",
"mysql-python"
] |
"Element is not clickable" error in selenium python | 37,965,056 | <p>I have been using the same scripts for over a year, but since yesterday i am getting this error when click on links having images. I am getting the element by xpath and then clicking it.</p>
<pre><code>test_101_HomePage_links (__main__.SprintTests) ... ERROR
========================================================... | 0 | 2016-06-22T10:16:24Z | 37,969,883 | <p>Using XPATHs like this <code>/html/body/div[5]/div[1]/div[3]/ul/li[1]/a/i</code> are problematic for a number of reasons. </p>
<p>First and foremost, they are extremely brittle. All it takes is a minor update to the site, one that might night even be visually perceptible, and the hard coded div indexes break. The s... | 1 | 2016-06-22T13:40:52Z | [
"python",
"selenium"
] |
How to replace elem from one list to elem from other using python | 37,965,118 | <p>I have lists</p>
<pre><code>a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 5, 6, 7]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13]
c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
</code></pre>
<p>I want to replace that with</p>
<pre><code>for (i, j, k) in zip(a, b, c):
if i == j:
i = k
print i
... | -3 | 2016-06-22T10:19:17Z | 37,965,525 | <p>Iterate over your index list and get values from the list you want.
Be more clear next time!</p>
<pre><code>new_list = [c[i-1] for i in a]
</code></pre>
<p>Output:</p>
<pre><code>['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'a', 'b', 'e', 'f', 'g']
</code></pre>
<p>If you have lists, I am not sure what you want... | 1 | 2016-06-22T10:36:44Z | [
"python"
] |
Twisted is blocking | 37,965,125 | <p>I am running into a problem whereby I have setup multiple consumers consuming from different queues using the twisted library. This is all well and working, however it does not seem to continue execution of the main program, rather it just sits and waits and never hits my print statements after I call <code>reactor... | -1 | 2016-06-22T10:19:43Z | 38,152,630 | <p>Nothing will run after <code>reactor.run()</code>, which is an event loop (a while loop in layman's terms). This is way your code is blocking. The idea is to have all your code execute in the event loop. One way you could do it would be to take your code that executes the consumers, put it into a function, remove ... | 0 | 2016-07-01T19:19:51Z | [
"python",
"python-2.7",
"asynchronous",
"rabbitmq",
"twisted"
] |
merging recurrent layers with dense layer in Keras | 37,965,139 | <p>I want to build a neural network where the two first layers are feedforward and the last one is recurrent.
here is my code :</p>
<pre><code> model = Sequential()
model.add(Dense(150, input_dim=23,init='normal',activation='relu'))
model.add(Dense(80,activation='relu',init='normal'))
model.add(SimpleRN... | 0 | 2016-06-22T10:20:26Z | 37,966,693 | <p>In Keras, you cannot put a Reccurrent layer after a Dense layer because the Dense layer gives output as (nb_samples, output_dim). However, a Recurrent layer expects input as (nb_samples, time_steps, input_dim). So, a Dense layer gives a 2-D output, but a Recurrent layer expects a 3-D input. However, you can do the r... | 0 | 2016-06-22T11:27:43Z | [
"python",
"machine-learning",
"tensorflow",
"theano",
"keras"
] |
Python Psycopg2 cursor.execute returning None | 37,965,198 | <p>Hello I'm working on a script in Python that will connect to a db retrieve some information and send emails. I'have a problem with queries done with Psycopg.</p>
<p>I'would like to retrieve all the users where <code>created_at = nb_days</code>. My query work very good in navicat/pgadmin and I'have 53 records with t... | 0 | 2016-06-22T10:23:25Z | 37,966,281 | <p><a href="http://initd.org/psycopg/docs/cursor.html#cursor.execute"><code>cursor.execute</code></a> allways returns <code>None</code>. You need to <a href="http://initd.org/psycopg/docs/cursor.html#fetch"><code>fetch</code></a> the record set:</p>
<pre><code>try:
self.cursor.execute(sql,data)
records = self.... | 5 | 2016-06-22T11:09:30Z | [
"python",
"postgresql",
"psycopg2"
] |
Why gtk.Dialog disappears direktly when entry received no focus | 37,965,242 | <p>I was searching for an solution to hide gtk dialog immediately after get the response. But now I am wondering why it disappears, but only if I don't click into the entry field:</p>
<pre><code>import gtk, time
def get_info():
entry = gtk.Entry()
entry.set_text("Hello")
dialog = gtk.Dialog(title = "Title... | 2 | 2016-06-22T10:25:05Z | 37,968,304 | <p>You don't have a main loop running. This usually means Gtk+ doesn't do anything -- windows wouldn't be shown in the first place -- but <code>dialog.run()</code> is special in that it happens to run its own short-lived mainloop so it looks like things are working. After <code>dialog.run()</code> exits you really don'... | 0 | 2016-06-22T12:39:58Z | [
"python",
"gtk",
"pygtk",
"gtk2"
] |
Spark with Cython | 37,965,248 | <p>I recently wanted to use <code>Cython</code> with Spark, for which I followed <a href="https://www.4info.com/Blog/October-2014/Enhancing-Spark-with-IPython-Notebook-and-Cython" rel="nofollow">the following reference</a>.</p>
<p>I wrote the following programs as mentioned but I am getting a:</p>
<pre><code>TypeErro... | 0 | 2016-06-22T10:25:14Z | 37,976,442 | <p>This is not a <code>Cython</code> nor a <code>PySpark</code> issue, you unfortunately added an extra function call during the definition of <code>spark_cython</code>. Specifically, the function that wraps the call to the <code>cython_function</code> is called with no arguments on return:</p>
<pre><code>return wrapp... | 1 | 2016-06-22T19:12:11Z | [
"python",
"pyspark",
"cython"
] |
Obtain multiple slices efficiently from Objectified XML | 37,965,249 | <p>If I have an XML which I have used lxml to Objectify, how do I get slices of the list efficiently?</p>
<p>My script.</p>
<pre><code># from lxml import etree
from lxml import objectify
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument("path", type=str, nargs="+")
parser.add_argument(... | 1 | 2016-06-22T10:25:17Z | 37,978,908 | <p>You could get multiple attribute in a single expression but you would need to add them in the order they appear if you wanted to know what belongs to which:</p>
<pre><code>.xpath(('//race/nomination/@*[name() = "number" or name() = "saddlecloth" or name() = "horse"]'
</code></pre>
<p>Another option is to pull from... | 1 | 2016-06-22T21:53:05Z | [
"python",
"xml",
"lxml",
"lxml.objectify"
] |
python pandas simple pivot table sum count | 37,965,380 | <p>I'm trying to identify the best way to make a simple pivot on my data:</p>
<pre><code>import pandas
dfn = pandas.DataFrame({
"A" : [ 'aaa', 'bbb', 'aaa', 'bbb' ],
"B" : [ 1, 10, 2, 30 ],
"C" : [ 2, 0, 3, 20 ] })
</code></pre>
<p>The output I would like to have is a data... | 3 | 2016-06-22T10:30:55Z | 37,965,538 | <p>One way to do this is to group by the column you want and then sum as shown below.</p>
<pre><code>r = dfn.groupby('A').sum()
r['counts'] = dfn.A.value_counts() # this could also be written as dfn['A'].value_counts()
</code></pre>
<p>The first line computes the sums and the second line gets the number of times each... | 1 | 2016-06-22T10:37:23Z | [
"python",
"pandas",
"dataframe",
"group-by",
"pivot-table"
] |
python pandas simple pivot table sum count | 37,965,380 | <p>I'm trying to identify the best way to make a simple pivot on my data:</p>
<pre><code>import pandas
dfn = pandas.DataFrame({
"A" : [ 'aaa', 'bbb', 'aaa', 'bbb' ],
"B" : [ 1, 10, 2, 30 ],
"C" : [ 2, 0, 3, 20 ] })
</code></pre>
<p>The output I would like to have is a data... | 3 | 2016-06-22T10:30:55Z | 37,965,583 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow">.agg()</a> function:</p>
<pre><code>In [227]: dfn.groupby('A').agg({'B':sum, 'C':sum, 'A':'count'}).rename(columns={'A':'count'})
Out[227]:
B count C
A
aaa 3 2 5... | 2 | 2016-06-22T10:39:14Z | [
"python",
"pandas",
"dataframe",
"group-by",
"pivot-table"
] |
python pandas simple pivot table sum count | 37,965,380 | <p>I'm trying to identify the best way to make a simple pivot on my data:</p>
<pre><code>import pandas
dfn = pandas.DataFrame({
"A" : [ 'aaa', 'bbb', 'aaa', 'bbb' ],
"B" : [ 1, 10, 2, 30 ],
"C" : [ 2, 0, 3, 20 ] })
</code></pre>
<p>The output I would like to have is a data... | 3 | 2016-06-22T10:30:55Z | 37,965,746 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.aggregate.html" rel="nofollow"><code>aggregate</code></a> with double <code>sum</code> and <code>len</code>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rename.html" rel="no... | 1 | 2016-06-22T10:46:07Z | [
"python",
"pandas",
"dataframe",
"group-by",
"pivot-table"
] |
Expected behaviour for repeated numpy operations | 37,965,407 | <p>I found this answer when looking for a problem on repeated actions on numpy arrays: <a href="http://stackoverflow.com/questions/7433142/increment-numpy-multi-d-array-with-repeated-indices">Increment Numpy multi-d array with repeated indices</a>. My question now is, WHY this behaviour is seen. </p>
<pre><code>impor... | 2 | 2016-06-22T10:32:09Z | 37,966,274 | <p>See the <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">documentation</a> for indexing an array and the difference between basic and advanced indexing. </p>
<p><code>t[[0,0,1],[0,0,1]]</code> falls under the category of advanced indexing and as stated in the doc:</p>
<blockq... | 1 | 2016-06-22T11:09:16Z | [
"python",
"arrays",
"numpy",
"indices",
"in-place"
] |
IOError: [Errno 22] invalid mode ('rb') or filename: '\x89PNG\n' | 37,965,502 | <p>I just started to program (with Python) because I needed to develop a kind of executable that allows me to perform diameter distributions. I managed to get to something that works (code below):</p>
<pre><code># Put here all modules you would need in order to represent your data
import matplotlib.pylab as plt
impo... | 0 | 2016-06-22T10:35:46Z | 37,966,085 | <p>The retrun value of <code>askopenfilename</code> is a string. As you were traversing over a string (Probabily a path like <code>C:\Somepath\someimage.png</code>) you got the following error. </p>
<blockquote>
<p>Errno2: No such file or directory: u'C' </p>
</blockquote>
<p>You need to use the <code>askopenfilena... | -1 | 2016-06-22T11:01:28Z | [
"python",
"image",
"ioerror"
] |
How to pass html attributes to wtf.form_field when using flask-wtf and flask-bootstrap | 37,965,758 | <p>I have some form in template rendered with flask-bootstrap macro:</p>
<pre><code>{% import 'bootstrap/wtf.html' as wtf %}
{{ wtf.form_field(form.name) }}
</code></pre>
<p>but I want to do this also:</p>
<pre><code>{{ form.name(class="form-control", placeholder='Name', maxlength=20, size=20) }}
</code></pre>
<p>H... | 0 | 2016-06-22T10:46:35Z | 37,967,415 | <p>I got it finally
I just can do this:</p>
<pre><code> wtf.form_field(form.name, class="form-control", placeholder='Name', maxlength=5, size=20)
</code></pre>
<p>I read macro definition and found "kwargs" argument
It's not in arguments list but somehow available in scope
Obviously, I need to find out more about macr... | 0 | 2016-06-22T11:59:59Z | [
"python",
"twitter-bootstrap",
"flask",
"wtforms"
] |
how add link to excel file using python | 37,965,920 | <p>I'm generating an csv file that is opened by excel and converted to xlsx manually.
The csv contains some path to .txt files.
Is it possible to build the file path in such way that when the csv is converted to xlsx , they became clickable hyperlinks ?</p>
<p>Thanks.</p>
| 0 | 2016-06-22T10:53:46Z | 37,968,032 | <p>I would be interested to understand your workflow a bit better, but to try and help with your specific request:</p>
<ul>
<li>The HYPERLINK solution proposed in the comments looks like a good one</li>
<li>If you are able to implement that upstream in the csv generation step then great</li>
<li>If not and/or you are ... | 0 | 2016-06-22T12:28:40Z | [
"python",
"excel",
"csv",
"report"
] |
Using the Right (second) CTRL key in Sikuli | 37,966,001 | <p>I am working on automation of a customised mainframe application which uses the Right CTRL and Right ENTER. Is there any way I can implement this using Sikuli?
Also, I can't install any other remapper software like autoHotKey etc.</p>
| 1 | 2016-06-22T10:58:00Z | 38,718,316 | <p>Sikuli has no platform related knowlegde at all. But AutoIt can do this, and you can call AutoIt from Sikuli. No remap just key-press: Send("{RCTRL}"), Send("{RSHIFT}") etcetera.</p>
<p>Reference:<br>
<a href="https://www.autoitscript.com/autoit3/docs/appendix/SendKeys.htm" rel="nofollow">https://www.autoitscript.c... | 1 | 2016-08-02T10:46:21Z | [
"python",
"sikuli",
"sikuli-script"
] |
How to pass const char* from python to c function | 37,966,432 | <p>I am using <code>ctypes</code> in Python to open a file for writing in C++.</p>
<p>My C++ code:</p>
<pre><code>extern "C" {
void openfile(const char *filename) {
cout<<"File to open for writing = " <<filename<<endl;
FILE *fp = fopen(filename,"w");
fprintf(fp,"writing into file");
... | 2 | 2016-06-22T11:15:31Z | 37,969,649 | <p>In python3 (and you are definitely using python3 as on python2 your code would luckily work)
strings are stored as <code>wchar_t[]</code> buffers, so when you pass <code>"myfirstfile.txt"</code>
the C function sees its arg as <code>"m\0y\0..."</code> which is obviously a C string of lenght one.
Here is the problem ... | 3 | 2016-06-22T13:32:04Z | [
"python",
"ctypes",
"python-c-api"
] |
WSO2 API POST Python Web Service - Empty or No Payload to server | 37,966,488 | <p>I am not able to send request payload to my POST service from WSO2.<br>
On rest console, my service is working.<br>
From WSO2 server I am able to do curl to my server with successful response.<br></p>
<p>here is my API configuration
<a href="http://i.stack.imgur.com/PPkLf.png" rel="nofollow"><img src="http://i.stac... | 0 | 2016-06-22T11:18:38Z | 37,981,908 | <p><a href="http://mytecheye.blogspot.com/2013/09/wso2-esb-all-about-wire-logs.html" rel="nofollow">enable wirelogs</a> and check following</p>
<ol>
<li>payload is coming into the API manager (swagger -> AM )</li>
<li>Payload is going out from api manager (AM -> backend)</li>
</ol>
<p>Also check the request headers c... | 0 | 2016-06-23T03:38:06Z | [
"python",
"wso2",
"wso2esb",
"wso2-am"
] |
Python - Validate if a sheet exists in my document xls | 37,966,536 | <p>I am trying to design a small program on my free time which loads an xls file, then select a sheet in the document to be scanned.</p>
<p>Step 1: the user imports an .xls file . After importing the program checks whether the file exists. (That I can do )</p>
<p>Step 2: I ask the user to give the name of the documen... | 0 | 2016-06-22T11:20:44Z | 37,966,737 | <p>The Python library <a href="http://openpyxl.readthedocs.io/en/latest/index.html" rel="nofollow"><code>openpyxl</code></a> is designed for reading and writing Excel <code>xlsx/xlsm/xltx/xltm</code> files. The following snippet code checks if a specific sheet name exists in a given workbook. </p>
<p>PS: For older Mic... | 0 | 2016-06-22T11:29:55Z | [
"python",
"xls"
] |
Python: How can I search a text file for a string input by the user that contains an integer? | 37,966,556 | <p>This is an example of what is on the text file that I am searching:</p>
<pre><code>15 - Project `enter code here`Name
APP_IDENTIFIER=ie.example.example
DISPLAY_NAME=Mobile Banking
BUNDLE_VERSION=1.1.1
HEADER_COLOR=#72453h
ANDROID_VERSION_CODE=3
20 - Project Name
APP_IDENTIFIER=ie.exampleTwo.exampleTwp
DISPLAY_NAM... | 0 | 2016-06-22T11:21:40Z | 37,970,031 | <p>There is no reason to list all individual numbers in a long <code>if..else</code> list. You can use a <a href="https://docs.python.org/2/library/re.html" rel="nofollow">regular expression</a> to check if a line starts with <em>any</em> digit. If it does, check if it matches the number you are looking for, and if it ... | 0 | 2016-06-22T13:47:49Z | [
"python",
"search"
] |
Python: How can I search a text file for a string input by the user that contains an integer? | 37,966,556 | <p>This is an example of what is on the text file that I am searching:</p>
<pre><code>15 - Project `enter code here`Name
APP_IDENTIFIER=ie.example.example
DISPLAY_NAME=Mobile Banking
BUNDLE_VERSION=1.1.1
HEADER_COLOR=#72453h
ANDROID_VERSION_CODE=3
20 - Project Name
APP_IDENTIFIER=ie.exampleTwo.exampleTwp
DISPLAY_NAM... | 0 | 2016-06-22T11:21:40Z | 37,970,064 | <p>Here you go:</p>
<pre><code>while True:
CUID = int(input("\nPlease choose an option:\n"))
if (CUID) == 0:
appid = value.split("APP_IDENTIFIER=")[1] # get the value after "APP_IDENTIFIER="
print appid
output >>> ie.example.example
</code></pre>
<p>You can apply the same code f... | 0 | 2016-06-22T13:49:23Z | [
"python",
"search"
] |
Python: How can I search a text file for a string input by the user that contains an integer? | 37,966,556 | <p>This is an example of what is on the text file that I am searching:</p>
<pre><code>15 - Project `enter code here`Name
APP_IDENTIFIER=ie.example.example
DISPLAY_NAME=Mobile Banking
BUNDLE_VERSION=1.1.1
HEADER_COLOR=#72453h
ANDROID_VERSION_CODE=3
20 - Project Name
APP_IDENTIFIER=ie.exampleTwo.exampleTwp
DISPLAY_NAM... | 0 | 2016-06-22T11:21:40Z | 37,970,806 | <pre><code>projectfile = open("projects", "r")
for line in projectfile:
if CUID in line:
appIdentifier = next(projectfile).split("=")[1]
displayName = next(projectfile).split("=")[1]
bundleVersion = next(projectfile).split("=")[1]
next(projectfile)
... | 0 | 2016-06-22T14:19:04Z | [
"python",
"search"
] |
How to use regex to escape some info in python? | 37,966,663 | <p>I have a text file and I read that using Python. It starts with a web address and provides other info starts with (y) or (n). Between the lines, there might be few blank lines. For example the text file can be like this, </p>
<pre><code>http://usatoday30.usatoday.com/money/industries/energy/2005-12-28-enron-partic... | -1 | 2016-06-22T11:26:31Z | 37,967,285 | <p>As suggested in the comments, you can use <code>startswith</code> to decide if you are going to process the row and use <code>re.sub</code> to remove <code>(y)</code>, leading spaces and line breaks <code>\n</code>, after that it should give you the expected output:</p>
<pre><code>import re
result = []
with open("t... | 1 | 2016-06-22T11:52:51Z | [
"python",
"regex"
] |
How to use regex to escape some info in python? | 37,966,663 | <p>I have a text file and I read that using Python. It starts with a web address and provides other info starts with (y) or (n). Between the lines, there might be few blank lines. For example the text file can be like this, </p>
<pre><code>http://usatoday30.usatoday.com/money/industries/energy/2005-12-28-enron-partic... | -1 | 2016-06-22T11:26:31Z | 37,967,831 | <p>I'd recommend read file line by line and process accordingly. The reason is that if your file is big, really big then it will be much better performance and less memory footprint.</p>
<pre><code>import io
import re
result = []
rx = re.compile(r'(?<=\(y\)).*', re.MULTILINE)
with open('data.txt','r+') as f:
... | 1 | 2016-06-22T12:19:10Z | [
"python",
"regex"
] |
Django admin: image saved but error occured when click | 37,966,813 | <p>I am ashamed to ask a question of that sort but I still can not solve my problem. I normally uploaded image in my media directory and can see image link in my admin but if I click on link I get:</p>
<blockquote>
<p>Page not found (404)
Request Method: GET
Request URL: <a href="http://127.0.0.1:8000/photo/i... | 1 | 2016-06-22T11:33:10Z | 37,967,034 | <p>Change your URL's patterns:</p>
<pre><code>from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code></pre>
<p>for more info <a href="https://docs.djangoproject.... | 0 | 2016-06-22T11:42:24Z | [
"python",
"django",
"url-routing"
] |
Django admin: image saved but error occured when click | 37,966,813 | <p>I am ashamed to ask a question of that sort but I still can not solve my problem. I normally uploaded image in my media directory and can see image link in my admin but if I click on link I get:</p>
<blockquote>
<p>Page not found (404)
Request Method: GET
Request URL: <a href="http://127.0.0.1:8000/photo/i... | 1 | 2016-06-22T11:33:10Z | 37,967,105 | <p>You need add the media <strong>MEDIA_ROOT</strong> and <strong>MEDIA_URL</strong> in your <strong>urlpatterns</strong></p>
<pre><code>urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code></pre>
<p>check following links for more deta... | 2 | 2016-06-22T11:45:30Z | [
"python",
"django",
"url-routing"
] |
Django admin: image saved but error occured when click | 37,966,813 | <p>I am ashamed to ask a question of that sort but I still can not solve my problem. I normally uploaded image in my media directory and can see image link in my admin but if I click on link I get:</p>
<blockquote>
<p>Page not found (404)
Request Method: GET
Request URL: <a href="http://127.0.0.1:8000/photo/i... | 1 | 2016-06-22T11:33:10Z | 37,967,435 | <p>First point: don't put uploaded medias in you <code>static</code> directory - <code>static</code> is for static files that are part of your project (css, js etc) -, you want to use <code>MEDIA_ROOT</code> and <code>MEDIA_URL</code> for this.</p>
<p>wrt/ serving the static and media contents, it depends on the envir... | 0 | 2016-06-22T12:00:55Z | [
"python",
"django",
"url-routing"
] |
Python Requests status_code 401 UNAUTHORIZED | 37,966,831 | <p>I'm trying to web scrape from WITHIN a secure network. Security is already tight and I have a username and password- but if you open the site I'm trying to get on with my program, you wouldn't be prompted to login (because you're inside the network). I'm having trouble with the authentication here...</p>
<pre><code... | 0 | 2016-06-22T11:34:32Z | 37,971,868 | <p>It's extremely unlikely we can give you the exact solution to your problem, but I would guess the intranet uses some sort of corporate proxy. I would think your requests need to be directed to the proxy and not as if it's hitting an external public site. </p>
<p>For more information on this check out the official ... | 0 | 2016-06-22T15:04:32Z | [
"python",
"authentication",
"python-requests"
] |
`requirements.txt` dependencies, getting only high level dependencies | 37,966,873 | <p>I have a three python projects A, B and C. Each depending on each other.</p>
<blockquote>
<p>How can I now "clean up" my requirements.txt that only the high level
dependencies that are required at this "level" are there.</p>
</blockquote>
<h1>Example</h1>
<h2><strong>A</strong> requirements:</h2>
<p>boto3==1... | 0 | 2016-06-22T11:36:34Z | 37,967,294 | <p><a href="https://github.com/naiquevin/pipdeptree" rel="nofollow"><code>pipdeptree</code></a> can display the dependencies tree, and for a given package tell you which other package(s) depends on it. </p>
| 3 | 2016-06-22T11:53:24Z | [
"python",
"pip",
"requirements.txt"
] |
How to evaluate if an extracted link is a subpath | 37,966,878 | <p>I'm using scrapy to crawl some pages. I am using python 2.7.
The spider returns the response object, and I am inspecting URLs found on the page. I want to restrict the spider to only follow URLS that are subpaths of a location I specify.</p>
<p>For instance, I would like to specify that the spider should only foll... | 0 | 2016-06-22T11:36:36Z | 37,973,289 | <p>You could use a <a href="http://doc.scrapy.org/en/latest/topics/link-extractors.html?#module-scrapy.linkextractors" rel="nofollow"><code>LinkExtractor</code></a> for this. The default one normalizes the links.</p>
<p>Then, it's a matter of building <code>Requests</code> out of the links you get from <code>.extract_... | 0 | 2016-06-22T16:11:25Z | [
"python",
"path",
"scrapy",
"web-crawler",
"scrapy-spider"
] |
Finding last item that matches criteria in python? | 37,966,943 | <p><a href="http://stackoverflow.com/a/9868665/433570">http://stackoverflow.com/a/9868665/433570</a> finds the first item.</p>
<p>I can think of doing <code>reverse</code> first before applying the solution above.
But then I would end up with two <code>reverse</code> which might be avoided.</p>
<p>Is there a better ... | 0 | 2016-06-22T11:38:58Z | 37,967,152 | <p>Instead of reversing the list, which may be a lengthy operation (<code>l.reverse()</code>) because it <strong>reverses the whole list</strong>, I'd simply use a <strong>reversed iterator</strong> <code>reversed(l)</code> with whatever matching method you want, since you can stop early at the first match, it may save... | 2 | 2016-06-22T11:47:26Z | [
"python"
] |
Finding last item that matches criteria in python? | 37,966,943 | <p><a href="http://stackoverflow.com/a/9868665/433570">http://stackoverflow.com/a/9868665/433570</a> finds the first item.</p>
<p>I can think of doing <code>reverse</code> first before applying the solution above.
But then I would end up with two <code>reverse</code> which might be avoided.</p>
<p>Is there a better ... | 0 | 2016-06-22T11:38:58Z | 37,967,165 | <pre><code>x = range(11)
y = next((i for i in reversed(x) if i % 2 == 1), None)
</code></pre>
| 0 | 2016-06-22T11:48:03Z | [
"python"
] |
Finding last item that matches criteria in python? | 37,966,943 | <p><a href="http://stackoverflow.com/a/9868665/433570">http://stackoverflow.com/a/9868665/433570</a> finds the first item.</p>
<p>I can think of doing <code>reverse</code> first before applying the solution above.
But then I would end up with two <code>reverse</code> which might be avoided.</p>
<p>Is there a better ... | 0 | 2016-06-22T11:38:58Z | 37,967,754 | <p>The accepted answer in related questions suggested to use an iterator on the list to build a generator containing only matching elements and take first element from that generator: </p>
<pre><code>next(obj for obj in objs if condition)
</code></pre>
<p>You can do the same using range in opposite order:</p>
<pre><... | 0 | 2016-06-22T12:15:46Z | [
"python"
] |
Using a shift() function within an apply function to compare rows in a Pandas Dataframe | 37,967,070 | <p>I would like to use <code>shift()</code> to pull in data from the previous index, provided values in one of the columns, <code>Letter</code>, is the same.</p>
<pre><code>import pandas as pd
df = pd.DataFrame(data=[['A', 'one'],
['A', 'two'],
['B', 'three'],
... | 2 | 2016-06-22T11:43:53Z | 37,967,481 | <p>Use <code>where</code> on your condition where the current row matches previous row using <code>shift</code>:</p>
<pre><code>In [11]:
df = pd.DataFrame(data=[['A', 'one'],
['A', 'two'],
['B', 'three'],
['B', 'four'],
['C... | 3 | 2016-06-22T12:03:07Z | [
"python",
"python-2.7",
"pandas"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.