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
In-game save feature (in tkinter game)
40,071,582
<p>I'm working on a text-based game in Python using Tkinter. All the time the window contains a Label and a few Buttons (mostly 3). If it didn't have GUI, I could just use Pickle or even Python i/o (.txt file) to save data and later retrieve it. But what is the best way to tell the program to load the exact widgets wi...
1
2016-10-16T14:46:37Z
40,071,607
<p>You need to save stuff in some kind of config file. In generel I'd recommend JSON and YAML as file formats also ini for ease of parsing.</p> <p>Also, do not forget about the windows registry (portability lost then though).</p>
1
2016-10-16T14:49:05Z
[ "python", "tkinter" ]
In-game save feature (in tkinter game)
40,071,582
<p>I'm working on a text-based game in Python using Tkinter. All the time the window contains a Label and a few Buttons (mostly 3). If it didn't have GUI, I could just use Pickle or even Python i/o (.txt file) to save data and later retrieve it. But what is the best way to tell the program to load the exact widgets wi...
1
2016-10-16T14:46:37Z
40,074,406
<p>My understanding was that you need a widget manager, to put them where you want and it is easy to pick up values.</p> <p>Create a new class called Manager, make two functions, _setNewWidget, _deleteWidget, like this:</p> <pre><code>class Manager(): def __init__(self, *args, **kwargs): objects = {} ...
1
2016-10-16T19:17:15Z
[ "python", "tkinter" ]
How to invoke an endpoint method using App Engine?
40,071,615
<p>this is a very simple question for App Engine users. I'm new in cloud computing but i would like to know how to invoke my endpoint.method. I'm developing on my machine using pycharm. This is my main.py code:</p> <pre><code>@endpoints.api(name='firstapi', version='v1') </code></pre> <p>class MainHandler(webapp2.Req...
0
2016-10-16T14:49:28Z
40,083,927
<p>You should follow the quick start guide for Google Endpoints for App Engine. <a href="https://cloud.google.com/endpoints/docs/frameworks/python/quickstart-frameworks-python" rel="nofollow">https://cloud.google.com/endpoints/docs/frameworks/python/quickstart-frameworks-python</a></p>
0
2016-10-17T10:25:46Z
[ "python", "google-app-engine", "google-cloud-platform" ]
Non Blocking calls using Tornado and Python Eve
40,071,624
<p>I have a Eve Application with Tornado. </p> <pre><code>http_server = HTTPServer(WSGIContainer(app)) http_server.listen(5000) IOLoop.instance().start() </code></pre> <p>I make a post call on of my API that takes a long time and sends a mail to the user when the process is done. How can I make the call non blocking ...
1
2016-10-16T14:50:00Z
40,077,706
<p>Eve is written in Flask so by design it's blocking code and there's no simple way to make it magically non-blocking. Running your eve project in tornado will not help either. You can however use <a href="http://gunicorn.org/" rel="nofollow"><code>gunicorn</code></a> or <a href="https://hendrix.readthedocs.io/en/late...
1
2016-10-17T02:34:36Z
[ "python", "tornado", "eve" ]
How to look up rows in certain condition
40,071,628
<p>I have a dataframe and I would like to search strange rows like below :</p> <pre><code>  month 0 201605     1 201606 2 201607 3 08 4 nan 5 201610 </code></pre> <p>For instance, I would like to extract rows with elements that is not 6 digits like below :</p> <pre><code> month 3 08 4 n...
0
2016-10-16T14:50:34Z
40,071,710
<p>Suppose your month column is of <code>str</code> type, you can use <code>.str.len()</code> to get the number of digits for each element and use the result for subsetting:</p> <pre><code>df[df.month.str.len() != 6] # month #3 08 #4 NaN </code></pre>
1
2016-10-16T14:59:16Z
[ "python", "pandas", "dataframe" ]
Python Regex sub doesn't replace line breaks
40,071,919
<p>I have a robot that brings me an html code like this:</p> <pre><code>&lt;div class="std"&gt; &lt;p&gt;CAR: &lt;span&gt;Onix&lt;/span&gt; &lt;/p&gt; &lt;p&gt;MODEL: LTZ&lt;/p&gt; &lt;p&gt; &lt;span&gt;COLOR: &lt;span&gt;Black&lt;/span&gt; &lt;/p&gt; &lt;p&gt;ACESSORIES: &lt;span&gt;ABS&lt...
0
2016-10-16T15:19:48Z
40,072,115
<p>I think this should work for you </p> <pre><code>&gt;&gt;&gt; string = """ CAR: Onix MODEL: LTZ COLOR: Black ACESSORIES: ABS DESCRIPTION: The Chevrolet Onix is a subcompact car launched by American automaker Chevrolet in Brazil at the 2012 São Paulo International Motor Show[1] to succeed some versions ...
0
2016-10-16T15:42:24Z
[ "python", "regex", "line-breaks" ]
Python Regex sub doesn't replace line breaks
40,071,919
<p>I have a robot that brings me an html code like this:</p> <pre><code>&lt;div class="std"&gt; &lt;p&gt;CAR: &lt;span&gt;Onix&lt;/span&gt; &lt;/p&gt; &lt;p&gt;MODEL: LTZ&lt;/p&gt; &lt;p&gt; &lt;span&gt;COLOR: &lt;span&gt;Black&lt;/span&gt; &lt;/p&gt; &lt;p&gt;ACESSORIES: &lt;span&gt;ABS&lt...
0
2016-10-16T15:19:48Z
40,072,166
<p>I think there are two parts to your problem, First is to Join the string in two lines like below<br> <code>COLOR: Black</code></p> <p>to<br> <code>COLOR: black</code></p> <p>and then remove all empty lines</p> <p>For first part you could use replace your <code>re.sub</code> with following<br> <code>cleantext = r...
1
2016-10-16T15:47:43Z
[ "python", "regex", "line-breaks" ]
How to use the NumPy installed by Pacman in virtualenv?
40,071,987
<p>My system is Archlinux. My project will use NumPy, and my project is in a virtual environment created by virtualenv.</p> <p>As it is difficult to install NumPy by pip, I install it by Pacman:</p> <p><code>sudo pacman -S python-scikit-learn</code></p> <p>But how can I use it in virtualenv?</p>
0
2016-10-16T15:27:56Z
40,072,017
<p>You can create the virtualenv with the <code>--system-site-packages</code> switch to use system-wide packages in addition to the ones installed in the stdlib.</p>
0
2016-10-16T15:30:59Z
[ "python", "linux", "virtualenv", "pacman", "archlinux-arm" ]
hasattr returns always True for app engine ndb entity
40,072,033
<p>I am applying <a href="http://stackoverflow.com/a/19869907/492258">this answer</a> to my project</p> <p>This is my ndb entity where is_deleted added later.</p> <pre><code>class FRoom(ndb.Model): location = ndb.StringProperty(default="") is_deleted = ndb.BooleanProperty(default=False) #added later #o...
0
2016-10-16T15:33:01Z
40,072,305
<p>This is expected behaviour due to the <code>is_deleted</code> property having the <code>default</code> option set: the datastore will automatically return that default value if the property was not explicitly set.</p> <p>From the <a href="https://cloud.google.com/appengine/docs/python/ndb/entity-property-reference#...
0
2016-10-16T16:02:13Z
[ "python", "google-app-engine", "hasattr" ]
Python server is sending truncated images over TCP
40,072,052
<p>I have a simple server on my Windows PC written in python that reads files from a directory and then sends the file to the client via TCP.</p> <p>Files like HTML and Javascript are received by the client correctly (sent and original file match).<br> The issue is that <strong>image data is truncated</strong>. </p> ...
1
2016-10-16T15:34:58Z
40,072,086
<p>Since you're dealing with images, which are binary files, you need to open the files in <em>binary</em> mode.</p> <pre><code>open(filename, 'rb') </code></pre> <p>From the Python documentation for <a href="https://docs.python.org/2/library/functions.html#open" rel="nofollow"><code>open()</code></a>:</p> <blockquo...
3
2016-10-16T15:39:11Z
[ "python", "tcp", "server" ]
How can i display my data in database and export it to pdf -Django
40,072,058
<p>my x variable is getting all the data in my database, i guess? someone help me how can i display all data and export it to pdf file.</p> <pre><code>response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="WishList.pdf"' buffer = BytesIO() # Create the PDF ob...
0
2016-10-16T15:35:40Z
40,100,704
<p>Your Variable x won't return anything you can print into the PDF, because its a querryset and not a couple strings attached to each other. I just started working with Django and getting the values works something like this:</p> <pre><code>x = Item.objects.all[0].name </code></pre> <p>This Code snippet will asigne ...
0
2016-10-18T06:05:47Z
[ "python", "django", "django-models", "django-views" ]
How would i loop this bit of code so that It will go to the start again?
40,072,080
<p>I'm a new to python and i need a bit of help. I just need to know how would i loop this bit of code so that after it says "please try again..." it will then go onto "Do you want to roll or stick". Thanks in advance.</p> <pre><code>Roll = input("Do you want to Roll or Stick?") if Roll in ("Roll" , "roll"): print...
1
2016-10-16T15:38:36Z
40,072,107
<p>You can wrap up your code with <a href="https://wiki.python.org/moin/WhileLoop" rel="nofollow"><code>while</code></a> loop:</p> <pre><code>while True: Roll = input("Do you want to Roll or Stick?") if Roll.lower() == 'exit': break ... else: print("Please try again. Type 'exit' to exit...
1
2016-10-16T15:40:52Z
[ "python" ]
Exception inside a while loop error
40,072,126
<p>I'm trying to get this code to loop until the user gives correct input but after the first loop if the user gives bad input again the program will crash and give me a ValueError</p> <pre><code>while True: try: input1,input2= input("Enter the Lat and Long of the source point separated by a comma eg 50,30...
0
2016-10-16T15:43:19Z
40,072,539
<p>The trick would be in using the <em>continue</em> statement when you get the exception. That will restart the loop and go into the area protected by the <em>try</em> statement so if you get another exception it won't crash your program.</p> <pre><code>while True: try: value1, value2 = input("Enter the L...
0
2016-10-16T16:24:36Z
[ "python", "while-loop", "exception-handling" ]
Random word generator python
40,072,142
<p>So this is the code I have. The outcome is something along "['jjjjjjj', 'tt', 'dddd', 'eeeeeeeee']". How can I change the list comprehension to allow for the function random.choice to repeat for each letter of each 'word'?</p> <pre><code>lista=[random.randint(1,10)*random.choice(string.ascii_letters) for i in range...
0
2016-10-16T15:44:44Z
40,072,246
<p>I suppose you mean you want "abcd" and "jdhn" instead of "aaaa" and "jjjj" for the purpose of testing a sorting algorithm or some such.</p> <p>If so, try this</p> <pre><code>lista=["".join(random.choice(string.ascii_letters) for j in range(random.randint(1,10)) ) for i in range(random.randint(1,10)) ] </code></pre...
1
2016-10-16T15:56:41Z
[ "python" ]
Random word generator python
40,072,142
<p>So this is the code I have. The outcome is something along "['jjjjjjj', 'tt', 'dddd', 'eeeeeeeee']". How can I change the list comprehension to allow for the function random.choice to repeat for each letter of each 'word'?</p> <pre><code>lista=[random.randint(1,10)*random.choice(string.ascii_letters) for i in range...
0
2016-10-16T15:44:44Z
40,072,252
<p>You'll need a nested list comorehension. You need to rerun random.choice for every letter. Something along the lines of</p> <pre><code>[ [Random.choice(string.asciiletters) for x in range(y)] for you in range(5)] </code></pre> <p>Will give you 5 'words' each of length y.</p>
0
2016-10-16T15:57:32Z
[ "python" ]
Installing matplotlib using pip gives error
40,072,151
<p>I am new to python and is using pip to download and install packages. I ran the following code on my command window and it throws an error</p> <pre><code>pip install matplotlib </code></pre> <p>And the process starts as </p> <pre><code>Collecting matplotlib Using cached matplotlib-1.5.3-cp27-cp27m-win32.whl Col...
0
2016-10-16T15:45:50Z
40,072,198
<p>Try <code>python -m pip install matplotlib</code>.</p> <p>or</p> <ol> <li>Open the <code>cmd</code> as administrator </li> <li>then <code>python -m pip install matplotlib</code></li> </ol>
0
2016-10-16T15:51:34Z
[ "python", "matplotlib", "pip" ]
redirection not working in python for locally hosted form snippet for cgiserver
40,072,177
<p>I am trying to use the following created html page to access information from a cgiserver using python. I am implementing auto redirection using javascript at bottom</p> <pre><code>&lt;form action="http://pi-web.cisco.com/pims-home/fcgi-bin/BugReport/DDTS.cgi?Function=DDTS"&gt; &lt;input type="hidden" name="Functio...
-1
2016-10-16T15:48:47Z
40,072,438
<p>You can only get first page because there is no redirect.</p> <p>In HTML page you have form, that is automatically submitted to <code>http://pi-web.cisco.com/pims-home/fcgi-bin/BugReport/DDTS.cgi?Function=DDTS</code>. First site returns with code 200 and not 301/302. Requests library doesn't parse javascript inside...
0
2016-10-16T16:14:31Z
[ "javascript", "python", "cgi", "python-requests" ]
Python 2.7: Add 2 list items in a function
40,072,224
<p>I want to be able to add multiple items to my code with a function. But I want to be able to still add one single item, or none. Here is and example.</p> <pre><code>listX = ["a", "b", "c"] def addList(add): if add != "null": listX.append(add) addList("d") </code></pre> <p>Adds d at the end. Simple.</...
1
2016-10-16T15:54:23Z
40,072,261
<p>Your Function <code>addList</code> expects only 1 argument, when you say</p> <pre><code>addList("e" + "f") # it passes it as addList("ef") </code></pre> <p>To solve your problem simply use <code>*</code> to get multiple arguments, and <code>extend</code> to add to it easily:</p> <pre><code>listX = ['a', 'b', 'c']...
1
2016-10-16T15:58:20Z
[ "python", "python-2.7", "function", "variables" ]
Python 2.7: Add 2 list items in a function
40,072,224
<p>I want to be able to add multiple items to my code with a function. But I want to be able to still add one single item, or none. Here is and example.</p> <pre><code>listX = ["a", "b", "c"] def addList(add): if add != "null": listX.append(add) addList("d") </code></pre> <p>Adds d at the end. Simple.</...
1
2016-10-16T15:54:23Z
40,072,291
<p>The problem is breaking down the <code>'e' + 'f'</code> thing you have there.</p> <p>As long as your parameter is an interable, this should work</p> <pre><code>def addList(iterable): for item in iterable: listX.append(item) </code></pre>
0
2016-10-16T16:01:05Z
[ "python", "python-2.7", "function", "variables" ]
Why can't I install Cassandra-driver
40,072,283
<p>I am studying Cassandra by its document. But when I use "pip install cassandra-driver" to install cassandra-driver ,failed like this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-...
0
2016-10-16T16:00:28Z
40,072,524
<p>I figure out</p> <p>"sudo pip install cassandra-driver"</p> <p>it takes a little long time I was just too impatient </p>
0
2016-10-16T16:23:02Z
[ "python", "database", "cassandra" ]
Appending to a list from a for loop (to read a text file)
40,072,316
<p>How do I append to an undetermined list from a for loop? The purpose is to first slice each line by '-'. Then I would like to append these slices to an array without a determined size. I have the following code, and am loosing hair because of how simple this seems! </p> <p>Each line in the text file looks like the ...
0
2016-10-16T16:03:02Z
40,072,518
<p>Do this: <code>for templine in f.read():</code> You forgot the read() methid</p>
-1
2016-10-16T16:22:25Z
[ "python", "string", "list", "append", "slice" ]
Appending to a list from a for loop (to read a text file)
40,072,316
<p>How do I append to an undetermined list from a for loop? The purpose is to first slice each line by '-'. Then I would like to append these slices to an array without a determined size. I have the following code, and am loosing hair because of how simple this seems! </p> <p>Each line in the text file looks like the ...
0
2016-10-16T16:03:02Z
40,072,665
<p>Try something like that if you want to get list of formated strings.</p> <pre><code>f = open('Lightning.txt') lightning =list() for templine in f: if not templine.startswith('2014'): continue # We are splitting the line by ',' to get [2014-06-13, 42.7,-73.8, 27] templine = templine.split(',') # Afte...
0
2016-10-16T16:36:09Z
[ "python", "string", "list", "append", "slice" ]
Appending to a list from a for loop (to read a text file)
40,072,316
<p>How do I append to an undetermined list from a for loop? The purpose is to first slice each line by '-'. Then I would like to append these slices to an array without a determined size. I have the following code, and am loosing hair because of how simple this seems! </p> <p>Each line in the text file looks like the ...
0
2016-10-16T16:03:02Z
40,073,657
<p>This is an ideal job for the <a href="https://docs.python.org/2/library/csv.html#csv.reader" rel="nofollow">csv</a> lib:</p> <pre><code>import csv with open('Lightning.txt') as f: data = [] # unpack the elements from each line/row for dte, _, _, i in csv.reader(f): # if the date starts with 201...
0
2016-10-16T18:07:51Z
[ "python", "string", "list", "append", "slice" ]
Python String Extraction for football results
40,072,320
<p>I have the following string:</p> <pre><code>"W-Leicester-3-0-H|W-Hull-2-0-A|L-Arsenal-0-3-A|L-Liverpool-1-2-H|D-Swansea-2-2-A" </code></pre> <p>What I would like to do is manipulate the string above so it returns the results of each game which is the first letter after each "|". In this instance it would be WWLLD...
-2
2016-10-16T16:03:14Z
40,072,348
<p>Try something like this:</p> <pre><code> string = "W-Leicester-3-0-H|W-Hull-2-0-A|L-Arsenal-0-3-A|L-Liverpool-1-2-H|D-Swansea-2-2-A" result = ''.join([s[0] for s in string.replace('||', '|').split('|')]) </code></pre>
1
2016-10-16T16:05:28Z
[ "python", "string" ]
Converting Complex-Valued Angles from Radians to Degrees in Python?
40,072,329
<p>After using cmath to compute the asin of 1.47, which returns a complex angle measured in radians;</p> <blockquote> <p>cmath.asin(1.47)</p> <p>(1.5707963267948966+0.9350931316301407j)</p> </blockquote> <p>Is there a way in which can I convert this value to degrees? math.degrees does not work since it cannot ...
0
2016-10-16T16:03:55Z
40,072,830
<p>Degrees make little sense in complex numbers. But if you must use them, just use the same math formula as for real numbers:</p> <pre><code>cmath.asin(1.47) * 180 / math.pi </code></pre> <p>You get the result</p> <pre><code>(90+53.576889894078214j) </code></pre> <p>Note the 90 degrees in the real part.</p> <p>Th...
1
2016-10-16T16:50:37Z
[ "python", "python-2.7" ]
Converting Complex-Valued Angles from Radians to Degrees in Python?
40,072,329
<p>After using cmath to compute the asin of 1.47, which returns a complex angle measured in radians;</p> <blockquote> <p>cmath.asin(1.47)</p> <p>(1.5707963267948966+0.9350931316301407j)</p> </blockquote> <p>Is there a way in which can I convert this value to degrees? math.degrees does not work since it cannot ...
0
2016-10-16T16:03:55Z
40,073,176
<p>To use math.degrees(), you need to get the real part of the complex number first.</p> <pre><code>import cmath import math rad = cmath.asin( 1.47 ) math.degrees( rad.real ) </code></pre>
0
2016-10-16T17:23:36Z
[ "python", "python-2.7" ]
Python: pexpect does not execute `backtick` command
40,072,385
<p>I'm trying to run this command:</p> <pre><code>foo=`ls /` </code></pre> <p>Works perfectly on bash but not if I execute it via pexpect:</p> <pre><code>p = pexpect.spawn("foo=`ls /`").interact() // Gives error command was not found or not executable: foo=`ls </code></pre> <p>What is the cause and how do I fix it...
-1
2016-10-16T16:08:33Z
40,072,663
<p>The command you are trying to execute requires <code>bash</code>. <code>pexpect</code> does not pass your command through <code>bash</code>, instead invoking your executable directly as if it were the shell.</p> <p>From <a href="http://pexpect.sourceforge.net/pexpect.html#spawn" rel="nofollow">the docs</a>:</p> <b...
1
2016-10-16T16:36:00Z
[ "python", "bash", "pexpect" ]
Interpolate without having negative values in python
40,072,420
<p>I've been trying to create a smooth line from these values but I can't have negative values in my result. So far all the methods I tried do give negative values. Would love some help.</p> <pre><code>import matplotlib.pyplot as plt from scipy.interpolate import UnivariateSpline import numpy as np y = np.asarray([0,5...
2
2016-10-16T16:13:38Z
40,072,832
<p>This does it, albeit in some sections better than others.</p> <pre><code>import matplotlib.pyplot as plt from scipy.interpolate import UnivariateSpline import numpy as np y = np.asarray([0,5,80,10,1,10,40,30,80,5,0]) x = np.arange(len(y)) plt.plot(x, y, 'r', ms=5) spl = UnivariateSpline(x, y) xs = np.linspace(0,l...
2
2016-10-16T16:50:43Z
[ "python", "numpy", "matplotlib", "scipy", "interpolation" ]
Interpolate without having negative values in python
40,072,420
<p>I've been trying to create a smooth line from these values but I can't have negative values in my result. So far all the methods I tried do give negative values. Would love some help.</p> <pre><code>import matplotlib.pyplot as plt from scipy.interpolate import UnivariateSpline import numpy as np y = np.asarray([0,5...
2
2016-10-16T16:13:38Z
40,074,468
<p>Spline fitting is known to overshoot. You seem to be looking for one of the so-called <em>monotonic</em> interpolators. For instance,</p> <pre><code>In [10]: from scipy.interpolate import pchip In [11]: pch = pchip(x, y) </code></pre> <p>produces</p> <pre><code>In [12]: xx = np.linspace(x[0], x[-1], 101) In [13...
5
2016-10-16T19:24:25Z
[ "python", "numpy", "matplotlib", "scipy", "interpolation" ]
How to remove elements from list when each character is identical (Python)?
40,072,449
<pre><code>sample = ['AAAA','ABCB','CCCC','DDEF'] </code></pre> <p>I need to eliminate all elements where every character is identical to itself in the element eg. AAAAA,CCCCC</p> <pre><code>output = ['ABCB','DDEF'] sample1 =[] for i in sample: for j in i: if j == j+1: #This needs to be corrected to if...
0
2016-10-16T16:16:01Z
40,072,461
<pre><code> sample = ['AAAA','ABCB','CCCC','DDEF'] output = [sublist for sublist in sample if len(set(sublist)) &gt; 1] </code></pre> <h1>EDIT to answer comment.</h1> <pre><code>sample = [['CGG', 'ATT'], ['ATT', 'CCC']] output = [] for sublist in sample: if all([len(set(each)) &gt; 1 for each in sublist]): ...
6
2016-10-16T16:16:59Z
[ "python", "for-loop" ]
How to remove elements from list when each character is identical (Python)?
40,072,449
<pre><code>sample = ['AAAA','ABCB','CCCC','DDEF'] </code></pre> <p>I need to eliminate all elements where every character is identical to itself in the element eg. AAAAA,CCCCC</p> <pre><code>output = ['ABCB','DDEF'] sample1 =[] for i in sample: for j in i: if j == j+1: #This needs to be corrected to if...
0
2016-10-16T16:16:01Z
40,072,474
<pre><code>sample = ['AAAA','ABCB','CCCC','DDEF'] sample1 = [] for i in sample: if len(set(i)) &gt; 1: sample1.append(i) </code></pre>
2
2016-10-16T16:17:51Z
[ "python", "for-loop" ]
Class vectors - multiplication of two vectors of non-specific dimension
40,072,501
<pre><code>class MyVector: def __init__(self, vector): # classic init self.vector = vector def get_vector(self): return self.vector def __mul__(self, other): for i in range(0, len(self.vector)): #cycle # if I did scalar_product += (self.vector[i] * other.vector[i]) her...
1
2016-10-16T16:20:19Z
40,072,517
<p>You need to define your scalar product first:</p> <pre><code> def __mul__(self, other): scalar_product = 0 # or 0.0 for i in range(0, len(self.vector)): scalar_product += self.vector[i] * other.vector[i] return scalar_product </code></pre> <p>You should also return an object of type <code>M...
1
2016-10-16T16:22:23Z
[ "python", "class", "vector" ]
Print part of String with matching Index
40,072,528
<p>I'm trying to make a Program that takes a given text, checks to see at which indexes (") is located throughout the text and prints anything in-between the quotation marks (") i.e. "xyz" blablabla "abc". In this case, xyz between 0 and 4 and abc between 16 and 20 would be printed. I've got the indexes part to work bu...
0
2016-10-16T16:23:17Z
40,072,637
<p>If you don't mind using regular expressions, I think this is an easier solution:</p> <pre><code>import re print(re.findall(r'"([^"]*)"', text)) </code></pre> <p>If not, you can use your <code>link_finder</code> function:</p> <pre><code>def link_finder(s): index = 0 while index &lt; len(s): index =...
1
2016-10-16T16:33:41Z
[ "python", "python-3.x" ]
REALLY simple functions with tuples (python)
40,072,541
<p>I know this is really easy but I can't understand how to code at all. So I need to create two functions (if you can only help me with one that's fine):</p> <p>Function a which receives a positive integer and transforms it into a tuple, like this:</p> <pre><code>&gt;&gt;&gt;a(34500) (3, 4, 5, 0, 0) &gt;&gt;&gt;a(3....
-4
2016-10-16T16:24:44Z
40,072,742
<p>The comments already state what you can do: Convert the int to str by doing (I know this does not work for floats, here you can show some further effort:)) </p> <pre><code>for c in str(integerVariable): print c </code></pre> <p>The other way around is even more simple.</p> <pre><code>''.join(tupleVariable) </...
0
2016-10-16T16:43:31Z
[ "python", "function", "tuples" ]
REALLY simple functions with tuples (python)
40,072,541
<p>I know this is really easy but I can't understand how to code at all. So I need to create two functions (if you can only help me with one that's fine):</p> <p>Function a which receives a positive integer and transforms it into a tuple, like this:</p> <pre><code>&gt;&gt;&gt;a(34500) (3, 4, 5, 0, 0) &gt;&gt;&gt;a(3....
-4
2016-10-16T16:24:44Z
40,072,770
<p>Try this</p> <pre><code>def a(n): result = [] while n &gt; 0: result.append(n%10) n=n//10 return tuple(reversed(result)) </code></pre> <p>for question 2, try doing the same thing in reverse i.e. multiplying each number by 1, 10, 100 and adding them up.</p> <p>also don't forget error checking code.</p>
0
2016-10-16T16:46:20Z
[ "python", "function", "tuples" ]
REALLY simple functions with tuples (python)
40,072,541
<p>I know this is really easy but I can't understand how to code at all. So I need to create two functions (if you can only help me with one that's fine):</p> <p>Function a which receives a positive integer and transforms it into a tuple, like this:</p> <pre><code>&gt;&gt;&gt;a(34500) (3, 4, 5, 0, 0) &gt;&gt;&gt;a(3....
-4
2016-10-16T16:24:44Z
40,072,842
<pre><code>def to_tuple(input_number): # check if input number is int or not if isinstance(input_number,(int)): # convert number to string to_string = str(input_number) # finally convert string to # list of numbers followed by converting the list to tuple tuple_output = t...
0
2016-10-16T16:51:34Z
[ "python", "function", "tuples" ]
How to iterate through instances in a tree?
40,072,568
<p>I have a problem with a self-written tree class in python:</p> <pre><code>class Tree: def __init__(self, parent=0, value=0): self.value = value self.parent = parent def __iter__(self): return self def next(self): tmp = self.value try: self.parent = self.parent...
1
2016-10-16T16:27:08Z
40,072,941
<p>Here you go:</p> <pre><code>class Tree: def __init__(self, parent=None, value=0): self.value = value self.parent = parent def __iter__(self): yield self.value root = self while root.parent is not None: yield root.parent.value root = root.pare...
0
2016-10-16T17:02:39Z
[ "python", "python-2.7" ]
How to iterate through instances in a tree?
40,072,568
<p>I have a problem with a self-written tree class in python:</p> <pre><code>class Tree: def __init__(self, parent=0, value=0): self.value = value self.parent = parent def __iter__(self): return self def next(self): tmp = self.value try: self.parent = self.parent...
1
2016-10-16T16:27:08Z
40,073,031
<p>I'm not sure you can call this a <code>Tree</code>. One would expect parent node(s) and multiple leaf nodes, and not just a linear connection of objects.</p> <p>See: <a href="http://stackoverflow.com/questions/2482602/a-general-tree-implementation-in-python">a general tree implementation in python</a></p> <p>On ...
0
2016-10-16T17:11:10Z
[ "python", "python-2.7" ]
Cython numpy array indexer speed improvement
40,072,572
<p>I wrote the following code in pure python, the description of what it does is in the docstrings:</p> <pre><code>import numpy as np from scipy.ndimage.measurements import find_objects import itertools def alt_indexer(arr): """ Returns a dictionary with the elements of arr as key and the corresponding s...
1
2016-10-16T16:27:38Z
40,072,854
<p>With <code>arr</code> having non-negative, not very large and many repeated <code>int</code> numbers, here's an alternative approach using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow"><code>np.bincount</code></a> to simulate the same behavior as <code>np.unique(ar...
1
2016-10-16T16:52:27Z
[ "python", "performance", "numpy", "cython" ]
Issues deploying Django project
40,072,623
<p>Okay I am new to the Django framework but I have a basic site that I want live. I have a droplet up on Digital Ocean and my files have been moved over to there.</p> <p>I get this error:</p> <pre><code>ImportError at / cannot import name patterns Request Method: GET Request URL: http://188.166.147.202/ Dja...
0
2016-10-16T16:32:39Z
40,072,684
<p><code>patterns</code> was deprecated in Django 1.8 and removed in Django 1.10. </p> <p>Your <code>urlpatterns</code> is already as it should be, a list of <code>url()</code> instances. Simply change your import to:</p> <pre><code>from django.conf.urls import include, url </code></pre>
2
2016-10-16T16:38:12Z
[ "python", "django", "digital-ocean" ]
Displaying nodes sorted by distance to a given node in Python
40,072,645
<p>I have a number of nodes, each has an x-axis and y-axis values which indicate a distance from each other. For example, </p> <pre><code>nodes = [ {'name': 'node1', 'x': 2, 'y': 4, 'friend': True}, {'name': 'node2', 'x': -3, 'y': 2, 'friend': True}, {'name': 'node3', 'x': 5, 'y': 0, 'friend': False}, {'name': 'node4'...
0
2016-10-16T16:34:34Z
40,072,708
<p>The sort function takes a key parameter:</p> <pre><code>main_node = nodes[0] nodes.sort(key=lambda node: math.hypot(node["x"] - main_node["x"], node["y"] - main_node["y"])) </code></pre>
0
2016-10-16T16:40:48Z
[ "python", "function", "sorting", "nodes" ]
IndexError in function
40,072,775
<pre><code>def AddVct(Vct1,Vct2,VctLen): Vct3 = [] n=1 while n &lt; VctLen: Vct3[n] = Vct1[n] + Vct2[n] n += 1 print(Vct[n]) return Vct3 </code></pre> <p>The program outputs:</p> <p><code>IndexError: list assignment index out of range.</code></p> <p>Could anyone tell me how t...
1
2016-10-16T16:46:35Z
40,072,818
<p>You can't assign to a list element that doesn't exist. And since you start with an empty list, no elements exist in it. Generally, you would <code>append()</code> instead.</p> <pre><code>Vct3.append(Vct1[n] + Vct2[n]) </code></pre> <p>Or, you could initialize <code>Vct3</code> to be the size you want beforehand:</...
0
2016-10-16T16:49:30Z
[ "python", "indexing" ]
Basic threading with one background worker and other thread
40,072,838
<p>I'm very much a beginner in both python and programming. Trying to get multithreading work but haven't managed so far. Grateful for any help or tips.</p> <pre><code>from threading import Thread import time import requests class crawler: def get_urls(self): while True: #r = self.s.get('http...
0
2016-10-16T16:51:26Z
40,072,905
<p>It has been a while since i have done thread programming in python but I remembered that you will have to call <code>.join()</code> on each thread or else the main thread will exit before your spawn thread get a chance to execute.</p> <pre><code>T1 = Thread(target=crawl.get_urls()).start() T2 = Thread(target=crawl....
0
2016-10-16T16:58:54Z
[ "python", "multithreading" ]
statistical summary table in sklearn.linear_model.ridge?
40,072,870
<p>In OLS form StatsModels, results.summary shows the summary of regression results (such as AIC, BIC, R-squared, ...). </p> <p>Is there any way to have this summary table in sklearn.linear_model.ridge? </p> <p>I do appreciate if someone guide me. Thank you.</p>
1
2016-10-16T16:54:17Z
40,078,035
<p>As I know, there is no R(or Statsmodels)-like summary table in sklearn. (Please check <a href="http://stackoverflow.com/a/26326883/3054161">this answer</a>) </p> <p>Instead, if you need it, there is <a href="http://statsmodels.sourceforge.net/devel/generated/statsmodels.regression.linear_model.OLS.fit_regularized.h...
0
2016-10-17T03:21:58Z
[ "python", "statsmodels", "sklearn-pandas" ]
Why do we need locks for threads, if we have GIL?
40,072,873
<p>I believe it is a stupid question but I still can't find it. Actually it's better to separate it into two questions:</p> <p>1) Am I right that we could have a lot of threads but because of GIL in one moment only one thread is executing?</p> <p>2) If so, why do we still need locks? We use locks to avoid the case wh...
3
2016-10-16T16:54:29Z
40,072,907
<p>the GIL prevents simultaneous execution of multiple threads, but not in all situations.</p> <p>The GIL is temporarily released during I/O operations executed by threads. That means, multiple threads can run at the same time. That's one reason you still need locks.</p> <p>I don't know where I found this reference.....
0
2016-10-16T16:58:58Z
[ "python", "multithreading" ]
Why do we need locks for threads, if we have GIL?
40,072,873
<p>I believe it is a stupid question but I still can't find it. Actually it's better to separate it into two questions:</p> <p>1) Am I right that we could have a lot of threads but because of GIL in one moment only one thread is executing?</p> <p>2) If so, why do we still need locks? We use locks to avoid the case wh...
3
2016-10-16T16:54:29Z
40,072,999
<p>GIL protects the Python interals. That means:</p> <ol> <li>you don't have to worry about something in the interpreter going wrong because of multithreading</li> <li>most things do not really run in parallel, because python code is executed sequentially due to GIL</li> </ol> <p>But GIL does not protect your own cod...
4
2016-10-16T17:07:55Z
[ "python", "multithreading" ]
Why do we need locks for threads, if we have GIL?
40,072,873
<p>I believe it is a stupid question but I still can't find it. Actually it's better to separate it into two questions:</p> <p>1) Am I right that we could have a lot of threads but because of GIL in one moment only one thread is executing?</p> <p>2) If so, why do we still need locks? We use locks to avoid the case wh...
3
2016-10-16T16:54:29Z
40,073,002
<p>At any moment, yes, only one thread is executing Python code (other threads may be executing some IO, NumPy, whatever). That is mostly true. However, this is trivially true on any single-processor system, and yet people still need locks on single-processor systems.</p> <p>Take a look at the following code:</p> <...
2
2016-10-16T17:08:04Z
[ "python", "multithreading" ]
AttributeError in a pygame.sprite.Sprite subclass
40,072,913
<p>I am currently developing a 2D platformer game with pygame and I have discovered an issue. I usually handled sprite rendering with a single sprite group declared inside of the main function. Now that I need to have some specific sprites over others/under sprites, having a single group won't cut it, and having multip...
1
2016-10-16T16:59:48Z
40,073,133
<p>furas at the comments has solved the mystery. I just forgot to remove the old definition of the class! Silly me. Its all working fine now. </p>
0
2016-10-16T17:19:33Z
[ "python", "class", "python-3.x", "oop", "pygame" ]
Concatenating pandas DataFrames keeping only rows with matching values in a column?
40,072,950
<p>I am trying to "merge-concatenate" two pandas DataFrames. Basically, I want to stack the two DataFrames, but only keep the rows from each DataFrame which matching values in the other DataFrame. So for example:</p> <pre><code>data1: +---+------------+-----------+-------+ | | first_name | last_name | class | +---+...
2
2016-10-16T17:03:12Z
40,073,112
<p>How about this?</p> <pre><code>In [335]: cls = np.intersect1d(data1['class'], data2['class']) In [336]: cls Out[336]: array([4, 5], dtype=int64) In [337]: pd.concat([data1.ix[data1['class'].isin(cls)], data2.ix[data2['class'].isin(cls)]]) Out[337]: first_name last_name class 3 Alice Aoni 4 4 ...
1
2016-10-16T17:17:48Z
[ "python", "pandas", "dataframe" ]
Trying to split string with regex
40,072,960
<p>I'm trying to split a string in Python using a regex pattern but its not working correctly.</p> <p>Example text:</p> <p><code>"The quick {brown fox} jumped over the {lazy} dog"</code></p> <p>Code:</p> <p><code>"The quick {brown fox} jumped over the {lazy} dog".split(r'({.*?}))</code></p> <p>I'm using a capture ...
0
2016-10-16T17:04:05Z
40,072,984
<p>You're calling the strings' split method, not re's</p> <pre><code>&gt;&gt;&gt; re.split(r'({.*?})', "The quick {brown fox} jumped over the {lazy} dog") ['The quick ', '{brown fox}', ' jumped over the ', '{lazy}', ' dog'] </code></pre>
1
2016-10-16T17:06:28Z
[ "python", "regex" ]
Patch Extracting In Python
40,072,988
<p>I have an image and I would like to extract patches of it and then save each patch as an image in that folder. Here is my first attempt:</p> <pre><code>from sklearn.feature_extraction import image from sklearn.feature_extraction.image import extract_patches_2d import os, sys from PIL import Image imgFile = Image...
0
2016-10-16T17:06:41Z
40,073,244
<p>As per <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.image.extract_patches_2d.html" rel="nofollow">documentation</a> first parameter for extract_patches_2d is an array or a shape. </p> <p>You should first create an array from your imgFile so you get the pixels, and then pass t...
0
2016-10-16T17:30:46Z
[ "python", "image", "patch" ]
Create Image Histogram Manually and Efficiently in Python
40,073,003
<p>I want to write codes that can show the histogram of an image without using built in Matplotlib hist function.</p> <p>Here is my codes:</p> <pre><code>import cv2 as cv import numpy as np from matplotlib import pyplot as plt def manHist(img): row, col = img.shape # img is a grayscale image y = np.zeros((256)...
1
2016-10-16T17:08:09Z
40,073,188
<p>A NumPy based vectorized solution would be with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow"><code>np.bincount</code></a> -</p> <pre><code>out = np.bincount(img.ravel(),minlength=256) </code></pre> <p>Another vectorized approach based on <a href="http://docs.sci...
1
2016-10-16T17:24:25Z
[ "python", "opencv", "numpy", "image-processing", "matplotlib" ]
Cannot webdriver.get(url) an IP address in Selenium 3
40,073,124
<p>So I wrote a python script that uses Selenium 2 to do various things to my modem. This fully works. </p> <p>I am now busy updating the script to use Selenium 3, but I immediately ran into a problem where I cannot even get to the login page of the modem. The problem seems to be with the <code>get()</code>.</p> <p>F...
0
2016-10-16T17:19:03Z
40,073,166
<p><code>10.0.0.2</code> is not a URL and so the browser falls back on searching for it. Try <code>http://10.0.0.2/</code></p>
1
2016-10-16T17:21:55Z
[ "python", "selenium", "firefox", "selenium-webdriver" ]
How to test standalone code outside of a scrapy spider?
40,073,136
<p>I can test my xpaths on a HTML body string by running the two lines under (1) below.</p> <p>But what if I have a local file <code>myfile.html</code> whose content is exactly the <code>body</code> string. How would I run some standalone code, <strong>outside of a spider</strong>? I am seeking something that is rough...
0
2016-10-16T17:19:39Z
40,084,225
<p>You can have a look at <a href="https://github.com/scrapy/scrapy/blob/master/tests/test_linkextractors.py" rel="nofollow">how scrapy tests for link extractors</a> are implemented.</p> <p>They use a <code>get_test_data()</code> helper to <a href="https://github.com/scrapy/scrapy/blob/129421c7e31b89b9b0f9c5f7d8ae59e4...
0
2016-10-17T10:38:45Z
[ "python", "xpath", "scrapy" ]
Find Max in List Using the Reduce Function
40,073,160
<p>In Torbjörn Lager's 46 python exercises, number 26 is finding the max in a list using the reduce function. I know how to add and multiply using the reduce function but it doesn't make sense to me how you could use it to find the largest number. Does anyone know how to do this?</p>
-2
2016-10-16T17:21:29Z
40,073,232
<p>Write a function that returns the larger of two numbers:</p> <pre><code>def larger(a, b): return a if a &gt; b else b </code></pre> <p>Then use it with <code>reduce</code>:</p> <pre><code>reduce(larger, [1, 2, 3, 4]) </code></pre> <p>Conveniently, Python already has a function like <code>larger</code> that's...
2
2016-10-16T17:29:26Z
[ "python" ]
How to remove a character from element and the corresponding character in another element in a list (Python)?
40,073,167
<pre><code>sample = ['A$$N','BBBC','$$AA'] </code></pre> <p>I need to compare every element to every other element in the list. So compare sample[0] and sample[1], sample[0] and sample[2], sample[1] and sample[2]. a If any pair in the comparison has "$", then "$" and the corresponding element needs to be eliminated. ...
1
2016-10-16T17:21:58Z
40,073,306
<p>This may not be the most beautiful code but will do the job.</p> <pre><code>from itertools import combinations sample = ['A$$N','BBBC','$$AA'] output = [] for i, j in combinations(range(len(sample)), 2): out = ['', ''] for pair in zip(sample[i], sample[j]): if '$' not in pair: out[0] += ...
1
2016-10-16T17:36:52Z
[ "python", "list", "character", "pop", "del" ]
django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail"
40,073,205
<p>TL;DR: I am getting this error and don't know why:</p> <blockquote> <p>django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the 'lookup_field' attribute...
0
2016-10-16T17:26:57Z
40,077,012
<p>I eventually fixed my second exception by printing the serializer in the Django shell/python interactive console. The result I got was this:</p> <pre><code>&gt;&gt;&gt; from snippets.serializers import UserSerializer &gt;&gt;&gt; print(UserSerializer()) UserSerializer(): url = HyperlinkedIdentityField(view_name...
0
2016-10-17T00:34:48Z
[ "python", "django", "rest", "hyperlink", "django-rest-framework" ]
How do I created a class with a printing function?
40,073,246
<p>I want to create a separate file class that will be a print function. So I want it to print out a list when it gets the parameter. So lets call the class <code>print_list</code> and let's take the start variable I want the function to go through the list and print out the data. How do I create this function?</p> <p...
-1
2016-10-16T17:31:03Z
40,073,600
<p>Why not try the build in <code>print</code> function of python? Something like</p> <pre><code>print(x) </code></pre> <p>or, if x is an iterable like a list, you could also do</p> <pre><code>print(*x) </code></pre>
0
2016-10-16T18:02:35Z
[ "python" ]
python quiz with jinja
40,073,247
<p>i'm learning at moment python and for a exercise i have to build a quiz with jinja. for the quiz i have to build a random function, so that the questions comes random. but i have the problem that my codes don't run the right way. with my code, i get the Error "TypeError: list indices must be integers, not NoneType" ...
1
2016-10-16T17:31:11Z
40,073,383
<pre><code>secret = random.seed(len(cities)) </code></pre> <p>This sets <code>secret</code> to <code>None</code>, because the seed function returns nothing. You probably confused <a href="https://docs.python.org/2/library/random.html#random.seed" rel="nofollow">seed</a> with <a href="https://docs.python.org/2/library/...
1
2016-10-16T17:44:59Z
[ "python", "jinja2" ]
Invalid literal for int()
40,073,276
<p>I am learning python and I am trying to code a calculator that compares prices of butter, calculates percentage differences, and which one has the lowest price for 100 grams.</p> <pre><code>def procenta(x,y): vysledek = (y-x)/x * 100 # (b-a) : a * 100 return round(vysledek, 2) tesco = float(input("Zade...
-1
2016-10-16T17:33:37Z
40,073,337
<p>You've defined <code>tesco_g</code> to be an integer by casting it with your 5th line. Your TypeError is telling you that the <code>varname[:2]</code> syntax doesn't work because your type doesn't have indices. To reframe what the interpreter is doing: 1. It reads <code>tesco_g[:2]</code> 2. It checks: does the ty...
0
2016-10-16T17:39:58Z
[ "python", "python-3.x" ]
Invalid literal for int()
40,073,276
<p>I am learning python and I am trying to code a calculator that compares prices of butter, calculates percentage differences, and which one has the lowest price for 100 grams.</p> <pre><code>def procenta(x,y): vysledek = (y-x)/x * 100 # (b-a) : a * 100 return round(vysledek, 2) tesco = float(input("Zade...
-1
2016-10-16T17:33:37Z
40,073,434
<p>If I will get it to work , it will be printed :</p> <pre><code>print("Tesco is the cheapest shop with price of",*cena_tesco*,"for 100 grams of butter.") </code></pre> <p>Its supposed to calculate price of butter for 100g. What should I do with tesco_g[:2] so it take first two digits from tesco_g and use them to ca...
0
2016-10-16T17:49:05Z
[ "python", "python-3.x" ]
Plotting list of lists in a same graph in Python
40,073,322
<p>I am trying to plot <code>(x,y)</code> where as <code>y = [[1,2,3],[4,5,6],[7,8,9]]</code>. </p> <p>Say, <code>len(x) = len(y[1]) = len(y[2])</code>.. The length of the y is decided by the User input. I want to plot multiple plots of y in the same graph i.e, <code>(x, y[1],y[2],y[3],...)</code>. When I tried using ...
0
2016-10-16T17:38:29Z
40,073,609
<p>Assuming some sample values for x below is the code that could give you the desired output.</p> <pre><code>import matplotlib.pyplot as plt x = [1,2,3] y = [[1,2,3],[4,5,6],[7,8,9]] plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.title("A test graph") for i in range(len(y)): plt.plot(x,[pt[i] for pt in y],label = ...
0
2016-10-16T18:03:09Z
[ "python", "matplotlib", "nested-lists" ]
Python Django Queryset
40,073,348
<p>I'm playing with querysets in django.</p> <p>What I'm looking it's to save a new foreign product or item but I can not achieve it.</p> <p><em>shell</em></p> <pre><code>from applaboratorio.models import Datos_empresa_DB, Datos_equipo_DB detalle = Datos_empresa_DB.objects.filter(pk=58) resp = Datos_equipo_DB(equi...
1
2016-10-16T17:41:56Z
40,073,393
<p>I think you're nearly there. You need to call the <code>save</code> method of the new product to <em>save</em> to the DB, and to <em>retrieve</em> the related client object, you should <code>get</code> not <code>filter</code> so you have the object itself and not a list of objects (or <em>QuerySet</em>):</p> <pre><...
2
2016-10-16T17:46:01Z
[ "python", "django", "django-queryset" ]
Converting python time stamp to day of year
40,073,373
<p>How can I convert a python timestamp into day of year:</p> <pre><code>Timestamp('2015-06-01 00:00:00') </code></pre> <p>I want a number where Jan 1 is 1, Jan 2 is 2... Dec 31 is 365 (for a non-leap year)</p>
-3
2016-10-16T17:43:41Z
40,073,424
<p>You might want to take a look at the function <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.timetuple" rel="nofollow"><code>datetime.timetuple()</code></a> which returns a <a href="https://docs.python.org/2/library/time.html#time.struct_time" rel="nofollow"><code>time.struct_time</code><...
2
2016-10-16T17:48:23Z
[ "python", "datetime" ]
Converting python time stamp to day of year
40,073,373
<p>How can I convert a python timestamp into day of year:</p> <pre><code>Timestamp('2015-06-01 00:00:00') </code></pre> <p>I want a number where Jan 1 is 1, Jan 2 is 2... Dec 31 is 365 (for a non-leap year)</p>
-3
2016-10-16T17:43:41Z
40,073,571
<p>First, you can convert it to a <code>datetime.datetime</code> object like this:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; format = "%Y-%m-%d %H:%M:%S" &gt;&gt;&gt; s = "2015-06-01 00:00:00" &gt;&gt;&gt; dt = datetime.datetime.strptime(s, format) </code></pre> <p>Now you can use the methods on <code>...
2
2016-10-16T18:00:18Z
[ "python", "datetime" ]
what type is,when I use web crawler to download the information from web?
40,073,381
<pre><code>import requests from bs4 import BeautifulSoup from pandas import Series,DataFrame def name1(): url='''https://www.agoda.com/zh-tw/pages/agoda/default/DestinationSearchResult.aspx?asq=%2bZePx52sg5H8gZw3pGCybdmU7lFjoXS%2ba xz%2bUoF4%2bbAw3oLIKgWQqUpZ91GacaGdIGlJ%2bfxiotUg7cHef4W8WIrREFyK%2bHWl%2ftRKlV...
-3
2016-10-16T17:44:47Z
40,073,518
<p>Use <code>.text</code> to get without tags. And <code>.strip()</code> to remove wihtespaces</p> <pre><code>for a in soup.find_all("h3",{"class":"hotel-name"}): print(a.text.strip()) </code></pre>
0
2016-10-16T17:55:39Z
[ "python", "python-3.x", "beautifulsoup", "web-crawler" ]
wxpython phoenix says that Frame init args are wrong
40,073,408
<p>I am trying to create simple window with menu in wx python 3.0.4. Actually I get an error:</p> <blockquote> <p>wx.Frame.<strong>init</strong>(self, ID_ANY, "Title", DefaultPosition, (350,200), DEFAULT_FRAME_STYLE, FrameNameStr) TypeError: Frame():</p> <p>arguments did not match any overloaded call: overloa...
0
2016-10-16T17:47:07Z
40,073,924
<pre><code>Frame(parent, id=ID_ANY, title="", pos=DefaultPosition, size=DefaultSize, style=DEFAULT_FRAME_STYLE, name=FrameNameStr) </code></pre> <p>You missed the parent argument.</p> <p>Working code</p> <pre><code>import wx class MainWindow(wx.Frame): def __init__(self): wx.Frame.__init__( ...
1
2016-10-16T18:30:30Z
[ "python", "user-interface", "wxpython", "python-3.5" ]
Removing negative values and printing the original and the new list
40,073,642
<p>To start of I am telling you this is for school as I am learning to code with Python. Please do explain why I should do something :)! I am looking to learn not just getting the answer.</p> <p>I am trying to get rid of the negative items in the list. I want to print the list Before (including the negative items) and...
0
2016-10-16T18:06:38Z
40,073,861
<p>You aren't modifying global variable <code>l</code> in your function.</p> <p>I propose this code in Python, which should work correctly:</p> <pre><code>import random def removeNegatives(listOfIntegers): return [x for x in listOfIntegers if not x &lt; 0] l = [] for i in xrange(0, random.randint(15,25)): #give...
1
2016-10-16T18:25:52Z
[ "python", "python-2.7" ]
Removing negative values and printing the original and the new list
40,073,642
<p>To start of I am telling you this is for school as I am learning to code with Python. Please do explain why I should do something :)! I am looking to learn not just getting the answer.</p> <p>I am trying to get rid of the negative items in the list. I want to print the list Before (including the negative items) and...
0
2016-10-16T18:06:38Z
40,074,223
<p>Just saw your comment relative to not being able to modify the code below l = []</p> <p>In that case, you need to reassign to listOfIntegers coming out of your function</p> <pre><code>def removeNegatives(listOfIntegers): global l k = listOfIntegers[:] #takes a copy of the list for item in lis...
0
2016-10-16T18:57:52Z
[ "python", "python-2.7" ]
Removing negative values and printing the original and the new list
40,073,642
<p>To start of I am telling you this is for school as I am learning to code with Python. Please do explain why I should do something :)! I am looking to learn not just getting the answer.</p> <p>I am trying to get rid of the negative items in the list. I want to print the list Before (including the negative items) and...
0
2016-10-16T18:06:38Z
40,074,433
<p>The "cleanest" way to modify external list will be to change its contents without reassigning - which changes list object reference. You can't remove elements when looping over list, and removing each non-compliant element while iterating over copy is very ineffective. </p> <p>But you may reassign contents of list ...
1
2016-10-16T19:20:51Z
[ "python", "python-2.7" ]
Removing negative values and printing the original and the new list
40,073,642
<p>To start of I am telling you this is for school as I am learning to code with Python. Please do explain why I should do something :)! I am looking to learn not just getting the answer.</p> <p>I am trying to get rid of the negative items in the list. I want to print the list Before (including the negative items) and...
0
2016-10-16T18:06:38Z
40,096,774
<p>Since you're studying Python, this is a good place to learn <code>list comprehension</code>:</p> <pre><code>$ cat /tmp/tmp.py _list = [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14, -2, -9, -14, 2, -10, -5, 8, 7] print("Before:",_list) print("After:",[a for a in _list if a &gt;= 0]) $ python3 /t...
0
2016-10-17T22:40:41Z
[ "python", "python-2.7" ]
How do I change my code to use arrays?
40,073,699
<p>This is my code so far. I can get my code to prompt the user to input 4 test scores. I have made it so it asks "Enter the score for test number N:" </p> <p>My problem lies in being able to extract the input values from what the user would input. My end goal is to be able to drop the lowest test grade and calculate ...
0
2016-10-16T18:12:53Z
40,073,821
<p>This is what you want:</p> <pre><code>def getNumbers(): scores=[] for testNum in range(4): print('Enter the score for test number %d'%(testNum+1)), scores.append(input(': ')) scores=[score for score in scores if min(scores)!=score] return scores scores= getNumbers() average= float(sum(sco...
0
2016-10-16T18:22:28Z
[ "python", "arrays" ]
How do I change my code to use arrays?
40,073,699
<p>This is my code so far. I can get my code to prompt the user to input 4 test scores. I have made it so it asks "Enter the score for test number N:" </p> <p>My problem lies in being able to extract the input values from what the user would input. My end goal is to be able to drop the lowest test grade and calculate ...
0
2016-10-16T18:12:53Z
40,074,622
<p>Your code was close. Just need to define a list, append to it, then return it </p> <pre><code>scores = [] for test in range(testNum): print('Enter the score for test number', int(test + 1), end='') score = int(input(': ') scores.append(score) return scores </code></pre> <p>You should calculate the ...
0
2016-10-16T19:38:52Z
[ "python", "arrays" ]
Function giving unexpected result
40,073,719
<p>Could anyone explain why this function gives "None" at the end? </p> <pre><code>def displayHand(hand): """ Displays the letters currently in the hand. For example: &gt;&gt;&gt; displayHand({'a':1, 'x':2, 'l':3, 'e':1}) Should print out something like: a x x l l l e The order of the l...
0
2016-10-16T18:15:02Z
40,073,748
<p>If a function doesn't return anything, then it automatically returns <code>None</code>.</p>
1
2016-10-16T18:16:55Z
[ "python", "function" ]
Function giving unexpected result
40,073,719
<p>Could anyone explain why this function gives "None" at the end? </p> <pre><code>def displayHand(hand): """ Displays the letters currently in the hand. For example: &gt;&gt;&gt; displayHand({'a':1, 'x':2, 'l':3, 'e':1}) Should print out something like: a x x l l l e The order of the l...
0
2016-10-16T18:15:02Z
40,073,777
<p>The function is returning None because there is no other explicit return value; If a function has no return statement, the default is None.</p>
2
2016-10-16T18:18:45Z
[ "python", "function" ]
Set number of digits after decimal
40,073,862
<p>I'm trying to set 3 digits after point but it returns me 0.03 instead of 0.030 Here's the code:</p> <pre><code>import decimal decimal.getcontext().prec = 3 a = float(input()) qur = [] x = 2 b = a / 100 while x &lt; 12: qur.append(b) b = (a * x) / 100 x += 1 print(" ".join([str(i) for i in qur])) </code>...
0
2016-10-16T18:25:54Z
40,073,917
<p>You are not using <code>decimal</code>s, so setting their precision has no effect. For output with a fixed number of digits, use string formatting:</p> <pre><code>print(" ".join('{0:.3f}'.format(i) for i in qur)) </code></pre>
2
2016-10-16T18:30:07Z
[ "python" ]
Strange Bug in creating Co-occurrence Matrix in Python
40,073,874
<p>I am trying to create a co-occurrence matrix in Python that outputs the number which words in L1 appear in pears (cat dog, cat house, cat tree e.t.c.) in L2, my code so far is:</p> <pre><code>co = np.zeros((5,5)) #the matrix L1 = ['cat', 'dog', 'house', 'tree', 'car'] #tags L2 = ['cat car dog', 'cat house dog', 'ca...
1
2016-10-16T18:27:02Z
40,074,031
<p>It's giving a correct result because you have <code>car</code> and <code>dog</code> in first item of <code>L2</code> which is <code>0</code> index.</p> <p>Here is a more pythonic approach that get the index based on first occurrence of the pairs in <code>L2</code>:</p> <pre><code>In [158]: L2 = ['cat car dog', 'ca...
3
2016-10-16T18:39:31Z
[ "python", "numpy", "matrix" ]
Python not executing in browser
40,073,888
<p>I have a cgi script which imports functions from a different python file. I'm using these files to setup a Hadoop cluster. So it's mostly got commands.getstatusoutput codes. The cgi file just calls these functions while passing the parameters. </p> <p>But it doesn't execute the functions. This works fine when i run...
0
2016-10-16T18:27:58Z
40,114,028
<p>Finally fixed it. I had to add a root@ipaddress to the scp commands</p> <p>from</p> <pre><code>commands.getstatusoutput("sshpass -p redhat scp temp1.txt "+rmip+":/hadoop2/etc/hadoop/core-site.xml") </code></pre> <p>to</p> <pre><code>commands.getstatusoutput("sshpass -p redhat scp temp1.txt root@"+rmip+":/hadoop2...
0
2016-10-18T16:58:35Z
[ "python", "apache", "shell", "cgi", "httpd.conf" ]
Where does pip install its modules? What if using a virtualenv? Also getting an error setting up mod_wsgi
40,073,901
<p>I am new to Python and there are some things which I am not able to apprehend. Questions may seem like very kiddish, so bear with me. </p> <p>As you know, Ubuntu comes with an outdated Python version. I wished to use the latest python. But since it is recommended not to override the system's python, I installed <co...
1
2016-10-16T18:28:52Z
40,074,107
<p>Concerning 1., if I have well understood, you would like to have the last 2.7 or 3.5 Python version on your distribution. Actually, you can have multiple python distribution on your distribution. I would suggest you to have a look on conda/anaconda (<a href="https://www.continuum.io/downloads" rel="nofollow">https:/...
0
2016-10-16T18:47:12Z
[ "python", "apache", "ubuntu", "mod-wsgi" ]
How to configure elasticsearch to use SSL with basic auth
40,073,938
<p>I am trying to deploy an app that uses Ramses (<a href="http://ramses.tech" rel="nofollow">http://ramses.tech</a>) on IBM Bluemix. Unfortunately, the app is crashing during the deploy process. In the local.ini configuration file I have set the following:</p> <pre><code># ElasticSearch elasticsearch.hosts = xxxx.db...
0
2016-10-16T18:31:49Z
40,091,483
<p>You will need to use the self-signed certificate provided as <code>ca_certificate_base64</code> in your VCAP_SERVICES credentials.</p> <p>It is base64 encoded. You need to decode the key before using it, as shown in the sample application at <a href="https://github.com/IBM-Bluemix/compose-elasticsearch-helloworld-n...
0
2016-10-17T16:36:06Z
[ "python", "ssl", "elasticsearch", "ibm-bluemix", "elasticsearch-py" ]
Regex doesn't filter out the right text on datatime
40,073,942
<p>I have a string below:</p> <pre><code>senton = "Sent: Friday, June 18, 2010 12:57 PM" </code></pre> <p>I created a regex to filter out the datetime portion:</p> <pre><code>reg_datetime = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (January|February|March|April|May|Ju...
1
2016-10-16T18:32:08Z
40,074,035
<p>If you want regex to return the all those values you have to make sure that they're in separate groups, like so:</p> <pre><code>reg_datetime = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (January|February|March|April|May|June|July|August|September|October|November|December) (\d{1,2}), (\d{4}) (\d{2...
0
2016-10-16T18:40:03Z
[ "python", "regex" ]
Regex doesn't filter out the right text on datatime
40,073,942
<p>I have a string below:</p> <pre><code>senton = "Sent: Friday, June 18, 2010 12:57 PM" </code></pre> <p>I created a regex to filter out the datetime portion:</p> <pre><code>reg_datetime = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (January|February|March|April|May|Ju...
1
2016-10-16T18:32:08Z
40,074,053
<p>The problem is that the match results that are returned to you are the ones between '(' ')' which are called group match. Thus, your regex should look like this to return all the data: </p> <pre><code>reg_datetime = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (January|February|March|April|May|June...
0
2016-10-16T18:41:33Z
[ "python", "regex" ]
Regex doesn't filter out the right text on datatime
40,073,942
<p>I have a string below:</p> <pre><code>senton = "Sent: Friday, June 18, 2010 12:57 PM" </code></pre> <p>I created a regex to filter out the datetime portion:</p> <pre><code>reg_datetime = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (January|February|March|April|May|Ju...
1
2016-10-16T18:32:08Z
40,074,145
<p>Function <a href="https://docs.python.org/2/library/re.html#re.findall" rel="nofollow"><code>re.findall</code></a> does the following:</p> <blockquote> <p>Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found...
1
2016-10-16T18:50:53Z
[ "python", "regex" ]
Regex doesn't filter out the right text on datatime
40,073,942
<p>I have a string below:</p> <pre><code>senton = "Sent: Friday, June 18, 2010 12:57 PM" </code></pre> <p>I created a regex to filter out the datetime portion:</p> <pre><code>reg_datetime = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (January|February|March|April|May|Ju...
1
2016-10-16T18:32:08Z
40,074,146
<p>without change <code>reg_datetime</code> and only use <code>search</code> </p> <pre><code>import re senton = "Sent: Friday, June 18, 2010 12:57 PM" reg_datetime = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (January|February|March|April|May|June|July|August|September|O...
1
2016-10-16T18:50:53Z
[ "python", "regex" ]
Models in Python Django not working for Many to Many relationships
40,073,984
<p>I am trying to create the proper Django model that could fit the following reqs:</p> <p>Person Class has 1 to many relations with the Address Class</p> <p>Person Class has many to many relations with the Group Class</p> <p>Book Class contains the collections of the Persons and the Groups</p> <p>This is my code:<...
1
2016-10-16T18:35:21Z
40,074,153
<p>1) The ManyToMany field should appear only in one of the models, and by looks of things you probably want it in the Person model. Its important to understand that the data about the ManyToMany field is saved in a differant table. Django only allows this field to be visable through buth models (so basiclly, choose wh...
1
2016-10-16T18:51:16Z
[ "python", "django", "django-models" ]
Why this for loop in Python3 return dictionary value split in letters?
40,073,995
<p>I am lerning Python from a book and there is this example. I rewrote example as it is shown in book, but the result differs from books.</p> <p><strong>This is the code</strong></p> <pre><code>favorite_languages = { 'jen': ['python','ruby'], 'bil': 'c', 'edward': ['ruby','haskell'], 'phil': 'python', ...
0
2016-10-16T18:36:51Z
40,074,036
<p>Because line:</p> <pre><code>for language in languages: </code></pre> <p>is iterating over string 'python' and giving you single letters, if you write it as ['python'] it'll iterate over list and write it as one word</p>
3
2016-10-16T18:40:10Z
[ "python", "python-3.x", "for-loop", "dictionary" ]
Access kivy popup parent
40,074,004
<p>The way popups are implemented in kivy, the popup seems to get attached to the window and not the parent object which created the popup. Popup comes with self.dismiss() to close the popup but I can't figure out any way to access the 'parent' object since despite creating the popup, it seems to exist outside of it.<...
2
2016-10-16T18:37:28Z
40,074,127
<p>It's implemented like that because it needs to be hidden most of the time, yet still active, so that <code>open()</code> could be called. Kivy doesn't seem to handle hiding of the widgets other way that actually <em>removing</em> it and keeping a reference somewhere (there's no <code>hide</code> property), so maybe ...
2
2016-10-16T18:49:37Z
[ "python", "python-2.7", "popup", "kivy" ]
Python Trouble getting cursor position (x, y) on desktop
40,074,054
<p>I've been looking for ways to find my cursor position and put it on to two variables, x and y. But most answers are outdated and i can't seem to make them work. I would rather if it is in pythons standard librarys or pywinauto. I would also prefer in python 2.7. Thanks.</p>
3
2016-10-16T18:41:46Z
40,074,079
<p>You can do this with <a href="https://pypi.python.org/pypi/PyMouse" rel="nofollow">PyMouse</a>.</p> <pre><code>&gt;&gt;&gt; import pymouse; &gt;&gt;&gt; mouse = pymouse.PyMouse() &gt;&gt;&gt; mouse.position() (288.046875, 396.15625) &gt;&gt;&gt; mouse.position() (0.0, 0.0) &gt;&gt;&gt; mouse.position() (1439.996093...
2
2016-10-16T18:44:42Z
[ "python", "windows-7", "cursor-position", "pywinauto" ]
Target WSGI script cannot be loaded as Python module + no module named Django
40,074,088
<p><em>I know that the question has already been asked here. I've read tons of answers, but nothing helped.</em></p> <p>I'm using virtualenv (/root/eb-virt); my Django project is called mediar. All public files are stored in /var/www/html/xxx.com/public_html/</p> <p>From error log:</p> <pre><code>[Sun Oct 16 18:40:1...
0
2016-10-16T18:45:36Z
40,074,311
<p>I would first try using the right python shebang in your wsgi file. Shouldn’t it be something like the following?</p> <pre><code>#!/root/eb-virt/bin/python </code></pre> <p>And then the second thing would be to explicitly add the virtualenv to the <code>sys.path</code> append in the wsgi file</p> <pre><code>sy...
0
2016-10-16T19:07:25Z
[ "python", "django", "apache", "mod-wsgi" ]
How to improve distance function in python
40,074,155
<p>I am trying to do a classification exercise on email docs (strings containing words). </p> <p>I defined the distance function as following:</p> <pre><code>def distance(wordset1, wordset2): if len(wordset1) &lt; len(wordset2): return len(wordset2) - len(wordset1) elif len(wordset1) &gt; len(wordset2): re...
3
2016-10-16T18:51:18Z
40,074,306
<p>One common measure of similarity for use in this situation is the <a href="https://nickgrattan.wordpress.com/2014/02/18/jaccard-similarity-index-for-measuring-document-similarity/" rel="nofollow">Jaccard similarity</a>. It ranges from 0 to 1, where 0 indicates complete dissimilarity and 1 means the two documents are...
2
2016-10-16T19:06:49Z
[ "python", "distance", "knn" ]
How to improve distance function in python
40,074,155
<p>I am trying to do a classification exercise on email docs (strings containing words). </p> <p>I defined the distance function as following:</p> <pre><code>def distance(wordset1, wordset2): if len(wordset1) &lt; len(wordset2): return len(wordset2) - len(wordset1) elif len(wordset1) &gt; len(wordset2): re...
3
2016-10-16T18:51:18Z
40,075,652
<p>You didn't mention the type of <code>wordset1</code> and <code>wordset2</code>. I'll assume they are both <code>strings</code>.</p> <p>You defined your distance as the word counting and got a bad score. It's obvious text length is not a good dissimilarity measure: two emails with different sizes can talk about the ...
1
2016-10-16T21:24:22Z
[ "python", "distance", "knn" ]
"TypeError: 'str' does not support the buffer interface" when writing to a socket
40,074,315
<pre><code>import socket def Main(): host = '127.0.0.1' port = 5000 s = socket.socket() s.connect((host, port)) filename = input("Filename? -&gt; ") if filename != 'q': s.send(filename) data = s.recv(1024) if data[:6] == 'EXISTS': filesize = long(data[6:]) message = input("File Exis...
0
2016-10-16T19:07:31Z
40,074,398
<p>Python 3 makes a clean distinction between text strings (in the unicode character set, but conceptually independent of any encoding) and sequences of bytes. To write text to a file or socket, it must be "encoded" using a suitable encoding. In your case, you could use </p> <pre><code>s.send(bytes(filename, encoding=...
0
2016-10-16T19:16:17Z
[ "python", "sockets", "python-3.x", "networking" ]
Is it possible to run program in python with additional HTTP server in infinite loop?
40,074,378
<p>I want to run program in infinite loop wich handles GPIO in raspberry PI and gets requests in infinite loop (as HTTP server). Is it possible? I tried Flask framework, but infinite loop waits for requests and then my program is executed. </p>
0
2016-10-16T19:14:17Z
40,074,663
<p>If I were to face with a problem like this right now, I wold do this:</p> <p>1) First I'd try figuring out if I can use the event loop of the web framework to execute the code communicating with raspberry-pi asynchronously (i.e. inside of the event handlers).</p> <p>2) If I failed to find a web framework extensibl...
0
2016-10-16T19:43:05Z
[ "python", "raspberry-pi" ]
Python Split Variable Output to Multiple Variables
40,074,385
<p>First, I apologize for my ignorance here as I'm very new to Python and I may say things that really don't make sense.</p> <p>I'm using the <code>youtube.search.list</code> API to create a variable <code>search_response</code>. This variable outputs the data on all searched videos in JSON format (I believe it's JSON...
2
2016-10-16T19:14:55Z
40,074,709
<p>Given the Jupyter notebook you referenced here's how you'd get the videoId from the data you've retrieved. Does this answer your question? </p> <p>I'm not fully sure how the Youtube search API works but I might have time to explore it if this isn't a full answer.</p> <pre><code>example = { 'etag': '"I_8xdZu766...
0
2016-10-16T19:47:10Z
[ "python", "json", "youtube", "youtube-api", "jupyter-notebook" ]
Zipline Error: AttributeError: 'NoneType' object has no attribute 'fetch_csv'
40,074,425
<p>I just installed Zipline on Windows 10, Python 2.7 system using <code>conda</code>. When I <a href="http://www.zipline.io/appendix.html?highlight=fetch_csv#zipline.api.fetch_csv" rel="nofollow">tried to use a function <code>fetch_csv</code> from <code>zipline.api</code></a>, I get an error</p> <pre><code>AttributeE...
2
2016-10-16T19:19:42Z
40,074,559
<p>The <a href="http://www.zipline.io/appendix.html?highlight=fetch_csv#zipline.api.fetch_csv" rel="nofollow">Zipline API reference</a> says that this methods is to "Fetch a csv from a remote url". For local files, I would suggest <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel=...
0
2016-10-16T19:32:04Z
[ "python", "python-2.7", "zipline" ]
Heapify each sublist in a list of lists in python?
40,074,472
<p>I have a list of lists called opened which was declared like this: </p> <pre><code>opened = [[] for i in range(5)] </code></pre> <p>Now <code>opened = [[], [], [], [], []]</code><br> How can I heapify each of the sublists using the <code>heapq.heapify()</code> function? i.e, opened[0], opened[1], opened[2], opene...
0
2016-10-16T19:24:44Z
40,074,586
<p>Each of those sub-lists is a list, so just use <code>heapify()</code> directly on each of them:</p> <pre><code>import heapq for j in range(5): heapq.heapify(opened[j]) </code></pre> <p>Of course, if you know that each of those sub-lists is empty, there is no need to do this: an empty list is already a heap. T...
3
2016-10-16T19:35:26Z
[ "python", "data-structures", "heap" ]
Python: Select particular characters from a file and add them to a new variable
40,074,474
<p>I'm fairly new to python and I'm not sure why what I'm doing is wrong.</p> <pre><code>numberOfOrders = 0 numberOfProducts = 0 allOrders = open("file.txt", "r") #A .txt file in the same directory as the .py file. #file.txt: #(A-&gt;[a:20,a:20,b:10,c:25,c:25]) #(B-&gt;[d:100,e:70]) #(C-&gt;[f:10000,g:200000]) whil...
0
2016-10-16T19:24:48Z
40,074,935
<p>You can keep the digits and commas by stripping everything else out using a regular expression. Then you have a string of decimals and commas that you can split to give a list of products in each order line.</p> <pre><code>import re with open('file.txt') as all_orders: # substitute '' for all non-digit non-com...
0
2016-10-16T20:09:32Z
[ "python", "file", "python-3.x", "if-statement", "for-loop" ]
Python: Select particular characters from a file and add them to a new variable
40,074,474
<p>I'm fairly new to python and I'm not sure why what I'm doing is wrong.</p> <pre><code>numberOfOrders = 0 numberOfProducts = 0 allOrders = open("file.txt", "r") #A .txt file in the same directory as the .py file. #file.txt: #(A-&gt;[a:20,a:20,b:10,c:25,c:25]) #(B-&gt;[d:100,e:70]) #(C-&gt;[f:10000,g:200000]) whil...
0
2016-10-16T19:24:48Z
40,075,115
<p>Regarding your code, the solution is to:</p> <ol> <li>Removing the "for theline in allOrders" which is not coherent</li> <li>Moving the initialization of listProducts before the while loop </li> </ol> <p>Of course this can be widely optimized using regex for example, as suggested by tdelaney.</p>
0
2016-10-16T20:29:17Z
[ "python", "file", "python-3.x", "if-statement", "for-loop" ]
PyQt5 port: how do I hide a window and let it appear at the same position
40,074,637
<p>I'm porting a PyQt4 program to PyQt5. One part of it is hiding the window, taking a screenshot of the area behind the window and showing the window again, which worked just fine with PyQt4.</p> <p>With my PyQt5 port, everything works fine, but the window appears on the position where it was when the program was sta...
2
2016-10-16T19:40:10Z
40,074,761
<p>If I use <code>self.old_pos</code> in <code>hideMe</code> and <code>showMe</code> then it works for me (Linux).</p> <pre><code>def hideMe(self): self.old_pos = self.pos() self.hide() QTimer.singleShot(300, self.showMe) def showMe(self): self.show() self.move(self.old_pos) </code></pre>
0
2016-10-16T19:54:12Z
[ "python", "pyqt4", "porting", "pyqt5" ]
PyQt5 port: how do I hide a window and let it appear at the same position
40,074,637
<p>I'm porting a PyQt4 program to PyQt5. One part of it is hiding the window, taking a screenshot of the area behind the window and showing the window again, which worked just fine with PyQt4.</p> <p>With my PyQt5 port, everything works fine, but the window appears on the position where it was when the program was sta...
2
2016-10-16T19:40:10Z
40,075,769
<p>It seems that in Qt5 the geometry won't be re-set if it is exactly the same - but I don't know why this behaviour has changed, or whether it is a bug. And note that it is not just the position that is affected - resizing is also ignored.</p> <p>Here is a hack to work around the problem:</p> <pre><code>from PyQt5.Q...
0
2016-10-16T21:37:15Z
[ "python", "pyqt4", "porting", "pyqt5" ]