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 |
---|---|---|---|---|---|---|---|---|---|
The JSON sent by Firebase is invalid | 39,942,360 | <pre><code>{ name: 'anonymous', text: 'Hello' }
{ name: 'anonymous', text: 'How are you' }
{ name: 'anonymous', text: 'I am fine' }
</code></pre>
<p>This code is returned by Firebase and I'm getting the error <code>No JSON object could be decoded</code>. I think this has to do something with the validity of the JSON format.</p>
<p>I'm getting this JSON data using the Firebase Node.JS SDK. Then I'm passing it to Python using Pyshell. When I use the <code>json.loads</code> in python, tt says:</p>
<pre><code>C:\Python27>node firebase2.js
{ name: 'anonymous', text: 'Hello' }
{ name: 'anonymous', text: 'How are you' }
{ name: 'anonymous', text: 'I am fine' }
C:\Python27\firebase2.js:40
if (err) throw err;
^
Error: ValueError: No JSON object could be decoded
at PythonShell.parseError (C:\Python27\node_modules\python-shell\index.js:183:17)
at terminateIfNeeded (C:\Python27\node_modules\python-shell\index.js:98:28)
at ChildProcess.<anonymous> (C:\Python27\node_modules\python-shell\index.js:88:9)
at emitTwo (events.js:87:13)
at ChildProcess.emit (events.js:172:7)
at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
----- Python Traceback -----
File "my_script.py", line 3, in <module>
myjson = json.loads(myinput)
File "C:\Python27\lib\json\__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode
raise ValueError("No JSON object could be decoded")
</code></pre>
| -3 | 2016-10-09T10:09:48Z | 39,944,089 | <p>This is not a valid JSON and I think that your <code>firebase2.js</code> is at fault here.</p>
<p>Instead of this:</p>
<pre><code>{ name: 'anonymous', text: 'Hello' }
{ name: 'anonymous', text: 'How are you' }
{ name: 'anonymous', text: 'I am fine' }
</code></pre>
<p>It should output this:</p>
<pre><code>[
{ "name": "anonymous", "text": "Hello" },
{ "name": "anonymous", "text": "How are you" },
{ "name": "anonymous", "text": "I am fine" }
]
</code></pre>
<p>All strings (including object keys) have to be quoted with double quotes. Arrays have to be included in square brackets and array elements need to be delimited with commas.</p>
<p>Check out your <code>firebase2.js</code> program and see how it generates its output. If it uses anything else than a single:</p>
<pre><code>console.log(JSON.stringify(SOME_VARIABLE));
</code></pre>
<p>Then here's your problem.</p>
<p>In any case, I am more than sure that Firebase is not returning
<code>{a:'b'}{c:'d'}</code> instead of <code>[{"a":"b"},{"c":"d"}]</code> - this is a typical error of beginners who don't know the JSON format, something hard to believe in the case of one of the biggest API providers in the world.</p>
<p>If you want to know what is the real response then use <code>curl</code>:</p>
<pre><code>curl -v https://example.com/some/endpoint -H 'auth header' ...
</code></pre>
<p>and if you see invalid JSON there, then it's time to contact Firebase support.</p>
<p>The JSON format is explained on <a href="http://json.org/" rel="nofollow">http://json.org/</a> - this is the simplest data format in existence.</p>
| 1 | 2016-10-09T13:20:35Z | [
"python",
"json",
"node.js",
"firebase",
"firebase-cloud-messaging"
] |
The JSON sent by Firebase is invalid | 39,942,360 | <pre><code>{ name: 'anonymous', text: 'Hello' }
{ name: 'anonymous', text: 'How are you' }
{ name: 'anonymous', text: 'I am fine' }
</code></pre>
<p>This code is returned by Firebase and I'm getting the error <code>No JSON object could be decoded</code>. I think this has to do something with the validity of the JSON format.</p>
<p>I'm getting this JSON data using the Firebase Node.JS SDK. Then I'm passing it to Python using Pyshell. When I use the <code>json.loads</code> in python, tt says:</p>
<pre><code>C:\Python27>node firebase2.js
{ name: 'anonymous', text: 'Hello' }
{ name: 'anonymous', text: 'How are you' }
{ name: 'anonymous', text: 'I am fine' }
C:\Python27\firebase2.js:40
if (err) throw err;
^
Error: ValueError: No JSON object could be decoded
at PythonShell.parseError (C:\Python27\node_modules\python-shell\index.js:183:17)
at terminateIfNeeded (C:\Python27\node_modules\python-shell\index.js:98:28)
at ChildProcess.<anonymous> (C:\Python27\node_modules\python-shell\index.js:88:9)
at emitTwo (events.js:87:13)
at ChildProcess.emit (events.js:172:7)
at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
----- Python Traceback -----
File "my_script.py", line 3, in <module>
myjson = json.loads(myinput)
File "C:\Python27\lib\json\__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode
raise ValueError("No JSON object could be decoded")
</code></pre>
| -3 | 2016-10-09T10:09:48Z | 39,944,273 | <p>I got my error after some debugging.</p>
<pre><code>ref.on("child_added", function(snapshot, prevChildKey) {
var newPost = snapshot.val();
newPost = JSON.stringify(newPost); //this line corrected my error
});
</code></pre>
<p>The following line removed the error:</p>
<pre><code>newPost = JSON.stringify(newPost);
</code></pre>
<p><br>By the way, thanks everyone for guiding me.</p>
| 0 | 2016-10-09T13:40:30Z | [
"python",
"json",
"node.js",
"firebase",
"firebase-cloud-messaging"
] |
Two separate lists with corresponding numbers. How to detect them remove them from the list? | 39,942,391 | <p>I'm looking to create a program which randomly generates coins on an 8x8 grid. I've got two lists being created (one list for the X co-ordinate and list for the Y co-ordinate). On these lists, the two co-ordinates cannot be the same. It's difficult to explain, so here's what I mean by example:</p>
<pre><code>[1, 7, 4, **6**, 9, 2, 3, **6**, 8, 0] (list for the x co-ordinate)
[9, 3, 3, **1**, 2, 8, 0, **1**, 6, 1] (list for the y co-ordinate)
</code></pre>
<p>So, two lists are created. However <code>(6,1)</code> appears twice. I don't want this. So, how would I allow for this in my code, to ensure that this is ignored and the numbers are regenerated into different co-ordinates? The code I have is below, I don't really know how to implement such a system thing! </p>
<pre><code>def treasurePro():
global coinListX, coinListY
coinListX = []
coinListY = []
for x in range(10):
num = randint(0,8)
coinListX.append(num)
print(coinListX)
for x in range(10):
num = randint(0,8)
if num == 0 and coinListX[x] == 0:
treasurePro() #goes back to the beginning to restart.
else:
coinListY.append(num)
print(coinListY)
</code></pre>
| 0 | 2016-10-09T10:12:52Z | 39,942,447 | <p>Your board is small enough that you can simply generate all possibilities, take a sample, and then transpose into the desired separate lists for X and Y.</p>
<pre><code>possibilities = [(a,b) for a in range(10) for b in range(10)]
places = random.sample(possibilities, 10)
x,y = zip(*places)
</code></pre>
| 1 | 2016-10-09T10:18:50Z | [
"python",
"arrays",
"list",
"python-3.x"
] |
Two separate lists with corresponding numbers. How to detect them remove them from the list? | 39,942,391 | <p>I'm looking to create a program which randomly generates coins on an 8x8 grid. I've got two lists being created (one list for the X co-ordinate and list for the Y co-ordinate). On these lists, the two co-ordinates cannot be the same. It's difficult to explain, so here's what I mean by example:</p>
<pre><code>[1, 7, 4, **6**, 9, 2, 3, **6**, 8, 0] (list for the x co-ordinate)
[9, 3, 3, **1**, 2, 8, 0, **1**, 6, 1] (list for the y co-ordinate)
</code></pre>
<p>So, two lists are created. However <code>(6,1)</code> appears twice. I don't want this. So, how would I allow for this in my code, to ensure that this is ignored and the numbers are regenerated into different co-ordinates? The code I have is below, I don't really know how to implement such a system thing! </p>
<pre><code>def treasurePro():
global coinListX, coinListY
coinListX = []
coinListY = []
for x in range(10):
num = randint(0,8)
coinListX.append(num)
print(coinListX)
for x in range(10):
num = randint(0,8)
if num == 0 and coinListX[x] == 0:
treasurePro() #goes back to the beginning to restart.
else:
coinListY.append(num)
print(coinListY)
</code></pre>
| 0 | 2016-10-09T10:12:52Z | 39,942,462 | <p>You want to generate random coordinates, but you also want to reject any
pair of coordinates that already appears in the list. (Incidentally,
instead of two separate lists of integers, I would suggest using one
list of ordered pairs, i.e., tuples of two integers.)</p>
<p>One way to reject duplicates would be to search the existing list for
the new set. This is O(n) and slower than it needs to be, though it
would certainly work in your use case where n can't exceed 64.</p>
<p>Another way would be to maintain a second data structure where you can
look up each of the 64 cells in O(1) time, such as an 8x8 array of
booleans. Indeed, you could use this one structure by itself; to get a
list of the coordinates used, just traverse it.</p>
| 0 | 2016-10-09T10:20:03Z | [
"python",
"arrays",
"list",
"python-3.x"
] |
Two separate lists with corresponding numbers. How to detect them remove them from the list? | 39,942,391 | <p>I'm looking to create a program which randomly generates coins on an 8x8 grid. I've got two lists being created (one list for the X co-ordinate and list for the Y co-ordinate). On these lists, the two co-ordinates cannot be the same. It's difficult to explain, so here's what I mean by example:</p>
<pre><code>[1, 7, 4, **6**, 9, 2, 3, **6**, 8, 0] (list for the x co-ordinate)
[9, 3, 3, **1**, 2, 8, 0, **1**, 6, 1] (list for the y co-ordinate)
</code></pre>
<p>So, two lists are created. However <code>(6,1)</code> appears twice. I don't want this. So, how would I allow for this in my code, to ensure that this is ignored and the numbers are regenerated into different co-ordinates? The code I have is below, I don't really know how to implement such a system thing! </p>
<pre><code>def treasurePro():
global coinListX, coinListY
coinListX = []
coinListY = []
for x in range(10):
num = randint(0,8)
coinListX.append(num)
print(coinListX)
for x in range(10):
num = randint(0,8)
if num == 0 and coinListX[x] == 0:
treasurePro() #goes back to the beginning to restart.
else:
coinListY.append(num)
print(coinListY)
</code></pre>
| 0 | 2016-10-09T10:12:52Z | 39,942,483 | <p>Don't create two lists with coordinates, at least not initially. That only makes it harder to detect duplicates.</p>
<p>You could either create <em>tuples</em> with coordinates so you can detect duplicates, or even produce a range of integers that represent your coordinates in sequence, then sample from those. The latter is extremely efficient.</p>
<p>To create tuples, essentially you want to create 8 unique such tuples:</p>
<pre><code>def treasurePro():
coords = []
while len(coords) < 8:
coord = randint(0, 8), randint(0, 8)
if coord not in coords:
coords.append(coord)
# now you have 8 unique pairs. split them out
coinListX, coinListY = zip(*coords)
</code></pre>
<p>This isn't all that efficient, as the <code>coord not in coords</code> test has to scan the whole list which is growing with each new coordinate. For a large number of coordinates to pick, this can slow down significantly. You'd have to add an extra <code>seen = set()</code> object that you also add coordinates to and test again in the loop to remedy that. There is a better way however.</p>
<p>Your board is a 9x9 size, so you have 81 unique coordinates. If you used <a href="https://docs.python.org/3/library/random.html#random.sample" rel="nofollow"><code>random.sample()</code></a> on a <a href="https://docs.python.org/3/library/stdtypes.html#ranges" rel="nofollow"><code>range()</code> object</a> (<code>xrange()</code> in Python 2), you could trivially create 8 unique values, then 'extract' a row and column number from those:</p>
<pre><code>def treasurePro():
coords = random.sample(range(9 * 9), 8) # use xrange in Python 2
coinListX = [c // 9 for c in coords]
coinListY = [c % 9 for c in coords]
</code></pre>
<p>Here <code>random.sample()</code> guarantees that you get 8 unique coordinates.</p>
<p>This is also far more efficient than generating all possible tuples up-front; using <code>range()</code> in Python 3 makes the above use O(K) memory, where K is the number of values you need to generate, while creating all coordinates up front would take O(N^2) memory (where N is the size of a board side).</p>
<p>You may want to store a list of <code>(x, y)</code> coordinates still rather than use two separate lists. Create one with <code>coords = [(c // 9, c % 9) for c in coords]</code>.</p>
| 1 | 2016-10-09T10:22:06Z | [
"python",
"arrays",
"list",
"python-3.x"
] |
Two separate lists with corresponding numbers. How to detect them remove them from the list? | 39,942,391 | <p>I'm looking to create a program which randomly generates coins on an 8x8 grid. I've got two lists being created (one list for the X co-ordinate and list for the Y co-ordinate). On these lists, the two co-ordinates cannot be the same. It's difficult to explain, so here's what I mean by example:</p>
<pre><code>[1, 7, 4, **6**, 9, 2, 3, **6**, 8, 0] (list for the x co-ordinate)
[9, 3, 3, **1**, 2, 8, 0, **1**, 6, 1] (list for the y co-ordinate)
</code></pre>
<p>So, two lists are created. However <code>(6,1)</code> appears twice. I don't want this. So, how would I allow for this in my code, to ensure that this is ignored and the numbers are regenerated into different co-ordinates? The code I have is below, I don't really know how to implement such a system thing! </p>
<pre><code>def treasurePro():
global coinListX, coinListY
coinListX = []
coinListY = []
for x in range(10):
num = randint(0,8)
coinListX.append(num)
print(coinListX)
for x in range(10):
num = randint(0,8)
if num == 0 and coinListX[x] == 0:
treasurePro() #goes back to the beginning to restart.
else:
coinListY.append(num)
print(coinListY)
</code></pre>
| 0 | 2016-10-09T10:12:52Z | 39,942,503 | <pre><code>cordX = [x for x in range(10)]
cordY = cordX[:]
random.shuffle(cordX)
random.shuffle(cordY)
</code></pre>
| 0 | 2016-10-09T10:23:47Z | [
"python",
"arrays",
"list",
"python-3.x"
] |
How to prevent python requests from percent encoding URLs contain semicolon? | 39,942,481 | <p>I want to post some data to a url like <code>http://www.google.com/;id=aaa</code><br>
I use follow codes:</p>
<pre><code>url = 'http://www.google.com/;id=aaa'
r = requests.post(url, headers=my_headers, data=my_data, timeout=10)
</code></pre>
<p>Unfortunately, I find <code>requests</code> just cut my uri to <code>http://www.google.com/</code> without any warning... </p>
<p>Is there some way to pass the the parameters in their original form - without percent encoding? </p>
<p>I try <code>config={'encode_uri': False}</code> but it was abandoned, and <code>urllib.unquote</code> wasn't useful as well.</p>
<p>Thanks!</p>
| -1 | 2016-10-09T10:22:02Z | 39,943,455 | <p><a href="https://tools.ietf.org/html/rfc2616#section-3.2.2" rel="nofollow">RFC 2616, section 3.2.2</a> specifies the syntax of an HTTP URL as:</p>
<pre class="lang-none prettyprint-override"><code>http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]]
</code></pre>
<p>It also says:</p>
<blockquote>
<p>If the abs_path is not present in the URL, it MUST be given as "/" when
used as a Request-URI for a resource</p>
</blockquote>
<p>In this URL:</p>
<pre class="lang-none prettyprint-override"><code>http://www.google.com;id=aaa
</code></pre>
<p>there is no <code>/</code>, so there is no <code>abs_path</code> and there is no <code>:</code>, so there is no <code>port</code>. It means that <code>www.google.com;id=aaa</code> is hostname.</p>
<p>Semicolons are not allowed in hostnames (see <a href="http://stackoverflow.com/a/3523068/389289">this answer</a> for what is allowed in hostname), so this <strong>URL is invalid</strong>.</p>
<p>This would be a valid URL, if <code>id=aaa</code> should be part of the path:</p>
<pre class="lang-none prettyprint-override"><code>http://www.google.com/;id=aaa
</code></pre>
<p>This also, if <code>id=aaa</code> should be part of the query:</p>
<pre class="lang-none prettyprint-override"><code>http://www.google.com/?;id=aaa
</code></pre>
<h1>EDIT</h1>
<p>The question has been modified to ask about <code>http://www.google.com/;id=aaa</code> instead.</p>
<p>That URL is valid, and as far as I was able to test it, <a href="/questions/tagged/python-requests" class="post-tag" title="show questions tagged 'python-requests'" rel="tag">python-requests</a> handles it without any problems.</p>
| 0 | 2016-10-09T12:09:21Z | [
"python",
"http",
"python-requests"
] |
Python - Concatenating | 39,942,600 | <p>I'm going crazy with the following code which should be really easy but doesn't work :/</p>
<pre><code>class Triangulo_String:
_string = ''
_iteraciones = 0
_string_a_repetir = ''
def __init__(self, string_a_repetir, iteraciones):
self._string_a_repetir = string_a_repetir
self._iteraciones = iteraciones
def concatenar(self):
for i in range(0, self._iteraciones, 1):
self._string = self._string_a_repetir + self._string + '\n'
</code></pre>
<p>I'm initializing <code>_iteraciones</code> to <code>3</code> and <code>_string_a_repetir</code> to <code>'*'</code></p>
<p>And the output is just: </p>
<pre><code>***
</code></pre>
<p>When I'm expecting:</p>
<pre><code>*
**
***
</code></pre>
<p>I've debugged it and when doing the concatenating it just concatenates the self._string_a_repetir, not the _string nor the line break.</p>
<p>Such an easy thing is driving me crazy ._.</p>
| 0 | 2016-10-09T10:33:59Z | 39,942,667 | <p>The relevant bit is in this part:</p>
<pre><code>for i in range(0, self._iteraciones, 1):
self._string = self._string_a_repetir + self._string + '\n'
</code></pre>
<p>Letâs go through the iterations one by one:</p>
<pre><code># Initially
_string = ''
_string_a_repetir = '*'
_iteraciones = 3
# i = 0
_string = _string_a_repetir + _string + '\n'
= '*' + '' + '\n'
= '*\n'
# i = 1
_string = _string_a_repetir + _string + '\n'
= '*' + '*\n' + '\n'
= '**\n\n'
# i = 2
_string = _string_a_repetir + _string + '\n'
= '*' + '**\n\n' + '\n'
= '***\n\n\n'
</code></pre>
<p>As you can see, this is totally expected to happen, since you never repeat that character more than once per line. And you are also incorrectly concatenating the previous string with the new string (placing it in between the current lineâs text and its line break).</p>
<p>What you are looking for is something like this:</p>
<pre><code>for i in range(0, self._iteraciones, 1):
self._string = self._string + (self._string_a_repetir * (i + 1)) + '\n'
</code></pre>
<p>The <code>string * number</code> works to repeat the <code>string</code> for <code>number</code> times.</p>
<hr>
<p>As a general note, you should not use those class members that way:</p>
<pre><code>class Triangulo_String:
_string = ''
_iteraciones = 0
_string_a_repetir = ''
</code></pre>
<p>This will create those members as <em>class</em> variables, which are shared across all its instances. This is not directly a problem if you never change the class members but it could cause confusion later. You should instead initialize all instance attributes inside the <code>__init__</code>:</p>
<pre><code>class Triangulo_String:
def __init__(self, string_a_repetir, iteraciones):
self._string = ''
self._string_a_repetir = string_a_repetir
self._iteraciones = iteraciones
</code></pre>
| 3 | 2016-10-09T10:40:20Z | [
"python"
] |
Connecting Raspberry pi with iPhone / iPad application | 39,942,649 | <p>I'm working on home automation using raspberry pi and all i want to do controll my home electricity using mobile application, this is my project ,I'm new to networking i want to know what is the best way to communicate to my electric device using mobile , e.g I wrote a code for electronics in python and now i want to write a program in swift which will than can easily communicate with python and turn on and off the switches easily...</p>
| 0 | 2016-10-09T10:38:15Z | 39,942,791 | <p>I think this would be the process which could take some efforts to do it.But i will guide you through some of the steps you can process.</p>
<ol>
<li><p>You have to build a web server for communicating between raspberry pi and iPhone.Since you know python , Django or Flask would be the go to way.Create web server that communicates the relays which are connected with Raspberry-pi.I would share a <a href="http://internetofthings-pune.blogspot.in/2013/10/home-automation-with-raspberrypi-python.html" rel="nofollow">link</a> that helped me to do so.</p></li>
<li><p>Now you want an iPhone app to do the control.If you have the knowledge of swift programming make APIs in Django or Flask web server and call it with your application.</p></li>
</ol>
<p>This would be the common steps you need to do for controlling your lights via an iPhone App.</p>
| 0 | 2016-10-09T10:55:11Z | [
"python",
"ios",
"iphone"
] |
Creating kivy behavior that dispatches event bubbling same way as on_touch_down | 39,942,694 | <p>Let's start with basic example:</p>
<pre><code>class OuterWidget(Widget):
def on_touch_down(self, touch):
if self.collide_point(*touch.pos):
print('on_touch_down', self)
return True # doesn't dispatch to InnerWidget
return super().on_touch_down(touch)
class InnerWidget(Widget):
def on_touch_down(self, touch):
if self.collide_point(*touch.pos):
print('on_touch_down', self)
return super().on_touch_down(touch)
</code></pre>
<p>Event dispatches to <code>OuterWidget</code> first, if it calls <code>super().on_touch_down(touch)</code> event dispatches to child widgets, else event doesn't dispatch next. That's clear.</p>
<p>I want to create some behavior that happens with <code>on_touch_down</code> and acts same way. Let's try:</p>
<pre><code>class TestBehavior(Widget):
def __init__(self, **kwargs):
self.register_event_type('on_test_event')
super().__init__(**kwargs)
def on_test_event(self, touch):
pass
def on_touch_down(self, touch):
self.dispatch('on_test_event', touch) # Some event that happens with on_touch_down
return super().on_touch_down(touch)
class OuterWidget(TestBehavior, Widget):
def on_test_event(self, touch):
if self.collide_point(*touch.pos):
print('on_test_event', self)
return True # doesn't affect anything, both widgets would recieve on_test_event
return super().on_test_event(touch)
class InnerWidget(TestBehavior, Widget):
def on_test_event(self, touch):
if self.collide_point(*touch.pos):
print('on_test_event', self)
return True
return super().on_test_event(touch)
</code></pre>
<p><code>on_test_event</code> bubbling wouldn't work same way as <code>on_touch_down</code>. Regardless of what <code>OuterWidget</code> returns event would be dispatched to <code>InnerWidget</code>. It happens because both widgets would receive <code>on_touch_down</code> event that fires <code>on_test_event</code>.</p>
<p>Looks like if I use <code>on_touch_down</code> to dispatch some event in behavior this event will be always dispatched to all children, regardless of what any of them returned. But I want not to dispatch <code>on_test_event</code> next if some widget didn't call <code>super().on_test_event(touch)</code>.</p>
<p>How can I do it? Any ideas?</p>
| 1 | 2016-10-09T10:42:40Z | 39,947,141 | <p>The Widget class handles its events to all its children like this:</p>
<p>(copied from widget.py)</p>
<pre><code>def on_touch_down(self, touch):
'''Receive a touch down event.
:Parameters:
`touch`: :class:`~kivy.input.motionevent.MotionEvent` class
Touch received. The touch is in parent coordinates. See
:mod:`~kivy.uix.relativelayout` for a discussion on
coordinate systems.
:Returns: bool
If True, the dispatching of the touch event will stop.
If False, the event will continue to be dispatched to the rest
of the widget tree.
'''
if self.disabled and self.collide_point(*touch.pos):
return True
for child in self.children[:]:
if child.dispatch('on_touch_down', touch):
return True
</code></pre>
<p>As you can see it iterates over its childern and dispatch the event until <em>True</em> is returned.</p>
<p>To create a similar behavior you may create your own <strong>mix-in class and make all you class inherent from it</strong> or to **monkey patch Widget **</p>
<p>IMHO that will be a bit messy, what I would do is to create a function:</p>
<pre><code>def fire_my_event(widget):
if hasattr(widget, 'on_test_event'):
if widget.on_test_event():
return True
for c in widget.children[:]:
if fire_my_event(c):
return True
#in your code somewhere
class SomeWidget(Image): #or anything else ...
def on_touch_down(self, touch):
fire_my_event(self)
</code></pre>
<p>Have fun!</p>
| 1 | 2016-10-09T18:36:20Z | [
"python",
"kivy"
] |
Function return value of x instead of y | 39,942,745 | <p>f(x) represents the function of a triangular waveform. In which you input the value x and it returns you the associated y value. However my function returns x every time instead of y. For example f(1) should give 2/pi instead of 1.</p>
<pre><code>def f(x):
y=x
if x in arange(-math.pi,-math.pi/2):
y=(-2/math.pi)*x-2
elif x in arange(-math.pi/2,math.pi/2):
y=(2/math.pi)*x
elif x in arange(math.pi/2,math.pi):
y=(-2/math.pi)*x+2
return y
</code></pre>
| 0 | 2016-10-09T10:50:14Z | 39,942,785 | <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html" rel="nofollow"><code>numpy.arange</code></a> returns an array of non-consecutive numbers. <code>in</code> operation against it will return <code>True</code> only if the left-hand operand belong to those numbers.</p>
<p>You'd better to use <code><=</code> / <code><</code> pair to avoid such problem. In addition to be correct, it also save cost of creating arrays.</p>
<pre><code>def f(x):
y = x
if -math.pi <= x < -math.pi/2:
y = (-2/math.pi)*x-2
elif -math.pi/2 <= x < math.pi/2:
y = (2/math.pi)*x
elif math.pi/2 <= x < math.pi:
y = (-2/math.pi)*x+2
return y
</code></pre>
| 1 | 2016-10-09T10:55:05Z | [
"python",
"function"
] |
Function return value of x instead of y | 39,942,745 | <p>f(x) represents the function of a triangular waveform. In which you input the value x and it returns you the associated y value. However my function returns x every time instead of y. For example f(1) should give 2/pi instead of 1.</p>
<pre><code>def f(x):
y=x
if x in arange(-math.pi,-math.pi/2):
y=(-2/math.pi)*x-2
elif x in arange(-math.pi/2,math.pi/2):
y=(2/math.pi)*x
elif x in arange(math.pi/2,math.pi):
y=(-2/math.pi)*x+2
return y
</code></pre>
| 0 | 2016-10-09T10:50:14Z | 39,942,793 | <p>The 'in' keyword only checks if the searched element lies in the list. Here, your list contains only values in the step of 1. Perhaps the value of x is not an integral step. Hence, the corrected function would be:</p>
<pre><code>def f(x):
y=x
if x>-math.pi and x<-math.pi/2:
y=(-2/math.pi)*x-2
elif x>-math.pi/2 and x<math.pi/2:
y=(2/math.pi)*x
elif x>math.pi/2 and x<math.pi:
y=(-2/math.pi)*x+2
return y
</code></pre>
| 0 | 2016-10-09T10:55:22Z | [
"python",
"function"
] |
how to split input line in custom format in python | 39,942,786 | <p>10.223.157.186 - - [15/Jul/2009:15:50:35 -0700] "GET /assets/js/lowpro.js HTTP/1.1" 200 10469</p>
<p>i have to take input as given below and have it as %h %l %u %t \"%r\" %>s %b</p>
<p>so that i can have 7 arguments :</p>
<p>%h is the IP address of the client</p>
<p>%l is identity of the client, or "-" if it's unavailable</p>
<p>%u is username of the client, or "-" if it's unavailable</p>
<p>%t is the time that the server finished processing the request. The format is [day/month/year:hour:minute:second zone]</p>
<p>%r is the request line from the client is given (in double quotes). It contains the method, path, query-string, and protocol or the request.</p>
<p>%>s is the status code that the server sends back to the client.</p>
<p>%b is the size of the object returned to the client, in bytes.</p>
| -4 | 2016-10-09T10:55:06Z | 39,943,333 | <p>Take the input as a string. Assuming that the identity of the user can have spaces, but the username cannot,</p>
<pre><code>import re
full_string = input() #python3
# First split at any one of [, ] or "
contents=re.split('[|]|"',full_string)
# Now, contents[0] = %h %l %u
# contents[1] = %t
# contents[2] = %r
# contents[3] = %>s %b
# For a string, directly using the split function splits the string at the passed argument, which is a space here
content_h, content_l, content_u = contents[0].split(' ')[0], contents[0].split(' ')[1:-1], contents[0].split(' ')[-1]
content_s, content_b = contents[3].split[' '][0], contents[3].split[' '][1]
</code></pre>
| 0 | 2016-10-09T11:57:31Z | [
"python",
"python-3.x",
"input"
] |
Reading core_properties using python-docx | 39,942,877 | <p>I'm trying to read the last_saved_by attribute on docx files. I've followed the comments on Github, and from <a href="http://stackoverflow.com/questions/22625022/reading-coreproperties-keywords-from-docx-file-with-python-docx">this question</a>. It seems that support has been added, but the documentation isn't very clear for me. </p>
<p>I've entered the following code into my script (Notepad++):</p>
<pre><code>import docx
document = Document()
core_properties = document.core_properties
core_properties.author = 'Foo B. Baz'
document.save('new-filename.docx')
</code></pre>
<p>I only get an error message at the end:</p>
<pre><code>NameError: name 'Document' is not defined
</code></pre>
<p>I'm not sure where I'm going wrong. :(</p>
<p>When I enter it line by line through python itself, the problem seems to come up from the second line.</p>
<p>I'm using Python 3.4, and docx 0.8.6</p>
| 0 | 2016-10-09T11:06:15Z | 39,943,146 | <p>Figured out where I was going wrong, for those that want to know:</p>
<pre><code>from docx import Document
import docx
document = Document('mine.docx')
core_properties = document.core_properties
print(core_properties.author)
</code></pre>
<p>There'll be a more succinct way of doing this, I'm sure (importing docx twice seems redundant for a start) - but it works, so I'm happy! :)</p>
| 1 | 2016-10-09T11:37:33Z | [
"python",
"python-3.x",
"word-2010",
"python-docx"
] |
Reading core_properties using python-docx | 39,942,877 | <p>I'm trying to read the last_saved_by attribute on docx files. I've followed the comments on Github, and from <a href="http://stackoverflow.com/questions/22625022/reading-coreproperties-keywords-from-docx-file-with-python-docx">this question</a>. It seems that support has been added, but the documentation isn't very clear for me. </p>
<p>I've entered the following code into my script (Notepad++):</p>
<pre><code>import docx
document = Document()
core_properties = document.core_properties
core_properties.author = 'Foo B. Baz'
document.save('new-filename.docx')
</code></pre>
<p>I only get an error message at the end:</p>
<pre><code>NameError: name 'Document' is not defined
</code></pre>
<p>I'm not sure where I'm going wrong. :(</p>
<p>When I enter it line by line through python itself, the problem seems to come up from the second line.</p>
<p>I'm using Python 3.4, and docx 0.8.6</p>
| 0 | 2016-10-09T11:06:15Z | 39,943,416 | <p>If the only thing you need from the <code>docx</code> module is <code>Document</code>, then you only need to use</p>
<pre><code>from docx import Document
</code></pre>
<p>If you use more than that, you could use</p>
<pre><code>import docx
document = docx.Document()
</code></pre>
<p>importing specific names from the <code>docx</code> module is your choice; either way, you don't <em>need</em> to have two lines importing from (or importing) <code>docx</code>, although it's not expensive to have both.</p>
| 0 | 2016-10-09T12:05:19Z | [
"python",
"python-3.x",
"word-2010",
"python-docx"
] |
Why do I have to close the shell for my script to work? (writing to text files) | 39,942,948 | <p>I have the following code in a .py file: </p>
<pre><code>f = open('exampleTextFile.txt', 'w')
f.write('This is a sentence.')
f.close
</code></pre>
<p>I open it up and press F5 to run.</p>
<p>The IDLE shell opens up and runs the code without a hitch. But then when I find the text file in my directory and open it up the text isn't there. Then when I close the shell and reopen the text file the text now appears. Why do I need to close the shell and what code can I write so that I don't have to do this?</p>
<p>I know the answer must be simple! Thanks.</p>
| 1 | 2016-10-09T11:14:37Z | 39,942,977 | <p>Your file is not closed properly. You forgot the parenthesis:</p>
<pre><code>f.close()
</code></pre>
| 0 | 2016-10-09T11:18:17Z | [
"python",
"python-2.7"
] |
Why do I have to close the shell for my script to work? (writing to text files) | 39,942,948 | <p>I have the following code in a .py file: </p>
<pre><code>f = open('exampleTextFile.txt', 'w')
f.write('This is a sentence.')
f.close
</code></pre>
<p>I open it up and press F5 to run.</p>
<p>The IDLE shell opens up and runs the code without a hitch. But then when I find the text file in my directory and open it up the text isn't there. Then when I close the shell and reopen the text file the text now appears. Why do I need to close the shell and what code can I write so that I don't have to do this?</p>
<p>I know the answer must be simple! Thanks.</p>
| 1 | 2016-10-09T11:14:37Z | 39,943,053 | <p>You can prevent these mistakes by using the <code>open</code> context manager</p>
<pre><code>with open('exampleTextFile.txt', 'w') as f:
f.write('This is a sentence.')
# file automatically closed
</code></pre>
<p>This has the additional benefit that the file will be closed on errors too:</p>
<pre><code>with open('exampleTextFile.txt', 'w') as f:
raise Exception()
# file still closed
</code></pre>
| 2 | 2016-10-09T11:26:26Z | [
"python",
"python-2.7"
] |
Get first letter of index? | 39,943,132 | <p>I have a pandas dataframe <code>df</code> that looks like this:</p>
<pre><code> population
n
France 66.03
Italy 59.83
</code></pre>
<p>I want to get the first letter of the index label, for each row, and set it as a new column so that I can start doing analysis with it. How can I do this?</p>
<p>Right now I'm doing this:</p>
<pre><code>def get_first_letter(row):
return row[0]
df1 = df.reset_index()
df1.first_letter = df1.n.apply(get_first_letter)
</code></pre>
<p>Is there a better way?</p>
| 0 | 2016-10-09T11:35:30Z | 39,943,399 | <p>I think there's nothing wrong with what you're doing. There are two things which you may do differently</p>
<ol>
<li>use lambda or list comprehension instead of the named function</li>
<li>set the index directly instead of reseting it.</li>
</ol>
<p>Like this:</p>
<pre><code>df1.n.apply(lambda x: x[0])
</code></pre>
<p>or</p>
<pre><code>df1.set_index(pd.Index((x[0] for x in df1.index)))
</code></pre>
| 0 | 2016-10-09T12:03:41Z | [
"python",
"pandas"
] |
Get first letter of index? | 39,943,132 | <p>I have a pandas dataframe <code>df</code> that looks like this:</p>
<pre><code> population
n
France 66.03
Italy 59.83
</code></pre>
<p>I want to get the first letter of the index label, for each row, and set it as a new column so that I can start doing analysis with it. How can I do this?</p>
<p>Right now I'm doing this:</p>
<pre><code>def get_first_letter(row):
return row[0]
df1 = df.reset_index()
df1.first_letter = df1.n.apply(get_first_letter)
</code></pre>
<p>Is there a better way?</p>
| 0 | 2016-10-09T11:35:30Z | 39,943,412 | <p>You could use the <a href="http://pandas.pydata.org/pandas-docs/version/0.18.1/generated/pandas.Index.get_level_values.html#pandas-index-get-level-values" rel="nofollow"><code>get_level_values</code> method</a> to obtain the index label. Then <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str" rel="nofollow">use <code>str[0]</code></a> to obtain the first letter:</p>
<pre><code>In [29]: df = pd.DataFrame({'population':[66.03,59.83]}, index=pd.Series(['France','Italy'], name='n')); df
Out[29]:
population
n
France 66.03
Italy 59.83
In [30]: df['first_letter'] = df.index.get_level_values('n').str[0]; df
Out[30]:
population first_letter
n
France 66.03 F
Italy 59.83 I
</code></pre>
| 1 | 2016-10-09T12:05:12Z | [
"python",
"pandas"
] |
how to get a python value from input type hidden in jquery | 39,943,209 | <p>I have this code:</p>
<pre><code><div class="popup" data-popup="popup-1">
<div class="popup-inner">
{{=form.custom.begin}}
<div style="display:none">
<input id="co_srid" type="hidden" value='{{=form.custom.widget.service_request_id}}' />
{{=form.custom.end}}
</div>
</div>
</code></pre>
<pre class="lang-js prettyprint-override"><code>$(document).ready(function(){
var cosrid = $("#co_srid").val();
alert("value is-" + cosrid);
});
</code></pre>
<p>I want to get the value of <code>#co_srid</code> that has a value from a Python code, now I when I <code>alert</code> the value I get this</p>
<p><a href="http://i.stack.imgur.com/PILkr.png" rel="nofollow"><img src="http://i.stack.imgur.com/PILkr.png" alt="enter image description here"></a></p>
<p>Is there anyway I can get the value <code>9</code> only?</p>
| 0 | 2016-10-09T11:44:00Z | 39,943,344 | <p>I changed</p>
<pre><code>value='{{=form.custom.widget.service_request_id}}'
</code></pre>
<p>to</p>
<pre><code>value='{{=get_data.service_request_id}}'
</code></pre>
| 0 | 2016-10-09T11:58:46Z | [
"jquery",
"python",
"web2py"
] |
How to set optimality gap in PULP-OR with CBC solver? | 39,943,236 | <p>I want to set the optimality gap when calculating a solution between the optimal and the actual solution. </p>
<p>I use PuLP version 1.6.1 and I want to pass the parameter of gap to the solver. Does anyone have an example or an idea on how to approach this issue. </p>
<p>The documentation that can be found here:</p>
<p><a href="https://pythonhosted.org/PuLP/solvers.html" rel="nofollow">https://pythonhosted.org/PuLP/solvers.html</a></p>
<p>Is not very helpful. </p>
<p>Thank you.</p>
| 0 | 2016-10-09T11:47:37Z | 39,943,517 | <p>The documentation exactly shows you how to pass options to the solvers. Maybe not all of cbcs options are supported, but pulp's code shows, that the task you want is handled by the argument <code>fracGap</code>.</p>
<pre><code>class COIN_CMD(LpSolver_CMD):
"""The COIN CLP/CBC LP solver
now only uses cbc
"""
def defaultPath(self):
return self.executableExtension(cbc_path)
def __init__(self, path = None, keepFiles = 0, mip = 1,
msg = 0, cuts = None, presolve = None, dual = None,
strong = None, options = [],
fracGap = None, maxSeconds = None, threads = None)
</code></pre>
<p>Let's take one pulp's examples <a href="https://github.com/coin-or/pulp/blob/master/examples/ComputerPlantProblem.py" rel="nofollow">from here</a>.</p>
<h3>Code of default-mode</h3>
<pre><code>"""
The Computer Plant Problem for the PuLP Modeller
Authors: Antony Phillips, Dr Stuart Mitchell 2007
"""
# Import PuLP modeler functions
from pulp import *
# Creates a list of all the supply nodes
Plants = ["San Francisco",
"Los Angeles",
"Phoenix",
"Denver"]
# Creates a dictionary of lists for the number of units of supply at
# each plant and the fixed cost of running each plant
supplyData = {#Plant Supply Fixed Cost
"San Francisco":[1700, 70000],
"Los Angeles" :[2000, 70000],
"Phoenix" :[1700, 65000],
"Denver" :[2000, 70000]
}
# Creates a list of all demand nodes
Stores = ["San Diego",
"Barstow",
"Tucson",
"Dallas"]
# Creates a dictionary for the number of units of demand at each store
demand = { #Store Demand
"San Diego":1700,
"Barstow" :1000,
"Tucson" :1500,
"Dallas" :1200
}
# Creates a list of costs for each transportation path
costs = [ #Stores
#SD BA TU DA
[5, 3, 2, 6], #SF
[4, 7, 8, 10],#LA Plants
[6, 5, 3, 8], #PH
[9, 8, 6, 5] #DE
]
# Creates a list of tuples containing all the possible routes for transport
Routes = [(p,s) for p in Plants for s in Stores]
# Splits the dictionaries to be more understandable
(supply,fixedCost) = splitDict(supplyData)
# The cost data is made into a dictionary
costs = makeDict([Plants,Stores],costs,0)
# Creates the problem variables of the Flow on the Arcs
flow = LpVariable.dicts("Route",(Plants,Stores),0,None,LpInteger)
# Creates the master problem variables of whether to build the Plants or not
build = LpVariable.dicts("BuildaPlant",Plants,0,1,LpInteger)
# Creates the 'prob' variable to contain the problem data
prob = LpProblem("Computer Plant Problem",LpMinimize)
# The objective function is added to prob - The sum of the transportation costs and the building fixed costs
prob += lpSum([flow[p][s]*costs[p][s] for (p,s) in Routes])+lpSum([fixedCost[p]*build[p] for p in Plants]),"Total Costs"
# The Supply maximum constraints are added for each supply node (plant)
for p in Plants:
prob += lpSum([flow[p][s] for s in Stores])<=supply[p]*build[p], "Sum of Products out of Plant %s"%p
# The Demand minimum constraints are added for each demand node (store)
for s in Stores:
prob += lpSum([flow[p][s] for p in Plants])>=demand[s], "Sum of Products into Stores %s"%s
# The problem data is written to an .lp file
prob.writeLP("ComputerPlantProblem.lp")
# The problem is solved using PuLP's choice of Solver
prob.solve(PULP_CBC_CMD())
# The status of the solution is printed to the screen
print("Status:", LpStatus[prob.status])
# Each of the variables is printed with it's resolved optimum value
for v in prob.variables():
print(v.name, "=", v.varValue)
# The optimised objective function value is printed to the screen
print("Total Costs = ", value(prob.objective))
</code></pre>
<h3>Output</h3>
<pre><code>...
('Total Costs = ', 228100.0)
</code></pre>
<h3>Code to set MIPGap</h3>
<pre><code>#prob.solve(PULP_CBC_CMD()) # old call
prob.solve(PULP_CBC_CMD(fracGap = 0.1))
</code></pre>
<h3>Output</h3>
<pre><code>...
('Total Costs = ', 230300.0)
</code></pre>
| 0 | 2016-10-09T12:17:00Z | [
"python",
"optimization",
"linear-programming",
"pulp"
] |
From subprocess.Popen to multiprocessing | 39,943,281 | <p>I got a function that invokes a process using <code>subprocess.Popen</code> in the following way:</p>
<pre><code> def func():
...
process = subprocess.Popen(substr, shell=True, stdout=subprocess.PIPE)
timeout = {"value": False}
timer = Timer(timeout_sec, kill_proc, [process, timeout])
timer.start()
for line in process.stdout:
lines.append(line)
timer.cancel()
if timeout["value"] == True:
return 0
...
</code></pre>
<p>I call this function from other function using a loop (e.g from range(1,100) ) , how can I make multiple calls to the function with multiprocessing? that each time several processes will run in parallel</p>
<p>The processes doesn't depend on each other, the only constraint is that each process would be 'working' on only one index (e.g no two processes will work on index 1)</p>
<p>Thanks for your help</p>
| 0 | 2016-10-09T11:52:47Z | 39,944,459 | <p>Just add the index to your <code>Popen</code> call and create a <a href="https://docs.python.org/3.6/library/multiprocessing.html" rel="nofollow">worker pool</a> with as many CPU cores you have available.</p>
<pre><code>import multiprocessing
def func(index):
....
process = subprocess.Popen(substr + " --index {}".format(index), shell=True, stdout=subprocess.PIPE)
....
if __name__ == '__main__':
p = multiprocessing.Pool(multiprocessing.cpu_count())
p.map(func, range(1, 100))
</code></pre>
| 0 | 2016-10-09T14:03:52Z | [
"python",
"multiprocessing"
] |
I can't use the sorted function to sort a two elements tuple list in descending numerical order then in ascending alphabetical order in case of a tie | 39,943,307 | <p>I used the sorted() function to sort a list of tuples, as it is shown below. the output is in descending order as wanted for the second elements (numbers). but what I really want is to sort the tuples in ascending alphabetical order in case of a tie.</p>
<p>Help please. </p>
<pre><code>sorted(word_Count, key = itemgetter(1,0), reverse = True)
</code></pre>
<p>Output: </p>
<pre><code>[('butter', 2), ('was', 1), ('the', 1), ('of', 1), ('but', 1),
('bought', 1), ('bitter', 1), ('bit', 1), ('betty', 1), ('a', 1)]
</code></pre>
<p>thank you</p>
| 0 | 2016-10-09T11:54:33Z | 39,943,342 | <p>You can use the <code>sorted()</code> function along with <a href="http://www.diveintopython.net/power_of_introspection/lambda_functions.html" rel="nofollow"><code>lambda</code></a> as:</p>
<pre><code>>>> sorted(word_count, key=lambda x: (-x[1], x[0]))
[('butter', 2), ('a', 1), ('betty', 1), ('bit', 1), ('bitter', 1), ('bought', 1), ('but', 1), ('of', 1), ('the', 1), ('was', 1)]
</code></pre>
<p>My <code>lambda</code> function is returning tuple as <code>(-x[1], x[0]))</code> which represents to sort the list in descending order of <code>x[1]</code> (<code>-</code> represents descending) and in case of match sort in the ascending order of <code>x[0]</code> (without <code>-</code> sign means ascending) </p>
| 3 | 2016-10-09T11:58:43Z | [
"python",
"function",
"sorting",
"tuples"
] |
I can't use the sorted function to sort a two elements tuple list in descending numerical order then in ascending alphabetical order in case of a tie | 39,943,307 | <p>I used the sorted() function to sort a list of tuples, as it is shown below. the output is in descending order as wanted for the second elements (numbers). but what I really want is to sort the tuples in ascending alphabetical order in case of a tie.</p>
<p>Help please. </p>
<pre><code>sorted(word_Count, key = itemgetter(1,0), reverse = True)
</code></pre>
<p>Output: </p>
<pre><code>[('butter', 2), ('was', 1), ('the', 1), ('of', 1), ('but', 1),
('bought', 1), ('bitter', 1), ('bit', 1), ('betty', 1), ('a', 1)]
</code></pre>
<p>thank you</p>
| 0 | 2016-10-09T11:54:33Z | 39,943,441 | <p>You could use <code>list.sort</code> twice, since, according to <code>list.sort</code>'s docstring, it is in place:</p>
<pre><code>L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
</code></pre>
<p>So, to sort your list, you could do</p>
<pre><code>>>> word_count.sort()
>>> word_count.sort(key=lambda x: x[1], reverse=True)
>>> print(word_count)
[('butter', 2), ('a', 1), ('betty', 1), ('bit', 1), ('bitter', 1),
('bought', 1), ('but', 1), ('of', 1), ('the', 1), ('was', 1)]
</code></pre>
<p>Just make sure to sort alphabetically first, then sort by the second key after that.</p>
| 0 | 2016-10-09T12:07:29Z | [
"python",
"function",
"sorting",
"tuples"
] |
How to keybind the return to the "=" code: Python | 39,943,509 | <p>I am trying to keybind the enter key to "=".</p>
<p>With the code I have now, I get an error when i put in two numbers and press enter, the error is:</p>
<pre><code>Exception in Tkinter callback
Traceback (most recent call last):
line 1550, in __call__
return self.func(*args)
line 68, in <lambda>
root.bind('<Return>', lambda x: Calculator.calcu('='))
TypeError: calcu() missing 1 required positional argument: 'entry_num'
</code></pre>
<p>The fact that the random window pops up at the start is just evidence that it's not working I guess. I believe that if the root window problem gets fixed, it could fix the key bind problem.</p>
<p>I get that error as I press enter, there is also a random window that opens up as I run the code as well if that helps anyone helping trying to solve the problem, please help me I'm really stuck.</p>
<p><strong>THE OVERALL PROBLEM IS:</strong>
I don't know how to key bind the enter key on my keyboard to "=" and make the entry get entered by doing so.</p>
<p><a href="http://i.stack.imgur.com/OgSvz.png" rel="nofollow">This is what I get when i run my code(picture)</a></p>
<pre><code> from __future__ import division
from functools import partial
from math import *
import tkinter as tk
from tkinter import *
root=Tk()
class Calculator(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.buttons_layout()
self.title("Thomas's calc")
textb = Entry(root)
def calcu(self,entry_num):
if entry_num == "=":
try:
total=eval(self.textb.get())
self.textb.insert(tk.END," = "+str(total))
except:
self.textb.insert(tk.END, " - Invalid Calculation - ")
elif entry_num == "del":
self.txt=self.textb.get()[:-1]
self.textb.delete(0,tk.END)
self.textb.insert(0,self.txt)
elif entry_num == "C":
self.textb.delete(0,END)
elif entry_num == "i":
infob= Toplevel(self.textb.insert(tk.END, ""))
infob = Label(infob, text="Thomas, Calculator").pack()
else:
if "=" in self.textb.get():
self.textb.delete(tk.END)
self.textb.insert(tk.END, entry_num)
def buttons_layout(self):
self.textb = tk.Entry(root, width=66, fg="white", bg="black", state="normal") #text color = fg // background colour bg // sets the entry box specs
self.textb.grid(row=0, column=0, columnspan=5)
buttona="groove"
ycol = 0
xrow = 1
button_list = ["1","2","3","+","C",
"4","5","6","-","del",
"7","8","9","/","",
"0",".","i","*","="]
for button in button_list:
calc1=partial(self.calcu, button)
tk.Button(root,text=button,height=4,command=calc1,bg="aquamarine", fg="red",width=10,state="normal",relief=buttona).grid(
row=xrow, column=ycol)
ycol= ycol + 1
if ycol > 4:
ycol=0
xrow= xrow + 3
class key_binding():
root.bind('<Return>', lambda x: Calculator.calcu('='))
end=Calculator()
end.mainloop()
root.mainloop()
</code></pre>
<p>THE KEYBIND IS AT THE BOTTOM OF MY CODE BY THE WAY</p>
| 0 | 2016-10-09T12:15:56Z | 40,003,769 | <p>This should work. I've also got rid of the second window that wasn't needed</p>
<pre><code>from __future__ import division
from functools import partial
from math import *
import tkinter as tk
from tkinter import *
#root=Tk()
class Calculator(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.buttons_layout()
self.title("Thomas's calc")
textb = Entry(self)
self.bind('<Return>', lambda x: self.calcu('='))
def calcu(self,entry_num):
if entry_num == "=":
try:
total=eval(self.textb.get())
self.textb.insert(tk.END," = "+str(total))
except:
self.textb.insert(tk.END, " - Invalid Calculation - ")
elif entry_num == "del":
self.txt=self.textb.get()[:-1]
self.textb.delete(0,tk.END)
self.textb.insert(0,self.txt)
elif entry_num == "C":
self.textb.delete(0,END)
elif entry_num == "i":
infob= Toplevel(self.textb.insert(tk.END, ""))
infob = Label(infob, text="Thomas, Calculator").pack()
else:
if "=" in self.textb.get():
self.textb.delete(tk.END)
self.textb.insert(tk.END, entry_num)
def buttons_layout(self):
self.textb = tk.Entry(self, width=66, fg="white", bg="black", state="normal") #text color = fg // background colour bg // sets the entry box specs
self.textb.grid(row=0, column=0, columnspan=5)
buttona="groove"
ycol = 0
xrow = 1
button_list = ["1","2","3","+","C",
"4","5","6","-","del",
"7","8","9","/","",
"0",".","i","*","="]
for button in button_list:
calc1=partial(self.calcu, button)
tk.Button(self,text=button,height=4,command=calc1,bg="aquamarine", fg="red",width=10,state="normal",relief=buttona).grid(
row=xrow, column=ycol)
ycol= ycol + 1
if ycol > 4:
ycol=0
xrow= xrow + 3
#class key_binding():
# root.bind('<Return>', lambda x: Calculator.calcu('='))
end=Calculator()
end.mainloop()
#root.mainloop()
</code></pre>
| 0 | 2016-10-12T16:30:28Z | [
"python",
"user-interface",
"tkinter",
"calculator"
] |
passing argument from python to subprocess.popen | 39,943,519 | <p>I have this code:</p>
<pre><code>from subprocess import Popen
link="abc"
theproc = Popen([sys.executable, "p1.py",link])
</code></pre>
<p>I want to send the variable "link" to p1.py,
and p1.py will print it.</p>
<p>something like this. here is p1.py:</p>
<pre><code>print "in p1.py link is "+ link
</code></pre>
<p>How can I do that?</p>
| -2 | 2016-10-09T12:17:09Z | 39,943,630 | <p>I'm assuming <code>python</code> refers to Python 2.x on your system.</p>
<p>Retrieve the command line argument in <code>p1.py</code> using <code>sys.argv</code>:</p>
<pre><code>import sys
if not len(sys.argv) > 1:
print "Expecting link argument."
else:
print "in p1.py link is " + sys.argv[1]
</code></pre>
<p>There's a function <code>subprocess.check_output</code> that is easier to use if you only want to call a program and retrieve its output:</p>
<pre><code>from subprocess import check_output
output = check_output(["python", "p1.py", "SOME_URL"])
print "p1.py returned the following output:\n'{}'".format(output)
</code></pre>
<p>Example output:</p>
<pre><code>$ python call_p1.py
p1.py returned the following output:
'in p1.py link is SOME_URL
'
</code></pre>
| 0 | 2016-10-09T12:29:15Z | [
"python",
"subprocess",
"popen"
] |
passing argument from python to subprocess.popen | 39,943,519 | <p>I have this code:</p>
<pre><code>from subprocess import Popen
link="abc"
theproc = Popen([sys.executable, "p1.py",link])
</code></pre>
<p>I want to send the variable "link" to p1.py,
and p1.py will print it.</p>
<p>something like this. here is p1.py:</p>
<pre><code>print "in p1.py link is "+ link
</code></pre>
<p>How can I do that?</p>
| -2 | 2016-10-09T12:17:09Z | 39,943,673 | <p>You have to parse the command line arguments in your <code>p1.py</code> to get it in a variable:</p>
<pre><code>import sys
try:
link = sys.argv[1]
except IndexError:
print 'argument missing'
sys.exit(1)
</code></pre>
| 0 | 2016-10-09T12:33:55Z | [
"python",
"subprocess",
"popen"
] |
python, dictionary in a data frame, sorting | 39,943,547 | <p>I have a python data frame called wiki, with the wikipedia information for some people.
Each row is a different person, and the columns are : 'name', 'text' and 'word_count'. The information in 'text' has been put in dictionary form (keys,values), to create the information in the column 'word_count'.</p>
<p>If I want to extract the row related to Barack Obama, then:</p>
<pre><code>row = wiki[wiki['name'] == 'Barack Obama']
</code></pre>
<p>Now, I would like the most popular word. When I do:</p>
<pre><code>adf=row[['word_count']]
</code></pre>
<p>I get another data frame because I see that:</p>
<pre><code>type(adf)=<class 'pandas.core.frame.DataFrame'>
</code></pre>
<p>and if I do </p>
<pre><code>adf.values
</code></pre>
<p>I get:</p>
<pre><code>array([[ {u'operations': 1, u'represent': 1, u'office': 2, ..., u'began': 1}], dtype=object)
</code></pre>
<p>However, what is very confusing to me is that the size is 1</p>
<pre><code>adf.size=1
</code></pre>
<p>Therefore, I do not know how to actually extract the keys and values. Things like <code>adf.values[1]</code> do not work</p>
<p>Ultimately, what I need to do is sort the information in word_count so that the most frequent words appear first.
But I would like to understand how to access a the information that is inside a dictionary, inside a data frame... I am lost about the types here. I am not new to programming, but I am relatively new to python.</p>
<p>Any help would be very very much appreciated</p>
| 0 | 2016-10-09T12:20:00Z | 39,944,248 | <p>If the name column is unique, then you can change the column to the index of the <code>DataFrame</code> object:<code>wiki.set_index("name", inplace=True)</code>. Then you can get the value by: <code>wiki.at['Barack Obama', 'word_count']</code>.</p>
<p>With your code:</p>
<pre><code>row = wiki[wiki['name'] == 'Barack Obama']
adf = row[['word_count']]
</code></pre>
<p>The first line use a bool array to get the data, here is the document: <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing</a></p>
<p><code>wiki</code> is a <code>DataFrame</code> object, and <code>row</code> is also a <code>DataFrame</code> object with only one row, if the name column is unique.</p>
<p>The second line get a list of columns from the <code>row</code>, here is the document: <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#basics" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/indexing.html#basics</a></p>
<p>You get a <code>DataFrame</code> with only one row and one column.</p>
<p>And here is the document of <code>.at[]</code>: <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#fast-scalar-value-getting-and-setting" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/indexing.html#fast-scalar-value-getting-and-setting</a></p>
| 2 | 2016-10-09T13:37:06Z | [
"python",
"sorting",
"pandas",
"dictionary",
"dataframe"
] |
Maximum recursion depth exceeded in python | 39,943,560 | <p>I am trying to make power function by recursion.
But I got run time error like Maximum recursion depth exceeded.
I will appreciate any help!!
Here is my code.</p>
<pre><code> def fast_power(a,n):
if(n==0):
return 1
else:
if(n%2==0):
return fast_power(fast_power(a,n/2),2)
else:
return fast_power(fast_power(a,n/2),2)*a
</code></pre>
| 0 | 2016-10-09T12:20:54Z | 39,943,590 | <p>You should use <code>n // 2</code> instead of <code>n / 2</code>:</p>
<pre><code>>>> 5 // 2
2
>>> 5 / 2
2.5
</code></pre>
<p>(At least in python3)</p>
<p>The problem is that once you end up with floats it takes quite a while before you end up at <code>0</code> by dividing by <code>2</code>:</p>
<pre><code>>>> from itertools import count
>>> n = 5
>>> for i in count():
... n /= 2
... if n == 0:
... break
...
>>> i
1076
</code></pre>
<p>So as you can see you would need more than 1000 recursive calls to reach <code>0</code> from <code>5</code>, and that's above the default recursion limit. Besides: that algorithm is meant to be run with integer numbers.</p>
<hr>
<p>This said I'd write that function as something like:</p>
<pre><code>def fast_power(a, n):
if n == 0:
return 1
tmp = fast_power(a, n//2)
tmp *= tmp
return a*tmp if n%2 else tmp
</code></pre>
<p>Which produces:</p>
<pre><code>>>> fast_power(2, 7)
128
>>> fast_power(3, 7)
2187
>>> fast_power(13, 793)
22755080661651301134628922146701289018723006552429644877562239367125245900453849234455323305726135714456994505688015462580473825073733493280791059868764599730367896428134533515091867511617127882942739592792838327544860344501784014930389049910558877662640122357152582905314163703803827192606896583114428235695115603966134132126414026659477774724471137498587452807465366378927445362356200526278861707511302663034996964296170951925219431414726359869227380059895627848341129113432175217372073248096983111394024987891966713095153672274972773169033889294808595643958156933979639791684384157282173718024930353085371267915606772545626201802945545406048262062221518066352534122215300640672237064641040065334712571485001684857748001990405649808379706945473443683240715198330842716984731885709953720968428395490414067791229792734370523603401019458798402338043728152982948501103056283713360751853
</code></pre>
| 2 | 2016-10-09T12:23:43Z | [
"python",
"function",
"recursion"
] |
Maximum recursion depth exceeded in python | 39,943,560 | <p>I am trying to make power function by recursion.
But I got run time error like Maximum recursion depth exceeded.
I will appreciate any help!!
Here is my code.</p>
<pre><code> def fast_power(a,n):
if(n==0):
return 1
else:
if(n%2==0):
return fast_power(fast_power(a,n/2),2)
else:
return fast_power(fast_power(a,n/2),2)*a
</code></pre>
| 0 | 2016-10-09T12:20:54Z | 39,949,967 | <p>I believe @Bakuriu's explanation of the problem is incomplete. Not his reimplementation, but his explanation of your bug(s). You might convince yourself of this by replacing <code>/</code> with <code>//</code> in your original code and try:</p>
<pre><code>fast_power(2, 2)
</code></pre>
<p>it still exceeds the stack. Try expanding the stack ten fold:</p>
<pre><code>sys.setrecursionlimit(10000)
</code></pre>
<p>it still exceeds the stack. The reason is you also have an infinte loop:</p>
<pre><code>if (n % 2 == 0):
return fast_power(..., 2)
</code></pre>
<p>Since 2 % 2 == 0, this simply keeps recursing forever. Adding another base case:</p>
<pre><code>if n == 2:
return a * a
</code></pre>
<p>fixes the problem. A complete solution:</p>
<pre><code>def fast_power(a, n):
if n == 0:
return 1
# if n == 1:
# return a
if n == 2:
return a * a
if n % 2 == 0:
return fast_power(fast_power(a, n // 2), 2)
return a * fast_power(fast_power(a, n // 2), 2)
</code></pre>
| 0 | 2016-10-10T00:45:04Z | [
"python",
"function",
"recursion"
] |
Deploying Django project on Linux | 39,943,598 | <p>Comming from PHP(without frameworks), I don't quite understand how deploying works in Python. I have completed my simple Django version: <em>(1, 10, 1, 'final', 1)</em> blog project and all I have to do is put it online. I am using linux openSUSE distro and virtualenv</p>
<p>I have access to a mysql database with phpmyadmin and I have some space, accessed with filezilla. hosting site: <em><a href="https://host.bg/" rel="nofollow">https://host.bg/</a></em></p>
<p>But then I started researching of how to deploy my project and I stumbled upon stuf like apache, Nginx, wsgi and other stuff I haven't used in the project and not quite familiar how they work.</p>
<p>So my question is: Can I make my project into a folder with some files in it, copy->paste them in filezilla and have a working site and if not, how does django deployment really work and what should I do from here ?!</p>
| 0 | 2016-10-09T12:25:03Z | 39,943,657 | <p>I would recommend you to use Git instead of FTP protocol. As you are using Linux you can easily connect to your SO using ssh.</p>
<p>About the deployment, I would recommend you to use GUnicorn for a WSGI way.
It's not hard to deploy with, but if you get in trouble you can use the official Django documentation for deploying Django with WSGI:</p>
<p><a href="https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/gunicorn/" rel="nofollow">Link</a></p>
<p>Ps.: As you are using Linux, I would recommend to you to use VirtualEnv to allow you server many Django sites in the same Linux instance with the isolated environments</p>
| 0 | 2016-10-09T12:32:06Z | [
"python",
"mysql",
"django"
] |
Deploying Django project on Linux | 39,943,598 | <p>Comming from PHP(without frameworks), I don't quite understand how deploying works in Python. I have completed my simple Django version: <em>(1, 10, 1, 'final', 1)</em> blog project and all I have to do is put it online. I am using linux openSUSE distro and virtualenv</p>
<p>I have access to a mysql database with phpmyadmin and I have some space, accessed with filezilla. hosting site: <em><a href="https://host.bg/" rel="nofollow">https://host.bg/</a></em></p>
<p>But then I started researching of how to deploy my project and I stumbled upon stuf like apache, Nginx, wsgi and other stuff I haven't used in the project and not quite familiar how they work.</p>
<p>So my question is: Can I make my project into a folder with some files in it, copy->paste them in filezilla and have a working site and if not, how does django deployment really work and what should I do from here ?!</p>
| 0 | 2016-10-09T12:25:03Z | 39,944,002 | <p>Check what version of Python is installed on the server hosting your account and if there's option for ssh access.</p>
<p>Host.bg and Bulgarian hosting providers in general fail to keep up with most things other than php and mysql. With shared plans they avoid installing anything new too.</p>
<p>I'd say contact support and see if they would be able to assist you with Apache configurations and whatever else is needed for your project.</p>
| 0 | 2016-10-09T13:11:36Z | [
"python",
"mysql",
"django"
] |
Python Spacy beginner : similarities function | 39,943,687 | <p>In the tutorial example of spaCy in Python the results of <code>apples.similarity(oranges)</code> is
<code>0.39289959293092641</code>
instead of <code>0.7857989796519943</code></p>
<p>Any reasons for that?
Original docs of the tutorial
<a href="https://spacy.io/docs/" rel="nofollow">https://spacy.io/docs/</a>
A tutorial with a different answer to the one I get:
<a href="http://textminingonline.com/getting-started-with-spacy" rel="nofollow">http://textminingonline.com/getting-started-with-spacy</a></p>
<p>Thanks</p>
| 1 | 2016-10-09T12:35:17Z | 39,984,831 | <p>That appears to be a bug in spacy.</p>
<p>Somehow <code>vector_norm</code> is incorrectly calculated. </p>
<pre><code>import spacy
import numpy as np
nlp = spacy.load("en")
# using u"apples" just as an example
apples = nlp.vocab[u"apples"]
print apples.vector_norm
# prints 1.4142135381698608, or sqrt(2)
print np.sqrt(np.dot(apples.vector, apples.vector))
# prints 1.0
</code></pre>
<p>Then <code>vector_norm</code> is used in <code>similarity</code>, which always returns a value that is always half of the correct value.</p>
<pre><code>def similarity(self, other):
if self.vector_norm == 0 or other.vector_norm == 0:
return 0.0
return numpy.dot(self.vector, other.vector) / (self.vector_norm * other.vector_norm)
</code></pre>
<p>If you are ranking similarity scores for synonyms, this might be OK. But if you need the correct cosine similarity score, then the result is incorrect.</p>
<p>I submitted the issue <a href="https://github.com/explosion/spaCy/issues/522" rel="nofollow">here</a>. Hopefully it will get fixed soon.</p>
| 1 | 2016-10-11T19:05:07Z | [
"python",
"nlp",
"spacy"
] |
Select from dataframe the last n records before event appears | 39,943,736 | <p>Suppose I have the following pandas Dataframe:</p>
<pre><code> name timestamp
1 event1 9/2016 13:47:49
1 event2 9/2016 13:47:55
1 event3 9/2016 13:49:30
1 event4 9/2016 13:50:49
1 trigger 9/2016 13:51:49
1 event6 9/2016 13:54:49
1 event7 9/2016 13:55:49
1 event8 9/2016 13:56:49
1 event9 9/2016 13:57:49
1 trigger 9/2016 13:58:49
1 event10 9/2016 13:59:49
1 event11 9/2016 13:59:59
1 event12 9/2016 14:00:49
1 event13 9/2016 14:00:59
1 event14 9/2016 14:01:49
</code></pre>
<p>What I am trying to do is the following:
Whenever there is a trigger column appearing, I would like to select the last 3 records. So at the end I want to have this:</p>
<pre><code> name timestamp
1 event2 9/2016 13:47:55
1 event3 9/2016 13:49:30
1 event4 9/2016 13:50:49
1 event7 9/2016 13:55:49
1 event8 9/2016 13:56:49
1 event9 9/2016 13:57:49
</code></pre>
<p>Is there a nice predefined pandas function to do that or will I have to iterate the dataframe and get them manually? </p>
<p>thank you!</p>
| 1 | 2016-10-09T12:40:40Z | 39,944,108 | <p>You can create a group variable based on the <code>cumsum</code> of whether <code>name</code> column is equal to <code>trigger</code> condition and then take the last three records for each group (the last group needs to be filtered out due to the fact that there is no <code>trigger</code> after it):</p>
<pre><code>g = (df.name == 'trigger').cumsum()
df[g < g.max()].groupby(g[g < g.max()]).tail(3)
# name timestamp
#1 event2 9/2016 13:47:55
#1 event3 9/2016 13:49:30
#1 event4 9/2016 13:50:49
#1 event7 9/2016 13:55:49
#1 event8 9/2016 13:56:49
#1 event9 9/2016 13:57:49
</code></pre>
| 3 | 2016-10-09T13:22:11Z | [
"python",
"pandas",
"select",
"dataframe"
] |
Remove Quotation marks from a dictionary | 39,943,765 | <p>I have a dictionary of bigrams, obtained by importing a csv and transforming it to a dictionary:</p>
<pre><code>bigram_dict = {"('key1', 'key2')": 'meaning', "('key22', 'key13')": 'mean2'}
</code></pre>
<p>I want keys' dictionary to be without quotation marks, i.e.:</p>
<pre><code>desired_bigram_dict={('key1', 'key2'): 'meaning', ('key22', 'key13'): 'mean2'}
</code></pre>
<p>Would you please suggest me how to do this?</p>
| 2 | 2016-10-09T12:42:49Z | 39,943,787 | <p>You can <a href="https://docs.python.org/2/library/ast.html#ast.literal_eval" rel="nofollow"><em>literal_eval</em></a> each key and reassign:</p>
<pre><code>from ast import literal_eval
bigram_dict = {"('key1', 'key2')": 'meaning', "('key22', 'key13')": 'mean2'}
for k,v in bigram_dict.items():
bigram_dict[literal_eval(k)] = v
</code></pre>
<p>Or to create a new dict, just use the same logic with a <em>dict comprehension</em>:</p>
<pre><code>{literal_eval(k):v for k,v in bigram_dict.items()}
</code></pre>
<p>Both will give you:</p>
<pre><code>{('key1', 'key2'): 'meaning', ('key22', 'key13'): 'mean2'}
</code></pre>
| 3 | 2016-10-09T12:46:02Z | [
"python",
"nltk"
] |
Remove Quotation marks from a dictionary | 39,943,765 | <p>I have a dictionary of bigrams, obtained by importing a csv and transforming it to a dictionary:</p>
<pre><code>bigram_dict = {"('key1', 'key2')": 'meaning', "('key22', 'key13')": 'mean2'}
</code></pre>
<p>I want keys' dictionary to be without quotation marks, i.e.:</p>
<pre><code>desired_bigram_dict={('key1', 'key2'): 'meaning', ('key22', 'key13'): 'mean2'}
</code></pre>
<p>Would you please suggest me how to do this?</p>
| 2 | 2016-10-09T12:42:49Z | 39,943,789 | <p>This can be done using a dictionary comprehension, where you call <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval">literal_eval</a> on the key:</p>
<pre><code>from ast import literal_eval
bigram_dict = {"('key1', 'key2')": 'meaning', "('key22', 'key13')": 'mean2'}
res = {literal_eval(k): v for k,v in bigram_dict.items()}
</code></pre>
<p>Result:</p>
<pre><code>{('key22', 'key13'): 'mean2', ('key1', 'key2'): 'meaning'}
</code></pre>
| 6 | 2016-10-09T12:46:20Z | [
"python",
"nltk"
] |
Finding the date in a year if i have a given number in Python | 39,943,809 | <p>I have two integers, one represents the year and one is the number of the day in that year.
Example: 2004 and 68</p>
<p>I have to find a way to turn the 68 into 8.03.2004</p>
<p>I just started using <strong>Python</strong> and I don't really know how to use the datetime command. If anyone could give me some tips it would be nice ;)</p>
| 0 | 2016-10-09T12:48:40Z | 39,943,858 | <p>You can use <code>datetime.timedelta</code> to advance from the beggining of year:</p>
<pre><code>from datetime import datetime, timedelta
# we start from day 1, not day 0, so we need to substract one day
print(datetime(2004, 1, 1) + timedelta(days=68 - 1))
# 2004-03-08 00:00:00
</code></pre>
| 3 | 2016-10-09T12:54:53Z | [
"python",
"date",
"datetime"
] |
Finding the date in a year if i have a given number in Python | 39,943,809 | <p>I have two integers, one represents the year and one is the number of the day in that year.
Example: 2004 and 68</p>
<p>I have to find a way to turn the 68 into 8.03.2004</p>
<p>I just started using <strong>Python</strong> and I don't really know how to use the datetime command. If anyone could give me some tips it would be nice ;)</p>
| 0 | 2016-10-09T12:48:40Z | 39,943,887 | <p>One way to calculate it:</p>
<pre><code>import datetime
year = 2004
day_of_year = 68
print datetime.date(year,1,1) + datetime.timedelta(days=day_of_year-1)
</code></pre>
| 1 | 2016-10-09T12:57:55Z | [
"python",
"date",
"datetime"
] |
Get the particular rows in Python | 39,943,874 | <p>I have two csv files. </p>
<p>One is as follows:</p>
<pre><code>"CONS_NO","DATA_DATE","KWH_READING","KWH_READING1","KWH"
"1652714033","2015/1/12","4747.3800","4736.8000","10.5800"
"3332440062","2015/1/12","408.6800","407.8200","0.8600"
"7804314033","2015/1/12","1794.3500","1792.5000","1.8500"
"0114314033","2015/1/12","3525.2000","3519.4400","5.7600"
"1742440062","2015/1/12","3097.1900","3091.4100","5.7800"
"8230100023","2015/1/12","1035.0500","1026.8400","8.2100"
</code></pre>
<p>About six million rows in all.</p>
<p>The other is as follows:</p>
<pre><code>6360609057
8771218657
1338004100
2500009393
9184968250
9710581700
8833903141
</code></pre>
<p>About 10 thousand rows in all.</p>
<p>The second csv file has the CONS_NO only. I want to find the rows in the first csv file corresponding to the number in the second csv file; and delete the other rows in the first csv file in Python.</p>
| -1 | 2016-10-09T12:56:31Z | 39,947,950 | <p>You can merge the two <code>DataFrame</code> using the merge method in <code>pandas</code>.</p>
<p>I change your example data to the following:</p>
<p><code>test1.csv</code> is:</p>
<pre><code>"CONS_NO","DATA_DATE","KWH_READING","KWH_READING1","KWH"
"1652714033","2015/1/12","4747.3800","4736.8000","10.5800"
"3332440062","2015/1/12","408.6800","407.8200","0.8600"
"7804314033","2015/1/12","1794.3500","1792.5000","1.8500"
"8833903141","2015/1/12","3525.2000","3519.4400","5.7600"
"1742440062","2015/1/12","3097.1900","3091.4100","5.7800"
"8833903141","2015/1/12","1035.0500","1026.8400","8.2100"
</code></pre>
<p>`test2.csv' is:</p>
<pre><code>6360609057
8771218657
1338004100
2500009393
9184968250
9710581700
8833903141
</code></pre>
<p>you can now merge them using the following code:</p>
<pre><code>import pandas as pd
df1 = pd.read_csv('test1.csv')
df2 = pd.read_csv('test2.csv', names=['CONS_NO'])
pd.merge(df1, df2, on='CONS_NO')
</code></pre>
<p>it gives the following output:</p>
<pre><code> CONS_NO DATA_DATE KWH_READING KWH_READING1 KWH
0 8833903141 2015/1/12 3525.20 3519.44 5.76
1 8833903141 2015/1/12 1035.05 1026.84 8.21
</code></pre>
| 0 | 2016-10-09T20:00:22Z | [
"python",
"csv",
"pandas",
"numpy"
] |
Django specific permissions for users | 39,943,917 | <p>for example i have a model with booleanfield</p>
<pre><code>class Item(BaseModel):
name = models.CharField(max_length=255)
pending = models.BooleanField(default=False)
</code></pre>
<p>if user creates new item from admin panel pending field is false and this item won't display on website until other user set this field into True, but this user mustn't be allowed to make change on pending field on his items but he can do this activity on other users items. any solutions?</p>
| -1 | 2016-10-09T13:01:55Z | 39,944,511 | <p>There are a number of ways to implement this, depending on how you are ultimately going to end up using it. The most straightforward is to add a foreignkey on your Item to the user (assuming you use django auth).</p>
<pre><code>from django.contrib.auth.models import User
class Item(BaseModels):
created_by = models.ForeignKey(User)
name = models.CharField(max_length=255)
pending = models.BooleanField(default=False)
</code></pre>
<p>assuming this only ever gets exposed via views, then you can just do:</p>
<pre><code>def some_view(request):
if item_being_edited.created_by = request.user and not item_being_edited.pending:
#rejection goes here
#do stuff
</code></pre>
<p>as a sidenote, change your pending field. Either have pending = True mean an item is pending, or have it to be approved = False. It will make things easier later if it makes sense to read it in your head without gymnastics.</p>
| 0 | 2016-10-09T14:09:47Z | [
"python",
"django"
] |
Cannot install obspy correctly | 39,943,974 | <p>It could be that obspy is installed, but I've missed a step off the installation process somewhere or some other issue. But in any case I followed the instructions as per this <a href="https://github.com/obspy/obspy/wiki/Installation-on-Mac-OS-X-using-Macports" rel="nofollow">link</a> and since I already have installed anacondas, I used:</p>
<pre><code>sudo port install py27-obspy
sudo port select python python27
</code></pre>
<p>then when finished...</p>
<pre><code>pip install obspy
</code></pre>
<p>Then, when running a basic python script in order to test the obspy library I receive import errors: </p>
<pre><code>ImportError: No module named obspy.imaging.mopad_wrapper
</code></pre>
<p>I tried importing the library in my python shell which gave this output:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/obspy/__init__.py", line 40, in <module>
from obspy.core.utcdatetime import UTCDateTime # NOQA
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/obspy/core/__init__.py", line 119, in <module>
from obspy.core.utcdatetime import UTCDateTime
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/obspy/core/utcdatetime.py", line 20, in <module>
from obspy.core.util.decorator import deprecated
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/obspy/core/util/__init__.py", line 41, in <module>
from obspy.core.util.testing import add_doctests, add_unittests
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/obspy/core/util/testing.py", line 28, in <module>
from lxml import etree
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lxml/etree.so, 2): Library not loaded: libxml2.2.dylib
Referenced from: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lxml/etree.so
Reason: Incompatible library version: etree.so requires version 12.0.0 or later, but libxml2.2.dylib provides version 10.0.0
</code></pre>
<p>Has anyone tried installing the obspy library and if so, did you encounter any issues getting this to work?</p>
| 0 | 2016-10-09T13:08:00Z | 39,962,538 | <p>If you are using anaconda, you will need to install <code>obspy</code> using <code>conda install</code></p>
<p><code>conda install --channel https://conda.anaconda.org/obspy obspy</code></p>
<hr>
<p><strong>TL;DR</strong></p>
<p>Since it is not in their default repository, you need to use the search function to find it:</p>
<p><code>anaconda search -t conda obspy</code></p>
<p>to find all of the related packages. For <code>obspy</code> the search returns:</p>
<pre><code>Using Anaconda Cloud api site https://api.anaconda.org
Run 'anaconda show <USER/PACKAGE>' to get more details:
Packages:
Name | Version | Package Types | Platforms
------------------------- | ------ | --------------- | ---------------
auto/obspydmt | 0.4.0 | conda | linux-64
: https://github.com/kasra-hosseini/obspyDMT
conda-forge/obspy | 1.0.2 | conda | linux-64, win-32, win-64, osx-64
krisvanneste/obspy | 0.9.2 | conda | win-64
mbyt/obspy | 0.10.0 | conda | linux-64
obspy/obspy | 1.0.2 | conda, pypi | linux-64, win-32, win-64, linux-32, osx-64
: ObsPy: A Python Toolbox for seismology/seismological observatories.
Found 5 packages
</code></pre>
<p>Then, it instructs you to use <code>anaconda show obspy/obspy</code> for more info about the package, which also gives the install instructions.</p>
<pre><code>Using Anaconda Cloud api site https://api.anaconda.org
Name: obspy
Summary: ObsPy: A Python Toolbox for seismology/seismological observatories.
Access: public
Package Types: conda, pypi
Versions:
+ 0.10.0rc1
+ 0.10.0
+ 0.0.0+archive
+ 0.10.1rc1
+ 0.10.1rc2
+ 0.10.1
+ 0.10.2
+ 1.0.0
+ 1.0.1
+ 1.0.2
To install this package with conda run:
conda install --channel https://conda.anaconda.org/obspy obspy
To install this package with pypi run:
pip install -i https://pypi.anaconda.org/obspy/simple obspy
</code></pre>
| 0 | 2016-10-10T16:17:50Z | [
"python",
"installation",
"anaconda"
] |
Python. What str.attribute could be used in key argument of method sort? set.sort(key) | 39,944,003 | <p>I'm a newbie just reading Lutz, so the example is partly from that book:</p>
<pre><code>l = ['aBe', 'ABD', 'abc'] #the following listing works ok
l.sort(key=str.lower)
l
>>>['abc', 'ABD', 'aBe']
</code></pre>
<p>And the quesition is what str.attribute could be used in that case?</p>
<pre><code>l.sort(key=str.replace('Be', 'aa')) #why does not this works for example?
</code></pre>
<p>Thanks a lot for the answers, please don't judge harshly;)</p>
| 1 | 2016-10-09T13:11:38Z | 39,944,097 | <p>As I commented, the key must be a callable, to do what you are trying to do you could use a <em>lambda</em> with chained <code>str.replace</code> calls like <code>x.replace("B","a").replace("e","a")</code> but a better solution would be to use <em>str.translate</em>:</p>
<pre><code>tbl = {ord("B"):"a", ord("e"):"a"}
l.sort(key=lambda x: x.translate(tbl))
</code></pre>
<p>Or use <a href="https://docs.python.org/3.6/library/operator.html#operator.methodcaller" rel="nofollow">operator.methodcaller</a> as <em>Bakuriu</em> commented:</p>
<pre><code>from operator import methodcaller
key=methodcaller('translate', tbl)
</code></pre>
<p>If you just want to match the full substring then it is a simple <code>l.sort(key=lambda x: x.replace("Be","aa"))</code> or <code>l.sort(key=methodcaller("replace","Be","aa"))</code>.</p>
| 2 | 2016-10-09T13:21:22Z | [
"python",
"sorting",
"set"
] |
How to set timeout for thread in case of no response and terminate the thread? | 39,944,011 | <p>Let's say we have a code sample as below which prints <code>hello, world</code> after 5 seconds. I want a way to check if <code>Timer</code> thread took more than 5 seconds then terminate the thread.</p>
<pre><code>from threading import Timer
from time import sleep
def hello():
sleep(50)
print "hello, world"
t = Timer(5, hello)
# after 5 seconds, "hello, world" will be printed
t.start()
</code></pre>
<p>In the above code block <code>hello</code> will take more than 5 seconds to process.</p>
<p>consider <code>hello</code> function, a call to outside server that returns no response and even no exception for timeout or anything! I wanted to simulate the issue with <code>sleep</code> function.</p>
| 1 | 2016-10-09T13:13:06Z | 39,944,130 | <p>You can use <code>signal</code> and call its <code>alarm</code> method. An exception (which you can handle) will be raised after the timeout time has passed. See an (incomplete) example below. </p>
<pre><code>import signal
class TimeoutException (Exception):
pass
def signalHandler (signum, frame):
raise TimeoutException ()
timeout_duration = 5
signal.signal (signal.SIGALRM, signalHandler)
signal.alarm (timeout_duration)
try:
"""Do something that has a possibility of taking a lot of time
and exceed the timeout_duration"""
except TimeoutException as exc:
"Notify your program that the timeout_duration has passed"
finally:
#Clean out the alarm
signal.alarm (0)
</code></pre>
<p>You can read more about Python's <code>signal</code> here <a href="https://docs.python.org/2/library/signal.html" rel="nofollow">https://docs.python.org/2/library/signal.html</a>.</p>
| 2 | 2016-10-09T13:25:36Z | [
"python",
"multithreading"
] |
Checkbutton and Scale conflict | 39,944,055 | <p>I have a problem with my Checkbutton widget. Every time I select it the slider on the scale widget above moves by itself to 1, deselecting the Checkbutton widget will set the Scale widget to 0. Both widgets are not intended to be related with each other in any way yet for some reason changing values in one of them affect the other. Can anyone explain to me why this is happening and how can I avoid such problems in the future?</p>
<pre><code> tk.Label(f7, text=("JakoÅÄ")).grid(row=3, column=0)
self.jakosc=tk.Scale(f7, orient='horizontal', variable=jakosc)
self.jakosc.grid(row=3, column=1)
self.rozpinany_sweter=tk.IntVar()
tk.Checkbutton(f7, text='Rozpinany',variable=rozpinany_sweter).grid(row=4, column=1)
</code></pre>
<p><a href="http://i.stack.imgur.com/b5UDf.png" rel="nofollow">In this example</a>
the slider is set to 56, after checking the checkbox on the slider sets itself to 1. </p>
<p>EDIT: MCVE provided: </p>
<pre><code>import tkinter as tk
from tkinter import ttk as ttk
RS=0
Q=0
class Aplikacja(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.grid()
self.create_widgets()
def create_widgets(self):
self.jakosc=tk.Scale(root, orient='horizontal', variable=Q)
self.jakosc.grid()
self.rozpinany_sweter=tk.IntVar()
tk.Checkbutton(root, variable=RS).grid()
root= tk.Tk()
app= Aplikacja(root)
root.mainloop()
</code></pre>
| -1 | 2016-10-09T13:16:37Z | 39,945,467 | <p>The <code>variable=</code> parameter to Tk widgets MUST be a Tk variable (created by Tk.IntVar() or similar calls). Your code passes Q and RS, which are ordinary Python variables; the one Tk variable you create is pointless, because you never use it anywhere. Tk variables have a special ability not possessed by Python variables: they can have watchers attached to them, which allows widgets to automatically update themselves when the variable is modified.</p>
<p>The Python representation of a Tk variable is basically just the Tk name of the variable. Both Q and RS happen to have the same value, so they're both referring to the same variable on the Tk side - that's why your scale and checkbox appear to be linked.</p>
| 0 | 2016-10-09T15:49:05Z | [
"python",
"tkinter"
] |
Read a title in HTML with Python script | 39,944,082 | <p>I have a small problem, I want to read a title in a HTML document, this is working so far, that I get the result of the string. Im using the libraray bs4 BeautifulSoup and urllib.request.</p>
<p><a href="http://i.stack.imgur.com/YuATM.png" rel="nofollow"><img src="http://i.stack.imgur.com/YuATM.png" alt="HTML Code"></a></p>
<p>You can see in the first image that the HTML code has a gap and this gap is even visible in the commandline, but I want only the title.
So how I can remove the HTML codes in the Output?</p>
<p><a href="http://i.stack.imgur.com/0W4cF.png" rel="nofollow"><img src="http://i.stack.imgur.com/0W4cF.png" alt="Command line Output"></a></p>
<p>Edit:
Here is the Python code you are looking for and which I have used</p>
<pre><code>import urllib.request
from bs4 import BeautifulSoup
import codecs
htmlfile = urllib.request.urlopen("https://www.packtpub.com/packt/offers/free-learning")
htmltext = htmlfile.read()
print(htmltext)
soup = BeautifulSoup(htmltext, 'html.parser')
print(soup)
f = codecs.open("freebook.html", "w", "utf-8")
f.write(soup.get())
f.close()
</code></pre>
<p>I hope this code help you</p>
| -2 | 2016-10-09T13:19:17Z | 39,944,182 | <p>Without example code it's hard to give you an exact solution, but you can use <code>h2.get_text(strip=true)</code> where <code>h2</code> is a variable pointing to the <code>h2</code> element yo want to print out.</p>
<p>This is the documentation on <code>get_text()</code> - <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text</a></p>
<p>Share your code and <code>html</code> if you need more help</p>
| 0 | 2016-10-09T13:31:00Z | [
"python",
"html",
"beautifulsoup",
"urllib",
"bs4"
] |
Read a title in HTML with Python script | 39,944,082 | <p>I have a small problem, I want to read a title in a HTML document, this is working so far, that I get the result of the string. Im using the libraray bs4 BeautifulSoup and urllib.request.</p>
<p><a href="http://i.stack.imgur.com/YuATM.png" rel="nofollow"><img src="http://i.stack.imgur.com/YuATM.png" alt="HTML Code"></a></p>
<p>You can see in the first image that the HTML code has a gap and this gap is even visible in the commandline, but I want only the title.
So how I can remove the HTML codes in the Output?</p>
<p><a href="http://i.stack.imgur.com/0W4cF.png" rel="nofollow"><img src="http://i.stack.imgur.com/0W4cF.png" alt="Command line Output"></a></p>
<p>Edit:
Here is the Python code you are looking for and which I have used</p>
<pre><code>import urllib.request
from bs4 import BeautifulSoup
import codecs
htmlfile = urllib.request.urlopen("https://www.packtpub.com/packt/offers/free-learning")
htmltext = htmlfile.read()
print(htmltext)
soup = BeautifulSoup(htmltext, 'html.parser')
print(soup)
f = codecs.open("freebook.html", "w", "utf-8")
f.write(soup.get())
f.close()
</code></pre>
<p>I hope this code help you</p>
| -2 | 2016-10-09T13:19:17Z | 39,944,219 | <p>It is my understanding that you have the text content of an h2 tag in a variable, and you want to strip whitespace. So you can use <code>strip=true</code> in bs4 or <code>title = title.strip()</code>. </p>
| 0 | 2016-10-09T13:34:27Z | [
"python",
"html",
"beautifulsoup",
"urllib",
"bs4"
] |
How to set sigalarm to repeat over and over again in linux? | 39,944,232 | <p>I'm trying to make alarm work over and over again.</p>
<p>My handler is</p>
<pre><code>def handler_SIGALRM(signum, frame):
print "waiting"
signal.alarm(2)
</code></pre>
<p>The alarm work only once, even though every time I set it again.
In my code I also use sigchld and sys.exit after the child working.</p>
<p>I'm running it with cygwin.</p>
<p>EDIT:
I need to write a code that will print "waiting" every second, with sigalarm and not loops</p>
<p>I'm an idiot, I edited the wrong code</p>
| 0 | 2016-10-09T13:35:20Z | 39,944,349 | <p>You put your <code>signal.alarm(2)</code> in a wrong place. See my example below.</p>
<pre><code>import time
import signal
class TimeoutException (Exception):
pass
def signalHandler (signum, frame):
raise TimeoutException ()
timeout_duration = 5
signal.signal (signal.SIGALRM, signalHandler)
for i in range (5):
signal.alarm (timeout_duration)
try:
"""Do something that has a possibility of taking a lot of time
and exceed the timeout_duration"""
time.sleep (20)
except TimeoutException as exc:
print "Notify your program that the timeout_duration has passed"
finally:
#Clean out the alarm
signal.alarm (0)
</code></pre>
| 0 | 2016-10-09T13:48:53Z | [
"python",
"cygwin",
"signals",
"posix"
] |
Reading a textfile into a String | 39,944,293 | <p>I'm just starting to learn python and have a textfile that looks like this:</p>
<pre><code>Hello
World
Hello
World
</code></pre>
<p>And I want to add the numbers '55' to the beggining and end of every string that starts with 'hello'</p>
<p>The numbers '66' to the beggining and every of every string that starts with 'World'</p>
<p>etc</p>
<p>So my final file should look like this:</p>
<pre><code>55Hello55
66World66
55Hello55
66World66
</code></pre>
<p>I'm reading the file in all at once, storing it in a string, and then trying to append accordingly</p>
<pre><code>fp = open("test.txt","r")
strHolder = fp.read()
print(strHolder)
if 'Hello' in strHolder:
strHolder = '55' + strHolder + '55'
if 'World' in strHolder:
strHolder = '66' + strHolder + '66'
print(strHolder)
fp.close()
</code></pre>
<p>However, my string values '55' and '66' are always being added to the front of the file and end of the file, not the front of a certain string and to the end of the string, where I get this output of the string:</p>
<pre><code>6655Hello
World
Hello
World
5566
</code></pre>
<p>Any help would be much appreciated.</p>
| 1 | 2016-10-09T13:42:19Z | 39,944,332 | <p>You are reading the whole file at once with <code>.read()</code>.</p>
<p>You can read it line by line in a <code>for</code> loop.</p>
<pre><code>new_file = []
fp = open("test.txt", "r")
for line in fp:
line = line.rstrip("\n") # The string ends in a newline
# str.rstrip("\n") removes newlines at the end
if "Hello" in line:
line = "55" + line + "55"
if "World" in line:
line = "66" + line + "66"
new_file.append(line)
fp.close()
new_file = "\n".join(new_file)
print(new_file)
</code></pre>
<p>You could do it all at once, by reading the whole file and splitting by "\n" (newline)</p>
<pre><code>new_file = []
fp = open("text.txt")
fp_read = fp.read()
fp.close()
for line in fp_read.split("\n"):
if "Hello" # ...
</code></pre>
<p>but this would load the whole file into memory at once, while the for loop only loads line by line (So this may not work for larger files).</p>
<p>The behaviour of this is that if the line has "Hello" in it, it will get "55" before and after it (even if the line is " sieohfoiHellosdf ") and the same for "World", and if it has both "Hello" and "World" (e.g. "Hello, World!" or "asdifhoasdfhHellosdjfhsodWorldosadh") it will get "6655" before and after it.</p>
<p>Just as a side note: You should use <code>with</code> to open a file as it makes sure that the file is closed later.</p>
<pre><code>new_file = []
with open("test.txt") as fp: # "r" mode is default
for line in fp:
line = line.rstrip("\n")
if "Hello" in line:
line = "55" + line + "55"
if "World" in line:
line = "66" + line + "66"
new_file.append(line)
new_file = "\n".join(new_file)
print(new_file)
</code></pre>
| 2 | 2016-10-09T13:47:17Z | [
"python"
] |
Reading a textfile into a String | 39,944,293 | <p>I'm just starting to learn python and have a textfile that looks like this:</p>
<pre><code>Hello
World
Hello
World
</code></pre>
<p>And I want to add the numbers '55' to the beggining and end of every string that starts with 'hello'</p>
<p>The numbers '66' to the beggining and every of every string that starts with 'World'</p>
<p>etc</p>
<p>So my final file should look like this:</p>
<pre><code>55Hello55
66World66
55Hello55
66World66
</code></pre>
<p>I'm reading the file in all at once, storing it in a string, and then trying to append accordingly</p>
<pre><code>fp = open("test.txt","r")
strHolder = fp.read()
print(strHolder)
if 'Hello' in strHolder:
strHolder = '55' + strHolder + '55'
if 'World' in strHolder:
strHolder = '66' + strHolder + '66'
print(strHolder)
fp.close()
</code></pre>
<p>However, my string values '55' and '66' are always being added to the front of the file and end of the file, not the front of a certain string and to the end of the string, where I get this output of the string:</p>
<pre><code>6655Hello
World
Hello
World
5566
</code></pre>
<p>Any help would be much appreciated.</p>
| 1 | 2016-10-09T13:42:19Z | 39,944,350 | <p>You need to iterate over each line of the file in order to get the desired result. In your code you are using <code>.read()</code>, instead use <code>.readlines()</code> to get list of all lines.</p>
<p>Below is the sample code:</p>
<pre><code>lines = []
with open("test.txt", "r") as f:
for line in f.readlines(): # < Iterate over each line
if line.startswith("Hello"): # <-- check if line starts with "Hello"
line = "55{}55".format(line)
elif line.startswith("World"):
line = "66{}66".format(line)
lines.append(line)
print "\n".join(lines)
</code></pre>
<p>Why to use <code>with</code>? Check <a href="https://docs.python.org/3/whatsnew/2.6.html#pep-343-the-with-statement" rel="nofollow">Python doc</a>:</p>
<blockquote>
<p>The âwithâ statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, Iâll discuss the statement as it will commonly be used. In the next section, Iâll examine the implementation details and show how to write objects for use with this statement.</p>
<p>The âwithâ statement is a control-flow structure whose basic structure is:</p>
<p>with expression [as variable]: with-block</p>
<p>The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has <strong>enter</strong>() and <strong>exit</strong>() methods).</p>
</blockquote>
| 0 | 2016-10-09T13:48:54Z | [
"python"
] |
Reading a textfile into a String | 39,944,293 | <p>I'm just starting to learn python and have a textfile that looks like this:</p>
<pre><code>Hello
World
Hello
World
</code></pre>
<p>And I want to add the numbers '55' to the beggining and end of every string that starts with 'hello'</p>
<p>The numbers '66' to the beggining and every of every string that starts with 'World'</p>
<p>etc</p>
<p>So my final file should look like this:</p>
<pre><code>55Hello55
66World66
55Hello55
66World66
</code></pre>
<p>I'm reading the file in all at once, storing it in a string, and then trying to append accordingly</p>
<pre><code>fp = open("test.txt","r")
strHolder = fp.read()
print(strHolder)
if 'Hello' in strHolder:
strHolder = '55' + strHolder + '55'
if 'World' in strHolder:
strHolder = '66' + strHolder + '66'
print(strHolder)
fp.close()
</code></pre>
<p>However, my string values '55' and '66' are always being added to the front of the file and end of the file, not the front of a certain string and to the end of the string, where I get this output of the string:</p>
<pre><code>6655Hello
World
Hello
World
5566
</code></pre>
<p>Any help would be much appreciated.</p>
| 1 | 2016-10-09T13:42:19Z | 39,944,413 | <p>once you have read the file:</p>
<pre><code>read_file = read_file.replace('hello','55hello55')
</code></pre>
<p>It'll replace all hellos with 55hello55</p>
<p>and use <code>with open(text.txt, 'r' ) as file_hndler:</code></p>
| 0 | 2016-10-09T13:57:43Z | [
"python"
] |
Reading a textfile into a String | 39,944,293 | <p>I'm just starting to learn python and have a textfile that looks like this:</p>
<pre><code>Hello
World
Hello
World
</code></pre>
<p>And I want to add the numbers '55' to the beggining and end of every string that starts with 'hello'</p>
<p>The numbers '66' to the beggining and every of every string that starts with 'World'</p>
<p>etc</p>
<p>So my final file should look like this:</p>
<pre><code>55Hello55
66World66
55Hello55
66World66
</code></pre>
<p>I'm reading the file in all at once, storing it in a string, and then trying to append accordingly</p>
<pre><code>fp = open("test.txt","r")
strHolder = fp.read()
print(strHolder)
if 'Hello' in strHolder:
strHolder = '55' + strHolder + '55'
if 'World' in strHolder:
strHolder = '66' + strHolder + '66'
print(strHolder)
fp.close()
</code></pre>
<p>However, my string values '55' and '66' are always being added to the front of the file and end of the file, not the front of a certain string and to the end of the string, where I get this output of the string:</p>
<pre><code>6655Hello
World
Hello
World
5566
</code></pre>
<p>Any help would be much appreciated.</p>
| 1 | 2016-10-09T13:42:19Z | 39,944,564 | <p>To read a <strong>text</strong> file, I recommend the following way which is compatible with Python 2 & 3:</p>
<pre><code>import io
with io.open("test", mode="r", encoding="utf8") as fd:
...
</code></pre>
<p>Here, I make the assumption that your file use uft8 encoding.</p>
<p>Using a <code>with</code> statement make sure the file is closed at the end of reading even if a error occurs (an exception). To learn more about context manager, take a look at the <a href="https://docs.python.org/2/library/contextlib.html" rel="nofollow">Context Library</a>. </p>
<p>There are several ways to read a text file:</p>
<ul>
<li>read the whole file with: <code>fd.read()</code>, or</li>
<li>read line by line with a loop: <code>for line in fd</code>.</li>
</ul>
<p>If you read the whole file, you'll need to split the lines (see <a href="https://docs.python.org/2/library/stdtypes.html?highlight=splitlines#str.splitlines" rel="nofollow">str.splitlines</a>. Here are the two solutions:</p>
<pre><code>with io.open("test", mode="r", encoding="utf8") as fd:
content = fd.read()
for line in content.splilines():
if "Hello" in line:
print("55" + line + "55")
if "World" in line:
print("66" + line + "66")
</code></pre>
<p>Or</p>
<pre><code>with io.open("test", mode="r", encoding="utf8") as fd:
for line in content.splilines():
line = line[:-1]
if "Hello" in line:
print("55" + line + "55")
if "World" in line:
print("66" + line + "66")
</code></pre>
<p>If you need to write the result in another file you can open the output file in write mode and use <code>print(thing, file=out)</code> as follow:</p>
<pre><code>with io.open("test", mode="r", encoding="utf8") as fd:
with io.open("test", mode="w", encoding="utf8") as out:
for line in content.splilines():
line = line[:-1]
if "Hello" in line:
print("55" + line + "55", file=out)
if "World" in line:
print("66" + line + "66", file=out)
</code></pre>
<p>If you use Python 2, you'll need the following directive to use the print function:</p>
<pre><code>from __future__ import print_function
</code></pre>
| 0 | 2016-10-09T14:14:39Z | [
"python"
] |
Python 2.7 Yahoo Finance No Definition Found | 39,944,314 | <p>Hope you are well. I'm Using Python 2.7 and new at it. I'm trying to use yahoo finance API to get information from stocks, here is my code:</p>
<pre><code>from yahoo_finance import Share
yahoo = Share('YHOO')
print yahoo.get_historical('2014-04-25', '2014-04-29')
</code></pre>
<p>This code thoug works once out of 4 attempts, the other 3 times gives me this errors:</p>
<pre><code>YQL Query error: Query failed with error: No Definition found for Table yahoo.finance.quote
</code></pre>
<p>Is there anyway to fix this error so to have the code working 100% of the time?
Thanks.
Warmest regards </p>
| 0 | 2016-10-09T13:45:28Z | 39,944,347 | <p>This is a <em>server-side error</em>. The <code>query.yahooapis.com</code> service appears to be handled by a cluster of machines, and some of those machines appear to be misconfigured. This could be a temporary problem.</p>
<p>I see the same error when accessing the API directly using curl:</p>
<pre><code>$ curl "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20%3D%20%22YHOO%22&format=json&env=store%3a//datatables.org/alltableswithkeys"
{"error":{"lang":"en-US","description":"No definition found for Table yahoo.finance.quote"}}
</code></pre>
<p>Other than retrying in a loop, there is no way to fix this on the Python side:</p>
<pre><code>data = None
for i in range(10): # retry 10 times
try:
yahoo = Share('YHOO')
data = yahoo.get_historical('2014-04-25', '2014-04-29')
break
except yahoo_finance.YQLQueryError:
continue
if data is None:
print 'Failed to retrieve data from the Yahoo service, try again later'
</code></pre>
| 1 | 2016-10-09T13:48:41Z | [
"python",
"yql",
"yahoo-api",
"yahoo-finance"
] |
How to group set of time under distinct date from csv file | 39,944,390 | <p>hi i have just gotten a set of time and date data from csv file using regex:</p>
<pre><code>datePattern = re.compile(r"(\d+/\d+/\d+\s+\d+:\d+)")
for i, line in enumerate(open('sample_data.csv')):
for match in re.finditer(datePattern, line):
date.append(match.groups());
</code></pre>
<p>the output is [('30/06/2016 08:30',), ('20/07/2016 09:30',),
('30/06/2016 07:30',)</p>
<p>How do i turn it into useful information such as listing all the time under the same date such as maybe [('30/06/2016 08:30',07.30),]</p>
| -2 | 2016-10-09T13:54:05Z | 39,944,613 | <p>Try this regex:</p>
<pre><code>r"(\d+/\d+/\d+)\s+(\d+:\d+)"
</code></pre>
<p><a href="https://repl.it/DrqS/2" rel="nofollow">Python code</a> follows, I have used dictionary of lists for such grouping</p>
<pre><code>import re
datePattern = re.compile(r"(\d+/\d+/\d+)\s+(\d+:\d+)")
dateDict =dict()
for i, line in enumerate(open('sample_data.csv')):
for match in re.finditer(datePattern,line):
if match.group(1) in dateDict:
dateDict[match.group(1)].append(match.group(2))
else:
dateDict[match.group(1)] = [match.group(2),]
print(dateDict)
</code></pre>
<p>It will output as follows:</p>
<pre><code>{'10/10/1990': ['12:20', '11:20'], '10/10/1991': ['16:20', '16:20']}
Tested with python 3+
</code></pre>
| 0 | 2016-10-09T14:19:29Z | [
"python",
"regex"
] |
Add shifted integers to list | 39,944,453 | <p>I have a list of integers, which I would like to inflate to include both the current integers, and their values shifted by +1 and -1.</p>
<p>For example, if I have :</p>
<pre><code>l1 = [3, 9, 15]
</code></pre>
<p>I would like the result to be (the order doesn't matter) :</p>
<pre><code>l2 = [2, 3, 4, 8, 9, 10, 14, 15, 16]
</code></pre>
<p>I can achieve it by doing this :</p>
<pre><code>l1 = [3, 9, 15]
l2 = l1[:]
l2.extend([i-1 for i in l1])
l2.extend([i+1 for i in l1])
</code></pre>
<p>However, is there a <strong>shorter / more efficient way</strong> to do this (using <code>numpy</code> if appropriate) ?</p>
<p><em>Please note that I would also like the "inflation" to work asymmetrically and with more than 2 added values, for example with -3, -2 and -1.</em></p>
| 0 | 2016-10-09T14:03:17Z | 39,944,520 | <p>How about this:</p>
<pre><code>l1 = [3, 9, 15]
l2 = [i+j for i in l1 for j in (-1, 0, 1)]
print (l2)
</code></pre>
<p>gives:</p>
<pre><code>[2, 3, 4, 8, 9, 10, 14, 15, 16]
</code></pre>
| 3 | 2016-10-09T14:10:20Z | [
"python",
"list",
"python-3.x",
"numpy"
] |
Add shifted integers to list | 39,944,453 | <p>I have a list of integers, which I would like to inflate to include both the current integers, and their values shifted by +1 and -1.</p>
<p>For example, if I have :</p>
<pre><code>l1 = [3, 9, 15]
</code></pre>
<p>I would like the result to be (the order doesn't matter) :</p>
<pre><code>l2 = [2, 3, 4, 8, 9, 10, 14, 15, 16]
</code></pre>
<p>I can achieve it by doing this :</p>
<pre><code>l1 = [3, 9, 15]
l2 = l1[:]
l2.extend([i-1 for i in l1])
l2.extend([i+1 for i in l1])
</code></pre>
<p>However, is there a <strong>shorter / more efficient way</strong> to do this (using <code>numpy</code> if appropriate) ?</p>
<p><em>Please note that I would also like the "inflation" to work asymmetrically and with more than 2 added values, for example with -3, -2 and -1.</em></p>
| 0 | 2016-10-09T14:03:17Z | 39,944,623 | <p>You may use list comprehension with <a href="http://pythoncentral.io/pythons-range-function-explained/" rel="nofollow"><code>range()</code></a> as:</p>
<pre><code>>>> [item + i for item in l1 for i in range(-1, 2)]
[2, 3, 4, 8, 9, 10, 14, 15, 16]
</code></pre>
| 0 | 2016-10-09T14:20:47Z | [
"python",
"list",
"python-3.x",
"numpy"
] |
Add shifted integers to list | 39,944,453 | <p>I have a list of integers, which I would like to inflate to include both the current integers, and their values shifted by +1 and -1.</p>
<p>For example, if I have :</p>
<pre><code>l1 = [3, 9, 15]
</code></pre>
<p>I would like the result to be (the order doesn't matter) :</p>
<pre><code>l2 = [2, 3, 4, 8, 9, 10, 14, 15, 16]
</code></pre>
<p>I can achieve it by doing this :</p>
<pre><code>l1 = [3, 9, 15]
l2 = l1[:]
l2.extend([i-1 for i in l1])
l2.extend([i+1 for i in l1])
</code></pre>
<p>However, is there a <strong>shorter / more efficient way</strong> to do this (using <code>numpy</code> if appropriate) ?</p>
<p><em>Please note that I would also like the "inflation" to work asymmetrically and with more than 2 added values, for example with -3, -2 and -1.</em></p>
| 0 | 2016-10-09T14:03:17Z | 39,944,636 | <p>With numpy is something like this</p>
<pre><code>value=1
p = np.array([3, 9, 15])
p = np.append(p,[[[i+value,i-value] for i in p]])
</code></pre>
<p>with output sorted:</p>
<pre><code>[2, 3, 4, 8, 9, 10, 14, 15, 16]
</code></pre>
<p>but you want with value 2 show for example in <strong>3</strong> [1,3,5] or [1,2,3,4,5] ?</p>
<p>if you want the second options is something like this</p>
<pre><code>value=2
p = np.array([3, 9, 15])
p = np.append(p,[[[i+range(1,value+1),i-range(1,value+1)] for i in p]])
</code></pre>
<p>output sorted:</p>
<pre><code>[1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17]
</code></pre>
| 0 | 2016-10-09T14:21:20Z | [
"python",
"list",
"python-3.x",
"numpy"
] |
Pickle load: ImportError: No module named doc2vec_ext | 39,944,487 | <p>This is the structure I'm dealing with:</p>
<pre><code>src/
processing/
station_level/
train_paragraph_vectors.py
doc2vec_ext.py
word_embeddings_station_level.py
</code></pre>
<p>I have trained and stored a model in <code>word_embeddings_station_level.py</code> like this:</p>
<pre><code>from src.doc2vec_ext import WeightedDoc2Vec
# ...
model = WeightedDoc2Vec(
# ...
)
train(model, vocab, station_sentences, num_epochs)
# Saving the model -> pickles it
model.save(open(model_file, "w"))
</code></pre>
<p>This is working fine so far. However, I want to load that model in <code>train_paragraph_vectors.py</code> like this:</p>
<pre><code>import sys
from src import doc2vec_ext
sys.modules["doc2vec_ext"] = doc2vec_ext
if __name__ == "__main__":
# ...
model = doc2vec_ext.WeightedDoc2Vec.load(station_level_sentence_vectors)
</code></pre>
<p>but I'm getting:</p>
<pre><code>Traceback (most recent call last):
File "E:/python/kaggle/seizure_prediction/src/processing/station_level/train_paragraph_vectors.py", line 57, in <module>
model = doc2vec_ext.WeightedDoc2Vec.load(station_level_sentence_vectors)
File "C:\Python27\lib\site-packages\gensim\models\word2vec.py", line 1684, in load
model = super(Word2Vec, cls).load(*args, **kwargs)
File "C:\Python27\lib\site-packages\gensim\utils.py", line 248, in load
obj = unpickle(fname)
File "C:\Python27\lib\site-packages\gensim\utils.py", line 911, in unpickle
return _pickle.loads(f.read())
ImportError: No module named doc2vec_ext
</code></pre>
<p><strong>doc2vec_ext.py</strong></p>
<p>Here you can see, that I just inherit from the <code>gensim.models.Doc2Vec</code> class and do some stuff:</p>
<pre><code>class WeightedDoc2Vec(Doc2Vec):
def __init__(self, dm=1,window=5, f_size=0, size=100, min_count=1, negative=0, dbow_words=1, alpha=0.015, workers=8, seed=42, dm_weighted=False, dm_stacked=False):
Doc2Vec.__init__(self,
# Constructor arguments ..
)
# ...
</code></pre>
<p>I don't know what's the problem here. I've tried to do the <code>sys.modules[]</code> but it's still not working properly.</p>
<p>How can I load my stored model?</p>
<hr>
<p><strong>Important:</strong></p>
<p>I noticed that I can't even load from the same module. If I try to load the model in the file where it was created (here <code>word_embeddings_station_level.py</code>) it's still not working giving me the same error.</p>
| 0 | 2016-10-09T14:07:01Z | 39,946,944 | <p>When saving and loading binary data like a pickle, you need to use binary mode, not text mode.</p>
<pre><code>model.save(open(model_file, "wb")) # 'b' for binary
</code></pre>
| 0 | 2016-10-09T18:17:26Z | [
"python",
"pickle",
"gensim"
] |
"Last modified by" (user name, not time) attribute for xlsx using Python | 39,944,495 | <p>I need to be able to view the "last modified by" attribute for xlsx files using Python. I've been able to do for docx files, and was hoping that the architecture would be similar enough to use on other Office applications, but unfortunately not. Does anybody know of a similar module for xlsx?</p>
<p>This is the script to view the field using python-docx:</p>
<pre><code>from docx import Document
import docx
document = Document('mine.docx')
core_properties = document.core_properties
print(core_properties.last_modified_by)
</code></pre>
<p>I'm using Python 3.4 and docx 0.8.6 here.</p>
| 0 | 2016-10-09T14:08:31Z | 39,944,616 | <pre><code>import os
filename = "C:\\test.xlsx"
statsbuf = os.stat(filename)
print "modified:",statsbuf.st_mtime
f = os.path.getmtime('C:\\test.xlsx')
print f
</code></pre>
<p>since the beginning </p>
| 0 | 2016-10-09T14:20:01Z | [
"python",
"excel",
"xlsx",
"python-docx"
] |
What to do when Jupyter suddenly hangs? | 39,944,576 | <p>I'm using Jupyter notebook 4.0.6 on OSX El Capitan. </p>
<p>Once in a while I'll start running a notebook and the cell will simply hang, with a <code>[ * ]</code> next to it and no output.</p>
<p>When this happens, I find that only killing Jupyter at the command line and restarting it solves the problem. Relaunching the kernel doesn't help. </p>
<p>Has anyone else had this problem? If so, any tips?</p>
| 0 | 2016-10-09T14:16:02Z | 39,946,960 | <p>I use Jupyter Notebook 4.2.3 on OSX El Capitan, so I might not be really helpful, but at least I can try to guess. </p>
<p>[*] basically means that something is going on, so if you are running a script with some complicated computations, you'd better wait a little bit. </p>
<p>To make sure, you may try to use a loading bar that can help you to control the process. A good one is suggested <a href="https://github.com/noamraph/tqdm" rel="nofollow">here</a>.
Otherwise, you can check out other notebooks with loading bars illustrating any processes by default. <a href="https://zeppelin.apache.org/" rel="nofollow">Apache Zeppelin</a> should have such feature. </p>
| 0 | 2016-10-09T18:18:46Z | [
"python",
"osx",
"jupyter-notebook"
] |
.clear() for list not working - python | 39,944,586 | <p>I am writing some code that is supposed to find the prime factorization of numbers. The main function increments through numbers; I'm doing that because I want to use the code to conduct timing experiments. I don't mind it not being super-efficient, part of the project for me will be making it more efficient myself. It is also not yet totally complete (for example, it doesn't simplify the prime factorization). I have tested all of the functions except the main function and they have worked, so there isn't a problem with those. </p>
<p>My code is </p>
<pre><code>import math
import time
primfac=[]
def primes(n):
sieve = [True] * n
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
return [2] + [i for i in xrange(3,n,2) if sieve[i]]
def factfind(lsp,n): #finds factors of n among primes
for i in lsp:
if n%i==0:
primfac.append(i)
else:
i+=1
def primfacfind(n1,n2):
while n1 < n2:
n = n1
time_start = time.clock()
factfind(primes(n),n)
print primfac
time_elapsed = time.clock() - time_start
print "time:", time_elapsed
primfac.clear()
n1+=1
print primfacfind(6,15)
</code></pre>
<p>And running it gives the output </p>
<pre><code>[2, 3]
time: 7.5e-05
Traceback (most recent call last):
File "python", line 43, in <module>
File "python", line 39, in primfacfind
AttributeError: 'list' object has no attribute 'clear'
</code></pre>
<p>And I'm not really sure what is wrong. It is giving the right numbers for the prime factorization and it is printing the time, but it can't seem to clear the list. Commenting out the line <code>primfac.clear()</code> has it working.</p>
<p>Any help would be appreciated. Thanks!</p>
| 0 | 2016-10-09T14:17:15Z | 39,944,681 | <p>Python's <code>list</code> does not have a <code>clear</code> method until Python 3.x. Your code will not work in Python 2.x or earlier. You can either create a new list or delete all the contents of the old list.</p>
<pre><code>#create a new list
primfac = []
#or delete all the contents of the old list
del primfac [:]
</code></pre>
| 0 | 2016-10-09T14:26:35Z | [
"python",
"list",
"runtime-error"
] |
.clear() for list not working - python | 39,944,586 | <p>I am writing some code that is supposed to find the prime factorization of numbers. The main function increments through numbers; I'm doing that because I want to use the code to conduct timing experiments. I don't mind it not being super-efficient, part of the project for me will be making it more efficient myself. It is also not yet totally complete (for example, it doesn't simplify the prime factorization). I have tested all of the functions except the main function and they have worked, so there isn't a problem with those. </p>
<p>My code is </p>
<pre><code>import math
import time
primfac=[]
def primes(n):
sieve = [True] * n
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
return [2] + [i for i in xrange(3,n,2) if sieve[i]]
def factfind(lsp,n): #finds factors of n among primes
for i in lsp:
if n%i==0:
primfac.append(i)
else:
i+=1
def primfacfind(n1,n2):
while n1 < n2:
n = n1
time_start = time.clock()
factfind(primes(n),n)
print primfac
time_elapsed = time.clock() - time_start
print "time:", time_elapsed
primfac.clear()
n1+=1
print primfacfind(6,15)
</code></pre>
<p>And running it gives the output </p>
<pre><code>[2, 3]
time: 7.5e-05
Traceback (most recent call last):
File "python", line 43, in <module>
File "python", line 39, in primfacfind
AttributeError: 'list' object has no attribute 'clear'
</code></pre>
<p>And I'm not really sure what is wrong. It is giving the right numbers for the prime factorization and it is printing the time, but it can't seem to clear the list. Commenting out the line <code>primfac.clear()</code> has it working.</p>
<p>Any help would be appreciated. Thanks!</p>
| 0 | 2016-10-09T14:17:15Z | 39,944,686 | <p>The <code>list.clear()</code> method was added in Python 3.3. The equivalent can be achieved in earlier versions by <code>del primfac[:]</code> instead.</p>
| 3 | 2016-10-09T14:26:50Z | [
"python",
"list",
"runtime-error"
] |
Is there a really efficient (FAST) way to read large text files in python? | 39,944,594 | <p>I am looking to open and fetch data from a large text file in python as fast as possible (<strong>It almost has 62603143 lines - size 550MB</strong>). As I don't want to stress my computer, I am doing it by following way ,</p>
<pre><code>import time
start = time.time()
for line in open(filePath):
#considering data as last element in file
if data in line:
do_something(data)
end = time.time()
print "processing time = %s" % (count, end-start)
</code></pre>
<p>But as I am doing by above method its taking almost <strong>18 seconds</strong> to read full file ( My computer has <em>Intel i3 processor and 4 GB RAM</em> ). Likewise if file size is more it is taking more time and considering user point of view its very large. I read lot of opinions on forums, referred multiple <em>Stack Overflow</em> questions but didn't get the fast and efficient way to read and fetch the data from large files. Is there really any way in Python to read large text files in few seconds?</p>
| -3 | 2016-10-09T14:18:03Z | 39,944,662 | <p>No, there is no faster way of processing a file line by line, not from Python.</p>
<p>Your bottleneck is <em>your hardware</em>, not how you read the file. Python is already doing everything it can (using a buffer to read the file in larger chunks before splitting into newlines).</p>
<p>I suggest upgrading your disk to an SSD.</p>
| 0 | 2016-10-09T14:25:08Z | [
"python",
"python-2.7",
"text-files"
] |
Finding average in a file | 39,944,637 | <p>One of the things I'm supposed to do is find the average inflation from data in a file I was given. It gives the <code>year</code>, <code>interest</code>, and <code>inflation</code>, with all the numbers below it. Looks something like this.</p>
<pre><code>year interest inflation
1900 4.61 8.1
</code></pre>
<p>This goes on quite a bit further, all the way to 2008. I've made some progress with some help, courtesy of germancoder. I'm still stuck though.</p>
<p>Here's what the code looks like so far.</p>
<pre><code>def myTest(file):
with open ('filename', 'r') as f:
inflation = []
header = 1
for line in f:
if header !=1:
infl = line.split(",")[2]
inflation.append(float(infl))
header += 1
avgInflation = sum(inflation)/len(inflation)
return avgInflation
</code></pre>
<p>The problem , I think, was that the year interest inflation at the top was causing problems. So with help I added stuff to the code, but I'm still getting an error. It says division by zero error, line 11. Any thoughts on what I should do now?</p>
<p>The actual file name is Inflation.csv. I made a simple program myself which prints it in the interpreter, which shows it separated by commas, hence why I did (",")</p>
| 0 | 2016-10-09T14:21:21Z | 39,944,678 | <p>Your condition for appending to the header will never be met as <code>header += 1</code> is under the condition <code>header != 1</code> and <code>header</code>'s initial value is <code>1</code>. Therefore you are looping over the array and doing nothing. At the end of your method where you calculate the average, your <code>inflation</code> list is still empty so <code>len(inflation)</code> resolves to <code>0</code>.</p>
<p>Also you are reading the lines in the file incorrectly. I think you are wanting to read them as lines using <code>f.readlines()</code>?</p>
<pre><code>def myTest(file):
with open ('filename', 'r') as f:
lines = f.readlines() <--- 2
inflation = []
header = 1
for line in lines:
if header !=1:
infl = line.split(",")[2]
inflation.append(float(infl))
header += 1 <--- 1
avgInflation = sum(inflation)/len(inflation)
return avgInflation
</code></pre>
| 0 | 2016-10-09T14:26:25Z | [
"python",
"average",
"mean"
] |
Finding average in a file | 39,944,637 | <p>One of the things I'm supposed to do is find the average inflation from data in a file I was given. It gives the <code>year</code>, <code>interest</code>, and <code>inflation</code>, with all the numbers below it. Looks something like this.</p>
<pre><code>year interest inflation
1900 4.61 8.1
</code></pre>
<p>This goes on quite a bit further, all the way to 2008. I've made some progress with some help, courtesy of germancoder. I'm still stuck though.</p>
<p>Here's what the code looks like so far.</p>
<pre><code>def myTest(file):
with open ('filename', 'r') as f:
inflation = []
header = 1
for line in f:
if header !=1:
infl = line.split(",")[2]
inflation.append(float(infl))
header += 1
avgInflation = sum(inflation)/len(inflation)
return avgInflation
</code></pre>
<p>The problem , I think, was that the year interest inflation at the top was causing problems. So with help I added stuff to the code, but I'm still getting an error. It says division by zero error, line 11. Any thoughts on what I should do now?</p>
<p>The actual file name is Inflation.csv. I made a simple program myself which prints it in the interpreter, which shows it separated by commas, hence why I did (",")</p>
| 0 | 2016-10-09T14:21:21Z | 39,944,684 | <p>You are initalizing <code>header = 1</code>, and you initialize the value of <code>infl</code> and <code>inflation</code> after checking if <code>header</code> is not one, hence, <code>avgInflation = sum(inflation)/len(inflation)</code> is effectively becoming: </p>
<p><code>avgInflation = sum(0/len(0))</code></p>
<p>Make sure to check that inflation has a value before using it in a division. Perhaps you meant to initialize <code>header = 0</code></p>
| 0 | 2016-10-09T14:26:45Z | [
"python",
"average",
"mean"
] |
Finding average in a file | 39,944,637 | <p>One of the things I'm supposed to do is find the average inflation from data in a file I was given. It gives the <code>year</code>, <code>interest</code>, and <code>inflation</code>, with all the numbers below it. Looks something like this.</p>
<pre><code>year interest inflation
1900 4.61 8.1
</code></pre>
<p>This goes on quite a bit further, all the way to 2008. I've made some progress with some help, courtesy of germancoder. I'm still stuck though.</p>
<p>Here's what the code looks like so far.</p>
<pre><code>def myTest(file):
with open ('filename', 'r') as f:
inflation = []
header = 1
for line in f:
if header !=1:
infl = line.split(",")[2]
inflation.append(float(infl))
header += 1
avgInflation = sum(inflation)/len(inflation)
return avgInflation
</code></pre>
<p>The problem , I think, was that the year interest inflation at the top was causing problems. So with help I added stuff to the code, but I'm still getting an error. It says division by zero error, line 11. Any thoughts on what I should do now?</p>
<p>The actual file name is Inflation.csv. I made a simple program myself which prints it in the interpreter, which shows it separated by commas, hence why I did (",")</p>
| 0 | 2016-10-09T14:21:21Z | 39,944,705 | <p>As I see you initiate variable <code>header</code> as 1 outside the for loop.
Inside the for loop you check if the <code>header</code> is not equal to 1 and not do anything if it equals to 1.
For loop never goes inside the <code>if header !=1:</code>
It just iterates over your whole file and goes out of for loop without doing anything.
In line 11, <code>len(inflation)</code> is 0 since you never append anything to it.
You should change your conditional loop or change your variable <code>header</code> in somewhere in your code.</p>
<pre><code>def myTest(file):
with open ('filename', 'r') as f:
inflation = []
header = 1
for line in f:
if header !=1: //Never goes inside
infl = line.split(",")[2]
inflation.append(float(infl))
header += 1
avgInflation = sum(inflation)/len(inflation) //Divison by zero
return avgInflation
</code></pre>
| -1 | 2016-10-09T14:28:51Z | [
"python",
"average",
"mean"
] |
Finding average in a file | 39,944,637 | <p>One of the things I'm supposed to do is find the average inflation from data in a file I was given. It gives the <code>year</code>, <code>interest</code>, and <code>inflation</code>, with all the numbers below it. Looks something like this.</p>
<pre><code>year interest inflation
1900 4.61 8.1
</code></pre>
<p>This goes on quite a bit further, all the way to 2008. I've made some progress with some help, courtesy of germancoder. I'm still stuck though.</p>
<p>Here's what the code looks like so far.</p>
<pre><code>def myTest(file):
with open ('filename', 'r') as f:
inflation = []
header = 1
for line in f:
if header !=1:
infl = line.split(",")[2]
inflation.append(float(infl))
header += 1
avgInflation = sum(inflation)/len(inflation)
return avgInflation
</code></pre>
<p>The problem , I think, was that the year interest inflation at the top was causing problems. So with help I added stuff to the code, but I'm still getting an error. It says division by zero error, line 11. Any thoughts on what I should do now?</p>
<p>The actual file name is Inflation.csv. I made a simple program myself which prints it in the interpreter, which shows it separated by commas, hence why I did (",")</p>
| 0 | 2016-10-09T14:21:21Z | 39,944,987 | <p>How about this?</p>
<pre><code>def myTest(file):
with open ('filename', 'r') as f:
inflation = []
header = 1
for line in f:
if header == 1:
header += 1
continue
else:
infl = line.split(",")[2]
inflation.append(float(infl))
avgInflation = sum(inflation)/len(inflation)
return avgInflation
</code></pre>
<p>I think this should solve the problem.</p>
| 1 | 2016-10-09T14:57:30Z | [
"python",
"average",
"mean"
] |
tring to export to csv file input from user in Tkinter | 39,944,699 | <p>I have code to take user import from Tkinter and put in a csv file. In the Tkinter window I can use pack to setup my input boxes but don't like the it and want to use grid instead. The following code works for pack but I can't figure out how to do it grid. Sorry I am one month into learing the language. Here is the code</p>
<pre><code>from Tkinter import *
import csv
class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.output()
def output(self):
Label(text='First Name:').pack (side=LEFT,padx=5,pady=5)
self.e = Entry(root, width=10)
self.e.pack(side=LEFT,padx=5,pady=5)
Label(text='Last Name:').pack (side=LEFT,padx=5,pady=5)
self.e1 = Entry(root, width=10)
self.e1.pack(side=LEFT,padx=5,pady=5)
self.b = Button(root, text='Submit',command=self.writeToFile)
self.b.pack(side=LEFT,padx=5,pady=5)
def writeToFile(self):
with open('WorkOrderLog.csv', 'a') as f:
w=csv.writer(f, delimiter=',')
w.writerow([self.e.get()])
w.writerow([self.e1.get()])
if __name__ == "__main__":
root=Tk()
root.title('Auto Logger')
root.geometry('500x200')
app=App(master=root)
app.mainloop()
root.mainloop()
</code></pre>
| 0 | 2016-10-09T14:28:11Z | 39,944,831 | <p>Use grid try think is like use a table, you asign the tkinterObjects in a "table" and then asign row/column, something like this.</p>
<pre><code>class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.output()
def output(self):
firstName=Label(self,text='First Name:')
firstName.grid(row=1,column=0, padx=5, pady=3)
self.e = Entry(self, width=10)
self.e.grid(row=1,column=1, padx=5, pady=3)
lastName=Label(self,text='Last Name:')
lastName.grid(row=1,column=2, padx=5, pady=3)
self.e1 = Entry(self, width=10)
self.e1.grid(row=1,column=3, padx=5, pady=3)
self.b = Button(self, text='Submit',command=self.writeToFile)
self.b.grid(row=1,column=4, padx=5, pady=3)
def writeToFile(self):
with open('WorkOrderLog.csv', 'a') as f:
w=csv.writer(f, delimiter=',')
w.writerow([self.e.get()])
w.writerow([self.e1.get()])
if __name__ == "__main__":
root=Tk()
root.title('Auto Logger')
root.geometry('500x200')
app=App(master=root)
app.mainloop()
root.mainloop()
</code></pre>
<p>all are in the "table" root</p>
| 0 | 2016-10-09T14:41:56Z | [
"python",
"tkinter"
] |
Python multiprocessing: Simple job split across many processes | 39,944,824 | <h3>EDIT</h3>
<p>The proposed code actually worked! I was simply running it from within an IDE that wasn't showing the outputs. </p>
<p>I'm leaving the question up because the comments/answers are instructive</p>
<hr>
<p>I need to split a big job across many workers.
In trying to figure out how to do this, I used the following simple example, with code mostly taken from <a href="https://gist.github.com/baojie/6047780" rel="nofollow">here</a>.
Basically, I am taking a list, breaking it up in shorter sublists (chunks), and asking <code>multiprocessing</code> to print the content of each sublist with a dedicated worker:</p>
<pre><code>import multiprocessing
from math import ceil
# Breaking up the long list in chunks:
def chunks(l, n):
return [l[i:i+n] for i in range(0, len(l), n)]
# Some simple function
def do_job(job_id, data_slice):
for item in data_slice:
print("{}_{}".format(job_id, item))
</code></pre>
<p>I then do this: </p>
<pre><code>if __name__ == '__main__':
# My "long" list
l = [letter for letter in 'abcdefghijklmnopqrstuvwxyz']
my_chunks = chunks(l, ceil(len(l)/4))
</code></pre>
<p>At this point, my_chunks is as expected: </p>
<pre><code>[['a', 'b', 'c', 'd', 'e', 'f', 'g'],
['h', 'i', 'j', 'k', 'l', 'm', 'n'],
['o', 'p', 'q', 'r', 's', 't', 'u'],
['v', 'w', 'x', 'y', 'z']]
</code></pre>
<p>Then:</p>
<pre><code> jobs = []
for i, s in enumerate(my_chunks):
j = mp.Process(target=do_job, args=(i, s))
jobs.append(j)
for j in jobs:
print('starting job {}'.format(str(j)))
j.start()
</code></pre>
<p><strong>Initially</strong>, I wrote the question because I was not getting the expected printouts from the <code>do_job</code>function. </p>
<p><strong>Turns out</strong> the code works just fine when run from command line.</p>
| 0 | 2016-10-09T14:41:19Z | 39,945,045 | <p>Maybe it's your first time with multiprocessing? Do you wait for the processes to exit or do you exit the main processes before your processes have time to complete there job?</p>
<pre><code>from multiprocessing import Process
from string import ascii_letters
from time import sleep
def job(chunk):
done = chunk[::-1]
print(done)
def chunk(data, parts):
divided = [None]*parts
n = len(data) // parts
for i in range(parts):
divided[i] = data[i*n:n*(i+1)]
if len(data) % 2 != 0:
divided[-1] += [data[-1]]
return divided
def main():
data = list(ascii_letters)
workers = 4
data_chunks = chunk(data, workers)
ps = []
for i in range(4):
w = Process(target=job, args=(data_chunks[i],))
w.deamon = True
w.start()
ps += [w]
sleep(2)
if __name__ == '__main__':
main()
</code></pre>
| 1 | 2016-10-09T15:04:43Z | [
"python",
"multiprocessing"
] |
Printing html like contents form a textarea using beautifulsoup | 39,944,843 | <p>We can get the text inside a tag using the get_text() function in BeautifulSoup. But what if the text area contains some html like code.</p>
<p>Example:</p>
<pre><code>from bs4 import BeautifulSoup
html = "<html><h1>#include <stdio.h></h1></html>"
soup = BeautifulSoup(html,"lxml")
print soup.h1.get_text()
</code></pre>
<p>The above program prints "#include" but I wanted it to be full text inside h1.
This is just a small example. I am working with with scraping a c++ code from web. I have navigated to the text area in which code is present but when I print it it doesn't print the header files.
Textarea:</p>
<pre><code><textarea rows="20" cols="70" name="file" id="file" style="width: 100%;" data-input-file="1">#include <bits/stdc++.h>
using namespace std;
struct points
{
int x;
int count;
};
points a[105];
int main()
{
int n;
int k;
int t;
int i;
int j;
scanf("%d",&t);
while(t--) {
scanf("%d%d",&n,&k);
for(i = 1; i <= k; i++) {
scanf("%d",&a[i].x);
a[i].count = 1;
if(a[i].x == -1) {
a[i].x = 1000000000;
}
}
for(i = 2; i <= k; i++) {
for(j = 1; j < i; j++) {
if((a[i-j].x + a[j].x) < a[i].x && (a[i-j].count + a[j].count) <= n) {
a[i].x = a[i-j].x + a[j].x;
a[i].count = a[i-j].count + a[j].count;
}
}
}
if(a[k].x == 1000000000) {
printf("-1\n");
}
else {
printf("%d\n",a[k].x);
}
}
}
</textarea>
</code></pre>
<p>My code for scraping:</p>
<pre><code>from robobrowser import RoboBrowser
browser = RoboBrowser(parser = "lxml")
browser.open('http://www.spoj.com/')
form = browser.get_form(id='login-form')
form['login_user'].value = username
form['password'].value = password
browser.submit_form(form)
browser.open('http://www.spoj.com/myaccount')
l = browser.find(id = "user-profile-tables").find_all('td')
link = l[0].a['href']
link = "http://www.spoj.com" + link
browser.open(link)
codelink = browser.find(title = 'Edit source code')['href']
codelang = browser.find(class_ = 'slang text-center').get_text()
codelink = "http://www.spoj.com" + codelink
browser.open(codelink)
print browser.find(id = 'submit_form').textarea.get_text()
</code></pre>
<p>Is there any way to achieve it?</p>
| 0 | 2016-10-09T14:42:57Z | 39,944,873 | <p>The problem is the lt and gt signs should be escaped like below:</p>
<pre><code>from bs4 import BeautifulSoup
html = "<html><h1>#include &lt;stdio.h&gt;</h1></html>"
soup = BeautifulSoup(html,"lxml")
print(soup.h1.get_text())
</code></pre>
<p>Which would then give you:</p>
<pre><code>#include <stdio.h>
</code></pre>
<p>None of the parsers are going to consider that text unless they are escaped. each one will give you <code>#include <stdio.h></stdio.h></code></p>
<p>You may just have to resort to a regex to extract the include statements from the source itself.</p>
<pre><code> patt = re.compile(r"<h1>(\s+)?(#include\s+.*?)(\s+)?</h1>")
</code></pre>
| 1 | 2016-10-09T14:45:09Z | [
"python",
"html",
"beautifulsoup"
] |
Webdriver Timeout Exception | 39,944,879 | <p>I try to understand where is the problem in code:</p>
<pre><code>class WebTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
binary = FirefoxBinary('/home/andrew/Downloads/firefox 45/firefox')
cls.browser = webdriver.Firefox(firefox_binary=binary)
cls.wait = WebDriverWait(cls.browser, 10)
cls.browser.maximize_window()
cls.browser.get('http://www.test.com/')
def test_login_menu_elements(self):
self.wait.until(EC.element_to_be_clickable((By.XPATH, "//a[@id='menu_min']"))).click()
check_icons(self)
self.wait.until(EC.element_to_be_clickable((By.XPATH, "//a[@id='menu_min']"))).click()
check_fields(self)
def test_add_news(self):
self.wait.until(EC.element_to_be_clickable((By.XPATH, "//span[contains(.,'News')]"))).click()
self.wait.until(EC.element_to_be_clickable((By.XPATH, "//a[@href='/manager/news']"))).click()
@classmethod
def tearDownClass(cls):
cls.browser.quit()
if __name__=='__main__':
unittest.main()
</code></pre>
<p>Every time I receive TimeoutException, and I really don't understand why, and where is the problem in the code</p>
| -2 | 2016-10-09T14:46:00Z | 39,947,669 | <p>A <code>TimeoutException</code> can be received without having any logical or syntantic errors with your code.</p>
<p><code>TimeoutException</code>s will be raised when the <code>wait.until</code> expected conditions aren't found.</p>
<p>Some things I have found to help:</p>
<ul>
<li>Isolate the xpath by using chrome/firefox dev tools and right clicking on the element, and show xpath</li>
<li>Using the xpath from the step above, make sure that the condition chose is correct</li>
<li>ime having front end experience, using css selectors is usually more intuative and more understandable than relative xpaths. </li>
<li>check the selector you are using by opening up dev tools console and using <code>$x({{ XPATH_HERE }})</code> to make sure it is valid</li>
<li>for dynamic HTML use python debugger and make sure that html is in the expected state between each expected condition</li>
</ul>
| 0 | 2016-10-09T19:29:16Z | [
"python",
"unit-testing",
"selenium",
"selenium-webdriver"
] |
Django: How to properly make shopping cart? ( Array string field ) | 39,944,880 | <p>Lately I've been needing to create a server-side shopping cart for my website that can have products inside. I could add cart and product in session cookies, but I prefer to add it to my custom made User model, so it can stay when the user decides to log out and log back in.</p>
<p>Since I'm making a shopping cart, I need to make a model for it, that will hold products as objects, so then they can be easily used, but I can't find any way to do so properly.</p>
<pre><code>class User(models.Model):
username = models.CharField(max_length=150)
joined = models.DateTimeField('registered')
avatar = models.CharField(max_length=300)
balance = models.IntegerField(default=0)
ban = models.BooleanField()
cart = models.???
def __str__(self):
return self.username
</code></pre>
<p>How can I achieve having array string in models with using Django's system? If not then can it be possible by other libraries ( Json, Pickle ), but I've seen it can be done by ForeignKey, if so how is it possible?</p>
| 1 | 2016-10-09T14:46:05Z | 39,945,128 | <p>I'd suggest using DB relationships instead of storing a string or an array of strings for this problem.</p>
<p>If you solve the problem using DB relationships, you'll need to use a <a href="https://docs.djangoproject.com/es/1.10/topics/db/examples/many_to_many/" rel="nofollow">ManyToManyField</a>.</p>
<pre><code>class User(models.Model):
...
cart = models.ManyToManyField(Product)
</code></pre>
<p>And assuming you have a model for your products.</p>
<pre><code>class Product(models.Model):
name = models.CharField(max_length=30)
price = models.DecimalField(max_digits=8, decimal_places=2)
</code></pre>
<p>When adding elements to the cart you'll use something like this.</p>
<pre><code>tv = Product(name='LED TV', ...)
tv.save()
diego = User.objects.get(username='dalleng')
diego.cart.add(some_product)
</code></pre>
| 2 | 2016-10-09T15:13:38Z | [
"python",
"django"
] |
How to find adjacent pairs in a sequence, python | 39,944,923 | <p>For one of my assignments, I have to write a code that will look for adjacent pairs in a sequence. If there are no pairs in the sequence, the output has to be None. Could be a list, string, whatever. The code that I have only worked for half of the test files (the true ones), yet I am having trouble passing the false test files. I am not sure what I am doing wrong and would like help to complete this task. Here is the code I am working with:</p>
<pre><code>def neighboring_twins(xs):
twins = False
for i in range(len(xs)):
for j in range(i+1,len(xs)):
if xs[i] == xs[j]:
twins = True
return twins
</code></pre>
<p>sample inputs:</p>
<pre><code>xs = [1,1]
</code></pre>
<p>output = <code>true</code></p>
<pre><code>xs = [2,1,2]
</code></pre>
<p>output = <code>False</code></p>
<pre><code>xs = []
</code></pre>
<p>output= <code>False</code></p>
| -1 | 2016-10-09T14:50:51Z | 39,945,109 | <p>Loop through <code>xs</code> starting from the <em>second</em> item, and compare to the previous item:</p>
<pre><code>def neighboring_twins(xs):
for i in range(1, len(xs)):
if xs[i] == xs[i-1]:
return True
return False
</code></pre>
| 0 | 2016-10-09T15:11:23Z | [
"python",
"python-3.x"
] |
Strip string values in a dictionary and convert it to a float. Values contain numbers separated by space | 39,944,982 | <p>I have a dictionary setup with the following data:</p>
<p><img src="http://i.stack.imgur.com/onSzu.jpg" alt="image of dictionary with values"></p>
<p>where its values are a list of <strong>strings</strong>:</p>
<pre><code>['2 1 0\n', '3 0 1\n', '4 0 3\n' .... ]
['-3.85995e-17 1.26224e+00 2.63053e-01\n']
</code></pre>
<p>Is there a way I can convert the values into a list of <strong>floats</strong> without having to use too many loops?</p>
| 1 | 2016-10-09T14:57:14Z | 39,951,489 | <p>You would probably have to find a library that handles such data to do it for you, I'm not aware of any native python method to convert a string into a list of floats.
If you're looking to save space, it'd probably just be easiest to write your own function that takes one of your values and returns a list of floats.</p>
<p>For example:</p>
<pre><code>def string_to_float_list(string):
split = string.strip().split(" ")
floats = []
for s in split:
if len(s) == 0:
continue
floats.append(float(s.strip()))
return floats
</code></pre>
<p>Takes input:</p>
<pre><code>string = '-3.85995e-17 1.26224e+00 2.63053e-01\n'
</code></pre>
<p>Gives output:</p>
<pre><code>[-3.85995e-17, 1.26224, 0.263053]
</code></pre>
| 0 | 2016-10-10T04:52:58Z | [
"python",
"string",
"dictionary"
] |
Strip string values in a dictionary and convert it to a float. Values contain numbers separated by space | 39,944,982 | <p>I have a dictionary setup with the following data:</p>
<p><img src="http://i.stack.imgur.com/onSzu.jpg" alt="image of dictionary with values"></p>
<p>where its values are a list of <strong>strings</strong>:</p>
<pre><code>['2 1 0\n', '3 0 1\n', '4 0 3\n' .... ]
['-3.85995e-17 1.26224e+00 2.63053e-01\n']
</code></pre>
<p>Is there a way I can convert the values into a list of <strong>floats</strong> without having to use too many loops?</p>
| 1 | 2016-10-09T14:57:14Z | 39,975,028 | <p>Thanks Xorgon!</p>
<p>I also tried using list comprehensions as follows:</p>
<pre><code>Connectivity = ['2 1 0\n', '3 0 1\n', '4 0 3\n']
aaa = [k.strip() for k in Connectivity]
bbb = [k.split() for k in aaa]
ccc = [[float(j) for j in i] for i in bbb]
</code></pre>
<p>But is there a faster way? The reason being that the variable Connectivity would contain about 5million items</p>
| 0 | 2016-10-11T10:12:55Z | [
"python",
"string",
"dictionary"
] |
Tensorflow reshape on convolution output gives TypeError | 39,945,037 | <p>When I try to reshape the output of a convolution using <code>tf.reshape()</code>, I get a TypeError</p>
<pre><code>TypeError: Expected binary or unicode string, got -1
</code></pre>
<p>The model I have written is:</p>
<pre><code>with tf.name_scope('conv1'):
filter = tf.Variable(tf.truncated_normal([5, 5, 1, self.num_hidden / 2], mean=0.0,
stddev=0.02, dtype=tf.float32),
name='filter')
b = tf.Variable(tf.zeros([self.num_hidden / 2], dtype=tf.float32),
name='b')
h1 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(inp, filter,
[1, 2, 2, 1], padding='SAME'), b))
with tf.name_scope('conv2'):
filter = tf.Variable(tf.truncated_normal([5, 5, self.num_hidden / 2, self.num_hidden], mean=0.0,
stddev=0.02, dtype=tf.float32),
name='filter')
b = tf.Variable(tf.zeros([self.num_hidden], dtype=tf.float32),
name='b')
h2 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(h1, filter,
[1, 2, 2, 1], padding='SAME'), b))
# h2 -> [-1, 7, 7, 32]
# num_units -> [-1, 1568]
shape = h2.get_shape()
num_units = shape[1]*shape[2]*shape[3]
with tf.name_scope('reshape'):
h2_flattened = tf.reshape(h2, [-1, num_units])
h2_flattened = tf.nn.dropout(h2_flattened, keep_prob=0.9)
with tf.name_scope('prediction'):
W = tf.Variable(tf.truncated_normal([num_units, 1], mean=0.0, stddev=0.01,
dtype=tf.float32), name='W')
b = tf.Variable(tf.zeros([1], dtype=tf.float32), name='b')
self.pred = tf.matmul(h2_flattened, W) + b
</code></pre>
<p>And the exact error I am getting is:</p>
<pre><code>Traceback (most recent call last):
File "single_model_conv.py", line 108, in <module>
gan = GAN(num_latent, 28, 'single')
File "single_model_conv.py", line 23, in __init__
self.adversary(self.gen_image)
File "single_model_conv.py", line 93, in adversary
h2_flattened = tf.reshape(h2, [-1, num_units])
File "/nfs/nemo/u3/idurugkar/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/ops/gen_array_ops.py", line 1977, in reshape
name=name)
File "/nfs/nemo/u3/idurugkar/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 490, in apply_op
preferred_dtype=default_dtype)
File "/nfs/nemo/u3/idurugkar/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 657, in convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "/nfs/nemo/u3/idurugkar/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/constant_op.py", line 180, in _constant_tensor_conversion_function
return constant(v, dtype=dtype, name=name)
File "/nfs/nemo/u3/idurugkar/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/constant_op.py", line 163, in constant
tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape))
File "/nfs/nemo/u3/idurugkar/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/tensor_util.py", line 422, in make_tensor_proto
tensor_proto.string_val.extend([compat.as_bytes(x) for x in proto_values])
File "/nfs/nemo/u3/idurugkar/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/util/compat.py", line 64, in as_bytes
(bytes_or_text,))
TypeError: Expected binary or unicode string, got -1
</code></pre>
<p>I don't understand why this is happening. It seems as if there is some error in converting the shape array into a tensor, but when I try and convert an arbitrary array to tensor it works.
I also tried converting all the dimensions to actual values (batch_size instead of -1), and that doesn't work either.</p>
<p>My tensorflow version is 0.11 and I am running it on a Linux machine with GPU support.</p>
| 1 | 2016-10-09T15:03:53Z | 39,945,609 | <p>I had to do this before. Change this</p>
<pre><code>shape = h2.get_shape()
</code></pre>
<p>to this:</p>
<pre><code>shape = h2.get_shape().as_list()
</code></pre>
| 0 | 2016-10-09T16:01:24Z | [
"python",
"tensorflow"
] |
Widget alignment in kivy | 39,945,095 | <p>i'm new in kivy and python and i would like to knkow what's wrong in my code.
I want to align a Label widget and a TextInput widget in a same layout. In other words, the two widgets have to start from the same x coordinate! In my example, i set the same x coordinate in pos_hint('center_x':0.5), but the widgets aren't align. I tried with other layout type before, but i didn't solve this issue.
any suggestion?</p>
<pre><code>from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
class MyWidget(FloatLayout):
def __init__(self, *args):
super(MyWidget, self).__init__(*args)
self.add_widget(Label(text="Hello", size_hint=(None, None), pos_hint={'center_x':0.5, 'center_y':0.5}))
self.add_widget(TextInput(text="MyText", multiline=False, size_hint=(0.1,0.05), pos_hint={'center_x':0.5, 'center_y':0.4}))
class ex(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
ex().run()
</code></pre>
| 0 | 2016-10-09T15:10:30Z | 39,945,516 | <p>This is what you want If I'm right about what you mean.</p>
<pre><code>self.add_widget(Label(text="Hello", size_hint=(None, None), pos_hint={'center_x':0.4, 'center_y':0.5}))
self.add_widget(TextInput(text="MyText", multiline=False, size_hint=(0.1,0.05), pos_hint={'center_x':0.5, 'center_y':0.5}))
</code></pre>
<p>I think you misunderstood the pos_hint. <code>center_x: 0.5</code> means the middle of x so <code>center_x: 0.4</code> means one level to the left.</p>
| 0 | 2016-10-09T15:53:02Z | [
"python",
"user-interface",
"layout",
"widget",
"kivy"
] |
How to create hierarchical columns in pandas? | 39,945,122 | <p>I have a pandas dataframe that looks like this:</p>
<pre><code> rank_2015 num_2015 rank_2014 num_2014 .... num_2008
France 8 1200 9 1216 .... 1171
Italy 11 789 6 788 .... 654
</code></pre>
<p>Now I want to draw a bar chart of the sums just the <code>num_</code> columns, by year. So on the x-axis I would like years from 2008 to 2015, and on the y-axis I would like the sum of the related <code>num_</code> column. </p>
<p>What's the best way to do this? I know how to get the sums for each column:</p>
<pre><code>df.sum()
</code></pre>
<p>But what I don't know is how to chart only the <code>num_</code> columns, and also how to re-label those columns so that the labels are integers rather than strings, in order to get them to chart correctly. </p>
<p>I'm wondering if I want to create hierarchical columns, like this:</p>
<pre><code> rank num
2015 2014 2015 2014 .... 2008
France 8 9 1200 1216 .... 1171
Italy 11 6 789 788 .... 654
</code></pre>
<p>Then I could just chart the columns in the <code>num</code> section. </p>
<p>How can I get my dataframe into this shape?</p>
| 0 | 2016-10-09T15:12:50Z | 39,945,309 | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#extracting-substrings" rel="nofollow"><code>str.extract</code></a> with the regex pattern <code>(.+)_(\d+)</code> to convert the columns
to a DataFrame:</p>
<pre><code>cols = df.columns.str.extract(r'(.+)_(\d+)', expand=True)
# 0 1
# 0 num 2008
# 1 num 2014
# 2 num 2015
# 3 rank 2014
# 4 rank 2015
</code></pre>
<p>You can then <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#creating-a-multiindex-hierarchical-index-object" rel="nofollow">build a hierarchical (MultiIndex) index</a> from <code>cols</code> and reassign it
to <code>df.columns</code>:</p>
<pre><code>df.columns = pd.MultiIndex.from_arrays((cols[0], cols[1]))
</code></pre>
<p>so that <code>df</code> becomes</p>
<pre><code> num rank
2008 2014 2015 2014 2015
France 1171 1216 1200 9 8
Italy 654 788 789 6 11
</code></pre>
<hr>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({ 'num_2008': [1171, 654],
'num_2014': [1216, 788],
'num_2015': [1200, 789],
'rank_2014': [9, 6],
'rank_2015': [8, 11]}, index=['France', 'Italy'])
cols = df.columns.str.extract(r'(.+)_(\d+)', expand=True)
cols[1] = pd.to_numeric(cols[1])
df.columns = pd.MultiIndex.from_arrays((cols[0], cols[1]))
df.columns.names = [None]*2
df['num'].sum().plot(kind='bar')
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/0gxbpm.png" rel="nofollow"><img src="http://i.stack.imgur.com/0gxbpm.png" alt="enter image description here"></a></p>
| 1 | 2016-10-09T15:33:20Z | [
"python",
"pandas"
] |
How to create hierarchical columns in pandas? | 39,945,122 | <p>I have a pandas dataframe that looks like this:</p>
<pre><code> rank_2015 num_2015 rank_2014 num_2014 .... num_2008
France 8 1200 9 1216 .... 1171
Italy 11 789 6 788 .... 654
</code></pre>
<p>Now I want to draw a bar chart of the sums just the <code>num_</code> columns, by year. So on the x-axis I would like years from 2008 to 2015, and on the y-axis I would like the sum of the related <code>num_</code> column. </p>
<p>What's the best way to do this? I know how to get the sums for each column:</p>
<pre><code>df.sum()
</code></pre>
<p>But what I don't know is how to chart only the <code>num_</code> columns, and also how to re-label those columns so that the labels are integers rather than strings, in order to get them to chart correctly. </p>
<p>I'm wondering if I want to create hierarchical columns, like this:</p>
<pre><code> rank num
2015 2014 2015 2014 .... 2008
France 8 9 1200 1216 .... 1171
Italy 11 6 789 788 .... 654
</code></pre>
<p>Then I could just chart the columns in the <code>num</code> section. </p>
<p>How can I get my dataframe into this shape?</p>
| 0 | 2016-10-09T15:12:50Z | 39,945,320 | <p>Probably you don't need re-shaping your dataset, it can be achieved easier.</p>
<ol>
<li>Create new dataset, which contains <code>num_</code> data only</li>
<li>Rename columns</li>
<li>Plot sum</li>
</ol>
<p>Dummy data:</p>
<p><a href="http://i.stack.imgur.com/gzPeAm.png" rel="nofollow"><img src="http://i.stack.imgur.com/gzPeAm.png" alt="enter image description here"></a></p>
<p>Code:</p>
<pre><code>df_num = df[[c for c in df.columns if c.startswith('num_')]]
df_num.columns = [c.lstrip('num_') for c in df_num.columns]
df_num.sum().plot(kind='bar')
</code></pre>
<p>Result:</p>
<p><a href="http://i.stack.imgur.com/0KsvVm.png" rel="nofollow"><img src="http://i.stack.imgur.com/0KsvVm.png" alt="enter image description here"></a></p>
| 1 | 2016-10-09T15:33:57Z | [
"python",
"pandas"
] |
Getting the ratio of a in b | 39,945,155 | <p>This is the current code I have, the issue is clearly that I can't divide strings by strings, but I'm unsure of how to go about editing the code to get it to run.</p>
<pre><code>def Fraction(c, s):
#Returns the fraction of 's' formed by 'c'.
return c / s
print(Fraction("a", "ababab"))
</code></pre>
<p>In theory, 0.5 should be printed; <code>'a'</code> forms half of all text in <code>'ababab'</code>.</p>
| -1 | 2016-10-09T15:17:27Z | 39,945,245 | <p>Apparently you want a ratio here; a number between 0.0 and 1.0 indicating what percentage of a larger string is using a smaller string:</p>
<pre><code>def ratio(c, s):
return (float(s.count(c) * len(c))) / len(s)
</code></pre>
<p>Demo:</p>
<pre><code>>>> def ratio(c, s):
... return (float(s.count(c) * len(c))) / len(s)
...
>>> ratio("a", "ababab")
0.5
>>> ratio("ab", "ababab")
1.0
</code></pre>
| 0 | 2016-10-09T15:26:32Z | [
"python",
"python-3.x"
] |
Ho do i make one to many relations in list of tuples | 39,945,162 | <p>I have a list consisting of tuples like the following:</p>
<pre><code>m = [('a', 'b', 'c', 'd'), (1, 2, 3, 4), ('alpha', 'beta', 'gamma', 'eta')]
</code></pre>
<p>how can i get the following output:</p>
<pre><code>['c', 3, 'gamma']
</code></pre>
<p>need only for 'c' and not for rest of the elements a,b,d</p>
| 0 | 2016-10-09T15:18:18Z | 39,945,357 | <p>Variable 'm' contains list of tuples, there are 3 tuples considered as 3 items in list. </p>
<p>Variable 'n' takes each element (tuple) in the list and prints its value according to its index number.</p>
<pre><code>m = [('a', 'b', 'c', 'd'), (1, 2, 3, 4), ('alpha', 'beta', 'gamma', 'eta')]
for n in m:
print (n[2])
</code></pre>
| 1 | 2016-10-09T15:37:19Z | [
"python",
"list",
"python-3.x",
"tuples"
] |
Unable to click-iterate through elements using selenium | 39,945,175 | <p>Im trying to click-iterate through google-translate element but the code isnt working </p>
<pre><code>from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("https://www.tripadvisor.com.br/ShowUserReviews-g1-d8729164-r425802060-TAP_Portugal-World.html")
for i in driver.find_elements_by_class_name("entry"):
wait = WebDriverWait(driver, 10)
google_translate = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".googleTranslation .link")))
actions = ActionChains(driver)
actions.move_to_element(google_translate).click().perform()
driver.find_element_by_class_name("ui_close_x").click()
driver.execute_script("window.scrollTo(0, 600);")
</code></pre>
<p>=======ISSUE======
Its itertaing through the very first element only</p>
<hr>
<p>Basically the code should show translation for each of the review in a popup, close that popup and then move to next review, translate etc</p>
| 1 | 2016-10-09T15:19:11Z | 39,945,554 | <pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
import time
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.tripadvisor.com.br/ShowUserReviews-g1-d8729164-r425802060-TAP_Portugal-World.html")
gt= driver.find_elements(By.CSS_SELECTOR,".googleTranslation>.link")
for i in gt:
i.click()
time.sleep(2)
driver.find_element_by_class_name("ui_close_x").click()
time.sleep(2)
</code></pre>
<p>The above code will solve your purpose of clicking on each review google translate.
PS: in For loop i have placed the time.sleep() so that you can see the code action, if you want you can remote it</p>
| 1 | 2016-10-09T15:56:07Z | [
"python",
"selenium",
"web-scraping"
] |
Why does `set_index` create an index label for the column name? | 39,945,178 | <p>I have a CSV file which begins like this:</p>
<pre><code>Year,Boys,Girls
1996,333490,315995
1997,329577,313518
1998,325903,309998
</code></pre>
<p>When I read it into pandas and set an index, it isn't doing quite what I expect:</p>
<pre><code>df = pd.read_csv('../data/myfile.csv')
df.set_index('Year', inplace=True)
df.head()
</code></pre>
<p>Why is there an index entry for the column label, with blank values next to it? Shouldn't this simply disappear?</p>
<p><a href="http://i.stack.imgur.com/6pkxa.png" rel="nofollow"><img src="http://i.stack.imgur.com/6pkxa.png" alt="enter image description here"></a></p>
<p>Also, I'm not clear on how to retrieve the values for 1998. If I try <code>df.loc['1998']</code> I get an error: <code>KeyError: 'the label [1998] is not in the [index]'</code>.</p>
| 2 | 2016-10-09T15:19:34Z | 39,945,278 | <p>You should set the name attribute of your index to <code>None</code>:</p>
<pre><code>df.index.names = [None]
df.head()
# Boys Girls
#1996 333490 315995
#1997 329577 313518
#1998 325903 309998
</code></pre>
<p>As for retrieving the data for <code>1998</code>, simply lose the quotes:</p>
<pre><code>df.loc[1998]
#Boys 325903
#Girls 309998
#Name: 1998, dtype: int64
</code></pre>
| 2 | 2016-10-09T15:29:42Z | [
"python",
"pandas"
] |
Add game loop to tornado server in python | 39,945,256 | <p>I've got a standard <code>tornado</code> application in <code>python</code>.</p>
<p>I am going to be making a game server using tornado's <code>websockets</code>.</p>
<p>The problem is, I need a game loop running on the server, to do things.</p>
<p>I could create a web handler '/startserver' and add the following code:</p>
<pre><code>@tornado.web.asynchronous
def get(self):
if not serverAlreadyStarted:
serverAlreadyStarted = True
while True:
(...)
</code></pre>
<p>This feels very hackish, and it means <strong>every time</strong> I want to start to server, I need to go to <strong><code>/startserver</code></strong></p>
<p>Is there a better way to do this? Is there somewhere when the server starts, I can add a loop?</p>
| 0 | 2016-10-09T15:27:08Z | 39,945,966 | <p>You could just start it in the background like:</p>
<pre><code>@gen.coroutine
def game_loop():
while True:
# Whatever your game loop does.
print("tick")
yield gen.sleep(1)
if __name__ == "__main__":
app = make_app()
app.listen(8888)
loop = tornado.ioloop.IOLoop.current()
loop.spawn_callback(game_loop)
loop.start()
</code></pre>
| 1 | 2016-10-09T16:40:26Z | [
"python",
"loops",
"tornado"
] |
Python SSHTunnel w/ Paramiko - CLI works, but not in script | 39,945,269 | <p><em>Context:</em><br>
I'm trying to connect to a remote MySQL install through SSH and in Python. I'm using paramiko and SSHTunnel, and currently on py 2.7.</p>
<p>I have had success connecting and querying records in the remote DB using bash shell, paramiko's forward.py, and even SSHTunnel's CLI command.</p>
<p><em>Problem:</em><br>
I'm running into issues when trying to migrate that over to a single script that will create the tunnel, and query the results. The issue appears to be with my formatting/structuring of SSHTunnel's syntax.</p>
<p>This is what I use to open the tunnel on the shell:</p>
<pre><code>ssh -p SSH_PORT SSH_USER@SERVER_IP -L 33060:127.0.0.1:3306
</code></pre>
<p>This is what I use to open with paramiko's forward.py:</p>
<pre><code>python t_forward.py SERVER_IP:SSH_PORT -r 3306 -u SSH_USER -p 33060 -K "/PATH/TO/PRIVATE/KEY"
</code></pre>
<p>note: I'm currently using a key with no passphrase (for testing/dev purposes)</p>
<p>This is what I used to open with SSHTunnel's command line:</p>
<pre><code>python -m sshtunnel -U SSH_USER -L :33060 -R 127.0.0.1:3306 -p SSH_PORT SERVER_IP -K "/PATH/TO/PRIVATE/KEY"
</code></pre>
<p>Per above, all these are working, and my py script that uses MySQLdb to connect to the database and retrieve records works.</p>
<p>Where things break down is when I try to add the SSH connection string into the script. This is what it currently looks like:</p>
<pre><code>server = SSHTunnelForwarder(
('SERVER_IP', SSH_PORT),
ssh_username='SSH_USER',
ssh_pkey='/PATH/TO/PRIVATE/KEY',
remote_bind_address=('127.0.0.1', 3306),
local_bind_address=('0.0.0.0', 33060)
)
</code></pre>
<p>The MYSQL connection line looks like this:</p>
<pre><code>con = MySQLdb.connect(user='MYSQLDBUSER',passwd='MYSQLDBUSERPASS',db='DATABASE',host='127.0.0.1', port=33060)
</code></pre>
<p>Given that I am able to connect through BASH and through both forward.py and SSHTunnel's CLI, it doesn't seem to be an issue on the server, but rather that my SSHTunnelForwarder is not properly formatted.</p>
<p>Error Message:</p>
<pre><code>Could not establish connection from ('127.0.0.1', 33060) to remote side of the tunnel
</code></pre>
<p>Looking at the var/log/auth.log on the server, I see that it's able to connect, it just seems to break down when the MySQLDB.connect kicks in.</p>
<p>auth.log messages when I get this error:</p>
<pre><code>Oct 9 17:36:31 HOSTSERVER sshd[21141]: Accepted publickey for SSH_USER from SOURCE_IP port 32918 ssh2: RSA <LONG KEY>
Oct 9 17:36:31 HOSTSERVER sshd[21141]: pam_unix(sshd:session): session opened for user SSH_USER by (uid=0)
Oct 9 17:36:31 HOSTSERVER systemd-logind[1217]: New session 144 of user SSH_USER.
Oct 9 17:36:32 HOSTSERVER sshd[21141]: pam_unix(sshd:session): session closed for user SSH_USER
</code></pre>
<p>auth.log message when I use the SSHTunnel CLI (and the results work):</p>
<pre><code>Oct 9 17:39:33 HOSTSERVER sshd[21625]: Accepted publickey for SSH_USER from SOURCE_IP port 44132 ssh2: RSA <LONG KEY>
Oct 9 17:39:33 HOSTSERVER sshd[21625]: pam_unix(sshd:session): session opened for user SSH_USER by (uid=0)
Oct 9 17:39:33 HOSTSERVER systemd-logind[1217]: Removed session 144.
Oct 9 17:39:33 HOSTSERVER systemd-logind[1217]: New session 145 of user SSH_USER.
</code></pre>
<p>It would seem that I'm missing something very basic here... Any help would be appreciated.</p>
| 0 | 2016-10-09T15:28:53Z | 39,946,827 | <p>Found the answer!</p>
<p>It turns out that the script continues to execute before the connection is established. Therefore MySQLDB tries to connect to the port mapping before the tunnel is fully established.</p>
<p>A simple:</p>
<pre><code>import time
...
sleep(1)
...
</code></pre>
<p>Does the trick.</p>
<p>In my case, I added the sleep(1) after "server.start()" and before the code that needs to access the remote DB.</p>
<p>Thanks to @kenster who made me look at the auth.log more carefully, which got me to think about timing more carefully.</p>
| 0 | 2016-10-09T18:05:33Z | [
"python",
"mysql",
"ssh"
] |
Removing first character in a String leaves whitespace | 39,945,294 | <p>I have a textfile that looks like this:</p>
<pre><code>6 Hello World
</code></pre>
<p>I'm reading it in as such:</p>
<pre><code>with open("test.txt") as fp:
for line in fp:
l = line.split(" ")
print(l)
</code></pre>
<p>Which prints me the entire string:</p>
<pre><code>6 Hello World
</code></pre>
<p>I want to remove the '6' character, and just store the string 'Hello World' in another string:</p>
<p>I've done this</p>
<pre><code>newStr = l.replace(l[0],"")
</code></pre>
<p>Which now gives me:</p>
<pre><code> Hello World
</code></pre>
<p>Now I want to remove the leading space, and store the string.
I tried this:</p>
<pre><code>newStr2 = newStr.replace(newStr[0],"")
print(newStr2)
</code></pre>
<p>But this prints:</p>
<pre><code>HelloWorld
</code></pre>
<p>Instead of <code>Hello World</code> (no leading space character)
What am I doing wrong here?
Also, using len() on newStr2 tells me the length is 11, even though it's 10. Is len() including a newline character?</p>
| 1 | 2016-10-09T15:31:33Z | 39,945,307 | <p>That's because <code>newStr.replace(newStr[0],"")</code> is the same as <code>newStr.replace(" ","")</code> which replaces every instance of a single space with an empty string. </p>
<p>What you want is <code>lstrip</code> which removes all leading whitespaces from your string.</p>
<p>More so, to be less verbose, you can simply <em>slice off</em> the leading character from the string and then <code>lstrip</code>:</p>
<pre><code>newStr = l[1:].lstrip()
</code></pre>
<p>On another note, a new line character is a character of length one and that is properly accounted for in <code>len</code>:</p>
<pre><code>>>> len('\n')
1
</code></pre>
<hr>
<p><em>Pro-Tip</em>: <code>line.split()</code> does the same and is more efficient than <code>line.split(" ")</code>. See <a href="http://stackoverflow.com/questions/38285654/why-is-str-strip-so-much-faster-than-str-strip">Why is str.strip() so much faster than str.strip(' ')?</a></p>
<hr>
<p>Essentially, your code becomes:</p>
<pre><code>with open("test.txt") as fp:
for line in fp:
l = line.split()
print(l[1:].lstrip())
</code></pre>
| 1 | 2016-10-09T15:33:05Z | [
"python"
] |
Removing first character in a String leaves whitespace | 39,945,294 | <p>I have a textfile that looks like this:</p>
<pre><code>6 Hello World
</code></pre>
<p>I'm reading it in as such:</p>
<pre><code>with open("test.txt") as fp:
for line in fp:
l = line.split(" ")
print(l)
</code></pre>
<p>Which prints me the entire string:</p>
<pre><code>6 Hello World
</code></pre>
<p>I want to remove the '6' character, and just store the string 'Hello World' in another string:</p>
<p>I've done this</p>
<pre><code>newStr = l.replace(l[0],"")
</code></pre>
<p>Which now gives me:</p>
<pre><code> Hello World
</code></pre>
<p>Now I want to remove the leading space, and store the string.
I tried this:</p>
<pre><code>newStr2 = newStr.replace(newStr[0],"")
print(newStr2)
</code></pre>
<p>But this prints:</p>
<pre><code>HelloWorld
</code></pre>
<p>Instead of <code>Hello World</code> (no leading space character)
What am I doing wrong here?
Also, using len() on newStr2 tells me the length is 11, even though it's 10. Is len() including a newline character?</p>
| 1 | 2016-10-09T15:31:33Z | 39,945,350 | <p>An alternative, if you want to skip the replacing altogether (and assuming that all of your data follows this pattern) is just to take everything from the second element of the list returned by the <code>.strip()</code> on, using <code>join</code> and slicing, as in:</p>
<pre><code>l = " ".join(line.split(" ")[1:])
</code></pre>
| 0 | 2016-10-09T15:36:32Z | [
"python"
] |
Writing multiple rows into CSV file | 39,945,349 | <p>I'm trying to write multiple rows in to a CSV file using python and I've been working on this code for a while to piece together how to do this. My goal here is simply to use the oxford dictionary website, and web-scrape the year and words created for each year into a csv file. I want each row to start with the year I'm searching for and then list all the words across horizontally. Then, I want to be able to repeat this for multiple years.</p>
<p>Here's my code so far:</p>
<pre><code>import requests
import re
import urllib2
import os
import csv
year_search = 1550
subject_search = ['Law']
path = '/Applications/Python 3.5/Economic'
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
header = {'User-Agent':user_agent}
request = urllib2.Request('http://www.oed.com/', None, header)
f = opener.open(request)
data = f.read()
f.close()
print 'database first access was successful'
resultPath = os.path.join(path, 'OED_table.csv')
htmlPath = os.path.join(path, 'OED.html')
outputw = open(resultPath, 'w')
outputh = open(htmlPath, 'w')
request = urllib2.Request('http://www.oed.com/search?browseType=sortAlpha&case-insensitive=true&dateFilter='+str(year_search)+'&nearDistance=1&ordered=false&page=1&pageSize=100&scope=ENTRY&sort=entry&subjectClass='+str(subject_search)+'&type=dictionarysearch', None, header)
page = opener.open(request)
urlpage = page.read()
outputh.write(urlpage)
new_word = re.findall(r'<span class=\"hwSect\"><span class=\"hw\">(.*?)</span>', urlpage)
print str(new_word)
outputw.write(str(new_word))
page.close()
outputw.close()
</code></pre>
<p>This outputs my string of words that were identified for the year 1550. Then I tried to make code write to a csv file on my computer, which it does, but I want to do two things that I'm messing up here:</p>
<ol>
<li>I want to be able to insert multiple rows into this
and </li>
<li>I want to have the year show up in the first spot</li>
</ol>
<p>Next part of my code:</p>
<pre><code>with open('OED_table.csv', 'w') as csvfile:
fieldnames = ['year_search']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'year_search': new_word})
</code></pre>
<p>I was using the <code>csv</code> module's <a href="https://docs.python.org/3/library/csv.html" rel="nofollow">online documentation</a> as a reference for the second part of the code. </p>
<p>And just to clarify, I included the first part of the code in order to give perspective.</p>
| 0 | 2016-10-09T15:36:28Z | 39,946,104 | <p>You really shouldn't parse html with a regex. That said, here's how to modify your code to produce a csv file of all the words found. </p>
<p>Note: for unknown reasons the list of result word varies in length from one execution to the next.</p>
<pre><code>import csv
import os
import re
import requests
import urllib2
year_search = 1550
subject_search = ['Law']
path = '/Applications/Python 3.5/Economic'
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
header = {'User-Agent':user_agent}
# commented out because not used
#request = urllib2.Request('http://www.oed.com/', None, header)
#f = opener.open(request)
#data = f.read()
#f.close()
#print 'database first access was successful'
resultPath = os.path.join(path, 'OED_table.csv')
htmlPath = os.path.join(path, 'OED.html')
request = urllib2.Request(
'http://www.oed.com/search?browseType=sortAlpha&case-insensitive=true&dateFilter='
+ str(year_search)
+ '&nearDistance=1&ordered=false&page=1&pageSize=100&scope=ENTRY&sort=entry&subjectClass='
+ str(subject_search)
+ '&type=dictionarysearch', None, header)
page = opener.open(request)
with open(resultPath, 'wb') as outputw, open(htmlPath, 'w') as outputh:
urlpage = page.read()
outputh.write(urlpage)
new_words = re.findall(
r'<span class=\"hwSect\"><span class=\"hw\">(.*?)</span>', urlpage)
print new_words
csv_writer = csv.writer(outputw)
for word in new_words:
csv_writer.writerow([year_search, word])
</code></pre>
<p>Here's the contents of the <code>OED_table.csv</code> file when it works:</p>
<pre class="lang-none prettyprint-override"><code>1550,above bounden
1550,accomplice
1550,baton
1550,civilist
1550,garnishment
1550,heredity
1550,maritime
1550,municipal
1550,nil
1550,nuncupate
1550,perjuriously
1550,rank
1550,semi-
1550,torture
1550,unplace
</code></pre>
| 3 | 2016-10-09T16:54:50Z | [
"python",
"csv",
"web-scraping"
] |
python: numpy-equivalent of list.pop? | 39,945,410 | <p>Is there a numpy method which is equivalent to the builtin <code>pop</code> for python lists? popping obviously doenst work on numpy arrays, and I want to avoid a list conversion.</p>
| 0 | 2016-10-09T15:42:49Z | 39,945,494 | <p>There is no <code>pop</code> method for NumPy arrays, but you could just use basic slicing (which would be efficient since it returns a view, not a copy):</p>
<pre><code>In [104]: y = np.arange(5); y
Out[105]: array([0, 1, 2, 3, 4])
In [106]: last, y = y[-1], y[:-1]
In [107]: last, y
Out[107]: (4, array([0, 1, 2, 3]))
</code></pre>
<p>If there were a <code>pop</code> method it would return the <code>last</code> value in <code>y</code> and modify <code>y</code>.</p>
<p>Above, </p>
<pre><code>last, y = y[-1], y[:-1]
</code></pre>
<p>assigns the last value to the variable <code>last</code> and modifies <code>y</code>.</p>
| 3 | 2016-10-09T15:51:13Z | [
"python",
"arrays",
"list",
"numpy",
"pop"
] |
keras import error no attribute 'getdlopenflags' | 39,945,443 | <p>I am new to <code>keras</code>, and I have downloaded <code>theano</code>, <code>scipy</code> and <code>numpy</code> modules, but when I want to <code>import keras</code>, the command window tells me that </p>
<pre><code>"Using TensorFlow backend.
Traceback (most recent call last):
File "F:\eclipse\dasd\aaa\aaaa.py", line 7, in <module>
import keras
File "D:\Anaconda2\lib\site-packages\keras\__init__.py", line 2, in <module>
from . import backend
File "D:\Anaconda2\lib\site-packages\keras\backend\__init__.py", line 64, in <module>
from .tensorflow_backend import *
File "D:\Anaconda2\lib\site-packages\keras\backend\tensorflow_backend.py", line 1, in <module>
import tensorflow as tf
File "D:\Anaconda2\lib\site-packages\tensorflow\__init__.py", line 23, in <module>
from tensorflow.python import *
File "D:\Anaconda2\lib\site-packages\tensorflow\python\__init__.py", line 47, in <module>
_default_dlopen_flags = sys.getdlopenflags()
AttributeError: 'module' object has no attribute 'getdlopenflags'"
</code></pre>
<p>my computer system is win7-64 and I haven't downloaded CUDA because my graphics card is ATI's.</p>
| 0 | 2016-10-09T15:45:26Z | 39,945,942 | <p>Keras is using Tensorflow by default. You need to explicitly switch to Theano, see the <a href="https://keras.io/backend/" rel="nofollow">official documentation</a> for the current procedure, for example by setting the environment variable <code>KERAS_BACKEND</code> to <code>theano</code>.</p>
| 0 | 2016-10-09T16:38:26Z | [
"python",
"machine-learning",
"theano",
"keras"
] |
How to verify only the elements names in a dictionary object? | 39,945,475 | <p>I have a VERY big dictionary in python and when I type dict.items(dic_name) it shows up so many stuff (matrix, vectors, etc). I just would like to see the elements names. What should I do?</p>
<p>For example when I have a list I type names (<code>my.list</code>) and it just displays the list elements name. Is there a command like that in Python?</p>
| -2 | 2016-10-09T15:49:33Z | 39,945,633 | <p>Well, if you only keys, ask for keys, not items :</p>
<pre><code>my_dict.keys()
</code></pre>
<p>If you strictly need it to be a list you can do :</p>
<pre><code>my_list = list(my_dict.keys())
</code></pre>
<p>Now if you want to iterate through them:</p>
<p>in python 2:</p>
<pre><code>for k in my_dict.iterkeys():
do_something_with(k)
</code></pre>
<p>in python 3:</p>
<pre><code>for k in my_dict.keys():
do_something_with(k)
</code></pre>
| 1 | 2016-10-09T16:04:51Z | [
"python",
"python-2.7",
"python-3.x"
] |
Callback not called if it is a class method | 39,945,584 | <p>Python newbie question: the callback method <code>handlePackets</code> never gets called if it is a class method. If it is not in a class it works fine. What can I do?</p>
<pre><code>class Receiver:
def __enter__(self):
self.serial_port = serial.Serial('/dev/ttyUSB0', 115200)
self.xbee = ZigBee(self.serial_port, escaped=True, callback=self.handlePackets)
Logger.info('Receiver: enter')
return self
def __exit__(self ,type, value, traceback):
Logger.info('Receiver: exit')
self.serial_port.close()
def handlePackets(data):
Logger.info('Receiver: packet incoming')
</code></pre>
| 0 | 2016-10-09T15:59:23Z | 39,945,648 | <p>I can bet it is because, whatever is calling your callback from within <code>ZigBee</code> is failing silently. The interpreter calls your function with 2 parameters, but as you have defined it -- it takes only one.</p>
<pre><code>def handlePackets(self, data):
#^^^^
</code></pre>
| 0 | 2016-10-09T16:05:47Z | [
"python",
"python-2.7"
] |
Callback not called if it is a class method | 39,945,584 | <p>Python newbie question: the callback method <code>handlePackets</code> never gets called if it is a class method. If it is not in a class it works fine. What can I do?</p>
<pre><code>class Receiver:
def __enter__(self):
self.serial_port = serial.Serial('/dev/ttyUSB0', 115200)
self.xbee = ZigBee(self.serial_port, escaped=True, callback=self.handlePackets)
Logger.info('Receiver: enter')
return self
def __exit__(self ,type, value, traceback):
Logger.info('Receiver: exit')
self.serial_port.close()
def handlePackets(data):
Logger.info('Receiver: packet incoming')
</code></pre>
| 0 | 2016-10-09T15:59:23Z | 39,945,716 | <p>I had to add <code>self</code> as first parameter to packetHandler. This is required for all class methods and I forgot to put it in.</p>
| 0 | 2016-10-09T16:12:56Z | [
"python",
"python-2.7"
] |
PolarColor map plot of grid data in Pyhton | 39,945,601 | <p>I want to plot a color map of a grid data, grid in polar form. In data, r ranges from 1 to 2 and theta 0 to 360. I want map like this:</p>
<p><a href="http://i.stack.imgur.com/NEFQ0.png" rel="nofollow"><img src="http://i.stack.imgur.com/NEFQ0.png" alt="enter image description here"></a>
I plotted like this </p>
<pre><code>#x1 of shape(12,)
#y1 0f shape(36,1)
#z of shape(36,12)
fig=plt.figure()
ax=fig.add_subplot(111) #Output Figure 1
#ax=fig.add_subplot(111,polar='True') #Output Figure 2
ax=fig.add_subplot(111)
ax.pcolor(y1,x1,z)
plt.show()
</code></pre>
<p>Output:
<a href="http://i.stack.imgur.com/INPNp.png" rel="nofollow"><img src="http://i.stack.imgur.com/INPNp.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/38RkJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/38RkJ.png" alt="enter image description here"></a></p>
<p>Any idea how to plot the above figure? I also tried converting r, theta into x,y then i got color map in r<1 range which i don't want.</p>
| 1 | 2016-10-09T16:00:44Z | 39,946,574 | <p>As pointed out <a href="http://stackoverflow.com/a/6457331/6935985">here</a>, <code>pcolormesh()</code> is useful for this.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
theta = np.linspace(0, 2*np.pi, 36)
r = np.linspace(1, 2, 12)
R, THETA = np.meshgrid(r, theta)
Z = np.sin(THETA) * R
plt.subplot(111, projection='polar')
plt.pcolormesh(THETA, R, Z)
plt.gca().set_rmin(0.0)
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/U9lbj.png" rel="nofollow">output figure</a></p>
| 1 | 2016-10-09T17:41:55Z | [
"python",
"matlab",
"matplotlib"
] |
Converting input string of integers to list, then to ints in python? | 39,945,615 | <p>I want the user to input an integer (6 digits long, so 123456 rather than just 1), and then convert that input into a list, <code>[1,2,3,4,5,6]</code>.</p>
<p>I tried this:</p>
<pre><code>user_input = list(input("Please enter an 8 digit number")
numbers = [int(i) for i in user_input]
</code></pre>
<p>I want to be able to perform mathematical stuff with the numbers list, but I keep getting the error "int is not iterable". To be frank, I'm not entirely sure what I'm doing, or sure that the "numbers = [...] " is even necessary, or if it should just be <code>numbers = user_input</code>. Trying <code>numbers = [i for i in user_input]</code> gets the same error.</p>
<p>Also, I realise I could either run a loop to get each number from the user, or ask them to use commas in between each in order to use the <code>.split(",")</code>, but I'd rather not as it seems messy to the user.</p>
<p>Edit: I've been switching things between versions, so sorry for any confusion. This was written in 2.7, though I intend to use Python 3.</p>
| 2 | 2016-10-09T16:02:32Z | 39,945,689 | <p>In Python 2.7, <code>input()</code> returns an integer. To read input as a string use the function <code>raw_input()</code> instead. Alternatively, you can switch to Python 3 and where <code>input()</code> always returns a string.</p>
<p>Also your solution isn't very neat in case the user is providing numbers with more than 1 digits. For example the string "123" can be interpreted as [1, 2, 3], [12, 3] and so on. </p>
<p>A neat solution is to ask the user to provide the input separated by spaces as follows x_1, x_2, ... x_n</p>
<p>Then your code in Python 3.0 will look like</p>
<pre><code>lst = [int(x) for x in input().split()]
</code></pre>
<p>And for Python 2.7</p>
<pre><code>lst = [int(x) for x in raw_input().split()]
</code></pre>
| 1 | 2016-10-09T16:10:20Z | [
"python"
] |
Converting input string of integers to list, then to ints in python? | 39,945,615 | <p>I want the user to input an integer (6 digits long, so 123456 rather than just 1), and then convert that input into a list, <code>[1,2,3,4,5,6]</code>.</p>
<p>I tried this:</p>
<pre><code>user_input = list(input("Please enter an 8 digit number")
numbers = [int(i) for i in user_input]
</code></pre>
<p>I want to be able to perform mathematical stuff with the numbers list, but I keep getting the error "int is not iterable". To be frank, I'm not entirely sure what I'm doing, or sure that the "numbers = [...] " is even necessary, or if it should just be <code>numbers = user_input</code>. Trying <code>numbers = [i for i in user_input]</code> gets the same error.</p>
<p>Also, I realise I could either run a loop to get each number from the user, or ask them to use commas in between each in order to use the <code>.split(",")</code>, but I'd rather not as it seems messy to the user.</p>
<p>Edit: I've been switching things between versions, so sorry for any confusion. This was written in 2.7, though I intend to use Python 3.</p>
| 2 | 2016-10-09T16:02:32Z | 39,945,704 | <p>Function <code>input</code> behaves quite differently in Python 2 and in Python 3.</p>
<p>This seems to be Python 2. In Python 2, <code>input</code> evaluates entered data as Python code. If only digits are entered, <code>input</code> will return one integer. Converting that to a list is not possible, hence the error.</p>
<p><code>input</code> is unsafe and causes many problems, so it is best to avoid it. Use <code>raw_input</code> instead.</p>
<pre><code>user_input = raw_input("Please enter an 8 digit number: ")
</code></pre>
<p>This will return a string, e.g. <code>'12345678'</code>.</p>
<p>This can be converted to a list. The list will iterate through the string character by character.</p>
<pre><code>digits = list(user_input) # e.g. ['1', '2', '3', '4', '5', '6', '7', '8']
</code></pre>
<p>But that is not even needed, you can directly do as you did:</p>
<pre><code>numbers = [int(i) for i in user_input] # e.g. [1, 2, 3, 4, 5, 6, 7, 8]
</code></pre>
<hr>
<p>BTW, the Python 3 version of <code>input</code> is the same as Python 2 <code>raw_input</code>.</p>
| 1 | 2016-10-09T16:11:54Z | [
"python"
] |
Adding values from a dataframe-A A.column1 by matching values in A.column2 to the B.column1 name of another dataframe B | 39,945,643 | <p>I have two dataframes (df) A and B. df A has a column called 'Symbol' with non-unique stock-ticker-symbols as values in random order and the corresponding amount of buy or sell quantities in another column called 'Shares'; it is indexed by non-negative integers. df B, indexed by dates in the same date-order as df A and same number of rows as df A, has the same ticker symbols as df A as unique column names. I need to populate all df B rows with the amount of stock purchase or sell amounts from corresponding <code>A.Shares.values</code>. I get an error when trying the below code. Alternatively, would it be possible to loop through the df A rows using <code>join</code> command constraint to match df A's column values to column names of df B similar to SQL queries? </p>
<p><code>import pandas as pd</code></p>
<p><code>bCN = B.dtypes.index # list of column names in df B to be used for populating its stock quantity based on matching values from df A</code></p>
<p><code>A = pd.DataFrame({'Date': ['2011-01-14', '2011-01-19', '2011-01-19'],
'Symbol': ['AAPL', 'AAPL', 'IBM'], 'Order':['BUY','SELL','BUY'],'Shares':[1500, 1500, 4000]}) #example of A</code></p>
<p><code>B = pd.DataFrame({'AAPL':[0,0,0],'IBM': [0,0,0], index = pd.date_range(start, end)}) #example of B</code></p>
<p>Expected Result </p>
<p><code>B = pd.DataFrame({'AAPL':[1500,0,-1500],'IBM': [0,0,400], index = pd.date_range(start, end)}) #example of resultant B</code></p>
<p>Attempt </p>
<pre><code> B = A.pivot('Date','Symbol','Shares')
B = B.fillna(value = 0)
B['Cash'] = pd.Series([0]*len(B.index),index=B.index)
for index, row in A.iterrows():
if row['Order'] == 'SELL':
B.loc[row, A['Symbol']] *= -1
</code></pre>
| 0 | 2016-10-09T16:05:22Z | 39,946,054 | <p>first of all, I highly suggest you to read <a href="http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples">how-to-make-good-reproducible-pandas-examples</a></p>
<p>I think you could use pivot such has:</p>
<pre><code>B = A.pivot('Date','Symbol','Shares')
</code></pre>
<p>Since image of dataframe are hard to copy paste I can't show you the exact result you could get using this method</p>
| 0 | 2016-10-09T16:49:42Z | [
"python",
"pandas",
"join",
"dataframe"
] |
TfidfVectorizer: ValueError: not a built-in stop list: russian | 39,945,693 | <p>I try to apply TfidfVectorizer with russian stop words </p>
<pre><code>Tfidf = sklearn.feature_extraction.text.TfidfVectorizer(stop_words='russian' )
Z = Tfidf.fit_transform(X)
</code></pre>
<p>and i get</p>
<pre><code>ValueError: not a built-in stop list: russian
</code></pre>
<p>When i use english stop words that's correct</p>
<pre><code>Tfidf = sklearn.feature_extraction.text.TfidfVectorizer(stop_words='english' )
Z = Tfidf.fit_transform(X)
</code></pre>
<p>How to improve it?
Full traceback</p>
<pre><code><ipython-input-118-e787bf15d612> in <module>()
1 Tfidf = sklearn.feature_extraction.text.TfidfVectorizer(stop_words='russian' )
----> 2 Z = Tfidf.fit_transform(X)
C:\Program Files\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py in fit_transform(self, raw_documents, y)
1303 Tf-idf-weighted document-term matrix.
1304 """
-> 1305 X = super(TfidfVectorizer, self).fit_transform(raw_documents)
1306 self._tfidf.fit(X)
1307 # X is already a transformed view of raw_documents so
C:\Program Files\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py in fit_transform(self, raw_documents, y)
815
816 vocabulary, X = self._count_vocab(raw_documents,
--> 817 self.fixed_vocabulary_)
818
819 if self.binary:
C:\Program Files\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py in _count_vocab(self, raw_documents, fixed_vocab)
745 vocabulary.default_factory = vocabulary.__len__
746
--> 747 analyze = self.build_analyzer()
748 j_indices = _make_int_array()
749 indptr = _make_int_array()
C:\Program Files\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py in build_analyzer(self)
232
233 elif self.analyzer == 'word':
--> 234 stop_words = self.get_stop_words()
235 tokenize = self.build_tokenizer()
236
C:\Program Files\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py in get_stop_words(self)
215 def get_stop_words(self):
216 """Build or fetch the effective stop words list"""
--> 217 return _check_stop_list(self.stop_words)
218
219 def build_analyzer(self):
C:\Program Files\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py in _check_stop_list(stop)
88 return ENGLISH_STOP_WORDS
89 elif isinstance(stop, six.string_types):
---> 90 raise ValueError("not a built-in stop list: %s" % stop)
91 elif stop is None:
92 return None
ValueError: not a built-in stop list: russian
</code></pre>
| 0 | 2016-10-09T16:10:47Z | 39,945,754 | <p>could you guys read <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html" rel="nofollow">documentation</a> first before posting?</p>
<blockquote>
<p>stop_words : string {âenglishâ}, list, or None (default)</p>
<p>If a string, it is passed to _check_stop_list and the appropriate stop list is returned. âenglishâ is currently the only supported
string value.</p>
<p>If a list, that list is assumed to contain stop words, all of which will be removed from the resulting tokens. Only applies if
analyzer == 'word'.</p>
<p>If None, no stop words will be used. max_df can be set to a value in the range [0.7, 1.0) to automatically detect and filter stop words
based on intra corpus document frequency of terms.</p>
</blockquote>
| 1 | 2016-10-09T16:16:19Z | [
"python",
"tf-idf"
] |
httplib.HTTPSConnection issue : CERTIFICATE_VERIFY_FAILED | 39,945,702 | <p>I'm trying to access a website with httplib library but i'm getting this error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)</p>
<pre><code>c = httplib.HTTPSConnection('IP', 443)
c.request(method,url);
</code></pre>
<p>Because the certificate is self-signed. How can I disable the certificate verification?</p>
<p>Thanks!</p>
| 0 | 2016-10-09T16:11:45Z | 39,945,733 | <p><a href="http://stackoverflow.com/questions/5319430/how-do-i-have-python-httplib-accept-untrusted-certs">How do I have python httplib accept untrusted certs?</a></p>
<pre><code>httplib.HTTPSConnection(hostname, timeout=5, context=ssl._create_unverified_context())
</code></pre>
| 2 | 2016-10-09T16:14:45Z | [
"python"
] |
Reading a pre-formatted file using read() in python | 39,945,719 | <p>I am trying to build a mini text based game just as a first project in python. I decided to write my story and content in text files. I am designing the game such that each character from the file is read and immediately printed out to the screen. </p>
<pre><code>def load_Intro():
liOb = open('loadgame.txt','r')
while True:
ch = liOb.read(1)
sys.stdout.write(ch)
time.sleep(0.002)
sys.stdout.flush()
if ch == "\n": continue
elif ch is None: break
print("\n")
</code></pre>
<p>However my text files have multiple paragraphs separated by one or two lines, and some of its own formatting. For example here is an excerpt from yet to be finalized intr : </p>
<blockquote>
<p>You are Max, a college student who lives a very ordinary life. One
day, you decide to get out of this ordinary life and do something
worth adventurous and be proud of! You skipped college for a week and
worked overtime in your workplace, just to get enough money. For the
past 1 week, you worked 16 hours a day, and had saved enough money for
a cozy little vacation in the small town of Belleyard Upon Tyne. You
pack your bags, and leave your house the next day.</p>
<p>Since you had to spend your money wisely, you decide to spend your
days in a older hotel. You checked in a hotel called The Silver Mare.
Your first two days were spent awesome. However this morning, after
you wake up, you wake up feeling tired. Not only that, few times you
felt someone following and creeping behind you. You looked back
multiple times...... only to notice there's no one there. You ignored
that feeling away as hangover due and prepare to enjoy your remaining
holidays.</p>
<p>Date : October 21, 1997</p>
<p>{More Content}</p>
</blockquote>
<p>When the program is run, it reads the first paragraph fine. Correct me if I am wrong, the last condition detects there are no more characters to detect, and is stuck in the loop. I need help in figuring out how to read and display the contents of the file exactly in the same format my file is written in, character by character till the end of the file.</p>
| 0 | 2016-10-09T16:13:28Z | 39,945,776 | <p>Why try to read character by character? Read it all into the buffer at once, and then display it character by character</p>
<pre><code>import sys
import time
liOb = open('loadgame.txt','r')
content=str(liOb.read())
for i in range(len(content)):
sys.stdout.write(content[i])
time.sleep(0.002)
sys.stdout.flush()
</code></pre>
| 0 | 2016-10-09T16:19:10Z | [
"python",
"python-3.x",
"python-3.5"
] |
Fixing return format for my function | 39,945,808 | <p>The code for my function works correctly, but it is not returning the function in the format I would like. The function counts seed values in a 2nd sequence and then is supposed to return the seed counts as a list of integers. It is returning the seed counts but on separate lines rather then in a list. Here is my code and what its returning in command prompt.</p>
<pre><code> def count_each(seeds,xs):
for c in seeds:
count=0
for d in xs:
if c==d:
count=count+1
print ([count])
</code></pre>
<p>count_each([10,20],[10,20,30,10])</p>
<p>count_each([4,8],[1,2,4,4,4,8,8,10])</p>
<p>In command prompt, I would like this function to print [2,1] for count_each([10,20],[10,20,30,10]) and [3,2] for count_each([4,8],[1,2,4,4,4,8,8,10]) but instead it is printing each seed value on its own line like so </p>
<p><a href="http://i.stack.imgur.com/vXAd3.png" rel="nofollow">http://i.stack.imgur.com/vXAd3.png</a></p>
<p>In the picture above it prints [2], [1], [3], and [2] on separate lines when it should instead print just two lines of [2,1] and [3,2] for the two sequences. How can I have the function return the seed values for each sequence as a list instead of having the values on separate lines.</p>
<p>Edit: I need to accomplish this without importing from other modules and with the simplest code possible.</p>
| 1 | 2016-10-09T16:23:02Z | 39,945,945 | <p>I think your code does not work. Try this:</p>
<pre><code>def count_each(seeds,xs):
from collections import Counter
counter_dict = dict(Counter(xs))
count = []
for s in seeds:
count.append(counter_dict[s])
print count
if __name__ == "__main__":
count_each([10,20],[10,20,30,10])
count_each([4,8],[1,2,4,4,4,8,8,10])
</code></pre>
<p>Basically, <code>Counter</code> gives you a count for each unique element in a list.</p>
<h1>Update:</h1>
<p>Just found a <code>count</code> method for Python's <code>list</code>. The code is as follows:</p>
<pre><code>def count_each(seeds,xs):
from collections import Counter
count = []
for s in seeds:
count.append(xs.count(s))
print count
</code></pre>
| 0 | 2016-10-09T16:38:39Z | [
"python",
"list",
"format",
"sequence"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.