title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
python wait queue and socket in single thread | 39,330,315 | <p>my app is a tcp server, using epoll to wait for requests.<br>
i wanna wait for a queue in the same loop.<br>
that is: <strong><code>wake up the thread either socket r/w is available or queue is not empty.</code></strong></p>
<p>i surely googled a lot, but none good solution found.<br>
i've thought about several way... | 0 | 2016-09-05T12:09:50Z | 39,330,490 | <p>It sounds like you should look into non-blocking sockets.</p>
<p><a href="https://docs.python.org/2/howto/sockets.html#non-blocking-sockets" rel="nofollow">https://docs.python.org/2/howto/sockets.html#non-blocking-sockets</a></p>
| 0 | 2016-09-05T12:19:39Z | [
"python",
"multithreading",
"sockets",
"queue",
"epoll"
] |
AttributeError: 'list' object has no attribute 'rename' | 39,330,442 | <pre><code>df.rename(columns={'nan': 'RK', 'PP': 'PLAYER','SH':'TEAM','nan':'GP','nan':'G','nan':'A','nan':'PTS','nan':'+/-','nan':'PIM','nan':'PTS/G','nan':'SOG','nan':'PCT','nan':'GWG','nan':'PPG','nan':'PPA','nan':'SHG','nan':'SHA'}, inplace=True)
</code></pre>
<p>This is my code to rename the columns accordin... | -1 | 2016-09-05T12:16:55Z | 39,330,725 | <p>You should first use the documentation. Here is the link for Python Data structure.<br>
<a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow">https://docs.python.org/3/tutorial/datastructures.html</a><br>
Select the right data data structure for your use case. </p>
| 0 | 2016-09-05T12:33:36Z | [
"python",
"html",
"spyder",
"data-science",
"edx"
] |
fitting location parameter in the gamma distribution with scipy | 39,330,483 | <p>Would somebody be able to explain to me how to use the location parameter with the gamma.fit function in Scipy?</p>
<p>It seems to me that a location parameter (μ) changes the support of the distribution from x ≥ 0 to y = ( x - μ ) ≥ 0. If μ is positive then aren't we losing all the data which doesn'... | 0 | 2016-09-05T12:19:14Z | 39,332,605 | <p>The <code>fit</code> function takes all of the data into consideration when finding a fit. Adding noise to your data will alter the fit parameters and can give a distribution that does not represent the data very well. So we have to be a bit clever when we are using <code>fit</code>.</p>
<p>Below is some code tha... | 2 | 2016-09-05T14:19:42Z | [
"python",
"scipy",
"distribution",
"gamma"
] |
Make a field to auto increment when I press CONFIRM SALE | 39,330,533 | <p><img src="http://i.stack.imgur.com/nyg8G.jpg" alt="enter image description here"></p>
<p>I have made the field 'internal reference' in customers to be auto increment as you can see on the picture (001, 002, 003....).
That happens every time I create a new customer.</p>
<p>Now my problem is that I want the same (in... | -1 | 2016-09-05T12:22:07Z | 39,401,433 | <p>You want something to trigger when the "Confirm Sale" Button is pressed?</p>
<p>Maybe look at overwriting "def action_confirm(self)" in the sale.order model (untested).</p>
| 0 | 2016-09-08T23:05:58Z | [
"python",
"xml",
"odoo-9"
] |
Make a field to auto increment when I press CONFIRM SALE | 39,330,533 | <p><img src="http://i.stack.imgur.com/nyg8G.jpg" alt="enter image description here"></p>
<p>I have made the field 'internal reference' in customers to be auto increment as you can see on the picture (001, 002, 003....).
That happens every time I create a new customer.</p>
<p>Now my problem is that I want the same (in... | -1 | 2016-09-05T12:22:07Z | 39,402,083 | <p>Just a more detailed example of Palza's answer above (which is correct). Override the action_confirm() method from sale.sale model. I think some variation of this should do the trick.</p>
<pre><code>class SaleOrder(models.Model):
_inherit = "sale.order"
@api.multi
def action_confirm(self):
impo... | 0 | 2016-09-09T00:32:18Z | [
"python",
"xml",
"odoo-9"
] |
Getting error like these in odoo | 39,330,614 | <blockquote>
<p>TypeError: cannot convert dictionary update sequence element #0 to a sequence</p>
</blockquote>
<p>My code</p>
<pre><code>@api.model
def action_purchase_order(self):
rec= self.env['purchase.order'].create({
'partner_id' : self.vendors,
'store_id' : self.store_id,
'purchas... | 1 | 2016-09-05T12:27:06Z | 39,331,654 | <p>use <code>@api.multi</code> decorator for buttons actions, <code>api.model</code> is used when you only care about the model and not the field values it contains</p>
<pre><code>@api.multi
def action_purchase_order(self):
rec= self.env['purchase.order'].create({
'partner_id' : self.vendors,
'stor... | 2 | 2016-09-05T13:26:41Z | [
"python",
"openerp",
"odoo-9"
] |
Python - Multiprocessing pool.map(): Processes don't do anything | 39,330,675 | <p>I am trying to use the python multiprocessing library in order to parallize a task I am working on:</p>
<pre><code>import multiprocessing as MP
def myFunction((x,y,z)):
...create a sqlite3 database specific to x,y,z
...write to the database (one DB per process)
y = 'somestring'
z = <large read-only glo... | 0 | 2016-09-05T12:31:13Z | 39,332,595 | <p>The lesson learned here was to follow the strategy suggested in one of the comments and use <code>multiprocessing.dummy</code> until everything works.</p>
<p>At least in my case, errors were not visible otherwise and the processes were still running as if nothing had happened.</p>
| 0 | 2016-09-05T14:19:13Z | [
"python",
"dictionary",
"parallel-processing",
"multiprocessing",
"pool"
] |
Correctly parse dates with timezones in Python | 39,330,719 | <p>I am working from Europe and I have a series of datetime that look like these: </p>
<pre><code> datetime(2016,10,30,0,0,0)
datetime(2016,10,30,1,0,0)
datetime(2016,10,30,2,0,0)
datetime(2016,10,30,2,0,0)
datetime(2016,10,30,3,0,0)
datetime(2016,10,30,4,0,0)
datetime(2016,10,30,5,0,0)
</code></pre>
<p>and so ... | 0 | 2016-09-05T12:33:19Z | 39,333,072 | <p>This local value:</p>
<pre><code>datetime(2016,10,30,2,0,0)
</code></pre>
<p>is ambiguous. 2am happens twice on October 30th 2016 in Berlin - once at 2016-10-30T00:00:00Z (with a UTC offset of +2), then once again at 2016-10-30T01:00:00Z (with a UTC offset of +1).</p>
<p>Now with your updated expectations, you ap... | 2 | 2016-09-05T14:46:41Z | [
"python",
"datetime",
"timezone",
"dst",
"pytz"
] |
Getting iDevices using instruments got stuck when running through Python subprocess | 39,330,843 | <p>I am writing a simple python script using Subprocess to get iDevices list attached to my mac. The command I am using is "instruments -s devices". This command works fine when I run through the command line but I am having issues when I use the same command using subprocess.</p>
<p>Below is my simple python script</... | 0 | 2016-09-05T12:40:27Z | 39,543,383 | <p>Do you have two versions of Xcode?
I was facing the exact same issue that subprocess(instruments -s devices) hangs. I have both XCode 8.0 and 7.3.1. This issue only happens after I switch to 7.3.1. It turns out subprocess.Popen('sudo instruments -s devices', stdout=subprocess.PIPE) works just fine. So probably a per... | 0 | 2016-09-17T06:04:44Z | [
"python",
"ios",
"instruments"
] |
Python regex, how to replace multiple groups from multiple matches | 39,330,881 | <p>I have a hunch I'm not seeing the simple solution to this so before I tear my hair out, maybe some one can help.</p>
<p>This is a bit of code:</p>
<pre><code>gr = regex.compile(r'({[^{]*(?>{[^{}]+})*)\s\\over\s([^{}]+(?>{[^{}]*})*})')
string1 = "{a \over b}"
string2 = "{x \over b{x}} {{d}d \over x}}"
m = re... | 0 | 2016-09-05T12:42:34Z | 39,345,438 | <p>To anyone interested:
After some thought I solved my own problem by using regex.split.</p>
<p>I split the whole line by catching wider matches, and then replacing each match individually.</p>
| 0 | 2016-09-06T09:29:16Z | [
"python"
] |
Django: is it possible to separate DB writing funcionality? | 39,331,091 | <p>I want to update DB using Windows Scheduler on a weekly basis. I have the code which extracts the data to be saved as a separate module, so I need to add DB write code there. Is it possible to run it without the server? If not, how to better run a server, make this task only and exit. I write like this now: </p>
<p... | 0 | 2016-09-05T12:54:53Z | 39,331,290 | <p>I would suggest you to write a <a href="https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/" rel="nofollow">custom management command</a> and then run it whenever you want.</p>
<p>Take a look at <a href="http://stackoverflow.com/a/573659/5098707">this</a> answer.</p>
| 1 | 2016-09-05T13:07:35Z | [
"python",
"django",
"windows"
] |
To change button state of a Tkinter button? | 39,331,101 | <p>How to make a <strong>tkinter program</strong> the button of which remains pressed when clicked once and takes input continuosly untill it is clicked again when it returns to its original state and the output is no more taken? <em>(as if like the work of record button)</em></p>
| 0 | 2016-09-05T12:55:53Z | 39,332,194 | <p>You can control the button's appearance by configuring its <code>relief</code> option.</p>
<pre><code>try:
import Tkinter as tk
except ImportError:
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid()
self... | 0 | 2016-09-05T13:56:21Z | [
"python",
"tkinter"
] |
Web scraping, distinguishing between resources and elements or a webpage | 39,331,113 | <pre><code>import mechanize
from bs4 import BeautifulSoup
import urllib2
import cookielib
cj = cookielib.CookieJar()
br = mechanize.Browser()
br.set_handle_robots(False)
br.set_cookiejar(cj)
br.open("*******")
br.select_form(nr=0)
br.form['ctl00$BodyContent$Username'] = '****'
br.form['ctl00$BodyContent$Password'... | 0 | 2016-09-05T12:56:28Z | 39,331,164 | <p>Your'e close, you should use beautiful soup to get the tags into a nice xml format. </p>
<pre><code>import mechanize
from bs4 import BeautifulSoup
import urllib2
import cookielib
cj = cookielib.CookieJar()
br = mechanize.Browser()
br.set_handle_robots(False)
br.set_cookiejar(cj)
br.open("*******")
br.selec... | 0 | 2016-09-05T12:59:53Z | [
"python",
"html",
"web-scraping"
] |
Python library to parse DNS from Wireshark capture file pcap | 39,331,137 | <p>I'm beginning with Python.
I have a .pcap file captured by Wireshark, that contains a DNS query and response. I need to open this file and extract the requested hostname and returned record types and IP addresses.
I've found several libraries capable of reading a pcap files, but i have no idea, which one will be mos... | 0 | 2016-09-05T12:58:24Z | 39,332,888 | <p><a href="http://www.secdev.org/projects/scapy/" rel="nofollow">Scapy</a> is a good one.</p>
<pre><code>from scapy.all import *
from scapy.layers.dns import DNS, DNSQR
types = {0: 'ANY', 255: 'ALL',1: 'A', 2: 'NS', 3: 'MD', 4: 'MD', 5: 'CNAME',
6: 'SOA', 7: 'MB',8: 'MG',9: 'MR',10: 'NULL',11: 'WKS',12: 'P... | 1 | 2016-09-05T14:35:53Z | [
"python",
"dns",
"pcap"
] |
Huge space between title and plot matplotlib | 39,331,143 | <p>I've a issue with matplotlib that generates a plot(graph) very far from the title. My code is:</p>
<pre><code>df = pandas.read_csv(csvpath, delimiter=',',
index_col=0,
parse_dates=[0], dayfirst=True,
names=['Date','test1'])
df.plot(subplots=True, ma... | 1 | 2016-09-05T12:58:38Z | 39,334,324 | <p>You can adjust the title location by grabbing the <code>figure</code> object from one of the 3 <code>axis</code> objects that is returned in an array from <code>df.plot</code>. Using <code>fig.tight_layout</code> removes extra whitespace, but a known problem is that is also sets the figure title within the top plot... | 1 | 2016-09-05T16:12:04Z | [
"python",
"matplotlib"
] |
How to log into Jupyter notebook's console instead of webpage after version 4.1.1 | 39,331,278 | <p>In version 4.1.0:</p>
<pre><code>import logging
r = logging.getLogger()
r.setLevel(logging.DEBUG)
logging.debug("debug")
</code></pre>
<p>will log into the console/terminal.<br>
And we can get a default <code>StreamHandler</code> by:
<code>stream_handler = root.handlers[0]</code></p>
<p>But in 4.1.1, the handler ... | 0 | 2016-09-05T13:06:42Z | 39,331,977 | <p>The solution is add the standard output unit by myself.</p>
<pre><code>root = logging.getLogger()
root.addHandler(logging.StreamHandler(os.fdopen(1, "w")))
</code></pre>
<p>now, <code>logging.debug</code> log into the console</p>
| 0 | 2016-09-05T13:44:37Z | [
"python",
"logging",
"jupyter",
"jupyter-notebook"
] |
Extract hyper-cubical blocks from a numpy array with unknown number of dimensions | 39,331,320 | <p>I have a bit of python code which currently is hard-wired with two-dimensional arrays as follows:</p>
<pre><code>import numpy as np
data = np.random.rand(5, 5)
width = 3
for y in range(0, data.shape[1] - W + 1):
for x in range(0, data.shape[0] - W + 1):
block = data[x:x+W, y:y+W]
# Do something... | 4 | 2016-09-05T13:08:55Z | 39,334,083 | <p>Here is my wack at this problem. The idea behind the code below is to find the "starting indices" for each slice of data. So for 4x4x4 sub-arrays of a 5x5x5 array, the starting indices would be <code>(0,0,0), (0,0,1), (0,1,0), (0,1,1), (1,0,0), (1,0,1), (1,1,1)</code>, and the slices along each dimension would be o... | 2 | 2016-09-05T15:54:45Z | [
"python",
"numpy",
"multidimensional-array"
] |
xpath for immediate preceding sibling | 39,331,326 | <p><strong>XML</strong></p>
<pre><code><root>
<p>nodea text 1</p>
<p>nodea text 2</p>
<nodea>
</nodea>
<p>nodeb text 1</p>
<p>nodeb text 2</p>
<nodeb>
</nodeb>
</root>
</code></pre>
<p>I want to get the first preceding... | 0 | 2016-09-05T13:09:18Z | 39,331,569 | <p>You can select <code>preceding-sibling::*[1][self::p]</code> to select the preceding sibling element if it is a <code>p</code> element.</p>
<p>As for your attempt, I think if you select the <code>nodeb</code> element, you then want to select <code>preceding-sibling::p[preceding-sibling::nodea][1]</code> as you want... | 3 | 2016-09-05T13:22:51Z | [
"python",
"xml",
"xpath",
"lxml"
] |
Find actual value of SyntaxError exception python | 39,331,358 | <p>I'm trying to evaluate python code stored in a string using the ast library, however when accessing the message attribute of the SyntaxException error produced, I can only print the reference to the object and not the actual value. How do I print this value?</p>
<p>Here's the code I'm using:</p>
<pre><code>#!/usr/... | -1 | 2016-09-05T13:11:11Z | 39,331,423 | <p>You're printing the generic SyntaxError class' message attribute, not the one from the actual exception that was thrown.</p>
<p>Try</p>
<pre><code>except SyntaxError as syntax_error:
return syntax_error.message
</code></pre>
<p>Note that it's a bit strange to have a function that returns True on success, or a... | 1 | 2016-09-05T13:14:21Z | [
"python"
] |
How to update load context variable after change in django template via AJAX call? | 39,331,369 | <p>My Table Items in page <code>customer_items.html</code>:</p>
<pre><code><table id="tblData" style="width: 100% !important;"
class="display table table-bordered table-striped table-condensed">
<thead>
<tr>
<th style="display: none">Item ID</th>
<th>N... | 0 | 2016-09-05T13:11:49Z | 39,332,281 | <p>In your Ajax function,</p>
<p>use <code>$('#myTable').html(data);</code> instead of <code>$('#myTable').html('').load(data);</code></p>
<p><code>.load()</code> is used for loading files but here you have source code. ;) </p>
| 0 | 2016-09-05T14:01:51Z | [
"javascript",
"jquery",
"python",
"ajax",
"django"
] |
append zero but not False in a list python | 39,331,381 | <p>I'm trying to move all zeros in a list to the back of the line, my only problem is there is a False bool in the list. I just found out that False == 0, so how do i move all zeros to the back of the list and keep false intact?</p>
<pre><code>def move_zeros(array):
#your code here
for i in array:
if i... | 6 | 2016-09-05T13:12:05Z | 39,331,501 | <pre><code>for i in array:
if i == 0 and i is not false:
array.remove(i)
array.append(i)
answer = array
print answer
</code></pre>
| 0 | 2016-09-05T13:18:56Z | [
"python",
"list"
] |
append zero but not False in a list python | 39,331,381 | <p>I'm trying to move all zeros in a list to the back of the line, my only problem is there is a False bool in the list. I just found out that False == 0, so how do i move all zeros to the back of the list and keep false intact?</p>
<pre><code>def move_zeros(array):
#your code here
for i in array:
if i... | 6 | 2016-09-05T13:12:05Z | 39,331,503 | <p>What you're doing is basically a custom sort. So just implement it this way:</p>
<pre><code>array.sort(key=lambda item: item is 0)
</code></pre>
<p>What this means is "Transform the array into a boolean one where items which are 0 are True and everything else is False." Then, sorting those booleans puts all the ... | 8 | 2016-09-05T13:19:00Z | [
"python",
"list"
] |
append zero but not False in a list python | 39,331,381 | <p>I'm trying to move all zeros in a list to the back of the line, my only problem is there is a False bool in the list. I just found out that False == 0, so how do i move all zeros to the back of the list and keep false intact?</p>
<pre><code>def move_zeros(array):
#your code here
for i in array:
if i... | 6 | 2016-09-05T13:12:05Z | 39,331,515 | <p>Here is one way. Note, <code>False == 0</code> is <code>True</code> but <code>False is 0</code> is <code>False</code>.</p>
<pre><code>>>> l = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9]
>>> [x for x in l if x is not 0] + [x for x in l if x is 0]
['a', 'b', None, 'c', 'd', 1,... | 3 | 2016-09-05T13:19:26Z | [
"python",
"list"
] |
append zero but not False in a list python | 39,331,381 | <p>I'm trying to move all zeros in a list to the back of the line, my only problem is there is a False bool in the list. I just found out that False == 0, so how do i move all zeros to the back of the list and keep false intact?</p>
<pre><code>def move_zeros(array):
#your code here
for i in array:
if i... | 6 | 2016-09-05T13:12:05Z | 39,331,566 | <p>You can use <a href="https://docs.python.org/3.4/library/functions.html#sorted" rel="nofollow"><code>sorted</code></a>:</p>
<pre><code>sorted(array, key=lambda x: x is 0)
</code></pre>
| 3 | 2016-09-05T13:22:38Z | [
"python",
"list"
] |
append zero but not False in a list python | 39,331,381 | <p>I'm trying to move all zeros in a list to the back of the line, my only problem is there is a False bool in the list. I just found out that False == 0, so how do i move all zeros to the back of the list and keep false intact?</p>
<pre><code>def move_zeros(array):
#your code here
for i in array:
if i... | 6 | 2016-09-05T13:12:05Z | 39,331,714 | <p><code>if i == 0 and type(i) is int :</code></p>
<p>You can do it in above way. Whole program looks as below:</p>
<pre><code>def move_zeros(array):
#your code here
for i in array:
if i == 0 and type(i) is int:
array.remove(i)
array.append(i)
answer = array
print answe... | 0 | 2016-09-05T13:29:20Z | [
"python",
"list"
] |
append zero but not False in a list python | 39,331,381 | <p>I'm trying to move all zeros in a list to the back of the line, my only problem is there is a False bool in the list. I just found out that False == 0, so how do i move all zeros to the back of the list and keep false intact?</p>
<pre><code>def move_zeros(array):
#your code here
for i in array:
if i... | 6 | 2016-09-05T13:12:05Z | 39,332,889 | <p>Because list sorting is stable you can do</p>
<pre><code>array.sort(key=(lambda x: 1 if (x==0 and x is not False) else 0))
</code></pre>
<p>comparing identity on numbers (<code>x is 0</code>) is dangerous because while it normally works, there is no guarantee.</p>
<p>Using <code>key</code> makes sorting much fast... | 0 | 2016-09-05T14:35:56Z | [
"python",
"list"
] |
append zero but not False in a list python | 39,331,381 | <p>I'm trying to move all zeros in a list to the back of the line, my only problem is there is a False bool in the list. I just found out that False == 0, so how do i move all zeros to the back of the list and keep false intact?</p>
<pre><code>def move_zeros(array):
#your code here
for i in array:
if i... | 6 | 2016-09-05T13:12:05Z | 39,333,141 | <p>I read from <a href="http://stackoverflow.com/questions/2764017/is-false-0-and-true-1-in-python-an-implementation-detail-or-is-it-guarante">this post</a> that Python treats 0 as boolean False. So it will always be placed on the end of your arrays like the 0s.
I suggest casting boolean False as type String first, 'Fa... | 0 | 2016-09-05T14:51:43Z | [
"python",
"list"
] |
append zero but not False in a list python | 39,331,381 | <p>I'm trying to move all zeros in a list to the back of the line, my only problem is there is a False bool in the list. I just found out that False == 0, so how do i move all zeros to the back of the list and keep false intact?</p>
<pre><code>def move_zeros(array):
#your code here
for i in array:
if i... | 6 | 2016-09-05T13:12:05Z | 39,430,922 | <p>The following is an O(n) linear scan algorithm, as opposed to the O(n<em>logn) and O(n</em>n) algorithms given already. Move non-0 items just once and add 0s in one batch.</p>
<pre><code>def move_zeros(array):
"Mutate list by putting int 0 items at the end, in O(n) time."
dest = 0
zeros = 0
for ite... | 0 | 2016-09-10T21:51:30Z | [
"python",
"list"
] |
How to create a loop, that goes through every row until the current value is not equal to the previous | 39,331,425 | <p>I have such excel document, with the list of product id's. I need to create an array of evaluation.</p>
<p><a href="http://i.stack.imgur.com/RXrSt.png" rel="nofollow"><img src="http://i.stack.imgur.com/RXrSt.png" alt="enter image description here"></a></p>
<p>So,my algorithm is follow:
1) While current product id ... | 1 | 2016-09-05T13:14:28Z | 39,334,448 | <p>I am not sure what you try to do exactly. I'll guess something like (warning: untested!):</p>
<pre><code>START_ROW, END_ROW = 3, 27
eval_list = []
previous_id = str(work_sheet.cell(row=START_ROW-1, column=6).value)
for row_num in range (START_ROW, END_ROW+1):
current_id = str(work_sheet.cell(row=row_num, column=... | 0 | 2016-09-05T16:21:29Z | [
"python",
"openpyxl"
] |
How to coreclty solve ZMQ socket error "zmq.error.ZMQError: Address in use" in python | 39,331,516 | <p><br>I am using a windows 7 machine with Python 2.7 to make a simple Client/Server ZMQ proof of concept. I ran into this scenario where the listening socket(Server side of the app) is already in use and this throws "zmq.error.ZMQError: Address in use" error. <br>How do you think is the best way to avoid this error? I... | 0 | 2016-09-05T13:19:26Z | 39,351,113 | <p>I tried another approach, instead of checking the availability of the socket, I am trying to manage it correclty, to do this:<br></p>
<ul>
<li>Created the listener async, on a separate thread.</li>
<li>Created a method that will close the socket at exit</li>
<li><p>In the socket binding I only catch the ZMQError an... | 0 | 2016-09-06T14:08:41Z | [
"python",
"sockets",
"pyzmq"
] |
Enter key press is not working in Firefox | 39,331,588 | <p>I have a scenario which involves pressing <code>Enter</code> key in the webpage. For <code>Chrome</code> my code works fine but when it comes to <code>Firefox</code> my code is not working. Please help me with an idea so that I can automate <code>Enter</code> key press in <code>Selenium</code> <code>Python</code> fo... | 1 | 2016-09-05T13:23:36Z | 39,338,361 | <p>Try</p>
<pre><code>from selenium.webdriver.common.keys import Keys
driver.find_element_by_name("Value").send_keys(Keys.RETURN)
</code></pre>
<p>Note that RETURN = '\ue006'</p>
| 0 | 2016-09-05T22:28:10Z | [
"python",
"selenium",
"firefox",
"selenium-webdriver",
"keypress"
] |
python - Datetime calculation between two columns in python pandas | 39,331,602 | <p>I have a DataFrame like this:
And this DataFrame is called<code>df_NoMissing_IDV</code>.</p>
<pre><code>NoDemande NoUsager Sens IdVehiculeUtilise Fait HeureArriveeSurSite HeureEffective Periods
42196000013 000001 + 287Véh 1 11/07/2015 08:02:07 11/07/2015 08:02:13 Matin
42196... | 1 | 2016-09-05T13:24:12Z | 39,333,073 | <p>I think that the cause of the error is that you have some dplicates in your data. </p>
<p>Try two things out:</p>
<pre><code>df_NoMissing_IDV['DureeService'] = df1['HeureEffective'].values -df1['HeureArriveeSurSite'].values
</code></pre>
<p>Or:</p>
<pre><code>df1 = df1.reset_index()
</code></pre>
<p><strong>EDI... | 1 | 2016-09-05T14:46:42Z | [
"python",
"datetime",
"pandas",
"dataframe"
] |
Exception Handling in Django - Is this necessary? | 39,331,659 | <p>Is this:</p>
<pre><code>@login_required
def remove_photo(request):
if request.is_ajax():
try:
BirdPhoto.objects.get( pk = request.POST.get('image_id') ).delete()
except Exception:
raise Exception
return HttpResponse(json.dumps({'msg':'success'}), content_type='app... | -2 | 2016-09-05T13:27:06Z | 39,331,915 | <p>First of all, is there a reason not to use <a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/generic-editing/#deleteview" rel="nofollow"><code>DeleteView</code></a>?</p>
<p>If so, it seems like using <a href="https://docs.djangoproject.com/en/1.10/topics/http/shortcuts/#get-object-or-404" rel="n... | 2 | 2016-09-05T13:40:47Z | [
"python",
"django",
"error-handling"
] |
Exception Handling in Django - Is this necessary? | 39,331,659 | <p>Is this:</p>
<pre><code>@login_required
def remove_photo(request):
if request.is_ajax():
try:
BirdPhoto.objects.get( pk = request.POST.get('image_id') ).delete()
except Exception:
raise Exception
return HttpResponse(json.dumps({'msg':'success'}), content_type='app... | -2 | 2016-09-05T13:27:06Z | 39,331,927 | <p>The first one is actually <em>worse</em> than the second one. If the second variant raises an exception, it will be a specific exception such as <code>BirdPhoto.DoesNotExist</code>, and your logfiles or the debug view will show you what the exact error is. The first variant will catch the more specific exception, an... | 4 | 2016-09-05T13:41:54Z | [
"python",
"django",
"error-handling"
] |
Pandas Dataframe, assign values to day of the week. Feature extraction | 39,331,717 | <p>I am extracting features to look for the weekdays. What I have so far is this:</p>
<pre><code>days = {0:'Mon', 1: 'Tues', 2:'Wed', 3:'Thurs', 4:'Fri', 5:'Sat', 6:'Sun'}
data['day_of_week'] = data['day_of_week'].apply(lambda x: days[x])
data['if_Weekday'] = np.where( (data['day_of_week'] == 'Mon') | (data['day_of_we... | 2 | 2016-09-05T13:29:28Z | 39,331,763 | <p>OK I think the easiest thing here is to use <code>np.where</code> to test whether the weekday is greater than or equal to 5 and if so assign <code>0</code>, else return the weekday value and add <code>1</code> to it:</p>
<pre><code>In [21]:
df['is_weekday'] = np.where(df['weekday'] >= 5, 0, df['weekday'] + 1)
df... | 0 | 2016-09-05T13:32:24Z | [
"python",
"pandas",
"numpy",
"multiple-columns",
"dayofweek"
] |
Pandas Dataframe, assign values to day of the week. Feature extraction | 39,331,717 | <p>I am extracting features to look for the weekdays. What I have so far is this:</p>
<pre><code>days = {0:'Mon', 1: 'Tues', 2:'Wed', 3:'Thurs', 4:'Fri', 5:'Sat', 6:'Sun'}
data['day_of_week'] = data['day_of_week'].apply(lambda x: days[x])
data['if_Weekday'] = np.where( (data['day_of_week'] == 'Mon') | (data['day_of_we... | 2 | 2016-09-05T13:29:28Z | 39,331,988 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mask.html" rel="nofollow"><code>mask</code></a>:</p>
<pre><code>data = pd.DataFrame({'day_of_week':[0,1,2,3,4,5,6]})
#original column to new, add 1
data['if_Weekday'] = data['day_of_week'] + 1
#map days if necessary
d... | 0 | 2016-09-05T13:45:01Z | [
"python",
"pandas",
"numpy",
"multiple-columns",
"dayofweek"
] |
Discovering data type of incoming socket data in python | 39,331,780 | <p>There are couple of devices which are sending socket data over <em>TCP/IP</em> to socket server. Some of the devices are sending data as <em>Binary encoded Hexadecimal string</em>, others are <em>ASCII string</em>.</p>
<p>Eg.;</p>
<p>If device sending data in <em>ASCII string</em> type, script is begin to process ... | 0 | 2016-09-05T13:33:16Z | 39,332,098 | <p>If you can you should make the sending devices signal what data they are sending eg by using different TCP ports or prepending each message with an <code>"h"</code> for hex or an <code>"a"</code> for ascii - possibly even use an established protocol like <a href="https://docs.python.org/3/library/xmlrpc.html" rel="n... | 1 | 2016-09-05T13:51:32Z | [
"python",
"sockets",
"types"
] |
Find a word with a for loop - python | 39,331,807 | <p>What I'm trying to do is have python go over all the RSS feed titles and make the terminal print out only the titles with a certain word.</p>
<pre><code>import feedparser
d = feedparser.parse('http://rss.cnn.com/rss/edition_technology.rss')
print d['feed']['title']
print 'number of entries: '
print len(d['entrie... | 0 | 2016-09-05T13:35:19Z | 39,332,066 | <p>Your code seems great.
What you are missing is an "if" which check if a specific word exists in the post.title</p>
<p>I've used "if" and "in" to filter only the relevant lines.</p>
<p>Details about "in" can be found here: <a href="http://www.jworks.nl/2013/11/07/python-goodness-the-in-keyword/" rel="nofollow">http... | 0 | 2016-09-05T13:49:43Z | [
"python",
"loops",
"parsing",
"rss",
"feed"
] |
How to extract a single row from multiple CSV files to a new file | 39,331,817 | <p>I have hundreds of CSV files on my disk, and one file added daily and I want to extract one row from each of them and put them in a new file. Then I want to daily add values to that same file. CSV files looks like this:</p>
<pre><code>business_day,commodity,total,delivery,total_lots
.
.
20160831,CTC,,201710,10
2016... | -3 | 2016-09-05T13:35:30Z | 39,332,334 | <p>Read the csv files and process them directly like so: </p>
<pre><code>with open('some.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
# do something here with `row`
break
</code></pre>
<p>I would recommend appending rows onto a list after processing for the rows that you desire, and t... | 0 | 2016-09-05T14:03:49Z | [
"python",
"python-3.x",
"csv",
"pandas"
] |
How to extract a single row from multiple CSV files to a new file | 39,331,817 | <p>I have hundreds of CSV files on my disk, and one file added daily and I want to extract one row from each of them and put them in a new file. Then I want to daily add values to that same file. CSV files looks like this:</p>
<pre><code>business_day,commodity,total,delivery,total_lots
.
.
20160831,CTC,,201710,10
2016... | -3 | 2016-09-05T13:35:30Z | 39,345,582 | <p>I ended up with the following:</p>
<pre><code>import pandas as pd
import glob
list_ = []
filenames = glob.glob('c:\\Financial Data\\*_DAILY.csv')
for filename in filenames:
df = pd.read_csv(filename, index_col = None, usecols = ['business_day', 'commodity', 'total', 'total_lots'], parse_dates = ['business_day'... | 1 | 2016-09-06T09:35:12Z | [
"python",
"python-3.x",
"csv",
"pandas"
] |
Call Grandparent Method without executing parent method through Mixin | 39,331,875 | <p>I need to override Parent method and call Grandparent method through mixin. Is it possible? </p>
<p>For example: <code>A</code> and <code>B</code> are library classes.</p>
<pre><code>class A(object):
def class_name(self):
print "A"
class B(A):
def class_name(self):
print "B"
super... | 2 | 2016-09-05T13:38:38Z | 39,332,067 | <p>One method is to use <a href="https://docs.python.org/2/library/inspect.html#inspect.getmro" rel="nofollow"><code>inspect.getmro()</code></a> but that is likely to break if the user writes <code>class D(B, Mixin)</code>.</p>
<p>Let me demonstrate:</p>
<pre><code>class A(object):
def class_name(self):
p... | 1 | 2016-09-05T13:49:51Z | [
"python",
"multiple-inheritance"
] |
How to print out the first and last 1000 lines using beautiful soup | 39,331,945 | <p>I am trying to print out the first and last 1000 lines using "prettify' from BeautifulSoup. I have downloaded Kafka's The Metamorphosis to my hard drive and I've successfully created a BeautifulSoup object:</p>
<p>Due to captcha issues with the Gutenberg site, I saved a copy of the document on my hard drive.</p>
... | -1 | 2016-09-05T13:42:59Z | 39,331,997 | <p>Just <em>slice</em> them:</p>
<pre><code>result = soup.prettify().splitlines()
print('\n'.join(result[:1000] + result[-1000:]))
</code></pre>
| 1 | 2016-09-05T13:45:34Z | [
"python",
"beautifulsoup",
"prettify"
] |
Using scipy.interpolate.interpn to interpolate a N-Dimensional array | 39,332,053 | <p>Suppose I have data that depends on 4 variables: a, b, c and d. I want interpolate to return a 2D array which corresponds to a single value of a and b, and an array of values for c and d. However, The array size need not be the same. To be specific, my data comes from a transistor simulation. The current depends on ... | 1 | 2016-09-05T13:49:20Z | 39,357,219 | <p>I'll try to explain this to you in 2D so that you get a better idea of what's happening. First, let's create a linear array to test with.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
# Set up grid and array of values
x1 = np.ar... | 1 | 2016-09-06T20:21:33Z | [
"python",
"python-2.7",
"numpy",
"scipy"
] |
How to output Regression Analysis summary from polynomial regression with scikit-learn? | 39,332,102 | <p>I currently have the following code, which does a polynomial regression on a dataset with 4 variables:</p>
<pre><code>def polyreg():
dataset = genfromtxt(open('train.csv','r'), delimiter=',', dtype='f8')[1:]
target = [x[0] for x in dataset]
train = [x[1:] for x in dataset]
test = genfromtxt(open(... | 1 | 2016-09-05T13:51:45Z | 39,339,076 | <p>This is not implemented in scikit-learn; the scikit-learn ecosystem is quite biased towards using cross-validation for model evaluation (this a good thing in my opinion; most of the test statistics were developed out necessity before computers were powerful enough for cross-validation to be feasible). </p>
<p>For m... | 1 | 2016-09-06T00:28:11Z | [
"python",
"python-2.7",
"scikit-learn",
"non-linear-regression"
] |
Thread-safe version of mock.call_count | 39,332,139 | <p>It appears that <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.call_count" rel="nofollow" title="Mock.call_count">Mock.call_count</a> does not work correctly with threads. For instance:</p>
<pre><code>import threading
import time
from mock import MagicMock
def f():
time.sleep... | 1 | 2016-09-05T13:53:25Z | 39,333,885 | <p>I finally made it work by using a counter linked to the side effect method and a lock.</p>
<pre><code>import threading
import time
from mock import MagicMock
lock_side_effect = threading.Lock()
def f():
with lock_side_effect:
f.call_count += 1
time.sleep(0.1)
f.call_count = 0
def test_1():
m... | 0 | 2016-09-05T15:39:07Z | [
"python",
"multithreading",
"unit-testing",
"mocking"
] |
Real Time temperature plotting with python | 39,332,157 | <p>I am currently making a project which requires real time monitoring of various quantities like temperature, pressure, humidity etc. I am following a approach of making individual arrays of all the sensors and ploting a graph using matplotlib and drwnow.</p>
<pre><code>HOST = "localhost"
PORT = 4223
UID1 = "tsJ" # ... | 0 | 2016-09-05T13:54:22Z | 39,334,399 | <blockquote>
<p>I'd like to ask that, does filling data in arrays continuosly makes the process slow or is it my misconception?</p>
</blockquote>
<p>That one is easy to test; creating an empty list and appending a few thousand values to it takes roughly 10^-4 seconds, so that shouldn't be a problem. For me somewhat ... | 0 | 2016-09-05T16:17:34Z | [
"python",
"matplotlib"
] |
TypeError: Invalid argument(s) 'pool_size' sent to create_engine() when using flask_sqlalchemy | 39,332,177 | <p>I'm using
SQLAlchemy==1.0.9 and
Flask-SQLAlchemy==2.1
in my Flask application and want to connect to a sqlite db.</p>
<p>I get the error</p>
<pre><code>TypeError: Invalid argument(s) 'pool_size' sent to create_engine(), using configuration SQLiteDialect_pysqlite/NullPool/Engine.
</code></pre>
<p>because flask_sq... | 1 | 2016-09-05T13:55:20Z | 39,347,839 | <p>Finally found it: A colleague introduced the config param SQLALCHEMY_POOL_SIZE in the Config Base Class to use it with mySQL.</p>
<p>Nevertheless it would be great if either flask_sqlalchemy or sqlalchemy would ignore the parameter instead of throwing an error.</p>
<p>I've created a ticket for the flask_sqlalchemy... | 0 | 2016-09-06T11:21:41Z | [
"python",
"sqlite",
"sqlalchemy",
"flask-sqlalchemy"
] |
return type of round () | 39,332,243 | <p>I have the following piece of code:</p>
<pre><code>a_round = round (3.5) # First use of a_round
a_round = 4.5 # Incompatible types, since a_round is regarded as an int
</code></pre>
<p>It turns out that the return value of round () is regarded as an int.
That this is so, I conclude because at the second statem... | -2 | 2016-09-05T13:59:24Z | 39,332,387 | <p>It depends on your implementation:</p>
<pre><code>>>> round(3.5)
4
>>> type(round(3.5))
<class 'int'>
>>> round(3.5,1)
3.5
>>> type(round(3.5,1))
<class 'float'>
</code></pre>
<p>Of course it is trivial to create a float in all cases:</p>
<pre><code>>>> flo... | 1 | 2016-09-05T14:07:07Z | [
"python",
"mypy"
] |
return type of round () | 39,332,243 | <p>I have the following piece of code:</p>
<pre><code>a_round = round (3.5) # First use of a_round
a_round = 4.5 # Incompatible types, since a_round is regarded as an int
</code></pre>
<p>It turns out that the return value of round () is regarded as an int.
That this is so, I conclude because at the second statem... | -2 | 2016-09-05T13:59:24Z | 39,332,469 | <p>Let's examine this script:</p>
<pre><code>a_round = round(3.5) # First use of a_round
print(a_round.__class__)
a_round = 4.5 # Incompatible types, since a_round is regarded as an int
print(a_round.__class__)
</code></pre>
<p>On python 2.7 the result is:</p>
<pre><code><type 'float'>
<type 'float'>... | 0 | 2016-09-05T14:11:55Z | [
"python",
"mypy"
] |
return type of round () | 39,332,243 | <p>I have the following piece of code:</p>
<pre><code>a_round = round (3.5) # First use of a_round
a_round = 4.5 # Incompatible types, since a_round is regarded as an int
</code></pre>
<p>It turns out that the return value of round () is regarded as an int.
That this is so, I conclude because at the second statem... | -2 | 2016-09-05T13:59:24Z | 39,332,594 | <p>To fully clarify:</p>
<pre><code>type (round (3.5, 0)) # <class 'float'>
type (round (3.5)) # <class 'int'>
</code></pre>
| 0 | 2016-09-05T14:19:04Z | [
"python",
"mypy"
] |
Trying to invoke python function from js using jQuery and Flask | 39,332,486 | <p>I'm trying to design an interactive website for a presentation I'm making. I'm new at all this flask stuff, and I'm having some hard time understanding why my code doesnt work.</p>
<p>I'm trying to create a website, that every line in it is clickable, and on click I want to bind a python function that according to ... | -1 | 2016-09-05T14:13:14Z | 39,332,908 | <p>You have two problems in your app.
The first one is that you are not importing the request module:</p>
<pre><code>from flask import Flask, jsonify, request
</code></pre>
<p>Second, in your template, you are referring to <code>this</code> that is out of scope.
This should work:</p>
<pre><code>$( "p" ).click(func... | 1 | 2016-09-05T14:36:57Z | [
"javascript",
"jquery",
"python",
"flask"
] |
Matplotlib cumulative plot | 39,332,553 | <p>What matplotlib function I should use for creating such "above" plots?</p>
<p>I've tried to find it in <a href="http://matplotlib.org/gallery.html" rel="nofollow">gallery</a>, but I've not managed to do it.</p>
<p><a href="http://i.stack.imgur.com/fUThW.png" rel="nofollow"><img src="http://i.stack.imgur.com/fUThW.... | 0 | 2016-09-05T14:17:06Z | 39,332,757 | <p>You can find a solution on this : <a href="http://matplotlib.org/examples/pylab_examples/stackplot_demo.html" rel="nofollow">http://matplotlib.org/examples/pylab_examples/stackplot_demo.html</a></p>
| 2 | 2016-09-05T14:28:35Z | [
"python",
"matplotlib"
] |
Matplotlib cumulative plot | 39,332,553 | <p>What matplotlib function I should use for creating such "above" plots?</p>
<p>I've tried to find it in <a href="http://matplotlib.org/gallery.html" rel="nofollow">gallery</a>, but I've not managed to do it.</p>
<p><a href="http://i.stack.imgur.com/fUThW.png" rel="nofollow"><img src="http://i.stack.imgur.com/fUThW.... | 0 | 2016-09-05T14:17:06Z | 39,332,770 | <p>You could use <code>matplotlib</code> <code>fill_between</code>, for example,</p>
<pre><code>#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0.0, 2, 0.1)
y = 10*np.ones(x.shape[0])
c = ['r', 'b', 'g', 'y', 'k']
fig, ax = plt.subplots()
for i in range(5):
r = np.random.ran... | 1 | 2016-09-05T14:29:17Z | [
"python",
"matplotlib"
] |
traversal tree NLP python. How to use DFS method to look for VP subtree to find the verb that is deepest in the subtree | 39,332,554 | <p>I am new to the NLP traversal. <a href="http://i.stack.imgur.com/9JBVS.png" rel="nofollow">enter image description here</a></p>
<p>for example the sentence: Scroll bar does not work the best either.
I would like to use DFS method to look for VP subtree to find the verb that is deepest in the subtree. Could you ple... | 2 | 2016-09-05T14:17:10Z | 39,570,523 | <p>u can use the stanford cornlp to get the triples</p>
| 0 | 2016-09-19T10:08:26Z | [
"python",
"python-2.7",
"tree",
"nlp",
"tree-traversal"
] |
Scikit Image Marching Cubes Output | 39,332,603 | <p>I'm using the Scikit Image implementation of the marching cubes algorithm to generate an isosurface.</p>
<pre><code>verts, faces = measure.marching_cubes(stack,10)
</code></pre>
<p>Creates an isosurface of value 10 of the image stack <code>stack</code>, and outputs the vertex data to <code>verts</code>, and face d... | 0 | 2016-09-05T14:19:34Z | 39,334,378 | <p>From the <a href="http://scikit-image.org/docs/stable/api/skimage.measure.html#marching-cubes" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>The output is a triangular mesh consisting of a set of unique vertices
and connecting triangles. The order of these vertices and triangles in
the output list is ... | 1 | 2016-09-05T16:16:11Z | [
"python",
"scikit-image",
"marching-cubes"
] |
group name can't start with number? | 39,332,611 | <p>It looks like I can't use regex like this one,</p>
<pre><code>(?P<74xxx>[0-9]+)
</code></pre>
<p>With re package it would raise and error,</p>
<pre><code>sre_constants.error: bad character in group name u'74xxx'
</code></pre>
<p>It looks like I can't use group names that starts with a number, why?</p>
<p>... | 1 | 2016-09-05T14:20:08Z | 39,332,698 | <p>Given the <a href="https://docs.python.org/2/library/re.html" rel="nofollow">doc</a>:</p>
<blockquote>
<p>Group names must be valid Python identifiers</p>
</blockquote>
<p>As the variables, identifiers mustn't start with a number in Python. See more about identifiers <a href="https://docs.python.org/2.5/ref/iden... | 2 | 2016-09-05T14:24:55Z | [
"python",
"regex"
] |
group name can't start with number? | 39,332,611 | <p>It looks like I can't use regex like this one,</p>
<pre><code>(?P<74xxx>[0-9]+)
</code></pre>
<p>With re package it would raise and error,</p>
<pre><code>sre_constants.error: bad character in group name u'74xxx'
</code></pre>
<p>It looks like I can't use group names that starts with a number, why?</p>
<p>... | 1 | 2016-09-05T14:20:08Z | 39,333,071 | <p>If this is the pattern you are searching <code>r'(?P<74xxx>[0-9]+)'</code> and you wanted to include <code>?</code> in your search pattern then you have to prepend <code>\</code> with it since it is the special character in python. So your search pattern should be <code>r'(\?P<74xxx>[0-9]+)'</code>.</p>
| -2 | 2016-09-05T14:46:39Z | [
"python",
"regex"
] |
Error when importing scipy | 39,332,631 | <p>When trying to import scipy I get the error: </p>
<pre><code>ImportError Traceback (most recent call last)
C:\Program Files\INRO\Emme\Emme 4\Emme-4.2.7\python-lib\win64\2.7\modeller\inro.director.application\inro\director\application\run.pyc in <module>()
----> 1 import scipy... | 0 | 2016-09-05T14:21:07Z | 39,332,689 | <p>u can import simply by using command prompt...if everything is installed correctly</p>
<blockquote>
<p>import scipy as sp</p>
</blockquote>
| -2 | 2016-09-05T14:24:25Z | [
"python",
"numpy",
"scipy"
] |
How to groupby with certain condition in pandas dataframe | 39,332,665 | <p>I have dataframe like this</p>
<pre><code> A B
0 1 a
1 2 a
2 3 b
3 4 b
4 5 a
</code></pre>
<p>I want to get result below(1row*4column dataframe),</p>
<pre><code>A_count_all means the number of rows in dataframe df.A.count()
A_sum_all means the df.A.sum()
A_count_a is df.loc[df.B==a,"A... | 1 | 2016-09-05T14:23:03Z | 39,332,727 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow"><code>DataFrame</code></a> constructor:</p>
<pre><code>A_count_all = df.A.count()
A_sum_all = df.A.sum()
A_count_a = df.loc[df.B=='a',"A"].count()
A_sum_a = df.loc[df.B=='a',"A"].sum()
print (pd.DataFra... | 3 | 2016-09-05T14:26:50Z | [
"python",
"pandas",
"dataframe",
"group-by",
"sum"
] |
Combination of functools.partialmethod and classmethod | 39,332,671 | <p>I would like to use <code>functools.partialmethod</code> on a classmethod. However the behavior I find is not what I would expect (and like to have).
Here is an example:</p>
<pre><code>class A(object):
@classmethod
def h(cls, x, y):
print(cls, x, y)
class B(A):
h = functools.partialmethod(A.h, ... | 1 | 2016-09-05T14:23:30Z | 39,333,234 | <p>Without going into too much detail, the <code>partial</code> object doesn't mix well with the descriptor protocol that <code>@classmethod</code> utilizes to create a class instance. The simple fix is to just define your overridden method in the usual fashion:</p>
<pre><code>class B(A):
@classmethod
def h(cl... | 2 | 2016-09-05T14:57:17Z | [
"python",
"python-3.x",
"python-3.5",
"class-method",
"functools"
] |
Combination of functools.partialmethod and classmethod | 39,332,671 | <p>I would like to use <code>functools.partialmethod</code> on a classmethod. However the behavior I find is not what I would expect (and like to have).
Here is an example:</p>
<pre><code>class A(object):
@classmethod
def h(cls, x, y):
print(cls, x, y)
class B(A):
h = functools.partialmethod(A.h, ... | 1 | 2016-09-05T14:23:30Z | 39,333,341 | <p>Use <a href="https://docs.python.org/3/library/functions.html#super" rel="nofollow"><code>super</code></a> (v2.7)</p>
<pre><code>class A(object):
@classmethod
def c(cls, x, y):
print('cls:{}, x:{}, y:{}'.format(cls, x, y))
class B(A):
def c(self, y):
super(B, self).c(x = 'fixed', y = y)... | 1 | 2016-09-05T15:03:52Z | [
"python",
"python-3.x",
"python-3.5",
"class-method",
"functools"
] |
Slightly different result using InterpolatedUnivariateSpline and interp1d | 39,332,728 | <p>I was using <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html" rel="nofollow">interp1d</a> to fit a cubic spline but ran into some memmory issues, so as per the following <a href="http://stackoverflow.com/questions/21435648/cubic-spline-memory-error/21440722#21440722">quest... | 2 | 2016-09-05T14:26:57Z | 39,345,270 | <p>I have found that the main difference is that InterpolatedUnivariateSpline attempts to perform a continuous fit while cubic interp1d applies a piecewise fit. </p>
<p>The only solution that I have come up with (for now) is to ensure that both functions only use 4 data points (around the highest data point), as both ... | 0 | 2016-09-06T09:21:02Z | [
"python",
"scipy",
"curve-fitting"
] |
Python: Can you set cpu counts with multiprocessing Process | 39,332,776 | <p>With <code>multiprocessing.Pool</code>, there are code samples in the tutorials where you can set number of processes with cpu counts. Can you set the number of cpu's with the <code>multiprocessing.Process</code> method. </p>
<pre><code>from multiprocessing import Process, Value, Array
def f(n, a):
n.value = ... | 0 | 2016-09-05T14:29:36Z | 39,333,206 | <p>Actually <code>Process</code> represents only one process which uses only one CPU (if you dont use threads) - it is up to you to create as many <code>Process</code>es as you need. </p>
<p>This means that you have to create as many <code>Process</code>es as you have CPUs to use all of them (possibly -1 if you are do... | 1 | 2016-09-05T14:55:28Z | [
"python",
"multiprocessing",
"cpu"
] |
Python 3: How to read file json into list of dictionary? | 39,332,792 | <p>I have file with Json format:</p>
<pre><code>{"uid": 2, "user": 1}
{"uid": 2, "user": 1}
{"uid": 2, "user": 1}
</code></pre>
<p>When i use following code, it show an error:</p>
<pre><code> raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 22)
with open... | -1 | 2016-09-05T14:30:29Z | 39,332,863 | <p>You'll have to iterate, because <code>json.load</code> won't do that automatically.
<br/>So should have something like this</p>
<pre><code>for line in file:
json_obj = json.loads(line)
my_list.append(json_obj)
</code></pre>
| 1 | 2016-09-05T14:34:31Z | [
"python",
"json",
"dictionary"
] |
Python 3: How to read file json into list of dictionary? | 39,332,792 | <p>I have file with Json format:</p>
<pre><code>{"uid": 2, "user": 1}
{"uid": 2, "user": 1}
{"uid": 2, "user": 1}
</code></pre>
<p>When i use following code, it show an error:</p>
<pre><code> raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 22)
with open... | -1 | 2016-09-05T14:30:29Z | 39,332,865 | <p>Your file is not a <code>JSON</code>, its a list of <code>JSON</code>. </p>
<pre><code>with open(filec , 'r') as f:
list = list(map(json.loads, f))
</code></pre>
| 2 | 2016-09-05T14:34:38Z | [
"python",
"json",
"dictionary"
] |
Python 3: How to read file json into list of dictionary? | 39,332,792 | <p>I have file with Json format:</p>
<pre><code>{"uid": 2, "user": 1}
{"uid": 2, "user": 1}
{"uid": 2, "user": 1}
</code></pre>
<p>When i use following code, it show an error:</p>
<pre><code> raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 22)
with open... | -1 | 2016-09-05T14:30:29Z | 39,332,906 | <p>It's not loading your content basically because it's not a valid json format, try this script:</p>
<pre><code>import json
try:
file_content = """{"uid": 2, "user": 1}
{"uid": 2, "user": 1}
{"uid": 2, "user": 1}"""
json.loads(file)
except Exception as e:
print("This is not JSON!")
print('-' * ... | 2 | 2016-09-05T14:36:44Z | [
"python",
"json",
"dictionary"
] |
Oceanographic plotting in Python | 39,332,868 | <p>I am plotting graphs. And I would like to have the range of values on the colorbars for graphs "U_velocity" and "U_shear_velocity" from -0.3 to 0.3. Moreover, I am trying to make the range of x ax in hours from 0 to 12.5 for U and V shear velocity plots but nothing works and instead of that I have meanings of the sp... | -1 | 2016-09-05T14:34:40Z | 39,334,489 | <p>This is not an easy question to answer with a wall of code, reference to unknown file <code>result.nc</code> and several unrelated and fairly specific problems. The following may help:</p>
<p>The colorbar range can be set by passing <code>vmin=-0.3</code> and <code>vmax=0.3</code> to <code>pcolormesh</code>. </p>
... | 0 | 2016-09-05T16:23:41Z | [
"python",
"python-2.7",
"python-3.x",
"numpy",
"matplotlib"
] |
Unable to find text although it is present | 39,332,890 | <p>I am learning web-scrapping with Python. I wrote code to retrieve company names form one of Indian yellow pages</p>
<pre><code>r = requests.get("http://xyzxyz", headers={'User-Agent' : "Magic Browser"})
soup= BeautifulSoup(r.content,"html.parser")
for link in soup.findAll("div", {"class" : "col-sm-5"}):
coLin... | 2 | 2016-09-05T14:35:56Z | 39,333,645 | <p>Not explaining the current problem, but providing an alternative solution - you can use a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="nofollow">CSS selector</a> that would match the desired <code>a</code> elements:</p>
<pre><code>for link in soup.select(".col-sm-5 .jcn a"):
... | 0 | 2016-09-05T15:23:02Z | [
"python",
"web-scraping",
"beautifulsoup",
"find"
] |
Failure to import sknn.mlp / Theano | 39,332,901 | <p>I'm trying to use scikit-learn's neural network module in iPython... running Python 3.5 on a Win10, 64-bit machine.</p>
<p>When I try to import <code>from sknn.mlp import Classifier, Layer</code> , I get back the following <code>AttributeError: module 'theano' has no attribute 'gof'</code> ...</p>
<p>The command l... | 0 | 2016-09-05T14:36:30Z | 39,334,690 | <p>Apparently it was caused by some issue with Visual Studio. The import worked when I reinstalled VS and restarted the computer.</p>
<p>Thanks @super_cr7 for the prompt reply!</p>
| 0 | 2016-09-05T16:39:58Z | [
"python",
"installation",
"attributes",
"scikit-learn",
"theano"
] |
How can I add code to the following code to clear the entry field once i have entered the data? | 39,332,913 | <p>I entered this thinking it might work but it doesn't. Not sure if this is correct or I need to change it. It doesn't work so I am guessing it does need changing.</p>
<p>Import from tkinter:</p>
<pre><code>from tkinter import *
import csv
def delete_entries():
for field in fields:
field.delete(0,END)
... | -2 | 2016-09-05T14:37:16Z | 39,333,764 | <p>you can add this to end of the code that submits the entries</p>
<pre><code>self.n.delete(0, END)
self.e.delete(0, END)
</code></pre>
| 0 | 2016-09-05T15:30:57Z | [
"python",
"tkinter"
] |
sum of particular items of N lists using Python | 39,332,915 | <p>I have a task to analyse N texts using NLTK. Each text is longer than 100k words, so it is hard for computer to process so many data and that's why I decided to split each text after tokenizing in sublists like this:</p>
<p><code>chunks = [tokens_words[x:x+1000] for x in range (0,len(tokens_words), 1000)]</code></p... | 0 | 2016-09-05T14:37:28Z | 39,345,300 | <p>Let's say you have 2 chunks, one with 13 nouns and one with 30 nouns. Your code will do the following:</p>
<pre><code>noun: 0
totalNoun: []
# processing chunk 1 with 13 nouns...
noun : 13
totalNoun : [13]
# processing chunk 2 with 30 nouns...
noun : 43
totalNoun : [13,43]
</code></pre>
<p>As far as I can see, ... | 0 | 2016-09-06T09:22:14Z | [
"python",
"python-2.7",
"nltk"
] |
Write list and value in same row csv | 39,332,927 | <p>I have several values and severals list with differents length.
I'd like to write them in the same CSV row. </p>
<p>i.e.
I have these values </p>
<pre><code>a=1234
b=["John","Bryan","Johnny"]
c="Value"
d=["Comedy","Action"]
</code></pre>
<p>As output I'd like a csv file like this : </p>
<pre><code>[1234;"J... | -2 | 2016-09-05T14:38:18Z | 39,333,003 | <p>Use <code>writerow</code> and combine each element together into a single <code>list</code>:</p>
<pre><code>wr.writerow([a] + b + [c] + d)
</code></pre>
<p>Some of the elements need to be wrapped in brackets to turn them into a <code>list</code> with a single element.</p>
| 1 | 2016-09-05T14:42:47Z | [
"python",
"csv"
] |
Write list and value in same row csv | 39,332,927 | <p>I have several values and severals list with differents length.
I'd like to write them in the same CSV row. </p>
<p>i.e.
I have these values </p>
<pre><code>a=1234
b=["John","Bryan","Johnny"]
c="Value"
d=["Comedy","Action"]
</code></pre>
<p>As output I'd like a csv file like this : </p>
<pre><code>[1234;"J... | -2 | 2016-09-05T14:38:18Z | 39,333,045 | <p>As TigerhawkT3 said you'll want to use <code>writerow</code> and also when you're instantiating your csv.writer set the <code>delimiter</code> to ';'.</p>
| 0 | 2016-09-05T14:45:17Z | [
"python",
"csv"
] |
Use Python script to extract data from excel sheet and input into website | 39,333,004 | <p>Hey I am python scripting novice, I was wondering if someone could help me understand how I could python, or any convenient scripting language, to cherry pick specific data values (just a few arbitrary columns on the excel sheet), and take the data and input into a web browser like chrome. Just a general idea of how... | -4 | 2016-09-05T14:42:50Z | 39,333,344 | <p>Okay. Lets get started.</p>
<h2>Getting values out of an excel document</h2>
<p><a href="https://www.getdatajoy.com/learn/Read_and_Write_Excel_Tables_from_Python" rel="nofollow">This page</a> is a great place to start as far as reading excel values goes. </p>
<p>Directly from the site:</p>
<pre><code>import pand... | 0 | 2016-09-05T15:03:58Z | [
"python",
"scripting"
] |
Truncating a random gammavariate result to an upper limit | 39,333,018 | <p>I want to draw a number from a gammavariate, but I want to set an upper limit.
Why this does not work?</p>
<pre><code>import random
[int(random.gammavariate(3, 3)) if x < 21 else 20 for x in range(1)]
Out[59]: [22]
</code></pre>
<p>Thanks.</p>
| 0 | 2016-09-05T14:43:46Z | 39,333,153 | <p>Why making things <a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">complicated</a>?</p>
<p><code>x</code> is always <code>0</code> in your list comprehension.</p>
<p>try it this way:</p>
<pre><code>x = int(random.gammavariate(3,3))
[x if x < 21 else 20]
</code></pre>
| 1 | 2016-09-05T14:52:20Z | [
"python",
"random"
] |
Truncating a random gammavariate result to an upper limit | 39,333,018 | <p>I want to draw a number from a gammavariate, but I want to set an upper limit.
Why this does not work?</p>
<pre><code>import random
[int(random.gammavariate(3, 3)) if x < 21 else 20 for x in range(1)]
Out[59]: [22]
</code></pre>
<p>Thanks.</p>
| 0 | 2016-09-05T14:43:46Z | 39,333,179 | <p>If I've understood correctly you want to clamp a random value following the <a href="https://docs.python.org/2/library/random.html#random.gammavariate" rel="nofollow">gamma distribution</a> in a certain range [0-20], you could do it like this:</p>
<pre><code>import random
def clamp(x, min_value, max_value):
r... | 0 | 2016-09-05T14:54:07Z | [
"python",
"random"
] |
Tweepy and Python: how to list all followers | 39,333,040 | <p>With tweepy in Python I'm looking for a way to list all followers from one account, with username and number of followers.
Now I can obtain the list of all ids in this way:</p>
<pre><code>ids = []
for page in tweepy.Cursor(api.followers_ids, screen_name="username").pages():
ids.extend(page)
time.sleep(1)
</... | 0 | 2016-09-05T14:44:58Z | 39,335,663 | <p>On the REST API, your are allowed <a href="https://dev.twitter.com/rest/public/rate-limiting" rel="nofollow">180 queries every 15 minutes</a>, and I guess the Streaming API has a similar limitation. You do not want to come too close to this limit, since your application will eventually get blocked even if you do not... | 1 | 2016-09-05T18:01:00Z | [
"python",
"twitter",
"tweepy"
] |
xlrd - issue on opening file | 39,333,103 | <p>I'm using <strong>xlrd 0.9.4</strong> and I would like verify if the file that I must open is valid.</p>
<p>To do this, I wrote this code <a href="http://stackoverflow.com/questions/28645167/how-to-check-if-valid-excel-file-in-python-xlrd-library">in according with this question</a>:</p>
<pre><code>try:
book =... | 0 | 2016-09-05T14:48:50Z | 39,333,464 | <p>You can see how to xlrd check the file before reading. In <a href="https://github.com/python-excel/xlrd/blob/master/xlrd/compdoc.py" rel="nofollow">xldr source</a> at lines 18-19 defined a «magic» bytes. First bytes of file compared with this byte sequence at line 85. If its not equal exception will be rise. File ... | 2 | 2016-09-05T15:11:16Z | [
"python",
"excel",
"xlrd"
] |
Python subclassing causes IDLE to restart | 39,333,238 | <p>I found this issue in a long, complex script, but while debugging stripped it down to this very minimal form which still causes the same problem:</p>
<pre><code>from PyQt5.QtWidgets import(QMainWindow)
class Window(QMainWindow):
pass
</code></pre>
<p>When I import this class through the IDLE interpreter, then... | 1 | 2016-09-05T14:57:40Z | 39,547,760 | <p>Thanks for your help - as far as I can tell, there was in fact a clash between tkinter and Qt. A reinstall of my Python environment seems to have taken care of the problem!</p>
| 0 | 2016-09-17T14:11:03Z | [
"python",
"class",
"subclass",
"python-idle"
] |
Pandas time subset time series - dates ABOVE certain time | 39,333,262 | <p>If <code>df[:'2012-01-07']</code> returns the sub-DataFrame with dates below <code>20120107</code>, what does return dates <em>above</em> 20120107? <code>df['2012-01-07':]</code> doesn't...</p>
| 2 | 2016-09-05T14:58:47Z | 39,333,463 | <p>For me it works perfect, but maybe in real data need sort index by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow"><code>sort_index</code></a>:</p>
<pre><code>df = pd.DataFrame({'a':[0,1,2,5,4]}, index=pd.date_range('2012-01-05', periods=5))
print (df)... | 2 | 2016-09-05T15:11:10Z | [
"python",
"pandas",
"indexing",
"dataframe",
"time-series"
] |
Count number of occurrence in a column Python | 39,333,383 | <p>I want to count the number of occurrences for each input in the column Echantillon. For example:</p>
<pre class="lang-none prettyprint-override"><code>Echantillon Classe
1001 0
956 1
9658 2
1001 0
8566 2
956 1
</code></pre>
<p>How can this be do... | -2 | 2016-09-05T15:06:47Z | 39,333,947 | <p>If I understand properly then you want total numbers by classes. If it so then you can do it by:</p>
<pre><code>In [9]: df
Out[9]:
Echantillon Classe
0 1001 0
1 956 1
2 9658 2
3 1001 0
4 8566 2
5 956 1
</code></pre>
<p>then ... | 0 | 2016-09-05T15:44:04Z | [
"python",
"pandas"
] |
How to determine the projection (2D or 3D) of a matplotlib axes object? | 39,333,446 | <p>In Python's matplotlib library it is easy to specify the projection of an axes object on creation: </p>
<pre><code>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
ax = plt.axes(projection='3d')
</code></pre>
<p>But how do I determine the projection of an existing axes object? There's no <co... | 1 | 2016-09-05T15:10:14Z | 39,334,099 | <p>I don't think there is an automated way, but there are obviously some properties that only the 3D projection has (e.g. <code>zlim</code>).</p>
<p>So you could write a little helper function to test if its 3D or not:</p>
<pre><code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
def axesDim... | 2 | 2016-09-05T15:55:59Z | [
"python",
"matplotlib",
"3d",
"2d",
"projection"
] |
Local Scope Issue in Tic Tac Toe game (Python) | 39,333,472 | <p>I've been learning python for the last couple days and in my book the challenge was to create a tic tac toe program. I think I have a general idea of how to do the game, but I ran into an issue in which insight would be helpful, </p>
<p>Heres the relevant part of my code</p>
<pre><code> board = []
for i in range... | 0 | 2016-09-05T15:11:44Z | 39,333,656 | <p>How about just returning the winner? Something along the lines of this:</p>
<pre><code>player_one = "X"
player_two = "O"
current_player_name = "Player One"
current_player = player_one
filled_board = False
winner = False
def check_win_col():
for i in range(0,3):
for j in range(0,3):
if board... | 0 | 2016-09-05T15:24:02Z | [
"python"
] |
Local Scope Issue in Tic Tac Toe game (Python) | 39,333,472 | <p>I've been learning python for the last couple days and in my book the challenge was to create a tic tac toe program. I think I have a general idea of how to do the game, but I ran into an issue in which insight would be helpful, </p>
<p>Heres the relevant part of my code</p>
<pre><code> board = []
for i in range... | 0 | 2016-09-05T15:11:44Z | 39,333,894 | <p>The issue with your function is not on the line you say gives an error, but rather on the line where you <code>print</code> or <code>return</code> the variable <code>the_winner</code>. That variable may not have been set in the loop, since the (buggy!) condition you're checking is not always be true.</p>
<p>There a... | 1 | 2016-09-05T15:39:45Z | [
"python"
] |
How to access(ask) token for user login | 39,333,514 | <p>I have used Django Rest Framework for Rest API and django-oauth-toolkit for token based authentication. I have designed and api for user registration. When user is registered, a token is generated and saved to the database. I want user login from that token. I mean a token based authentication because i want to deve... | 0 | 2016-09-05T15:14:15Z | 39,340,353 | <p>So if you want a api to get token depend on username and password will look like this:</p>
<pre><code>def get_token(request):
username = request.POST.get("username")
password = request.POST.get("password")
.... # other parameters
try:
user = User.objects.get(username=username, password=passw... | 0 | 2016-09-06T03:47:54Z | [
"python",
"django",
"python-3.x",
"oauth",
"django-rest-framework"
] |
Sympy's subs limitations | 39,333,567 | <p>I am working with some long equations but not really complex, and I wanted to use <strong>sympy</strong> to simplify and "factorize" them. But I have encountered a few problems. Here is a list of some minimal examples:</p>
<p><strong>Problem 1: symmetry</strong></p>
<pre><code>from sympy import *
from __future__ i... | 0 | 2016-09-05T15:18:07Z | 39,334,056 | <p>Here's a possible solution to your problems:</p>
<pre><code>from sympy import *
a = symbols('a')
b = symbols('b')
expr = 1 / 12 * b + 1
print(expr.subs((1 / 12) * b, a))
print(expr.subs(b * (1 / 12), a))
x = symbols('x')
y = symbols('y')
expr = ((x + 1)**2 - x).expand()
print(expr.subs(x**2 + x, y - x + 1))
</cod... | 1 | 2016-09-05T15:52:49Z | [
"python",
"sympy",
"substitution",
"symbolic-math"
] |
Sympy's subs limitations | 39,333,567 | <p>I am working with some long equations but not really complex, and I wanted to use <strong>sympy</strong> to simplify and "factorize" them. But I have encountered a few problems. Here is a list of some minimal examples:</p>
<p><strong>Problem 1: symmetry</strong></p>
<pre><code>from sympy import *
from __future__ i... | 0 | 2016-09-05T15:18:07Z | 39,338,219 | <p>Regarding problem 1, note that <code>1/12*b</code> and <code>b*1/12</code> are <em>not</em> the same thing in sympy. The first is a floating number mutliplied by a symbol, whereas the second is an exact symbolic expression (you can check it out by a simple print statement). Since <code>expr</code> contains <code>1/1... | 1 | 2016-09-05T22:10:21Z | [
"python",
"sympy",
"substitution",
"symbolic-math"
] |
Sympy's subs limitations | 39,333,567 | <p>I am working with some long equations but not really complex, and I wanted to use <strong>sympy</strong> to simplify and "factorize" them. But I have encountered a few problems. Here is a list of some minimal examples:</p>
<p><strong>Problem 1: symmetry</strong></p>
<pre><code>from sympy import *
from __future__ i... | 0 | 2016-09-05T15:18:07Z | 39,356,387 | <p>There is a major gotcha in SymPy, which is that, because of the way Python works, <code>number/number</code> gives a floating point (or does integer division if you use Python 2 and don't <code>from __future__ import division</code>). </p>
<p>In the first case and in your original expression, Python evaluates <code... | 3 | 2016-09-06T19:22:06Z | [
"python",
"sympy",
"substitution",
"symbolic-math"
] |
python divide value by 0 | 39,333,631 | <p>I am trying to compare values in a table, it so happens that some might be zero and I therefore get an error message that I cannot divide by 0.
Why isn't the script returning inf instead of an error?
When I test this script on a dataframe with one column it works, with more than one column it breaks with the Zero Di... | 0 | 2016-09-05T15:21:56Z | 39,333,743 | <p>Looks like python has a specific <code>ZeroDivisionError</code>, you should use <code>try except</code> to do something else in that case.</p>
<pre><code>try:
table[change] = ['{0}%'.format(str(round(100*x,2)) for x in \
(table.ix[:,table.shape[1]-1] - table.ix[:,0]) / t... | 1 | 2016-09-05T15:29:39Z | [
"python",
"dataframe"
] |
python divide value by 0 | 39,333,631 | <p>I am trying to compare values in a table, it so happens that some might be zero and I therefore get an error message that I cannot divide by 0.
Why isn't the script returning inf instead of an error?
When I test this script on a dataframe with one column it works, with more than one column it breaks with the Zero Di... | 0 | 2016-09-05T15:21:56Z | 39,333,779 | <p>Dividing by zero is usually a serious error; defaulting to infinity would not be appropriate for most situations.</p>
<p>Before attempting to calculate the value, check if the divisor (<code>table.ix[:,0]</code> in this case) is equal to zero. If it is, then skip the calculation and just assign whatever value you ... | 1 | 2016-09-05T15:31:46Z | [
"python",
"dataframe"
] |
Not able to install modules using pip due to HTTPSHandler error Cygwin | 39,333,652 | <p>I was not being able to installed any module in the cygwin.</p>
<p>I have already:</p>
<ol>
<li>Removed and reinstalled Python</li>
<li>Removed and reinstalled openssl and openssl-devel</li>
</ol>
<p>However, the problems still happens?</p>
<pre><code> $ pip install iplib
Traceback (most recent call last):
... | 0 | 2016-09-05T15:23:29Z | 39,333,934 | <p>If reinstalling <code>virtaulenv</code> doesn't solve your problem, try installing OpenSSl(I do realize you've already reinstalled openssl but doesn't hurt to try it again): </p>
<pre><code>yum install openssl openssl-devel -y
</code></pre>
<p>See <a href="http://www.leonli.co.uk/blog/723/solve-python-importerror-... | 0 | 2016-09-05T15:43:22Z | [
"python",
"cygwin"
] |
remember me option in GAE python | 39,333,653 | <p>I am working on a project in which i am working on a signup/login module. I have implemented the sessions in webapp2 python successfully. Now i want to implement the remember me feature on login. I am unable to find anything which can help me. I do know that i have to set the age of session. But i do not know how. H... | 0 | 2016-09-05T15:23:35Z | 39,333,859 | <p>First in case you don't know the difference between sessions and cookies</p>
<blockquote>
<p>What is a <strong>Cookie</strong>? A cookie is a small piece of text stored on a
user's computer by their browser. Common uses for cookies are
authentication, storing of site preferences, shopping cart items, and
se... | 1 | 2016-09-05T15:36:42Z | [
"python",
"google-app-engine",
"webapp2"
] |
selenium server, selenium client, on an UBUNTU GUI server | 39,333,726 | <p>i have a <code>VPS</code> with <code>ubuntu 14.04 LTS</code> and with the desktop package installed, that mean I can launch firefox from a <code>ssh -X</code> session.
To make tests, I launched from my server the selenium standalone server jar <code>(selenium-server-standalone-3.0.0-beta3.jar)</code>
After launching... | 1 | 2016-09-05T15:28:46Z | 39,334,165 | <p>It seems you're trying <code>selenium 3</code> with latest firefox version. To support latest firefox with <code>selenium 3</code>, need to <a href="https://github.com/mozilla/geckodriver/releases" rel="nofollow">download latest <code>geckodriver</code> executable from this link</a> and extract it into you system at... | 0 | 2016-09-05T16:00:28Z | [
"java",
"python",
"selenium",
"ubuntu",
"ssh"
] |
Most efficient row multiplication with matrix in Pandas | 39,333,750 | <p>Suppose I have a matrix as such </p>
<pre><code>df = pd.DataFrame(randint(2,size=(3,9)))
df.values
array([[0, 1, 0, 1, 1, 1, 0, 1, 1],
[1, 0, 1, 1, 1, 1, 0, 0, 1],
[0, 0, 0, 1, 0, 0, 1, 1, 0]])
</code></pre>
<p>Again; each row in this example represents three 3D coordinates, that need to rotated by, ... | 3 | 2016-09-05T15:30:06Z | 39,338,683 | <p>This should never touch a dataframe until you are done with your transformations.</p>
<pre><code>a = np.array([
[0, 1, 0, 1, 1, 1, 0, 1, 1],
[1, 0, 1, 1, 1, 1, 0, 0, 1],
[0, 0, 0, 1, 0, 0, 1, 1, 0]
])
rotmat = np.array([
[ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00],
... | 2 | 2016-09-05T23:16:28Z | [
"python",
"pandas",
"numpy",
"matrix"
] |
Delete similar items that start the same from a list | 39,333,772 | <p>For example, I have this list:</p>
<pre><code>list = ["192.168.1.1", "0.1.2.3", "0.2.3.4", "192.168.1.2", "0.3.4.5", "192.168.1.3"]
</code></pre>
<p>How can I remove with a command all the items that start with <code>"0."</code>?</p>
| 1 | 2016-09-05T15:31:24Z | 39,333,810 | <p>You can filter the desired items in a list using a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> using <a href="https://docs.python.org/2/library/stdtypes.html#str.startswith" rel="nofollow"><code>str.startswith()</code></a> to check if a s... | 9 | 2016-09-05T15:33:36Z | [
"python",
"list",
"python-3.x"
] |
Delete similar items that start the same from a list | 39,333,772 | <p>For example, I have this list:</p>
<pre><code>list = ["192.168.1.1", "0.1.2.3", "0.2.3.4", "192.168.1.2", "0.3.4.5", "192.168.1.3"]
</code></pre>
<p>How can I remove with a command all the items that start with <code>"0."</code>?</p>
| 1 | 2016-09-05T15:31:24Z | 39,333,819 | <p>With <code>filter()</code>:</p>
<pre><code>lst = ["192.168.1.1", "0.1.2.3", "0.2.3.4", "192.168.1.2", "0.3.4.5, 192.168.1.3"]
new_lst = list(filter(lambda x: x if not x.startswith("0") else None, lst))
print(new_lst)
</code></pre>
| 1 | 2016-09-05T15:34:22Z | [
"python",
"list",
"python-3.x"
] |
Change decorator's parameter inside function | 39,333,804 | <p>I am using flask-breadcrumbs add-on for python flask web server,
but I think this is more general question of python decorator,</p>
<pre><code>@app.route('/dashboard')
@register_breadcrumb(app, '.', parameter)
def render_dashboard_page():
...
</code></pre>
<p>is it possible to set "parameter" from within the func... | 1 | 2016-09-05T15:33:19Z | 39,334,094 | <p>It's not possible to pass arguments to a function's decorator from inside the function, as the decorator executes before the function is defined. A guide on how decorators work can be found <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=240808" rel="nofollow">here</a> and <a href="http://www.artima.com/w... | 1 | 2016-09-05T15:55:41Z | [
"python",
"python-2.7",
"flask",
"breadcrumbs"
] |
Python overwriting and resizing list | 39,333,830 | <p>I want to create a list in python of a fixed size, let's so 3 to begin with. I have a method that writes data to this list every time the method is called, I want to add this to the list until the list is full, once the list is full it should start overwriting the data in the list in ascending order (e.g. starting w... | 2 | 2016-09-05T15:34:46Z | 39,334,153 | <p>This should do the trick. There are tons of prebuilt modules that have similar functionality but I thought it would be best if you could visualize the process!</p>
<pre><code>class SizedList(list):
def __init__(self, size):
list().__init__(self)
self.__size = size
self.__wrap_location = ... | 2 | 2016-09-05T15:59:36Z | [
"python",
"arrays",
"list"
] |
Python overwriting and resizing list | 39,333,830 | <p>I want to create a list in python of a fixed size, let's so 3 to begin with. I have a method that writes data to this list every time the method is called, I want to add this to the list until the list is full, once the list is full it should start overwriting the data in the list in ascending order (e.g. starting w... | 2 | 2016-09-05T15:34:46Z | 39,334,524 | <p>This simple solution should do:</p>
<pre><code>def add(l, item, max_len):
l.insert(0, item)
return l[:max_len]
l = ["banana", "peanut", "bicycle", "window"]
l = add(l, "monkey", 3)
print(newlist)
</code></pre>
<p>prints:</p>
<pre><code>> ['monkey', 'banana', 'peanut']
</code></pre>
<p>The the list t... | 2 | 2016-09-05T16:26:15Z | [
"python",
"arrays",
"list"
] |
Python overwriting and resizing list | 39,333,830 | <p>I want to create a list in python of a fixed size, let's so 3 to begin with. I have a method that writes data to this list every time the method is called, I want to add this to the list until the list is full, once the list is full it should start overwriting the data in the list in ascending order (e.g. starting w... | 2 | 2016-09-05T15:34:46Z | 39,344,849 | <p>Here is how I went about it in the end. I set a variable called length_list which was originally set at 3. </p>
<pre><code>def add_to_list():
if len(list) < length_list:
append
else:
del list[0]
self.add_to_list()
def increase_length():
length_list += 1
</code></pre>
| 0 | 2016-09-06T09:01:29Z | [
"python",
"arrays",
"list"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.