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 |
|---|---|---|---|---|---|---|---|---|---|
What is the proper way of testing throttling in DRF? | 39,309,046 | <p>What is the proper way of testing throttling in DRF? I coulnd't find out any answer to this question on the net. I want to have separate tests for each endpoint since each one has custom requests limits (ScopedRateThrottle).</p>
<p>The important thing is that it can't affect other tests - they have to somehow run w... | 1 | 2016-09-03T16:29:37Z | 39,350,391 | <p>Like people already mentioned, this doesn't exactly fall within the scope of unit tests, but still, how about simply doing something like this:</p>
<pre><code>from django.core.urlresolvers import reverse
from django.test import override_settings
from rest_framework.test import APITestCase, APIClient
class Throttl... | 0 | 2016-09-06T13:35:30Z | [
"python",
"django",
"testing",
"django-rest-framework",
"throttling"
] |
Python Simon Game: I Got Stuck Finishing the Sequence | 39,309,130 | <p>I'm finally finishing my Simon Game, but I have some doubts about how to complete the sequence.</p>
<p>Edit: As you asked I have edited my post. Here I will post my code as it was before this post. So here are my actual problems.</p>
<p>1) I don't know how to add one number to the sequence after each turn.</p>
<p... | 1 | 2016-09-03T16:37:15Z | 39,317,854 | <p>Here is the code based on furas' solution in the comments</p>
<pre><code>def showSequence():
global sequence
number_added = True
r = random.randint(1, 4)
if r == 1:
elif r == 2:
elif r == 3:
elif r == 4:
else:
number_added = False
return number_added # this will b... | 0 | 2016-09-04T14:15:53Z | [
"python",
"tkinter"
] |
Python Simon Game: I Got Stuck Finishing the Sequence | 39,309,130 | <p>I'm finally finishing my Simon Game, but I have some doubts about how to complete the sequence.</p>
<p>Edit: As you asked I have edited my post. Here I will post my code as it was before this post. So here are my actual problems.</p>
<p>1) I don't know how to add one number to the sequence after each turn.</p>
<p... | 1 | 2016-09-03T16:37:15Z | 39,362,560 | <p>I've answered this question already but you still had some problems, here is the full and complete code. I've made it more efficient and fixed the problems :)</p>
<p>This is working I've tested it. Just comment if there is anything you need to know</p>
<pre><code>import Tkinter # you don't need to import Tkinter a... | 1 | 2016-09-07T06:25:44Z | [
"python",
"tkinter"
] |
Simple index on DATE and TIME columns | 39,309,165 | <p>I have a CSV containing data that looks like this:</p>
<pre><code><DATE> <TIME> <OPEN> <LOW> <HIGH> <CLOSE>
2001-01-03 00:00:00 0.9507 0.9505 0.9509 0.9506
....
2015-05-13 02:00:00 0.9496 0.9495 0.9509 0.9505
</code></pre>
<p>I want to create an index... | 2 | 2016-09-03T16:40:59Z | 39,309,256 | <p><strong>UPDATE:</strong></p>
<pre><code>In [170]: df = pd.read_csv('/path/to/file.csv', parse_dates={'TIMESTAMP': ['DATE','TIME']}).set_index('TIMESTAMP')
In [171]: df
Out[171]:
OPEN LOW HIGH CLOSE
TIMESTAMP
2001-01-03 00:00:00 0.9507 0.9505 0.9509 0.9506
2001-01-03 01:00:00 0.... | 2 | 2016-09-03T16:52:07Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Flask-Admin refresh files list | 39,309,227 | <p>The <a href="https://github.com/flask-admin/flask-admin/blob/master/examples/forms/app.py" rel="nofollow">Flask-Admin form tutorial code</a> creates a list from the files in a directory. This is the populating of the list: </p>
<pre><code>def build_sample_db():
# Populating the pdf files
db.drop_all()
... | 0 | 2016-09-03T16:48:33Z | 39,329,336 | <p>Override your view's <code>index_view</code> method. Something like (untested) :</p>
<pre><code>from flask_admin import expose
class FileView(sqla.ModelView):
# Pass additional parameters to 'path' to FileUploadField constructor
form_args = {
'path': {
'label': 'File',
'base... | 1 | 2016-09-05T11:10:42Z | [
"python",
"flask",
"flask-admin"
] |
Flask-Admin refresh files list | 39,309,227 | <p>The <a href="https://github.com/flask-admin/flask-admin/blob/master/examples/forms/app.py" rel="nofollow">Flask-Admin form tutorial code</a> creates a list from the files in a directory. This is the populating of the list: </p>
<pre><code>def build_sample_db():
# Populating the pdf files
db.drop_all()
... | 0 | 2016-09-03T16:48:33Z | 39,333,703 | <p><a href="https://github.com/flask-admin/flask-admin/blob/master/examples/file/app.py" rel="nofollow">Flask-Admin file example</a> also answers the question. The files refresh, only the database is not added, but that's OK: </p>
<pre><code>from flask_admin.contrib import fileadmin
# irrelevant code removed - see in ... | 0 | 2016-09-05T15:27:20Z | [
"python",
"flask",
"flask-admin"
] |
how to remove the first occurence of an integer in a list | 39,309,238 | <p>this is my code:</p>
<pre><code>positions = []
for i in lines[2]:
if i not in positions:
positions.append(i)
print (positions)
print (lines[1])
print (lines[2])
</code></pre>
<p>the output is: </p>
<pre><code>['1', '2', '3', '4', '5']
['is', 'the', 'time', 'this', 'ends']
['1', '2', '3', '4', '1', '5'... | 1 | 2016-09-03T16:49:57Z | 39,309,267 | <p>You'll need to first detect what values are duplicated before you can build <code>positions</code>. Use an <code>itertools.Counter()</code> object to test if a value has been seen more than once:</p>
<pre><code>from itertools import Counter
counts = Counter(lines[2])
positions = []
for i in lines[2]:
counts[i]... | 3 | 2016-09-03T16:54:15Z | [
"python",
"python-3.x"
] |
how to remove the first occurence of an integer in a list | 39,309,238 | <p>this is my code:</p>
<pre><code>positions = []
for i in lines[2]:
if i not in positions:
positions.append(i)
print (positions)
print (lines[1])
print (lines[2])
</code></pre>
<p>the output is: </p>
<pre><code>['1', '2', '3', '4', '5']
['is', 'the', 'time', 'this', 'ends']
['1', '2', '3', '4', '1', '5'... | 1 | 2016-09-03T16:49:57Z | 39,309,302 | <p>You can reverse your list, create the positions and then reverse it back as mentioned by @tobias_k in the comment:</p>
<pre><code>lst = ['1', '2', '3', '4', '1', '5']
positions = []
for i in reversed(lst):
if i not in positions:
positions.append(i)
list(reversed(positions))
# ['2', '3', '4', '1', '5']... | 4 | 2016-09-03T16:58:02Z | [
"python",
"python-3.x"
] |
how to remove the first occurence of an integer in a list | 39,309,238 | <p>this is my code:</p>
<pre><code>positions = []
for i in lines[2]:
if i not in positions:
positions.append(i)
print (positions)
print (lines[1])
print (lines[2])
</code></pre>
<p>the output is: </p>
<pre><code>['1', '2', '3', '4', '5']
['is', 'the', 'time', 'this', 'ends']
['1', '2', '3', '4', '1', '5'... | 1 | 2016-09-03T16:49:57Z | 39,309,848 | <p>you can use a dictionary to save the last position of the element and then build a new list with that information</p>
<pre><code>>>> data=['1', '2', '3', '4', '1', '5']
>>> temp={ e:i for i,e in enumerate(data) }
>>> sorted(temp, key=lambda x:temp[x])
['2', '3', '4', '1', '5']
>>>... | 0 | 2016-09-03T17:58:47Z | [
"python",
"python-3.x"
] |
Migrating sales from xl to odoo using XML-RPC | 39,309,268 | <p>Im trying to migrate sales order from excel sheet to odoo using xmlrpc so far i have the products working,client working but when i try to insert the sale order i get this error</p>
<pre><code>Traceback (most recent call last):
File "/home/oasis/PycharmProjects/somig/migrator.py", line 75, in <module>
'... | 0 | 2016-09-03T16:54:22Z | 39,309,633 | <p>I think the issue is that you execute a search for partnerids which will result in an array. However if you do not find any you create a partner which is represented by an integer. You then assign partnerids to the partner_id in your sale.order. </p>
<p>Sometimes you are assigning it an integer and other times an a... | 1 | 2016-09-03T17:38:29Z | [
"python",
"openerp",
"xml-rpc"
] |
Migrating sales from xl to odoo using XML-RPC | 39,309,268 | <p>Im trying to migrate sales order from excel sheet to odoo using xmlrpc so far i have the products working,client working but when i try to insert the sale order i get this error</p>
<pre><code>Traceback (most recent call last):
File "/home/oasis/PycharmProjects/somig/migrator.py", line 75, in <module>
'... | 0 | 2016-09-03T16:54:22Z | 39,315,389 | <p>The Error message says:</p>
<blockquote>
<p>ProgrammingError: column "partner_id" is of type integer but expression is of type integer[].</p>
</blockquote>
<p>Just give <code>partnerids</code> as an integer: </p>
<pre><code>if partnerids:
partnerids = partnerids[0]
print partnerids
</code></pre>
| 0 | 2016-09-04T09:17:38Z | [
"python",
"openerp",
"xml-rpc"
] |
Python Elasticsearch urllib3 exception | 39,309,299 | <p>I have to use python-elasticsearch library on a machine where I could only execute programs. I am trying to use elasticsearch module by appending sys.path as mentioned below. I am facing below issue. It looks like the problem related to what is mentioned here
<a href="https://github.com/elastic/elasticsearch-py/is... | 0 | 2016-09-03T16:57:51Z | 39,350,543 | <p>@nehal Thanks for your suggestion I was able to get it fixed. Please find the
series of steps I used to install</p>
<ol>
<li>Used easy_install to install package pip</li>
<li>Appended PYTHONPATH</li>
<li>used pip to install virtualenv</li>
<li>Activated new virtualenv</li>
<li><p>Installed elasticsearch using pip... | 0 | 2016-09-06T13:42:26Z | [
"python",
"python-2.7",
"elasticsearch",
"urllib3"
] |
Why does this piece of code gets slower with time? | 39,309,327 | <p>I'm trying to preprocess my images adding them to a 4D array. It starts off right but it gets slower with time, I thought this was due to my CPU but I tried running it on a GPU on the cloud and it still gets slower. Is this due to RAM? How can I optimize this to run faster?</p>
<pre><code>import tensorflow as tf
im... | 0 | 2016-09-03T17:01:16Z | 39,309,525 | <p>I don't know much about TensorFlow, but I believe the problem is <code>process_image</code> is using a bunch of globals, particularly <code>tf</code>. Every time it's called you're running TensorFlow on an ever increasing set of images. First there's <a href="https://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2... | 1 | 2016-09-03T17:25:34Z | [
"python",
"performance",
"numpy",
"tensorflow"
] |
Unable to feed value for placeholder tensor | 39,309,367 | <p>I have written a simple version bidirectional lstm for sentence classification. But it keeps giving me "You must feed a value for placeholder tensor 'train_x'" error and it seems this come from the variable initialization step. </p>
<pre><code>data = load_data(FLAGS.data)
model = RNNClassifier(FLAGS)
init = tf.init... | 13 | 2016-09-03T17:05:58Z | 39,440,287 | <p>This is what I did.. </p>
<p>I could change the way I initialised my input variables as:</p>
<pre><code>data = load_data(FLAGS.data)
model = RNNClassifier(FLAGS, data)
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start... | 0 | 2016-09-11T20:21:28Z | [
"python",
"tensorflow"
] |
Unable to feed value for placeholder tensor | 39,309,367 | <p>I have written a simple version bidirectional lstm for sentence classification. But it keeps giving me "You must feed a value for placeholder tensor 'train_x'" error and it seems this come from the variable initialization step. </p>
<pre><code>data = load_data(FLAGS.data)
model = RNNClassifier(FLAGS)
init = tf.init... | 13 | 2016-09-03T17:05:58Z | 39,479,736 | <p>It looks like the problem is in this method, in <code>RNNClassifier</code>:</p>
<pre><code>def batch_data(self):
# ...
batched_inputs, batched_labels = tf.train.batch(
tensors=[self._train_x, self._train_y],
batch_size=self.params.batch_size,
dynamic_pad=True,
enqueue_many=Tr... | 0 | 2016-09-13T22:10:34Z | [
"python",
"tensorflow"
] |
How to sum and to mean one DataFrame to create another DataFrame | 39,309,435 | <p>After creating DataFrame with some duplicated cell values in the column <strong>Name</strong>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Name': ['Will','John','John','John','Alex'],
'Payment': [15, 10, 10, 10, 15],
'Duration': [30, 15, 15, 15, 20]})
</code></pr... | 6 | 2016-09-03T17:14:09Z | 39,309,481 | <p>You can apply different functions to different columns with groupby.agg:</p>
<pre><code>df.groupby('Name').agg({'Duration': 'mean', 'Payment': 'sum'})
Out:
Payment Duration
Name
Alex 15 20
John 30 15
Will 15 30
</code></pre>
| 8 | 2016-09-03T17:19:47Z | [
"python",
"pandas",
"dataframe"
] |
Extracting text within frame tree in html | 39,309,488 | <p>I would like to scrape a frame within a website (<a href="https://www.harris.com/careers/jobs" rel="nofollow">https://www.harris.com/careers/jobs</a>). THe Xpath for the location for the first listed job position is </p>
<pre><code>/html/body/center/table[2]/tbody/tr/td/form/table[3]/tbody/tr[3]/td/table/tbody/tr[3... | -1 | 2016-09-03T17:20:44Z | 39,344,273 | <p>Here I will give working code for that:</p>
<pre><code>from selenium.webdriver.common.keys import Keys
from selenium import webdriver
import time
driver=webdriver.Chrome('./chromedriver.exe')
try:
driver.get("https://www.harris.com/careers/jobs")
driver.switch_to.frame("frmJobs");
time.sleep(5)
#s ... | 0 | 2016-09-06T08:34:14Z | [
"python",
"xpath",
"web-scraping",
"lxml",
"python-3.5"
] |
How to access the same JSON file from both javascript and python? | 39,309,558 | <p>NOTE: This is not for web programming. We use javascript to interface with low level hardware, hence let's not go with jQuery APIs etc.</p>
<p>I have a javascript file that performs a sequence of actions on a device, and I have a python file that will be invoked later to validate these actions. There is a set of ha... | 2 | 2016-09-03T17:29:50Z | 39,309,697 | <p>It looks like <code>load()</code> <em>executes</em> the specified file, not read it and return the contents. If this is your <em>only</em> option to read another file, then I suggest you use <a href="https://en.wikipedia.org/wiki/JSONP" rel="nofollow">JSONP</a> instead of JSON.</p>
<p>JSONP works by adding a <em>ca... | 2 | 2016-09-03T17:44:31Z | [
"javascript",
"python",
"json"
] |
How to get a name of Column or change the name of existing? | 39,309,615 | <p>I have a task to build a function "removePunctuation" that strips the punctuation and as result pass this test:</p>
<pre><code># TEST Capitalization and punctuation (4b)
testPunctDF = sqlContext.createDataFrame([(" The Elephant's 4 cats. ",)])
testPunctDF.show()
Test.assertEquals(testPunctDF.select(removePunctuatio... | 1 | 2016-09-03T17:36:30Z | 39,309,732 | <p>I would try:</p>
<pre><code>stringWithPunctuation.translate(None, string.punctuation)
</code></pre>
<p>which uses <a href="/questions/tagged/c" class="post-tag" title="show questions tagged 'c'" rel="tag">c</a> under the hood, simply the best in terms of efficiency!</p>
<hr>
<p>Your attempt:</p>
<pre><c... | 2 | 2016-09-03T17:47:50Z | [
"python",
"string",
"apache-spark",
"distributed-computing",
"punctuation"
] |
How to get a name of Column or change the name of existing? | 39,309,615 | <p>I have a task to build a function "removePunctuation" that strips the punctuation and as result pass this test:</p>
<pre><code># TEST Capitalization and punctuation (4b)
testPunctDF = sqlContext.createDataFrame([(" The Elephant's 4 cats. ",)])
testPunctDF.show()
Test.assertEquals(testPunctDF.select(removePunctuatio... | 1 | 2016-09-03T17:36:30Z | 39,309,742 | <p>Surprisingly I was able just to pass column object in <code>regexp_replace()</code> args instead of column name. </p>
| 1 | 2016-09-03T17:48:31Z | [
"python",
"string",
"apache-spark",
"distributed-computing",
"punctuation"
] |
How do I multithread SQL Queries in python such that I obtain the results of all of the queries | 39,309,714 | <p>Is there a way to use threads to simultaneously perform the SQL queries so I can cut down on processing time of my code below? Is there a better method to perform the same result as below without using the pandas module? Given the size of the data sets I am working with I cannot store the entire dataset in memory an... | 0 | 2016-09-03T17:46:26Z | 39,310,039 | <p>Some advices:</p>
<p>Instead of reading the records by chucks using a iterator, you ought to use pagination. </p>
<p>See this questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/14468586/efficient-paging-in-sqlite-with-millions-of-records">Efficient paging in SQLite with millions of records</a></l... | 1 | 2016-09-03T18:18:35Z | [
"python",
"multithreading",
"sqlite3"
] |
PyCharm Edu introduction course, string multiplication | 39,309,791 | <p>I'm new to Python and currently running the "Introduction to Python" course for PyCharm Edu. I'm having a problem with the following task (strings -> string multiplication)</p>
<blockquote>
<p>Python supports a string-by-number multiplication (but not the other
way around!). </p>
<p>Use hello to get the
... | 1 | 2016-09-03T17:53:04Z | 39,311,871 | <p>You are doing it right. They maybe are trying to teach you the difference between the string "hello" and The variable.</p>
| 0 | 2016-09-03T22:28:16Z | [
"python",
"pycharm"
] |
PyCharm Edu introduction course, string multiplication | 39,309,791 | <p>I'm new to Python and currently running the "Introduction to Python" course for PyCharm Edu. I'm having a problem with the following task (strings -> string multiplication)</p>
<blockquote>
<p>Python supports a string-by-number multiplication (but not the other
way around!). </p>
<p>Use hello to get the
... | 1 | 2016-09-03T17:53:04Z | 39,333,904 | <p>If anyone else is completing the PyCharm Edu tutorial I noticed a problem with the string_multiplication exercise. When attempting to complete the solution an error messsage "Use multiplication" occurs. This is due to the source code of the PyCharm project. For anyone interested the solution is to go into you file s... | 5 | 2016-09-05T15:40:52Z | [
"python",
"pycharm"
] |
PyCharm Edu introduction course, string multiplication | 39,309,791 | <p>I'm new to Python and currently running the "Introduction to Python" course for PyCharm Edu. I'm having a problem with the following task (strings -> string multiplication)</p>
<blockquote>
<p>Python supports a string-by-number multiplication (but not the other
way around!). </p>
<p>Use hello to get the
... | 1 | 2016-09-03T17:53:04Z | 39,629,930 | <p>There was a missing else in the code that was fixed Aug 13, 2016 (<a href="https://github.com/lbilger/pycharm-courses/commit/32b4d3e9adc32e7b9c6a293e4c6e2bcc29b35210" rel="nofollow">see commit on github</a>). However, the current Version: 2016.2.3 Released: September 6, 2016 is still missing the 'else' in the test.p... | 0 | 2016-09-22T03:49:59Z | [
"python",
"pycharm"
] |
Number guessing game, unable to take the next guess | 39,309,804 | <p>Here is the concept of my game, the computer randomly generates a number from 1-100 and the player has to guess that number. If the number they guess is higher or lower the computer tells them so.</p>
<p>I added some code to make sure that the guess that the user enters is a number, but for some reason, it only wor... | 1 | 2016-09-03T17:54:08Z | 39,309,841 | <p>You need to surround your guessing logic in another loop that continues until the guess is correct.</p>
<p>pseudocode:</p>
<pre><code>choose_target_answer
while player_has_not_guessed_answer
get_player_guess
if player_guess_is_valid
respond_to_player_guess
else
give_error_message
</code... | 1 | 2016-09-03T17:58:07Z | [
"python",
"random"
] |
Number guessing game, unable to take the next guess | 39,309,804 | <p>Here is the concept of my game, the computer randomly generates a number from 1-100 and the player has to guess that number. If the number they guess is higher or lower the computer tells them so.</p>
<p>I added some code to make sure that the guess that the user enters is a number, but for some reason, it only wor... | 1 | 2016-09-03T17:54:08Z | 39,309,866 | <p>I've fixed your code for you. Try this:</p>
<pre><code>import random
x = random.randint(1, 100)
while True:
try:
guess = int(raw_input("Guess the number: "))
except ValueError:
print("Not a valid number, try again!")
continue
if guess < x:
print("Too low, guess agai... | 2 | 2016-09-03T18:00:57Z | [
"python",
"random"
] |
Number guessing game, unable to take the next guess | 39,309,804 | <p>Here is the concept of my game, the computer randomly generates a number from 1-100 and the player has to guess that number. If the number they guess is higher or lower the computer tells them so.</p>
<p>I added some code to make sure that the guess that the user enters is a number, but for some reason, it only wor... | 1 | 2016-09-03T17:54:08Z | 39,309,906 | <p>Your <code>if</code> statements are all independent:</p>
<pre><code>if x > int(guess):
print("Too low, guess again")
guess = input("Guess the number")
if x < int(guess):
print("Too high, guess again")
guess = input("Guess the number")
if x == int(guess):
print ("That is correct!")
br... | 2 | 2016-09-03T18:04:37Z | [
"python",
"random"
] |
ValueError: script argument must be unicode. - Python3.5, SQLite3 | 39,309,820 | <p>I'm writing following python script:</p>
<pre class="lang-py prettyprint-override"><code>import sqlite3
import sys
if len(sys.argv) < 2:
print("Error: You must supply at least SQL script.")
print("Usage: %s table.db ./sql-dump.sql" % (sys.argv[0]))
sys.exit(1)
script_path = sys.argv[1]
if len(sys.... | 0 | 2016-09-03T17:55:47Z | 39,309,873 | <p>You opened the script file as <em>binary</em>:</p>
<pre><code>with open(script_path,'rb') as f:
</code></pre>
<p>This produces a <code>b'...'</code> bytes value, not a Unicode <code>str</code> object. Remove the <code>b</code>, and perhaps add an <code>encoding</code> argument to specific what codec to use to deco... | 0 | 2016-09-03T18:01:46Z | [
"python",
"unicode",
"sqlite3"
] |
Is assigning a,b = c,a the same as b,a = a,c? | 39,309,928 | <p>Is assigning </p>
<pre><code>a,b = c,a
</code></pre>
<p>the same as </p>
<pre><code>b,a = a,c
</code></pre>
<p>It seems to be the same for the simple case where <code>a</code>, <code>b</code>, and <code>c</code> are numbers.</p>
<p>Is there a case where this fails?</p>
| 1 | 2016-09-03T18:06:28Z | 39,309,959 | <p>No, there is no case where this fails. The two statements are exactly equivalent, because <code>a</code> and <code>b</code> are <em>independent</em>.</p>
<p>That's because the right-hand side values are put on the stack <em>first</em> before assignment takes place (from left to right). Assigning to <code>a</code> b... | 5 | 2016-09-03T18:10:02Z | [
"python",
"python-2.7"
] |
Is assigning a,b = c,a the same as b,a = a,c? | 39,309,928 | <p>Is assigning </p>
<pre><code>a,b = c,a
</code></pre>
<p>the same as </p>
<pre><code>b,a = a,c
</code></pre>
<p>It seems to be the same for the simple case where <code>a</code>, <code>b</code>, and <code>c</code> are numbers.</p>
<p>Is there a case where this fails?</p>
| 1 | 2016-09-03T18:06:28Z | 39,309,961 | <p>It's the same in all cases, no matter what you're working with. So long as statements are equivalent (like yours are), the result will be the same.</p>
| 1 | 2016-09-03T18:10:14Z | [
"python",
"python-2.7"
] |
Is assigning a,b = c,a the same as b,a = a,c? | 39,309,928 | <p>Is assigning </p>
<pre><code>a,b = c,a
</code></pre>
<p>the same as </p>
<pre><code>b,a = a,c
</code></pre>
<p>It seems to be the same for the simple case where <code>a</code>, <code>b</code>, and <code>c</code> are numbers.</p>
<p>Is there a case where this fails?</p>
| 1 | 2016-09-03T18:06:28Z | 39,309,974 | <p>Short Answer ----- "Yes"..
a,b = c,a means a=c and b=a ...
b,a = a,c means b=a and a=c</p>
| 0 | 2016-09-03T18:11:38Z | [
"python",
"python-2.7"
] |
(PyQT) How can I make sure values in all following spinboxes are higher than the last | 39,309,929 | <p>The following is an example of inputs that could potentially be added.</p>
<p>value 0: [ 0 ] [ 100 ]
<br>value 1: [ 200 ] [ 300 ]
<br>value 2: [ 400 ] [ 500 ]</p>
<p>The above is correct</p>
<p>value 0: [ 0 ] [ 800 ]
<br>value 1: [ 700 ] [ 600 ]
<br>value 2: [ 5... | 0 | 2016-09-03T18:06:34Z | 39,315,901 | <p>you could use the <code>valueChanged()</code> signal of <code>QSpinBox</code> to <code>setMinimum()</code> of the following spinboxes according to the value of the former spinbox, so the spinboxes only accept values >= minimum, here a working example:</p>
<pre><code>import sys
from PyQt5.QtCore import *
from PyQt5.... | 2 | 2016-09-04T10:21:56Z | [
"python",
"pyqt"
] |
What I sure method I used to authenticate in webpy? | 39,309,937 | <p>Hello I have an application on my localhost, the application is made with webpy, this application is an administration panel, cpanel style, I can only access because it is running on 127.0.0.1</p>
<p>Now I would like to use it on my public server.</p>
<p>But you need a very secure method of authentication with web... | 0 | 2016-09-03T18:07:54Z | 39,314,255 | <ul>
<li><p>To use SSL: Add the following lines to the the web.py main file.</p>
<p><code>from web.wsgiserver import CherryPyWSGIServer
CherryPyWSGIServer.ssl_certificate = "/path/to/ssl_certificate" CherryPyWSGIServer.ssl_private_key = "/path/to/ssl_private_key"</code></p>
<p>which allows you to use htt... | 0 | 2016-09-04T06:44:03Z | [
"python",
"security",
"web.py"
] |
Does particular string match strings in text file | 39,310,010 | <p>I have a text file containing many words (single word on each line). I have to read in each word, modify the words, and then check if the modified word matches any of the words in the file. I am having trouble with the last part (it is the hasMatch method in my code). It sounds simple enough and I know what I should... | -1 | 2016-09-03T18:15:21Z | 39,310,053 | <p>Several problems here</p>
<ol>
<li>you have to strip the lines or you get linefeed/CR chars that fail the match</li>
<li>you have to read the file once and for all or the file iterator runs out after the first time</li>
<li>the speed is bad: sped up for the search using a <code>set</code> instead of a <code>list</c... | 2 | 2016-09-03T18:19:46Z | [
"python",
"string",
"python-2.7"
] |
Does particular string match strings in text file | 39,310,010 | <p>I have a text file containing many words (single word on each line). I have to read in each word, modify the words, and then check if the modified word matches any of the words in the file. I am having trouble with the last part (it is the hasMatch method in my code). It sounds simple enough and I know what I should... | -1 | 2016-09-03T18:15:21Z | 39,310,086 | <p>In your code, you're not slicing just the first and last character but the first and last two characters.</p>
<pre><code>rmFirstLast = str[1:len(str)-2]
</code></pre>
<p>Change that to:</p>
<pre><code>rmFirstLast = str[1:len(str)-1]
</code></pre>
| 0 | 2016-09-03T18:23:57Z | [
"python",
"string",
"python-2.7"
] |
how to match items between 2 different lists | 39,310,062 | <p>I have 2 different lists:</p>
<pre><code>['2', '1']
['equals', 'x']
</code></pre>
<p>I want to match the items so 2 = "equals" and 1 = "x" in order to recreate the original sentence "x equals x", also i have a third list which is:</p>
<pre><code>['1', '2', '1']
</code></pre>
<p>I need the third list to recreate ... | 0 | 2016-09-03T18:20:35Z | 39,310,093 | <p>A dictionary might be what you need here which maps keys to values. You can create a dictionary from the first two lists by zipping them. And with this dictionary, it should be fairly straight forward to map any list of numbers to words:</p>
<pre><code>mapping = dict(zip(['2', '1'], ['equals', 'x']))
mapping
# {'1... | 1 | 2016-09-03T18:24:39Z | [
"python",
"list",
"python-2.7",
"python-3.x"
] |
Unexpected output from "mimic" function exercise from Google Python Class | 39,310,164 | <p>First of all, apologies if some stupid error lies ahead: I have just started to ("re")learn Python (I am using Python 2.7).</p>
<p>I have completed one exercise from the Google Python Class, called "mimic", but I'm sometimes getting some strange results and I would like to understand why this is happening.</p>
<p>... | 0 | 2016-09-03T18:34:25Z | 39,310,369 | <p>You missed two characters.</p>
<p><code>d[''] = words[0]</code> should be <code>d[''] = [words[0]]</code>.</p>
| 1 | 2016-09-03T19:00:29Z | [
"python",
"python-2.7"
] |
Peewee - Update an entry with a dictionary | 39,310,191 | <p>I found <a href="https://stackoverflow.com/questions/22750439/peewee-how-to-convert-a-dict-into-a-model">this handy answer</a> on how to <strong>create</strong> a new table entry using a dictionary.</p>
<p>Now i'd like to <strong>update</strong> an entry with the same method. but i don't know how to adress the spec... | 1 | 2016-09-03T18:38:22Z | 39,311,315 | <p>The double star shortcut is a python thing. It allows you to expand a dictionary into key-word arguments in a method. That means you can do something like this:</p>
<pre><code>fruit = { "name": "Banana", "color": "yellow"}
some_method(**fruit)
</code></pre>
<p>which would be the equivelent of doing:</p>
<pre><cod... | 1 | 2016-09-03T21:04:51Z | [
"python",
"dictionary",
"peewee"
] |
Peewee - Update an entry with a dictionary | 39,310,191 | <p>I found <a href="https://stackoverflow.com/questions/22750439/peewee-how-to-convert-a-dict-into-a-model">this handy answer</a> on how to <strong>create</strong> a new table entry using a dictionary.</p>
<p>Now i'd like to <strong>update</strong> an entry with the same method. but i don't know how to adress the spec... | 1 | 2016-09-03T18:38:22Z | 39,319,387 | <p>To update an object, you can:</p>
<pre><code>entry = entries_index[idx]
entry.something = 'new value'
entry.another_thing = 'another thing'
entry.save()
</code></pre>
<p>Alternatively:</p>
<pre><code>Entry.update(**{'something': 'new value', 'another_thing': 'another'}).where(Entry.id == entry.id).execute()
</cod... | 1 | 2016-09-04T17:00:50Z | [
"python",
"dictionary",
"peewee"
] |
Entering Data in tkinter frames | 39,310,212 | <p>I'm writing a program to keep the score of a 14-1 billiard(pool) match. Since I needed multiple windows I used tkinter frames. The frames for 2 pages work with out difficulty. My problem is entering data. The first item to be entered in each players name. Both text boxes appear on the screen, and data can be entered... | 0 | 2016-09-03T18:40:12Z | 39,310,371 | <p>Your code and your post is so messy.
About your problem: I refer you to use GET method, from each entry box take data with using GET method, next ascribe it into a variable, it's simplest way to take a data from entry box. In applications like yours, I make button near entry box, and in command attribute I do someth... | -1 | 2016-09-03T19:00:30Z | [
"python",
"tkinter"
] |
Entering Data in tkinter frames | 39,310,212 | <p>I'm writing a program to keep the score of a 14-1 billiard(pool) match. Since I needed multiple windows I used tkinter frames. The frames for 2 pages work with out difficulty. My problem is entering data. The first item to be entered in each players name. Both text boxes appear on the screen, and data can be entered... | 0 | 2016-09-03T18:40:12Z | 39,310,695 | <p>I can't see any attempt to access the contents of the text entry widgets. As such your code does exactly what I'd expect it to do.</p>
<p>If you want to read the contents of a text entry widget you should create a <code>StringVar</code> to hold the contents</p>
<pre><code>self.playerone = StringVar()
self.entry1 =... | 0 | 2016-09-03T19:40:59Z | [
"python",
"tkinter"
] |
Implementing a modified do-while loop in Python i.e. do at least once and another time at the end of the loop? | 39,310,229 | <p>I am having problems implementing something that equates a do while loop.</p>
<p><strong>PROBLEM DESCRIPTION</strong></p>
<p>I am scraping a site and the results pages are paginated, i.e.</p>
<pre><code>1, 2, 3, 4, 5, .... NEXT
</code></pre>
<p>I am iterating through the pages using a test condition for the exis... | 0 | 2016-09-03T18:41:31Z | 39,310,322 | <p>When you are searching for next link change code to find_elements which will return a list of size 1 if Next is present else list of size 0 but no exception.</p>
<pre><code>next_link = driver.find_elements(By.XPATH, "//a[contains(text(),'Next')][@style='text-decoration:underline; cursor: pointer;']")
</code></pre>
... | 2 | 2016-09-03T18:53:41Z | [
"python",
"loops",
"selenium",
"for-loop",
"while-loop"
] |
Implementing a modified do-while loop in Python i.e. do at least once and another time at the end of the loop? | 39,310,229 | <p>I am having problems implementing something that equates a do while loop.</p>
<p><strong>PROBLEM DESCRIPTION</strong></p>
<p>I am scraping a site and the results pages are paginated, i.e.</p>
<pre><code>1, 2, 3, 4, 5, .... NEXT
</code></pre>
<p>I am iterating through the pages using a test condition for the exis... | 0 | 2016-09-03T18:41:31Z | 39,310,602 | <p>You should try using <code>find_elements</code>, it would return either list of WebElement or empty list. So just check its length as below :-</p>
<pre><code>while True:
findRecords()
next_link = driver.find_elements(By.XPATH, "//a[contains(text(),'Next')][@style='text-decoration:underline; cursor: pointer;... | 1 | 2016-09-03T19:28:23Z | [
"python",
"loops",
"selenium",
"for-loop",
"while-loop"
] |
Setting a proxy using python, selenium, and phantomJS | 39,310,307 | <p>I have tried the solution posted by Alex on the following page but I keep getting this error.
<a href="http://stackoverflow.com/questions/14699718/how-do-i-set-a-proxy-for-phantomjs-ghostdriver-in-python-webdriver/">How do I set a proxy for phantomjs/ghostdriver in python webdriver?</a></p>
<p>I have phantomJS in m... | 0 | 2016-09-03T18:51:28Z | 39,310,375 | <p>Whelp... Made a small mistake.</p>
<p>The following line
phan_args = ['--proxy=88.157.149.250:8080', 'proxy-type=http']
should be
phan_args = ['--proxy=88.157.149.250:8080', '--proxy-type=http']</p>
| 0 | 2016-09-03T19:01:12Z | [
"python",
"selenium",
"proxy",
"phantomjs"
] |
Merge Sort not happening correctly - Python | 39,310,370 | <p>Sorting is not happening correctly. Can some one help on sorting with this approach. Also please let me know where I am going wrong. I am new to Python so I am doing this myself. I am using the usual approach as we do in C or other languages.</p>
<pre><code>base =[5,4,3,2,1]
def splitarray (low, high):
if low... | 2 | 2016-09-03T19:00:29Z | 39,310,884 | <p>Visually the way the algorithm operates is:<a href="http://i.stack.imgur.com/obJIB.png" rel="nofollow"><img src="http://i.stack.imgur.com/obJIB.png" alt="enter image description here"></a></p>
<p>So the most obvious way to implement merge sort is to return a new list for each merge. Maybe that can be optimized to w... | 2 | 2016-09-03T20:05:30Z | [
"python",
"mergesort"
] |
Merge Sort not happening correctly - Python | 39,310,370 | <p>Sorting is not happening correctly. Can some one help on sorting with this approach. Also please let me know where I am going wrong. I am new to Python so I am doing this myself. I am using the usual approach as we do in C or other languages.</p>
<pre><code>base =[5,4,3,2,1]
def splitarray (low, high):
if low... | 2 | 2016-09-03T19:00:29Z | 39,313,429 | <p>The issue with your current (updated) code appears to be with the last loop:</p>
<pre><code>l = low
k= 0
while l <= high:
base[l] = result[l]
l += 1
</code></pre>
<p>Here you're copying the values from the <code>results</code> list to the <code>base</code> list. However, the results are all at the start... | 1 | 2016-09-04T04:00:15Z | [
"python",
"mergesort"
] |
Parsing text into it's own field, counting, and reshaping select fields to wide format | 39,310,464 | <p>I'm doing an analysis using Python to see how long we are keeping conversations in our social media channels by counting the number of interactions and reading the messages.</p>
<p>I'm thinking the approach would be to make the first table look like the second table. Steps to get there:</p>
<ol>
<li>Parse our the... | 2 | 2016-09-03T19:11:46Z | 39,311,887 | <p>Your transformation process should include several steps, I will give an idea only to one of them.</p>
<p>Concerning user extraction:
First you should apply <code>re.sub(pattern, repl, string)</code> function from the <strong>re</strong> package to the raws in the Outbound message column (in a loop). The <code>sub<... | 1 | 2016-09-03T22:31:07Z | [
"python",
"pandas",
"dataframe",
"aggregate",
"reshape"
] |
Parsing text into it's own field, counting, and reshaping select fields to wide format | 39,310,464 | <p>I'm doing an analysis using Python to see how long we are keeping conversations in our social media channels by counting the number of interactions and reading the messages.</p>
<p>I'm thinking the approach would be to make the first table look like the second table. Steps to get there:</p>
<ol>
<li>Parse our the... | 2 | 2016-09-03T19:11:46Z | 39,314,625 | <p><strong><em>Note</em></strong><br>
You need to <code>groupby</code> <code>user</code> and <code>df.Account</code> because it is possible to have messages from different accounts for the same user.</p>
<pre><code># helper function to flatten multiindex objects
def flatten_multiindex(midx, sep=' '):
n = midx.nlev... | 1 | 2016-09-04T07:37:30Z | [
"python",
"pandas",
"dataframe",
"aggregate",
"reshape"
] |
Python Freezing: general process and user input? | 39,310,494 | <p>I'm relatively new to the process of freezing and packaging code, and one of my concerns with freezing my project is how I'd deal with user input. I have a main file in a project that deals with physics stuff with an input area like this: </p>
<pre><code>#Coil(center, radius, normal vector, current, scene, loops(d... | 0 | 2016-09-03T19:15:19Z | 39,313,975 | <p>Once your code is frozen the contents of the code can no longer be changed, (without going back to the original code), but there are a number of strategies that you can use:</p>
<ul>
<li>Prompt the user for <em>missing</em> parameters one at a time - <em>makes the program hard to use</em></li>
<li>Allow the user to... | 1 | 2016-09-04T05:59:52Z | [
"python",
"python-2.7",
"vpython",
"code-freeze"
] |
Getting an error "could not broadcast input array from shape (252,4) into shape (4)" in optimization | 39,310,546 | <p>I a relatively new to python scipy library. I was trying to use the scipy.optimize to find the maximum value of the sharpe() function in the following code</p>
<pre><code>def sharpe(dr, wts):
portfolio=np.ones(dr.shape[0])
dr[0:]=wts*dr[0:]
sharpe_ratio=-np.mean(np.sum(dr, axis=1))/np.std(np.sum(dr, axi... | 0 | 2016-09-03T19:20:58Z | 39,314,478 | <p>I think you need to swap the arguments in your definition of the <code>sharpe</code> function. It is defined as <code>sharpe(dr,wts)</code> but then it looks like you call minimize as <code>sharpe(wts,dr)</code> based on your use of <code>args</code>. Edit: I have just seen that this is pointed out in the above comm... | 0 | 2016-09-04T07:18:08Z | [
"python",
"optimization",
"scipy"
] |
Python stacked histogram grouped data | 39,310,559 | <p>How can I create a stacked Histogram like this:
<a href="http://i.stack.imgur.com/vVKq3.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/vVKq3.jpg" alt="enter image description here"></a></p>
<pre><code>import numpy as np
import pylab as P
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use... | 4 | 2016-09-03T19:22:05Z | 39,311,219 | <p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a> your DataFrame so that each group is in a different column and then generate the histogram.</p>
<pre><code>df1 = pd.DataFrame({'A': [1,2,3,4,5,6,7,8,9],'group': [1,0,0,0,0,1,1,1,... | 3 | 2016-09-03T20:51:10Z | [
"python",
"pandas",
"plot",
"visualization"
] |
sqlite3 in Python: is manual string formatting safe for selecting or updating variable columns? | 39,310,731 | <p>It is well known that one shouldn't assemble SQL queries using native string operations, but instead use prepared statements with placeholders for variables. The sqlite3 in Python handle this this way:</p>
<pre><code>c.execute('UPDATE stock SET price = ? WHERE symbol = ?', the_price, the_symbol)
</code></pre>
<p>T... | 0 | 2016-09-03T19:45:27Z | 39,315,081 | <p>If any of the strings you're inserting directly into the SQL statement might be controlled by the user, you have a problem.</p>
<p>For values, you can use SQL parameters.</p>
<p>There is no such mechamism for table/column names (because asking the user for these names usually does not happen; SQL was designed befo... | 0 | 2016-09-04T08:42:45Z | [
"python",
"sqlite3"
] |
Log file creation in Python vs Shell | 39,310,892 | <p>I am having a difficult time to understand log creation on Python. I come from shell programming and trying to see if a similarity exists b/w shell and Python logging</p>
<p>In shell- I have a driver script where I describe the log location and name . Log from all the scripts that I call from the diver will be dir... | 0 | 2016-09-03T20:06:20Z | 39,310,928 | <p>Best way to create logs in python is with a logging library documented here: <a href="https://docs.python.org/3/library/logging.html" rel="nofollow">https://docs.python.org/3/library/logging.html</a> </p>
<p>It's pretty sofisticated and can be a pain to set up when you want to your logging to be sofisticated (log d... | 0 | 2016-09-03T20:11:41Z | [
"python",
"shell",
"logging"
] |
Retrieving a specific line of text | 39,310,902 | <pre><code><li class="b-list__box-list-item b-list__box-list-item_type_block">
<i class="b-list__box-item-title b-list__box-item-title_type_width">
Height:
</i>
6' 2"
</li>
</code></pre>
<p>For the above, I only want to retrieve 6'2" and ignore "height." my code</p>
... | 0 | 2016-09-03T20:09:05Z | 39,310,977 | <pre><code>In [1]: from bs4 import BeautifulSoup
In [2]: h = """<li class="b-list__box-list-item b-list__box-list-item_type_block">
...: <i class="b-list__box-item-title b-list__box-item-title_type_width">
...: Height:
...: </i>
...: 6' 2"
...: </li>
... | 1 | 2016-09-03T20:17:25Z | [
"python",
"beautifulsoup"
] |
Error details: Field `af` does not exist | 39,310,919 | <p>I am getting this error for 2 days.
I have read any links regarding the same error and each time no effect.</p>
<p>I am trying simple inheritance
Here is my <code>employee.py</code> file</p>
<pre><code>class Employee(models.Model):
_inherit = 'hr.employee'
_description = "Inherited modules"
af = field... | 0 | 2016-09-03T20:10:46Z | 39,310,990 | <p>Add your employee.py file into an __init__.py file in the same directory.
If it is in the same directory as your other .py files.</p>
<pre><code>from . import controllers
from . import models
from . import employee
</code></pre>
<p>Update your addon</p>
| 1 | 2016-09-03T20:19:33Z | [
"python",
"orm",
"openerp",
"odoo-8",
"odoo-9"
] |
Error details: Field `af` does not exist | 39,310,919 | <p>I am getting this error for 2 days.
I have read any links regarding the same error and each time no effect.</p>
<p>I am trying simple inheritance
Here is my <code>employee.py</code> file</p>
<pre><code>class Employee(models.Model):
_inherit = 'hr.employee'
_description = "Inherited modules"
af = field... | 0 | 2016-09-03T20:10:46Z | 39,311,862 | <p>Add <code>from . import employee</code> to <code>__init__.py</code> inside <code>models</code> folder. </p>
<p><code>models/__init__.py</code> file: </p>
<pre><code>...
from . import employee
</code></pre>
| 0 | 2016-09-03T22:27:03Z | [
"python",
"orm",
"openerp",
"odoo-8",
"odoo-9"
] |
What's the fastest way to find all occurences of the substring in large string in python | 39,310,956 | <p>Edited to clarify input/output. I think this will be somewhat slow no matter what, but up until now I haven't really considered speed in my python scripts, and I'm trying to figure out ways to speed up operations like these.</p>
<p>My input is pickled dictionaries of the genome sequences. I'm currently working with... | 2 | 2016-09-03T20:15:08Z | 39,311,165 | <h2>Use built-ins</h2>
<p>Instead of manually iterating through your long string, try <a href="https://docs.python.org/3/library/stdtypes.html#str.find" rel="nofollow"><code>str.find</code></a> or <a href="https://docs.python.org/3/library/stdtypes.html#str.index" rel="nofollow"><code>str.index</code></a>. Don't slice... | 3 | 2016-09-03T20:44:17Z | [
"python"
] |
What's the fastest way to find all occurences of the substring in large string in python | 39,310,956 | <p>Edited to clarify input/output. I think this will be somewhat slow no matter what, but up until now I haven't really considered speed in my python scripts, and I'm trying to figure out ways to speed up operations like these.</p>
<p>My input is pickled dictionaries of the genome sequences. I'm currently working with... | 2 | 2016-09-03T20:15:08Z | 39,311,383 | <p>Finds the longest chromosome string, and creates an empty array with one row per chromosome, and columns up to the longest one in the dictionary. Then it puts each chromosome into its own row, where you can call <code>np.where</code> on the whole array</p>
<pre><code>import numpy as np
longest_chrom = max([len(x) ... | 0 | 2016-09-03T21:13:19Z | [
"python"
] |
What's the fastest way to find all occurences of the substring in large string in python | 39,310,956 | <p>Edited to clarify input/output. I think this will be somewhat slow no matter what, but up until now I haven't really considered speed in my python scripts, and I'm trying to figure out ways to speed up operations like these.</p>
<p>My input is pickled dictionaries of the genome sequences. I'm currently working with... | 2 | 2016-09-03T20:15:08Z | 39,312,394 | <p>To be honest, I think you've been doing the right things.</p>
<p>There are a few more tweaks you can make to your code, though. In general, when performance is key, only do the bare minimum in your innermost loops. Looking through your code, there are still some quick optimizations left on this front:</p>
<ol>
<... | 1 | 2016-09-04T00:04:33Z | [
"python"
] |
How to align nodes and edges in networkx | 39,310,983 | <p>I am going through an O'Reilly data science book and it gives you the python code to more or less create this node viz ...</p>
<p><a href="http://i.stack.imgur.com/Cg5Bn.png" rel="nofollow"><img src="http://i.stack.imgur.com/Cg5Bn.png" alt="enter image description here"></a></p>
<p>But it doesn't tell you how to m... | 1 | 2016-09-03T20:19:08Z | 39,317,347 | <p>You can so something similar with NetworkX. You'll need use a different layout method than "spring_layout" or set the node positions explicitly like this:</p>
<pre><code>import networkx as nx
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_nodes_from([user["id"] for user in users])
G.add_edges_from(friendships)... | 1 | 2016-09-04T13:20:12Z | [
"python",
"matplotlib",
"networkx"
] |
Q : Python time | 39,311,047 | <p>I would like to use ·time()· to launch an event. An example would be to <code>print("test")</code> for 3 seconds. For that I did this: </p>
<pre><code>from time import time, sleep
from random import random
t = time()
n = 3
print(n, time() - t)
for i in range(100):
sleep(0.04)
print(time() - t)
if ... | 0 | 2016-09-03T20:26:36Z | 39,311,131 | <p>If I've understood correctly, it seems you don't know how to run a simple gameloop and run some test code after 3 seconds, here's some naive approach:</p>
<pre><code>from time import time, sleep
from random import random
start_time = time()
n = 3
while True:
elapsed_time = time() - start_time
sleep(0.04)... | 0 | 2016-09-03T20:39:25Z | [
"python",
"python-2.7",
"time"
] |
Q : Python time | 39,311,047 | <p>I would like to use ·time()· to launch an event. An example would be to <code>print("test")</code> for 3 seconds. For that I did this: </p>
<pre><code>from time import time, sleep
from random import random
t = time()
n = 3
print(n, time() - t)
for i in range(100):
sleep(0.04)
print(time() - t)
if ... | 0 | 2016-09-03T20:26:36Z | 39,311,357 | <p>if you want to achieve something else during the 3 second delay period, rather than just going round a while loop, try using a time-delayed thread. For example, the following </p>
<pre><code>import threading
import time
def afterThreeSec():
print("test")
return
t1 = threading.Timer(3, afterThreeSec)
t1.se... | 0 | 2016-09-03T21:09:49Z | [
"python",
"python-2.7",
"time"
] |
How does distutils determine what binary files to copy? | 39,311,094 | <p>I have a <code>setup</code> command defined like this for distutils (using py2app for Mac OS X, if it matters):</p>
<pre><code>setup(...,
extensions=Extension('tracking_funcs',
['tracking_funcs/tracking_funcs.pyx'],
include_dirs=[numpyincludedirs,]),
... | 0 | 2016-09-03T20:34:14Z | 39,550,233 | <p>Py2app <a href="https://pythonhosted.org/py2app/implementation.html" rel="nofollow">uses</a> <a href="http://pythonhosted.org/modulegraph/index.html" rel="nofollow">modulegraph</a> to recursively build a source tree containing all the dependencies of all the dependencies of your project. Running py2app with the <a h... | 0 | 2016-09-17T18:20:09Z | [
"python",
"distutils",
"py2app"
] |
Is my threading proper ? if yes then why code is not working? | 39,311,172 | <p>I am creating an alarm clock in python using PyQt4 and in that I am using LCD display widget, which display current updating time. For that I am using threading. But I am new to it so the problem is I have no clue how to debug that thing.</p>
<p>This is my code</p>
<pre><code>import sys
from PyQt4 import QtGui, ui... | 0 | 2016-09-03T20:45:19Z | 39,313,242 | <p>Qt does not support doing GUI operations in threads other than the main thread. So when you call self.lcddisplay.display(showTime) from within the context of your spawned thread, that is an error and Qt will not work correctly.</p>
<p>As tdelaney suggested in his comment, the best way to handle this sort of thing ... | 0 | 2016-09-04T03:21:13Z | [
"python",
"multithreading",
"pyqt4",
"lcd"
] |
Is my threading proper ? if yes then why code is not working? | 39,311,172 | <p>I am creating an alarm clock in python using PyQt4 and in that I am using LCD display widget, which display current updating time. For that I am using threading. But I am new to it so the problem is I have no clue how to debug that thing.</p>
<p>This is my code</p>
<pre><code>import sys
from PyQt4 import QtGui, ui... | 0 | 2016-09-03T20:45:19Z | 39,335,590 | <p>As has been said elsewhere, you do not need to use threading for this, as a simple timer will do. Here is a basic demo script:</p>
<pre><code>import sys
from PyQt4 import QtCore, QtGui
class Clock(QtGui.QLCDNumber):
def __init__(self):
super(Clock, self).__init__(8)
self.timer = QtCore.QTimer(s... | 0 | 2016-09-05T17:55:44Z | [
"python",
"multithreading",
"pyqt4",
"lcd"
] |
Django Internationalization (I18N) not changing text | 39,311,230 | <p>I created an simple website to test internationalization, but I can't make it work the way I wanted. I would like to change messages in my views.py without checking the <strong>request.LANGUAGE_CODE</strong> (which is showing correctly).</p>
<p>I can go to the urls with prefix <strong>/en/</strong> and <strong>/pt-... | 0 | 2016-09-03T20:52:44Z | 39,313,487 | <p>I think my path was not correct. I believe the extra slash was wrong... I deleted /translations/ from the LOCALE_PATH and it is working now.</p>
<pre><code>LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale'),
]
</code></pre>
<p>Then I run</p>
<pre><code>django-admin compilemessages -l pt_BR
</code></pre>
<p>Mo... | 0 | 2016-09-04T04:13:02Z | [
"python",
"django",
"django-i18n"
] |
Fitting text into a rectangle (width x by height y) with tkinter | 39,311,244 | <p>I'm trying to make a program which will fit text into a rectangle (x by y) depending on the text, the font and the font size</p>
<p>Here is the code</p>
<pre><code>def fit_text(screen, width, height, text, font):
measure_frame = Frame(screen) # frame
measure_frame.pack()
measure_frame.pack_forget()
... | 0 | 2016-09-03T20:55:00Z | 39,311,345 | <p>The widget will not have a width until it is packed. You need to put the label into the frame, then pack it, then forget it.</p>
| 1 | 2016-09-03T21:08:17Z | [
"python",
"fonts",
"tkinter",
"widget",
"pixels"
] |
Fitting text into a rectangle (width x by height y) with tkinter | 39,311,244 | <p>I'm trying to make a program which will fit text into a rectangle (x by y) depending on the text, the font and the font size</p>
<p>Here is the code</p>
<pre><code>def fit_text(screen, width, height, text, font):
measure_frame = Frame(screen) # frame
measure_frame.pack()
measure_frame.pack_forget()
... | 0 | 2016-09-03T20:55:00Z | 39,311,963 | <p>The problem with your code is that you're using the width of a widget, but the width will be 1 until the widget is actually laid out on the screen and made visible, since the actual width depends on a number of factors that aren't present until that happens.</p>
<p>You don't need to put the text in a widget in orde... | 1 | 2016-09-03T22:46:46Z | [
"python",
"fonts",
"tkinter",
"widget",
"pixels"
] |
Fitting text into a rectangle (width x by height y) with tkinter | 39,311,244 | <p>I'm trying to make a program which will fit text into a rectangle (x by y) depending on the text, the font and the font size</p>
<p>Here is the code</p>
<pre><code>def fit_text(screen, width, height, text, font):
measure_frame = Frame(screen) # frame
measure_frame.pack()
measure_frame.pack_forget()
... | 0 | 2016-09-03T20:55:00Z | 39,312,199 | <p>I've actually stumbled across a way of doing this through trial and error</p>
<p>By using <code>measure.update_idletasks()</code> it calculates the width properly and it works! Bryan Oakley definitely has a more efficient way of doing it though but I think this method will be useful in other situations</p>
<p>P.S.... | 1 | 2016-09-03T23:27:05Z | [
"python",
"fonts",
"tkinter",
"widget",
"pixels"
] |
Clicking on xpath button with Selenium on Python | 39,311,292 | <p>i used Selenium IDE on Firefox to find the <a href="http://i.stack.imgur.com/bcLp8.jpg" rel="nofollow">xpath of buttons.</a> The next step is to click the button on Python. I tried inserting the xpath in the code below, but no luck. I do not know how to change the xpath so that it fits to the code below.</p>
<pre>... | 0 | 2016-09-03T21:02:05Z | 39,314,664 | <p>Be careful with quotes and double quotes, use double outside and simple inside, for example</p>
<pre><code>"//*[@class='myClass']"
</code></pre>
<p>Try this:</p>
<pre><code>browser.find_element_by_xpath("(//button[@type='button'])[20ââ9]")
</code></pre>
<p>You should get the selector manually in another way,... | 1 | 2016-09-04T07:42:41Z | [
"python",
"python-3.x",
"selenium",
"xpath",
"selenium-webdriver"
] |
How can I avoid repetition in python/kivy? | 39,311,323 | <p>I have been trying to make an app that have many functions associate to one buttons each. This way, if I have 70 buttons I have 70 different functions. I want to add, the respective value, when I click respective button, to a respective variable label (I am using numericproperty). As the change between this function... | 0 | 2016-09-03T21:06:18Z | 39,317,460 | <p>for your .kv file I recommend using Classes like</p>
<pre><code><MyButton@Button>:
markup: True
font_size: '20dp'
size_hint_y: None
</code></pre>
<p>then in your code you could use instances of MyButton which could minify your code a little bit.</p>
| 0 | 2016-09-04T13:32:13Z | [
"python",
"kivy"
] |
Measure Tomcat's Shutdown Interval | 39,311,344 | <p>I am trying to measure my Tomcat server shutdown interval and write it to the log. I'm trying to use the following Python code:</p>
<pre><code> log_times.append(datetime.now().strftime(TIME_PATTERN)) # logs start time
subprocess.check_call(['service', 'tomcat7', 'stop'])
pid = subprocess.Popen(['pgrep', ... | 0 | 2016-09-03T21:08:08Z | 39,312,079 | <p>You can try use a bash script. For example stop_tomcat.sh:</p>
<pre><code>START=$(date +%s.%N)
service tomcat7 stop
END=$(date +%s.%N)
DIFF=$(echo "$END - $START" | bc)
echo $DIFF
</code></pre>
<p>Change permissions :</p>
<pre><code>chmod 755
</code></pre>
<p>call it from python and take it stdout :</p>
<pre><... | 0 | 2016-09-03T23:07:18Z | [
"java",
"python",
"tomcat"
] |
sleekxmpp with ejabberd muc | 39,311,417 | <p>I want to make a muc scprit with sleekxmpp and ejabberd use.
What should I do?</p>
<p>I tried this tutorial to understand eating sleekxmpp <a href="http://sleekxmpp.com/getting_started/echobot.html" rel="nofollow">http://sleekxmpp.com/getting_started/echobot.html</a>
but, number of connected users at the ejabberd p... | 0 | 2016-09-03T21:16:52Z | 39,315,726 | <p>Here is the problem:</p>
<pre class="lang-xml prettyprint-override"><code>DEBUG SEND (IMMED): <stream:stream to='192.168.1.103' xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client' xml:lang='en' version='1.0'>
DEBUG RECV: <stream:stream from="localhost" id="3423333123714766535" xml:l... | 0 | 2016-09-04T10:00:31Z | [
"python",
"xmpp",
"ejabberd",
"multiuserchat"
] |
Running Ipython Notebook on Mac | 39,311,481 | <p>Have a question.</p>
<p>I know that Ipython Notebook can be opened by entering <code>ipython notebook</code> in terminal on macOS. But is there another option to run it? for example, using some nice app or smth.</p>
<p>Thanks!</p>
| 0 | 2016-09-03T21:24:14Z | 39,326,867 | <p>If you are using Anaconda, you can use the <a href="https://docs.continuum.io/anaconda-launcher/" rel="nofollow">anaconda launcher</a>. If you don't have it, you can install it with:</p>
<pre><code>conda install launcher
</code></pre>
<p>This will install an application called Launcher which will give you a GUI to... | 0 | 2016-09-05T08:47:41Z | [
"python",
"osx",
"ipython",
"anaconda",
"jupyter-notebook"
] |
How to scrape value from page that loads dynamicaly? | 39,311,545 | <p>The homepage of the website I'm trying to scrape displays four tabs, one of which reads "[Number] Available Jobs". I'm interested in scraping the [Number] value. When I inspect the page in Chrome, I can see the value enclosed within a <code><span></code> tag.</p>
<p><a href="http://i.stack.imgur.com/xeirT.png... | 0 | 2016-09-03T21:36:14Z | 39,311,664 | <p>1.A value can be loaded dynamically with ajax, ajax loads asynchronously that means that the rest of the site does not wait for ajax to be rendered, that's why when you get the DOM the elements loaded with ajax does not appear in it.</p>
<p>2.For scraping dynamic content you should use selenium, <a href="http://thi... | 0 | 2016-09-03T21:54:32Z | [
"python",
"html",
"httprequest",
"httpresponse"
] |
How to scrape value from page that loads dynamicaly? | 39,311,545 | <p>The homepage of the website I'm trying to scrape displays four tabs, one of which reads "[Number] Available Jobs". I'm interested in scraping the [Number] value. When I inspect the page in Chrome, I can see the value enclosed within a <code><span></code> tag.</p>
<p><a href="http://i.stack.imgur.com/xeirT.png... | 0 | 2016-09-03T21:36:14Z | 39,311,673 | <p>If the content doesn't appear in the page source then it is probably generated using javascript. For example the site might have a REST API that lists jobs, and the Javascript code could request the jobs from the API and use it to create the node in the DOM and attach it to the available jobs. That's just one possib... | 2 | 2016-09-03T21:55:37Z | [
"python",
"html",
"httprequest",
"httpresponse"
] |
How to scrape value from page that loads dynamicaly? | 39,311,545 | <p>The homepage of the website I'm trying to scrape displays four tabs, one of which reads "[Number] Available Jobs". I'm interested in scraping the [Number] value. When I inspect the page in Chrome, I can see the value enclosed within a <code><span></code> tag.</p>
<p><a href="http://i.stack.imgur.com/xeirT.png... | 0 | 2016-09-03T21:36:14Z | 39,324,761 | <ol>
<li>for data that load dynamically you should look for an xhr request in the networks and if you can make that data productive for you than voila!! </li>
<li>you can you phantom js, it's a headless browser and it captures the html of that page with the dynamically loaded content. </li>
</ol>
| 0 | 2016-09-05T06:10:40Z | [
"python",
"html",
"httprequest",
"httpresponse"
] |
Can't import my own module distributed with distutils | 39,311,658 | <p>I'd like to package my application to share it between several projects.
My setup.py looks like this:</p>
<pre><code># -*- coding: utf-8 -*-
from distutils.core import setup
setup(
name='foo_bar',
version='1.0',
py_modules=['foo_bar'],
install_requires=[
'bitstring==3.1.5',
'pytz==2... | 1 | 2016-09-03T21:52:38Z | 39,407,522 | <p>Could you provide your directory structure? Are you in the same virtualenv when you're trying to import your module? Why are you using <code>py_modules</code> and not <code>packages</code>?</p>
<p>Moreover, you're trying to import <code>foo_bar</code>, however there is no <code>foo_bar.py</code> in your package! Tr... | 1 | 2016-09-09T08:50:22Z | [
"python",
"pip",
"importerror",
"distutils"
] |
Beautifulsoup - scraping everything but table data | 39,311,702 | <p>Hi I'm new to python and currently trying to download data from a table on a website (<a href="http://www.pa.org.mt/AppList?ReceivedDate=2016-8-31" rel="nofollow">http://www.pa.org.mt/AppList?ReceivedDate=2016-8-31</a>)</p>
<p>I've tried many different solutions but everything I try keeps returning an empty list. I... | 2 | 2016-09-03T22:01:06Z | 39,312,342 | <p>If you clear your cache and go directly to <em><a href="http://www.pa.org.mt/appsreceived?month=01/08/2016" rel="nofollow">http://www.pa.org.mt/appsreceived?month=01/08/2016</a></em> you see no data at all just like you see in your own output:</p>
<p><a href="http://i.stack.imgur.com/2Wo7T.png" rel="nofollow"><img ... | 2 | 2016-09-03T23:53:47Z | [
"python",
"html",
"css",
"beautifulsoup"
] |
creating a for loop where xpath increases | 39,311,773 | <p>I am trying to create a for loop where xpath buttons are to be clicked for x times. There is a list of xpathes</p>
<pre><code>(//button[@type='button'])[47]
(//button[@type='button'])[65]
(//button[@type='button'])[83]
(//button[@type='button'])[101]
(//button[@type='button'])[119]
</code></pre>
<p>So the numbers ... | 2 | 2016-09-03T22:13:06Z | 39,311,851 | <p>You need to use string formatting to construct a valid XPath query, eg:</p>
<pre><code>build_xpath = "(//button[@type='button'])[{}]".format
for n in range(47, 47 + 18 * times, 18):
brower.find_element_by_xpath(build_xpath(n)).click()
</code></pre>
| 1 | 2016-09-03T22:25:43Z | [
"python",
"python-3.x",
"xpath"
] |
How can I create a figure with optimal resolution for printing? | 39,311,794 | <p>I'm rather fond of <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/5/50/Logistic_Bifurcation_map_High_Resolution.png/800px-Logistic_Bifurcation_map_High_Resolution.png" rel="nofollow">The Logistic Map' Period Doubling Bifurcation</a> and would like to print it on a canvas.</p>
<p>I can create the plot... | 0 | 2016-09-03T22:15:55Z | 39,320,429 | <p>I think the source of the jaggies is underlying pixel size + that you are drawing this using very small 'point' markers. The pixels that the line are going through are getting fully saturated so you get the 'jaggy'.</p>
<p>A somewhat better way to plot this data is to do the binning ahead of time and then have mpl... | 1 | 2016-09-04T18:56:24Z | [
"python",
"matplotlib",
"figure"
] |
django 1.10 media images don't show | 39,311,816 | <p>I have had django media images working in an existing django 1.7 project by adding the following to site urls.py:</p>
<pre><code>urlpatterns = patters(
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
</code></pre>
<p>This url stru... | 1 | 2016-09-03T22:18:20Z | 39,331,676 | <p>You can use this:
(<a href="https://docs.djangoproject.com/en/1.10/howto/static-files/" rel="nofollow">Django docs 1.10 Serving files uploaded by a user during development</a>)</p>
<pre><code>urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code></pre>
<p>OR you can use t... | 0 | 2016-09-05T13:27:51Z | [
"python",
"django",
"django-staticfiles",
"django-media",
"django-1.10"
] |
Programmatically generate if elif elif elif else | 39,311,998 | <p>I would like to condense some wet code that looks like this:</p>
<pre><code>if slips[i] < 3000:
ac.setBackgroundColor(wheel['slip'], 0, 0, 0)
# setBackgroundOpacity deliberately omitted here
elif slips[i] < 3700:
ac.setBackgroundColor(wheel['slip'], .2, .4, .2)
ac.setBackgroundOpacity(wheel['s... | 2 | 2016-09-03T22:52:49Z | 39,312,115 | <p>Here's one possible solution.</p>
<pre><code>def least_bound_index(value, bounds):
"""return the least index such that value < bounds[i], or else len(bounds)"""
for i, b in enumerate(bounds):
if value < b:
return i
return i+1
bounds = [3000, 3700, 4100, 4500]
bgcolors = [(0, ... | 2 | 2016-09-03T23:14:30Z | [
"python",
"if-statement",
"dry"
] |
Programmatically generate if elif elif elif else | 39,311,998 | <p>I would like to condense some wet code that looks like this:</p>
<pre><code>if slips[i] < 3000:
ac.setBackgroundColor(wheel['slip'], 0, 0, 0)
# setBackgroundOpacity deliberately omitted here
elif slips[i] < 3700:
ac.setBackgroundColor(wheel['slip'], .2, .4, .2)
ac.setBackgroundOpacity(wheel['s... | 2 | 2016-09-03T22:52:49Z | 39,312,121 | <p>In case 'setBackgroundOpacity' was omitted by mistake or it doesn't matter if it is included in the first case as well, this is a solution you might be looking for:</p>
<pre><code>color_map = [ (3000, 0, 0, 0),
(3700, .2, .4, .2),
(4100, 0, 1, 0),
(4500, 0, 0, 1),
... | 2 | 2016-09-03T23:14:50Z | [
"python",
"if-statement",
"dry"
] |
Programmatically generate if elif elif elif else | 39,311,998 | <p>I would like to condense some wet code that looks like this:</p>
<pre><code>if slips[i] < 3000:
ac.setBackgroundColor(wheel['slip'], 0, 0, 0)
# setBackgroundOpacity deliberately omitted here
elif slips[i] < 3700:
ac.setBackgroundColor(wheel['slip'], .2, .4, .2)
ac.setBackgroundOpacity(wheel['s... | 2 | 2016-09-03T22:52:49Z | 39,312,167 | <pre><code>c = [[0,0,0],[.2,.4,.2],[0,1,0],[0,0,1]]
threshold = [3000,3700,4100,4500]
if slips[i] >= 4500:
ac.setBackgroundColor(wheel['slip'],1,0,0)
else:
for x in range(4):
if slips[i] < threshold[x]:
ac.setBackgroundColor(wheel['slip'],c[x][0],c[x][1],c[x][2])
break
if s... | 1 | 2016-09-03T23:21:51Z | [
"python",
"if-statement",
"dry"
] |
Programmatically generate if elif elif elif else | 39,311,998 | <p>I would like to condense some wet code that looks like this:</p>
<pre><code>if slips[i] < 3000:
ac.setBackgroundColor(wheel['slip'], 0, 0, 0)
# setBackgroundOpacity deliberately omitted here
elif slips[i] < 3700:
ac.setBackgroundColor(wheel['slip'], .2, .4, .2)
ac.setBackgroundOpacity(wheel['s... | 2 | 2016-09-03T22:52:49Z | 39,312,237 | <p>My take on it (untested as to the actual <code>ac...</code> calls):</p>
<pre><code>from functools import partial
mapping = [
(3000, (0, 0, 0), None),
(3700, (.2, .4, .2), 1),
(4100, (0, 1, 0), 1),
(4500, (0, 0, 1), 1),
(float('inf'), (1, 0, 0), 1)
]
def if_replacer(canvas, value, mapping):
... | 1 | 2016-09-03T23:32:34Z | [
"python",
"if-statement",
"dry"
] |
django - How to change existing code to ModelForm instance | 39,312,031 | <p>New to Django and this is my first web application.</p>
<p>I'm having trouble with django's ModelForm feature and I wanted to know:</p>
<p>How do I modify my code so that I can create an instance of ModelForm, and specifically, how can I extract the form data to upload to the backend? I will need to reference this... | 2 | 2016-09-03T22:58:55Z | 39,312,324 | <p>Implementing a basic ModelForm is just a matter of the following:</p>
<pre><code>from django.forms import ModelForm
from .models import CustomerDetail
class CustomerDetailForm(ModelForm):
class Meta:
model = CustomerDetail
fields = ['address', 'date_of_birth', 'company', 'home_phone', 'work_ph... | 1 | 2016-09-03T23:49:55Z | [
"python",
"django",
"modelform"
] |
django - How to change existing code to ModelForm instance | 39,312,031 | <p>New to Django and this is my first web application.</p>
<p>I'm having trouble with django's ModelForm feature and I wanted to know:</p>
<p>How do I modify my code so that I can create an instance of ModelForm, and specifically, how can I extract the form data to upload to the backend? I will need to reference this... | 2 | 2016-09-03T22:58:55Z | 39,312,516 | <p>After creating CustomerDetailForm as @John Carter said, you might want to change your view.py to the following</p>
<pre class="lang-py prettyprint-override"><code>
def create_profile(request):
if request.POST:
form = CustomerDetailForm(request.POST)
if form.is_valid():
## save data i... | 1 | 2016-09-04T00:29:08Z | [
"python",
"django",
"modelform"
] |
Why is ''.join() faster than += in Python? | 39,312,099 | <p>I'm able to find a bevy of information online (on Stack Overflow and otherwise) about how it's a very inefficient and bad practice to use <code>+</code> or <code>+=</code> for concatenation in Python.</p>
<p>I can't seem to find WHY <code>+=</code> is so inefficient. Outside of a mention <a href="http://stacko... | 55 | 2016-09-03T23:11:19Z | 39,312,172 | <p>Let's say you have this code to build up a string from three strings:</p>
<pre><code>x = 'foo'
x += 'bar' # 'foobar'
x += 'baz' # 'foobarbaz'
</code></pre>
<p>In this case, Python first needs to allocate and create <code>'foobar'</code> before it can allocate and create <code>'foobarbaz'</code>.</p>
<p>So for e... | 72 | 2016-09-03T23:22:51Z | [
"python",
"optimization"
] |
Why is ''.join() faster than += in Python? | 39,312,099 | <p>I'm able to find a bevy of information online (on Stack Overflow and otherwise) about how it's a very inefficient and bad practice to use <code>+</code> or <code>+=</code> for concatenation in Python.</p>
<p>I can't seem to find WHY <code>+=</code> is so inefficient. Outside of a mention <a href="http://stacko... | 55 | 2016-09-03T23:11:19Z | 39,314,264 | <p>I think this behaviour is best explained in <a href="https://www.lua.org/pil/11.6.html">Lua's string buffer chapter</a>.</p>
<p>To rewrite that explanation in context of Python, let's start with an innocent code snippet (a derivative of the one at Lua's docs):</p>
<pre><code>s = ""
for l in some_list:
s += l
</c... | 5 | 2016-09-04T06:44:35Z | [
"python",
"optimization"
] |
if statements not executing | 39,312,193 | <p>New to the language and this rock paper scissors thing is the first thing I've ever done in python so im aware the code is inefficient and nooby but any pointers will be appreciated! Basically im getting a response as if none of the if statements are being executed and found = False is staying as such throughout the... | -2 | 2016-09-03T23:26:02Z | 39,312,227 | <p>This should solve your problem:</p>
<pre><code>MyChoice = int(input('> '))
</code></pre>
<p>You were comparing strings (MyChoice) and integers (aiChoice).</p>
| 1 | 2016-09-03T23:30:42Z | [
"python",
"python-3.x"
] |
if statements not executing | 39,312,193 | <p>New to the language and this rock paper scissors thing is the first thing I've ever done in python so im aware the code is inefficient and nooby but any pointers will be appreciated! Basically im getting a response as if none of the if statements are being executed and found = False is staying as such throughout the... | -2 | 2016-09-03T23:26:02Z | 39,312,232 | <p><code>input</code> returns a string so you must wrap <code>MyString</code> with an integer converter like so:</p>
<pre><code>MyChoice = int(input("> "))
</code></pre>
<p>Since a string cannot be accurately compared to an integer, <code>found</code> isn't being set to True, thus <code>found</code> is False, lead... | 1 | 2016-09-03T23:31:34Z | [
"python",
"python-3.x"
] |
if statements not executing | 39,312,193 | <p>New to the language and this rock paper scissors thing is the first thing I've ever done in python so im aware the code is inefficient and nooby but any pointers will be appreciated! Basically im getting a response as if none of the if statements are being executed and found = False is staying as such throughout the... | -2 | 2016-09-03T23:26:02Z | 39,312,258 | <p>Firstly, these are already global variables. No need to use them as parameters. </p>
<pre><code>aiWins = 0
MyWins = 0
found = False
</code></pre>
<p>Now, you can define the method like so and use the <code>global</code> keyword to ensure you're using those global variables. </p>
<pre><code>def whowon(MyChoice, ai... | -1 | 2016-09-03T23:37:00Z | [
"python",
"python-3.x"
] |
Applying comma seperator formatting to an entire DataFrame in python 3 | 39,312,218 | <p>I want to format all numbers in a DataFrame to have comma seperators (e.g. 1,000,000 instead of 1000000). It can be applied to a single number using <code>'{:,}'.format(number)</code>. Naively applying the same to a DataFrame gives the error</p>
<pre><code> TypeError: non-empty format string passed to object.__f... | 2 | 2016-09-03T23:29:35Z | 39,312,274 | <p>Use <code>applymap</code></p>
<pre><code>df = pd.DataFrame(np.random.randint(1000, 10000, (5, 5)))
df.applymap('{:,}'.format)
</code></pre>
<p><a href="http://i.stack.imgur.com/ikJ1k.png" rel="nofollow"><img src="http://i.stack.imgur.com/ikJ1k.png" alt="enter image description here"></a></p>
| 4 | 2016-09-03T23:40:21Z | [
"python",
"python-3.x",
"pandas",
"dataframe",
"formatting"
] |
Extracting user information from tweets using Python | 39,312,316 | <p>I am trying to extract some user information from the tweets I have downloaded. Below is the code that I am using, however, it only returns "None" in the list for all the tweets.</p>
<pre><code>map(lambda test: test['place']['country'] , data)
</code></pre>
<p>Also, tried the following:- </p>
<pre><code>map(la... | 0 | 2016-09-03T23:48:12Z | 39,327,095 | <p>This will just be due to the fact that the vast majority of tweets do not seem to carry the 'place' data - Its nearly always set to None.</p>
<p>Your best bet for a location would be to use the location key inside the 'user' section of the data dump - but even that isnt always filled out (You would have to try/exce... | 0 | 2016-09-05T09:01:32Z | [
"python",
"python-2.7",
"python-3.x",
"twitter"
] |
How do I execute a Python script based off user inputed fields from a Website | 39,312,358 | <p>Using the following python.py file below as an example, how could a user on a website form select the position from something like a dropdown field or the user could input WR, RB, QB themselves. (position="WR" is currently what is in the code below) and click submit and the code will execute the query into a table?<... | 1 | 2016-09-03T23:57:48Z | 39,312,471 | <p>I'm no expert, but be able to run code in response to any user interaction on your website, there should be some kind of web service running that would run your code.
The general idea would be to first have the Wordpress server able to send out a "GET" to your postgre server, and be able to receive its answer.
Then ... | 0 | 2016-09-04T00:20:10Z | [
"php",
"python",
"sql",
"wordpress",
"postgresql"
] |
Trying to sort a list of tuples in python first by date then by greatest number | 39,312,362 | <p>I have a list of tuples and I am trying to sort by date and then by the greatest number. So basically when you have two dates that are the same it will then put the tuple with the greatest number first. See example below. </p>
<p><strong>My list of tuples</strong></p>
<pre><code>dataLst = [["Mike", 50, "08/10/2016... | 2 | 2016-09-03T23:58:30Z | 39,312,403 | <p>You cannot compare the dates as strings because of the order <em>mm/dd/yyyy</em>, you could use <em>datetime</em> to : </p>
<pre><code>from datetime import datetime
strp = datetime.strptime
srted = sorted(dataLst, key=lambda sub: (strp(sub[2],"%m/%d/%Y"), -sub[1]))
</code></pre>
<p>Or just split and reverse the... | 2 | 2016-09-04T00:06:25Z | [
"python",
"list",
"sorting"
] |
Trying to sort a list of tuples in python first by date then by greatest number | 39,312,362 | <p>I have a list of tuples and I am trying to sort by date and then by the greatest number. So basically when you have two dates that are the same it will then put the tuple with the greatest number first. See example below. </p>
<p><strong>My list of tuples</strong></p>
<pre><code>dataLst = [["Mike", 50, "08/10/2016... | 2 | 2016-09-03T23:58:30Z | 39,312,405 | <p>You need to reverse the order of the sorts - the "tie-breakers" are done before the "main" sort which works because Python's sort is stable, so they retain the order of the tiebreaker when sorted into the main order, eg:</p>
<pre><code>from datetime import datetime
from operator import itemgetter
dataLst = [["Mike... | 2 | 2016-09-04T00:06:37Z | [
"python",
"list",
"sorting"
] |
Trying to sort a list of tuples in python first by date then by greatest number | 39,312,362 | <p>I have a list of tuples and I am trying to sort by date and then by the greatest number. So basically when you have two dates that are the same it will then put the tuple with the greatest number first. See example below. </p>
<p><strong>My list of tuples</strong></p>
<pre><code>dataLst = [["Mike", 50, "08/10/2016... | 2 | 2016-09-03T23:58:30Z | 39,312,877 | <p>Similar to @Ninja Puppy's answer, but in one sort iteration, not two:</p>
<pre><code>dataLst.sort(key=lambda l: (datetime.strptime(l[2], '%m/%d/%Y'), -l[1]))
</code></pre>
| 0 | 2016-09-04T01:52:14Z | [
"python",
"list",
"sorting"
] |
How to merge multiple files? | 39,312,470 | <p>My files are in txt format and I wrote a short code to merge all three into a single one. Input files are (1) 18.8MB with over 16K columns, (2) 18.8MB with over 16K columns and (3) 10.5MB with over 7K columns. The code works, however it only merges first two files and creates output file. The data from the third inp... | 0 | 2016-09-04T00:20:01Z | 39,312,486 | <p>Simply use <a href="https://docs.python.org/3/library/fileinput.html" rel="nofollow"><code>fileinput</code></a> from the standard library:</p>
<pre><code>import fileinput
filenames = [ '...' ]
with open(output_file, 'w') as file_out, fileinput.input(filenames) as file_in:
file_out.writelines(file_in)
</code></... | 2 | 2016-09-04T00:23:30Z | [
"python",
"python-3.x"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.