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 ways to work around it:</p> <ol> <li><p>set a timeout(e.g.0.5) for epoll.wait, and then queue.get_nowait until empty. in this way, cpu resource is wasted even if nothing to deal with. and it's not that real-time.</p></li> <li><p>use domain socket instead of queue, so that epoll can wait for both. in this way, sender has to convert the python-object to string/binary data to transfer (and receiver versa), which is boring.</p></li> </ol> <p>--- none of them satisfy me.</p> <p>i wonder if epoll can wait for Event? --so that i can event.set() after queue.put(). or</p> <p>Is there a good way to solve my problem?</p> <p>THANKS!</p>
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 according to <a href="http://www.espn.com/nhl/statistics/player/_/stat/points/sort/points/year/2015/seasontype/2" rel="nofollow">http://www.espn.com/nhl/statistics/player/_/stat/points/sort/points/year/2015/seasontype/2</a></p> <p>I want both the tables to have same column names. I am using python2 in spyder IDE.<br> When I run the code above, it gives me this error:</p> <pre><code>AttributeError: 'list' object has no attribute 'rename' </code></pre>
-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 (&mu;) changes the support of the distribution from x &ge; 0 to y = ( x - &mu; ) &ge; 0. If &mu; is positive then aren't we losing all the data which doesn't satisfy x - &mu; &ge; 0?</p> <p>Thanks!</p>
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 that generates data, <code>y1</code>, with <code>loc=2</code> and <code>scale=1</code> using numpy. It also adds noise to the data over the range 0 to 10 to create <code>y2</code>. Fitting <code>y1</code> yield excellent results, but attempting to fit the noisy <code>y2</code> is problematic. The noise we added smears out the distribution. However, we can also hold 1 or more parameters constant when fitting the data. In this case we pass <code>floc=2</code> to the <code>fit</code>, which forces the location to be held at <code>2</code> when performing the fit, returning much better results.</p> <pre><code>from scipy.stats import gamma import numpy as np import matplotlib.pyplot as plt x = np.arange(0,10,.1) y1 = np.random.gamma(shape=1, scale=1, size=1000) + 2 # sets loc = 2 y2 = np.hstack((y1, 10*np.random.rand(100))) # add noise from 0 to 10 # fit the distributions, get the PDF distribution using the parameters shape1, loc1, scale1 = gamma.fit(y1) g1 = gamma.pdf(x=x, a=shape1, loc=loc1, scale=scale1) shape2, loc2, scale2 = gamma.fit(y2) g2 = gamma.pdf(x=x, a=shape2, loc=loc2, scale=scale2) # again fit the distribution, but force loc=2 shape3, loc3, scale3 = gamma.fit(y2, floc=2) g3 = gamma.pdf(x=x, a=shape3, loc=loc3, scale=scale3) </code></pre> <p>And make some plots...</p> <pre><code># plot the distributions and fits. to lazy to do iteration today fig, axes = plt.subplots(1, 3, figsize=(13,4)) ax = axes[0] ax.hist(y1, bins=40, normed=True); ax.plot(x, g1, 'r-', linewidth=6, alpha=.6) ax.annotate(s='shape = %.3f\nloc = %.3f\nscale = %.3f' %(shape1, loc1, scale1), xy=(6,.2)) ax.set_title('gamma fit') ax = axes[1] ax.hist(y2, bins=40, normed=True); ax.plot(x, g2, 'r-', linewidth=6, alpha=.6) ax.annotate(s='shape = %.3f\nloc = %.3f\nscale = %.3f' %(shape2, loc2, scale2), xy=(6,.2)) ax.set_title('gamma fit with noise') ax = axes[2] ax.hist(y2, bins=40, normed=True); ax.plot(x, g3, 'r-', linewidth=6, alpha=.6) ax.annotate(s='shape = %.3f\nloc = %.3f\nscale = %.3f' %(shape3, loc3, scale3), xy=(6,.2)) ax.set_title('gamma fit w/ noise, location forced') </code></pre> <p><a href="http://i.stack.imgur.com/JoY9O.png" rel="nofollow"><img src="http://i.stack.imgur.com/JoY9O.png" alt="enter image description here"></a></p>
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 (internal reference to be auto increment) but not when I create a customer but when I click CONFIRM SALE button.</p> <p>Can someone help me with the Python code and .xml file how can I do that?</p> <p>It should be something like this but still is the thing I search:</p> <pre><code>@api.onchange('state', 'partner_id') def _onchange_partner(self): if self.partner_id: contact_id = self.partner_id.address_get().get('contact', False) if contact_id: contact = self.env['res.partner'].browse(contact_id) self.name = self.name or contact.name – </code></pre>
-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 (internal reference to be auto increment) but not when I create a customer but when I click CONFIRM SALE button.</p> <p>Can someone help me with the Python code and .xml file how can I do that?</p> <p>It should be something like this but still is the thing I search:</p> <pre><code>@api.onchange('state', 'partner_id') def _onchange_partner(self): if self.partner_id: contact_id = self.partner_id.address_get().get('contact', False) if contact_id: contact = self.env['res.partner'].browse(contact_id) self.name = self.name or contact.name – </code></pre>
-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): import logging _logger = logging.getLogger(__name__) _logger.info("OVERRIDING action_confirm()") _logger.info("CURRENT INT REF: " + str(self.internal_reference)) self.write({'internal_reference':self.internal_reference+1}) _logger.info("NEW INT REF: " + str(self.internal_reference)) return super(SaleOrder, self).action_confirm() </code></pre>
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, 'purchase_order_type' : self.order_type, 'date_order' : self.date_order, 'product_id' : self.product_id, 'date_planned' : self.date_order, 'product_qty' : self.name, 'brand_id' : self.brand_id, 'product_id' : self.product_id, 'part_number': self.part_number, 'date_planned' : self.date_order, 'product_qty' : self.quantity_no, }) return rec </code></pre> <p>Access through button..</p>
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, 'store_id' : self.store_id, 'purchase_order_type' : self.order_type, 'date_order' : self.date_order, 'product_id' : self.product_id, 'date_planned' : self.date_order, 'product_qty' : self.name, 'brand_id' : self.brand_id, 'part_number': self.part_number, }) return rec </code></pre> <p>from the <a href="https://www.odoo.com/documentation/8.0/reference/orm.html#module-openerp.api" rel="nofollow">docs</a></p> <blockquote> <p>openerp.api.multi(method)</p> <p>Decorate a record-style method where self is a recordset. The method typically defines an operation on records.</p> <p>openerp.api.model(method)</p> <p>Decorate a record-style method where self is a recordset, but its contents is not relevant, only the model is.</p> </blockquote>
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 = &lt;large read-only global dictionary to be shared&gt; jobs = [] for x in X: jobs.append((x,y,z,)) pool = MP.Pool(processes=16) pool.map(myFunction,jobs) pool.close() pool.join() </code></pre> <p>Sixteen processes are started as seen in <code>htop</code>, however no errors are returned, no files written, no CPU is used.</p> <p>Could it happen that there is an error in myFunction that is not reported to STDOUT and blocks execution?</p> <p>Perhaps it is relevant that the python script is called from a bash script running in background.</p>
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 on for the entire day. I would like to convert them to UTC datetime which, in the end, should look something like this:</p> <pre><code>2016-10-30 00:00:00 + 02:00 2016-10-30 01:00:00 + 02:00 2016-10-30 02:00:00 + 02:00 2016-10-30 02:00:00 + 01:00 2016-10-30 03:00:00 + 01:00 2016-10-30 04:00:00 + 01:00 </code></pre> <p>I used the following code to convert the timezones, but I get something that looks like this instead.</p> <pre><code>2016-10-30 00:00:00 + 02:00 2016-10-30 01:00:00 + 02:00 2016-10-30 02:00:00 + 02:00 2016-10-30 02:00:00 + 02:00 2016-10-30 03:00:00 + 01:00 2016-10-30 04:00:00 + 01:00 </code></pre> <p>The dates actually come from an Excel, but at the moment I am trying this to check if the conversion is correct. </p> <pre><code>import pytz import datetime from pytz.reference import UTC european = pytz.timezone('Europe/Berlin') startdate = datetime.datetime(2016,10,30,0,0,0) hours = [] for i in range(3): hours.append(startdate + datetime.timedelta(hours = i)) hours.append(hours[2]) for i in range(3,24): hours.append(startdate + datetime.timedelta(hours = i)) for i in range(len(hours)): hours[i] = european.localize(hours[i], is_dst = True) hours[i] = hours[i].astimezone(UTC) hours[i] = european.normalize(hours[i].astimezone(european)) print(hours[i]) </code></pre> <p>Update: Edited to make the question more clearer; hopefully<br> Update: Edited the time values in the code</p>
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 appear to be wanting the same input value to give a different output value the second time you call it... look here at your input:</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) </code></pre> <p>Lines 3 and 4 are the same. But you expect output of:</p> <pre><code>2016-10-30 00:00:00 + 02:00 2016-10-30 01:00:00 + 02:00 2016-10-30 02:00:00 + 02:00 2016-10-30 02:00:00 + 01:00 </code></pre> <p>Now lines 3 and 4 are different.</p> <p>The only way I can see for that to work is to detect that you've just tried the same value, and this time pass <code>is_dst = False</code>. Fundamentally, you shouldn't expect to run the same code on the same input and it to psychically work out whether you really "meant" DST this time or not.</p> <p>If you're genuinely running through all the hours of a day, then just work out the start time of the day in UTC and add an hour to <em>that</em> each time. Fundamentally, converting a local time to UTC is problematic precisely because of the potential for ambiguous local times (around the "fall back") and skipped local times (around the "spring forward").</p> <p>Your question has changed several times so it's not <em>really</em> clear what your input data is (something to do with Excel, but quite possibly not the values you've shown us) but you need to work out what you want to do with a given local time... the <code>is_dst</code> flag allows you to express a preference for or against DST, but you can't expect <code>pytz</code> to know more about your context than you do.</p>
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</p> <pre><code> import subprocess cmd = ['instruments', '-s', 'devices'] response = subprocess.Popen(cmd,stdout=subprocess.PIPE) print response.communicate() </code></pre> <p>My terminal screen looks as below when I run the above python command</p> <pre><code>MacBook-Pro-9:lib darren$ python iOSRemoteLib.py 2016-09-05 14:30:38.648 instruments[21276:1052546] WebKit Threading Violation - initial use of WebKit from a secondary thread. </code></pre> <p>The python process gets hung up and not returning any response. Looks like some threading issue and I am not able to figure out what.</p> <p>Thanks </p>
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 permission issue. </p>
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'({[^{]*(?&gt;{[^{}]+})*)\s\\over\s([^{}]+(?&gt;{[^{}]*})*})') string1 = "{a \over b}" string2 = "{x \over b{x}} {{d}d \over x}}" m = regex.match(gr,string2) reLine = regex.sub(gr,r"\\test"+m.group(1)+"}{"+m.group(2),string2) </code></pre> <p>The objective is basically this:</p> <pre><code>before {a \over b} after \test{a}{b} </code></pre> <p>And I have to look through the text file and replace all these matches.</p> <p>My problem is with regex.search or regex.match it only matches once and returns one match with its groups, but I need multiple matches in case {a \over b} repeats multiple times on the same line.</p> <p>So with 'string2' it captures '{x' as the first group, 'b{x}}' as the second, and stops capturing. So then when I try to replace, it replaces the groups of the first match with the second '\over' equation as well.</p> <p>I have practiced regular expressions on regexr.com and it has a 'replace' function. It takes all the matches and replaces ($1,$2) all the matches and groups respectively.</p> <p>Am I missing something on python regex module? Or is this problem more complicated than I imagined?</p> <p>Thanks. </p>
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> <pre><code>e = Employee() e.profile_link = ... ... e.save() models.py: from django.db import models class Employee(models.Model): profile_link = models.TextField(primary_key=True) ... </code></pre>
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.createWidgets() def createWidgets(self): self.recording = False self.recButton = tk.Button(self, text='Record', command=self.clicked, relief=tk.SUNKEN) self.recButton.grid() self.quitButton = tk.Button(self, text='Quit', command=self.quit) self.quitButton.grid() def clicked(self): self.recording = not self.recording if self.recording: self.recButton.config(relief=tk.RAISED) else: self.recButton.config(relief=tk.SUNKEN) app = Application() app.master.title('Stateful Button') app.mainloop() </code></pre>
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'] = '****' br.submit() print br.response().read() </code></pre> <p>At the moment this scrapes a web page and returns the resources, but not the actual html of the page (content and such). How do I change it so that I can get the html instead? </p>
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.select_form(nr=0) br.form['ctl00$BodyContent$Username'] = '****' br.form['ctl00$BodyContent$Password'] = '****' br.submit() soup = BeautifulSoup(br.response().read()) print soup or for row in soup: print row </code></pre>
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 most suitable for this. Can you please recommend something?</p>
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: 'PTR', 13: 'HINFO',14: 'MINFO',15: 'MX',16: 'TXT',17: 'RP',18: 'AFSDB', 28: 'AAAA', 33: 'SRV',38: 'A6',39: 'DNAME'} dns_packets = rdpcap('file.pcap') for packet in dns_packets: if packet.haslayer(DNS): print(packet.show()) dst = packet[IP].dst rec_type = packet[DNSQR].qtype print(dst, types[rec_type]) </code></pre> <p>Example of output:</p> <pre><code>###[ Ethernet ]### dst = 00:16:e3:19:27:15 src = 00:04:76:96:7b:da type = 0x800 ###[ IP ]### version = 4L ihl = 5L tos = 0x0 len = 70 id = 0 flags = DF frag = 0L ttl = 64 proto = udp chksum = 0xb753 src = 192.168.1.2 dst = 192.168.1.1 \options \ ###[ UDP ]### sport = 2128 dport = domain len = 50 chksum = 0x8397 ###[ DNS ]### id = 12575 qr = 0L opcode = QUERY aa = 0L tc = 0L rd = 1L ra = 0L z = 0L ad = 0L cd = 0L rcode = ok qdcount = 1 ancount = 0 nscount = 0 arcount = 0 \qd \ |###[ DNS Question Record ]### | qname = '2.1.168.192.in-addr.arpa.' | qtype = PTR | qclass = IN an = None ns = None ar = None ('192.168.1.1', 'PTR') </code></pre> <p>The last line is the outgoing IP address and the record type. There is a bunch of data, just select what you need.</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, marker='.',markersize=8, title ="test", fontsize = 10, color=['b','g','g'], figsize=(8, 22)) imagepath = 'capture.png' plt.savefig(imagepath) </code></pre> <p>An example of the graph generated is:</p> <p><a href="http://i.stack.imgur.com/ZBKEP.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZBKEP.png" alt="enter image description here"></a></p> <p>Any idea why this is happening? Thanks a lot.</p>
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. However, you can fix that using the last line below.</p> <pre><code>ax = df.plot(subplots=True, marker='.', markersize=8, title ="test", fontsize = 10, color=['b','g','g'], figsize=(8, 22))[0] fig = ax.get_figure() fig.tight_layout() fig.subplots_adjust(top=0.95) </code></pre>
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 is missing and the code above will log to the webpage.</p> <p>I can not find the release note or changelog of 4.1.1.</p> <p>How can I log into console in the latest version of jupyter notebook?</p>
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 with this block </code></pre> <p>Now, this is hard coded for a 2-dimensional array and I would like to extend this to 3D and 4D arrays. I could, of course, write more functions for other dimensions but I was wondering if there is a python/numpy trick to generate these sub-blocks without having to replicate this function for multidimensional data.</p>
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 of length 4. </p> <p>To get the sub-arrays, you just need to iterate over the different tuples of slice objects and pass them to the array.</p> <pre><code>import numpy as np from itertools import product def iterslice(data_shape, width): # check for invalid width assert(all(sh&gt;=width for sh in data_shape), 'all axes lengths must be at least equal to width') # gather all allowed starting indices for the data shape start_indices = [range(sh-width+1) for sh in data_shape] # create tuples of all allowed starting indices start_coords = product(*start_indices) # iterate over tuples of slice objects that have the same dimension # as data_shape, to be passed to the vector for start_coord in start_coords: yield tuple(slice(coord, coord+width) for coord in start_coord) # create 5x5x5 array arr = np.arange(0,5**3).reshape(5,5,5) # create the data slice tuple iterator for 3x3x3 sub-arrays data_slices = iterslice(arr.shape, 3) # the sub-arrays are a list of 3x3x3 arrays, in this case sub_arrays = [arr[ds] for ds in data_slices] </code></pre>
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>&lt;root&gt; &lt;p&gt;nodea text 1&lt;/p&gt; &lt;p&gt;nodea text 2&lt;/p&gt; &lt;nodea&gt; &lt;/nodea&gt; &lt;p&gt;nodeb text 1&lt;/p&gt; &lt;p&gt;nodeb text 2&lt;/p&gt; &lt;nodeb&gt; &lt;/nodeb&gt; &lt;/root&gt; </code></pre> <p>I want to get the first preceding sibling p tag of nodea or nodeb if there is one. For example for the above xml the preceding siblings for respective node are </p> <p><strong>nodea</strong> preceding siblings</p> <pre><code>&lt;p&gt;nodea text 1&lt;/p&gt; &lt;p&gt;nodea text 2&lt;/p&gt; </code></pre> <p><strong>nodeb</strong> preceding siblings</p> <pre><code>&lt;p&gt;nodeb text 1&lt;/p&gt; &lt;p&gt;nodeb text 2&lt;/p&gt; </code></pre> <p>i have tried the below xpath but it gives me the preceding p tag of nodea instead of nodeb.</p> <pre><code>nodeb = xml.find('nodeb') nodeb.xpath('preceding-sibling::p[not(preceding-sibling::nodea)][1]') </code></pre> <p>If there is no preceding p tag before the node then it should return empty list. For example for the below xml there are no preceding sibling p tags for nodeb.</p> <pre><code>&lt;root&gt; &lt;p&gt;nodea text 1&lt;/p&gt; &lt;nodea&gt; &lt;/nodea&gt; &lt;nodeb&gt; &lt;/nodeb&gt; &lt;/root&gt; </code></pre> <p>It would be nice if someone can also explain why my xpath is not working and what should i keep in mind when writing xpath?</p>
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 to look at the sibling <code>p</code>s that are between the <code>nodeb</code> and the <code>nodea</code> element. Your condition <code>preceding-sibling::p[not(preceding-sibling::nodea)][1]</code> indeed selects <code>p</code> siblings that don't have a preceding <code>nodea</code> sibling and these are the first two <code>p</code> elements in document order.</p>
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/bin/python import ast def is_valid_python(code): try: ast.parse(code) except SyntaxError: return str(SyntaxError.message) return True code = 'print("hello"")' print(is_valid_python(code)) </code></pre> <p>and the message printed is: </p> <pre><code>&lt;attribute 'message' of 'exceptions.BaseException' objects&gt; </code></pre>
-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 string on failure.</p>
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>&lt;table id="tblData" style="width: 100% !important;" class="display table table-bordered table-striped table-condensed"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th style="display: none"&gt;Item ID&lt;/th&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Supplier Code&lt;/th&gt; &lt;th&gt;Location Code&lt;/th&gt; &lt;th&gt;Part Number&lt;/th&gt; &lt;th&gt;Part Group&lt;/th&gt; &lt;th&gt;Unit Price&lt;/th&gt; &lt;th&gt;Currency&lt;/th&gt; &lt;th style="display: none"&gt;Location ID&lt;/th&gt; &lt;th style="display: none"&gt;Currency ID&lt;/th&gt; &lt;th style="display: none;"&gt;Line ID&lt;/th&gt; &lt;th style="display: none;"&gt;UOM&lt;/th&gt; &lt;th style="display: none;"&gt;Supplier ID&lt;/th&gt; &lt;th&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; {% if items_list %} &lt;tbody&gt; {% for i in items_list %} &lt;tr class="gradeX" id="{{ i.line_id }}"&gt; &lt;td style="text-align: right; display: none;"&gt;{{ i.item_id }}&lt;/td&gt; &lt;td style="text-align: left"&gt;{{ i.item_name }}&lt;/td&gt; &lt;td style="text-align: left"&gt;{{ i.supplier_code }}&lt;/td&gt; &lt;td style="text-align: left"&gt;{{ i.location_code }}&lt;/td&gt; &lt;td style="text-align: left"&gt;{{ i.part_no }}&lt;/td&gt; &lt;td style="text-align: right;"&gt;{{ i.part_gp }}&lt;/td&gt; &lt;td style="text-align: left"&gt;{{ i.sales_price }}&lt;/td&gt; &lt;td style="text-align: left;"&gt;{{ i.currency }}&lt;/td&gt; &lt;td style="text-align: right; display: none;"&gt;{{ i.location_id }}&lt;/td&gt; &lt;td style="text-align: right; display: none"&gt;{{ i.currency_id }}&lt;/td&gt; &lt;td style="text-align: right; display: none"&gt;{{ i.line_id }}&lt;/td&gt; &lt;td style="text-align: right; display: none"&gt;{{ i.uom }}&lt;/td&gt; &lt;td style="text-align: right; display: none"&gt;{{ i.supplier_id }}&lt;/td&gt; &lt;td&gt;&lt;input type="checkbox" name="choices" id="{{ i.line_id }}" class="call-checkbox" value="{{ i.sales_price }}"&gt;&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/tbody&gt; {% endif %} &lt;/table&gt; </code></pre> <p>In my main page, I include the customer items page inside it:</p> <pre><code>&lt;div class="adv-table" id="myTable"&gt; {% include 'customer_items.html' %} &lt;/div&gt; </code></pre> <p>I used ajax to update items_list after change customer event run:</p> <pre><code>function customer_items(hdCustomerId) { $.ajax({ method: "POST", url: '/orders/change_customer_items/', data: { 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(), 'customer_id': hdCustomerId, }, responseTime: 200, response: function (settings) { if (settings.data.value) { this.responseText = '{"success": true}'; } else { this.responseText = '{"success": false, "msg": "required"}'; } }, success: function (data) { debugger; console.log(data); $('#myTable').html('').load(data); } }); } </code></pre> <p>But when I change customer the table still empty although the new items_list has data.</p> <pre><code>views.py: def customer_items(request): if request.method == 'POST': if request.is_ajax(): customer_id = request.POST.get('customer_id') items_list = CustomerItem.objects.filter(customer_id=customer_id).values() \ .annotate(supplier_code=F('item__supplieritem__supplier__code')) \ .annotate(supplier_id=F('item__supplieritem__supplier')) \ .annotate(location_code=F('customer__company__location__code')) \ .annotate(location_id=F('customer__company__location__id')) \ .annotate(custome_name=F('customer__name')) \ .annotate(item_id=F('item_id')) \ .annotate(item_name=F('item__name')) \ .annotate(part_no=F('item__part_no')) \ .annotate(part_gp=F('item__part_gp')) \ .annotate(uom=F('item__sales_measure__name')) \ .annotate(currency=F('currency__code')) \ .annotate(currency_id=F('currency_id')) \ .annotate(line_id=Value(0, output_field=models.CharField())) for i, j in enumerate(items_list): if (i &lt; items_list.__len__()): i += 1 j['line_id'] = i return render(request, 'customer_items.html', {'items_list': items_list}) urls.py: url(r'^change_customer_items/$', views.customer_items, name='change_customer_items'), </code></pre> <p>How can I run the load function after the ajax call successfully in the ajax to fill data to my table. Please help me!</p>
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 == 0: array.remove(i) array.append(i) answer = array print answer </code></pre> <p><code>move_zeros(["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9])</code></p> <p>This is what it returns when you run it.</p> <pre><code>['a', 'b', None, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, False, 0, 0, False, 0, 0] </code></pre>
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 == 0: array.remove(i) array.append(i) answer = array print answer </code></pre> <p><code>move_zeros(["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9])</code></p> <p>This is what it returns when you run it.</p> <pre><code>['a', 'b', None, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, False, 0, 0, False, 0, 0] </code></pre>
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 False values at the left (because they are like 0), and the True values at the right (like 1).</p> <hr> <p>Originally I had written a solution which is not supported in Python 3:</p> <pre><code>array.sort(lambda L,R: -1 if R is 0 else 0) </code></pre> <p>What this means is "L is less than R if R is 0". Then we sort according to that. So we end up with any zeros on the right, because anything is less than them. The above only works in Python 2, however.</p>
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 == 0: array.remove(i) array.append(i) answer = array print answer </code></pre> <p><code>move_zeros(["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9])</code></p> <p>This is what it returns when you run it.</p> <pre><code>['a', 'b', None, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, False, 0, 0, False, 0, 0] </code></pre>
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>&gt;&gt;&gt; l = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9] &gt;&gt;&gt; [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, False, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] </code></pre> <p>EDIT: This is worse than the <code>sorted</code> solutions, both less elegant and requires iterating over the list twice.</p>
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 == 0: array.remove(i) array.append(i) answer = array print answer </code></pre> <p><code>move_zeros(["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9])</code></p> <p>This is what it returns when you run it.</p> <pre><code>['a', 'b', None, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, False, 0, 0, False, 0, 0] </code></pre>
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 == 0: array.remove(i) array.append(i) answer = array print answer </code></pre> <p><code>move_zeros(["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9])</code></p> <p>This is what it returns when you run it.</p> <pre><code>['a', 'b', None, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, False, 0, 0, False, 0, 0] </code></pre>
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 answer </code></pre>
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 == 0: array.remove(i) array.append(i) answer = array print answer </code></pre> <p><code>move_zeros(["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9])</code></p> <p>This is what it returns when you run it.</p> <pre><code>['a', 'b', None, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, False, 0, 0, False, 0, 0] </code></pre>
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 faster.</p> <p>Actually you could also do</p> <pre><code>sorted_array=[] zeroes=0 for e in array: if e==0 and e is not False: zeroes+=1 else: sorted_array.append(e) sorted_array.extend([0]*zeroes) </code></pre> <p>which in theory should be less work but is propably much slower in practice</p>
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 == 0: array.remove(i) array.append(i) answer = array print answer </code></pre> <p><code>move_zeros(["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9])</code></p> <p>This is what it returns when you run it.</p> <pre><code>['a', 'b', None, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, False, 0, 0, False, 0, 0] </code></pre>
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, 'False', so it will not be affected by your sort.</p> <p>my_list=["a",0,0,"b",None,"c","d",0,1,'False',0,1,0,3,[],0,1,9,0,0,{},0,0,9]</p> <p>When you need to use it as boolean just cast it as bool:</p> <pre><code>false = False print type(false) //output is &lt;type 'bool'&gt; </code></pre>
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 == 0: array.remove(i) array.append(i) answer = array print answer </code></pre> <p><code>move_zeros(["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9])</code></p> <p>This is what it returns when you run it.</p> <pre><code>['a', 'b', None, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, False, 0, 0, False, 0, 0] </code></pre>
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 item in array: if not item and type(item) is int: # int 0 zeros += 1 else: if zeros: array[dest] = item dest += 1 array[-zeros:] = [0] * zeros inn = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9] move_zeros(inn) print(inn) # ['a', 'b', None, 'c', 'd', 1, False, 1, 3, [], 1, 9, {}, 9, # 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] </code></pre>
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 value is equal to previous one add an evaluation value to product array 2) When current product id is not equal to previous one - create a new product array. </p> <p>I'm using openpyxl to get an access to xlsx files. But my loop is not working incorrect, going infinitely. </p> <pre><code>import openpyxl import os import glob from openpyxl import load_workbook from openpyxl import Workbook file = load_workbook("Snippet_output.xlsx") work_sheet = file.active for row_num in range (3, 28): query = str(work_sheet.cell(row = row_num, column= 6).value) query_prev = str(work_sheet.cell(row = row_num-1, column= 6).value) evaluation = str(work_sheet.cell(row = row_num, column= 9).value) eval_list = [] while True: eval_list.append(evaluation) if query == query_prev: break print(eval_list) </code></pre> <p>Can you help me with a loop My output should look like, eval_list1 = [3,2,1,2,3,2,1,2,3,1] eval_list2 = [1,3,2,1,2,3,2,3,1,1] etc</p>
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=6).value) current_result = str(work_sheet.cell(row=row_num, column=9).value) if current_id == previous_id: eval_lost.append(current_result) # same ID, continue appending else: print (eval_list) # different ID, print previous list eval_list = [] # start new empty list for next ID previous_id = current_id # update for next iteration print (eval_list) # </code></pre> <p>N.b. your question did not specify python2 or python3, use parenthesis in prints according to python version.</p> <p>Good luck!</p>
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 was thinking of, when binding the socket catch this error and if error is thrown restart the context and the socket. This is not working, is still throws and error when binding. Server code:</p> <pre><code>class ZMQServer: context = None socket = None def __init__(self, port): self.context = zmq.Context() self.socket = self.context.socket(zmq.REP) try: self.socket.bind("tcp://*:"+str(port)) except zmq.error.ZMQError: print ("socket already in use, restarting") self.socket.close() self.context.destroy() self.context = zmq.Context() self.socket = self.context.socket(zmq.REP) self.socket.bind("tcp://*:"+str(port)) </code></pre>
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 and display it, I didn;t find a way to fix the blocked socked there.<br></p></li> <li><p>The recv method that receives the messages is NON-blocking</p></li> </ul> <p>So, the code now looks like this:</p> <p>"</p> <pre><code>import time import zmq import threading class ZMQServer: context = None socket = None alive = False ZMQthread = None def __init__(self, port): self.context = zmq.Context() self.socket = self.context.socket(zmq.REP) try: self.socket.bind("tcp://*:"+str(port)) except zmq.error.ZMQError: print ("socket already in use, try restarting it") self.alive = False self.alive = True def StartAsync(self): self.alive = True ZMQthread = threading.Thread(target=self.Start) ZMQthread.start() def Start(self): while self.alive == True: # Wait for next request from client print("Wait for next request from client") try: message = self.socket.recv(zmq.NOBLOCK) print("Received request: %s" % message) # Do some 'work' time.sleep(1) # Send reply back to client self.socket.send(b"World") except: print "no message received in time. trying again" def CloseServer(self): print("Stoping the server") self.alive = False if(self.socket.closed == False): self.socket.close() if self.ZMQthread and self.ZMQthread.is_alive() == True: self.ZMQthread.join() if __name__ == '__main__': zmqServer = ZMQServer(5555) zmqServer.StartAsync() time.sleep(20) zmqServer.CloseServer() </code></pre>
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> for <code>Firefox</code> driver. </p> <p>Below are the codes that I have used.</p> <pre><code>browser1.find_element_by_xpath("path").send_keys(u'\ue007') browser1.find_element_by_xpath("path").send_keys(Keys.ENTER) </code></pre>
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 42196000013 000001 - 287Véh 1 11/07/2015 08:17:09 11/07/2015 08:17:13 Matin 42196000002 000314 + 263Véh 1 11/07/2015 09:37:43 11/07/2015 09:53:37 Matin 42196000016 002372 + 287Véh 1 11/07/2015 09:46:42 11/07/2015 10:01:39 Matin 42196000015 000466 + 287Véh 1 11/07/2015 09:46:42 11/07/2015 10:01:39 Matin 42196000002 000314 - 263Véh 1 11/07/2015 10:25:17 11/07/2015 10:38:11 Matin 42196000015 000466 - 287Véh 1 11/07/2015 10:48:51 11/07/2015 10:51:30 Matin 42196000016 002372 - 287Véh 1 11/07/2015 11:40:56 11/07/2015 11:41:01 Matin 42196000004 002641 + 263Véh 1 11/07/2015 13:39:29 11/07/2015 13:52:50 Soir 42196000004 002641 - 263Véh 1 11/07/2015 13:59:56 11/07/2015 14:07:41 Soir </code></pre> <p>I need to get the marge between column <code>HeureArriveeSurSite</code> and <code>HeureEffective</code>,and they are already <code>datetime.datetime()</code> data.</p> <p>And here is a new <code>DataFrame</code> called <code>df1</code>.</p> <pre><code>df1 = df_NoMissing_IDV[(df_NoMissing_IDV['Sens'] == '+') &amp; (df_NoMissing_IDV['Periods'] == 'Matin')] </code></pre> <p>And <code>df1</code> looks like this:</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 42196000002 000314 + 263Véh 1 11/07/2015 09:37:43 11/07/2015 09:53:37 Matin 42196000016 002372 + 287Véh 1 11/07/2015 09:46:42 11/07/2015 10:01:39 Matin 42196000015 000466 + 287Véh 1 11/07/2015 09:46:42 11/07/2015 10:01:39 Matin </code></pre> <p>Since they all are <code>datetime.datetime()</code> data, I tried to do the subtraction directly with:</p> <pre><code>df_NoMissing_IDV['DureeService'] = df1['HeureEffective']-df1['HeureArriveeSurSite'] </code></pre> <p>But it returned <code>TypeError: unsupported operand type(s) for -: 'unicode' and 'unicode'</code></p> <p>And I also tried to do the calculation with <code>datetime.time()</code> type, and it returned with <code>TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'</code> What should I do with it?</p> <p><strong>EDIT</strong></p> <p>I convert columns in <code>df1</code> to <code>datetime()</code>:</p> <pre><code>df1.HeureArriveeSurSite = pd.to_datetime(df1.HeureArriveeSurSite) df1.HeureEffective = pd.to_datetime(df1.HeureEffective) </code></pre> <p>But the next step is still wrong which returned: <code>ValueError: cannot reindex from a duplicate axis</code></p> <p>And if I convert columns in <code>df_NoMissing_IDV</code> to <code>datetime()</code>:</p> <pre><code>df_NoMissing_IDV.HeureArriveeSurSite = pd.to_datetime(df_NoMissing_IDV.HeureArriveeSurSite) df_NoMissing_IDV.HeureEffective = pd.to_datetime(df_NoMissing_IDV.HeureEffective) </code></pre> <p>The same problem remains.</p> <p>Any help will be appreciated~</p>
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>EDIT:</strong> What you can also try is <code>timedelta</code>:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; time_difference = df1['HeureEffective']-df1['HeureArriveeSurSite'] &gt;&gt;&gt; time_difference_in_seconds = time_difference / timedelta(seconds=1) </code></pre>
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='application/json') </code></pre> <p>better than this:</p> <pre><code>@login_required def remove_photo(request): if request.is_ajax(): BirdPhoto.objects.get( pk = request.POST.get('image_id') ).delete() return HttpResponse(json.dumps({'msg':'success'}), content_type='application/json') </code></pre> <p>? I have to admit, I don't pay as much attention to error handling and testing as I should. So I just wrote this new function, and I was thinking I should make sure I am handling the errors. Once I kind of got to the basic level of handling errors, I looked at it and said to myself: this isn't really doing anything. It seems to me the two functions will act the same way. This is django, so in production environment the server should catch this and just return a general http response. Am I OK leaving it as the 4 line version and instead of the 6 line version?</p>
-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="nofollow"><code>get_object_or_404</code></a> is the most suitable solution:</p> <pre><code>@login_required def remove_photo(request): if request.is_ajax(): get_object_or_404(BirdPhoto, pk=request.POST.get('image_id')).delete() return HttpResponse(json.dumps({'msg':'success'}), content_type='application/json') </code></pre>
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='application/json') </code></pre> <p>better than this:</p> <pre><code>@login_required def remove_photo(request): if request.is_ajax(): BirdPhoto.objects.get( pk = request.POST.get('image_id') ).delete() return HttpResponse(json.dumps({'msg':'success'}), content_type='application/json') </code></pre> <p>? I have to admit, I don't pay as much attention to error handling and testing as I should. So I just wrote this new function, and I was thinking I should make sure I am handling the errors. Once I kind of got to the basic level of handling errors, I looked at it and said to myself: this isn't really doing anything. It seems to me the two functions will act the same way. This is django, so in production environment the server should catch this and just return a general http response. Am I OK leaving it as the 4 line version and instead of the 6 line version?</p>
-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, and raise a useless <code>Exception</code> with no error message. </p> <p>The first rule of exception handling is <em>be specific</em>. You should catch specific exceptions that you know might occur, and specifically handle the error case the way you want. In this case, you know that the id can be invalid, and <code>BirdPhoto.objects.get()</code> might raise a <code>BirdPhoto.DoesNotExist</code> exception. You should catch that exception specifically, and handle it appropriately -- for example by returning a response with status code 404:</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 BirdPhoto.DoesNotExist: return HttpResponse(json.dumps({'msg': 'error'}), status=404, content_type='application/json') return HttpResponse(json.dumps({'msg':'success'}), content_type='application/json') </code></pre> <p>Now if the code raises an exception that you did not expect, a <code>500 Internal Server Error</code> will be returned, and the debug view or logfiles will show the exact error message. You can then fix your code, or if the exception is to be expected, handle the exception appropriately. </p>
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_week'] == 'Tues') | (data['day_of_week'] == 'Wed') | (data['day_of_week'] == 'Thurs') | (data['day_of_week'] == 'Friday'), '1', '0') </code></pre> <p>This code will assign Mon-Fri as a <code>1</code> and Sat-Sun as a <code>0</code>. However, I would like to assign different values for the weekdays. For instance, Mon = 1, Tues = 2, Wed = 3, Thurs = 4, Fri = 5 and Sat and Sun should both equal 0.</p> <p>Any help would be much appreciated. </p>
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'] &gt;= 5, 0, df['weekday'] + 1) df Out[21]: dates weekday is_weekday 0 2016-01-01 4 5 1 2016-01-02 5 0 2 2016-01-03 6 0 3 2016-01-04 0 1 4 2016-01-05 1 2 5 2016-01-06 2 3 6 2016-01-07 3 4 7 2016-01-08 4 5 8 2016-01-09 5 0 9 2016-01-10 6 0 </code></pre>
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_week'] == 'Tues') | (data['day_of_week'] == 'Wed') | (data['day_of_week'] == 'Thurs') | (data['day_of_week'] == 'Friday'), '1', '0') </code></pre> <p>This code will assign Mon-Fri as a <code>1</code> and Sat-Sun as a <code>0</code>. However, I would like to assign different values for the weekdays. For instance, Mon = 1, Tues = 2, Wed = 3, Thurs = 4, Fri = 5 and Sat and Sun should both equal 0.</p> <p>Any help would be much appreciated. </p>
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 days = {0:'Mon', 1: 'Tues', 2:'Wed', 3:'Thurs', 4:'Fri', 5:'Sat', 6:'Sun'} data['day_of_week'] = data['day_of_week'].map(days) #correct weekend days data['if_Weekday'] = data['if_Weekday'].mask(data['if_Weekday'] &gt;= 6, 0) print (data) day_of_week if_Weekday 0 Mon 1 1 Tues 2 2 Wed 3 3 Thurs 4 4 Fri 5 5 Sat 0 6 Sun 0 </code></pre>
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 immediately without any conversion.</p> <p>If device sending <em>Binary encoded HEX string</em>, script should has to convert <em>Binary encoded Hex string</em> into <em>Hex string</em> first with;</p> <pre><code>data = binascii.hexlify(data) </code></pre> <p>There are two scripts running for different data types for that simple single line. But, I think this could be done in one script if script be aware of the incoming data type. Is there a way to discover type of the incoming socket data in Python?</p>
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="nofollow">XML-RPC</a></p> <p>Actually you can only be sure in <em>some</em> cases as all hex-encoded strings are valid ascii and some ascii-strings are valid hex like <code>"CAFE"</code>. You can make sure you can decode a string as hex with</p> <pre><code>import string def is_possibly_hex(s): return all(c in string.hexdigits for c in s) </code></pre> <p>or</p> <pre><code>import binascii def is_possibly_hex(s): try: binascii.unhexlify(s) except binascii.Error: return False return True </code></pre>
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['entries']) for post in d.entries: print post.title + ": " </code></pre>
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://www.jworks.nl/2013/11/07/python-goodness-the-in-keyword/</a></p> <pre><code>myword = "NASA" for post in d.entries: if myword in post.title: print post.title </code></pre>
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 20160831,CTC,,201711,10 20160831,CTC,,201712,10 20160831,CTC,Total,,385 20160831,HTC,,201701,30 20160831,HTC,,201702,30 . . </code></pre> <p>I want to fetch the row that contains 'Total' from each file. The new file should look like:</p> <pre><code>business_day,commodity,total,total_lots 20160831,CTC,Total,385 20160901,CTC,Total,555 . . </code></pre> <p>The raw files on my disk are named '20160831_foo.CSV', '20160901_foo.CSV etc..</p> <p>After Googling this I have yet not seen any examples on how to extract only one value from a CSV file. Any hints/help much appreciated. Happy to use pandas if that makes life easier. </p>
-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 then passing it onto a <a href="http://pandas.pydata.org/" rel="nofollow">pandas Dataframe</a> that will simplify your data manipulations a lot.</p>
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 20160831,CTC,,201711,10 20160831,CTC,,201712,10 20160831,CTC,Total,,385 20160831,HTC,,201701,30 20160831,HTC,,201702,30 . . </code></pre> <p>I want to fetch the row that contains 'Total' from each file. The new file should look like:</p> <pre><code>business_day,commodity,total,total_lots 20160831,CTC,Total,385 20160901,CTC,Total,555 . . </code></pre> <p>The raw files on my disk are named '20160831_foo.CSV', '20160901_foo.CSV etc..</p> <p>After Googling this I have yet not seen any examples on how to extract only one value from a CSV file. Any hints/help much appreciated. Happy to use pandas if that makes life easier. </p>
-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'], infer_datetime_format = True) df = df[((df['commodity'] == 'CTC') &amp; (df['total'] == 'Total'))] list_.append(df) df = pd.concat(list_, ignore_index = True) df['total_lots'] = df['total_lots'].astype(int) df = df.sort_values(['business_day']) df = df.set_index('business_day') </code></pre> <p>Then I save it as my required file. </p>
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(B, self).class_name() # other methods ... </code></pre> <p>Now I need to override <code>class_name</code> method from <code>B</code> and call it's super.</p> <pre><code>class Mixin(object): def class_name(self): print "Mixin" # need to call Grandparent class_name instead of parent's # super(Mixin, self).class_name() class D(Mixin, B): # Here I need to override class_name method from B and call B's super i.e. A's class_name, # It is better if I can able to do this thourgh Mixin class. ( pass </code></pre> <p>Now when I called <code>D().class_name()</code>, it should print <code>"Mixin" and "A"</code>only. Not "B"</p>
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): print "A" class B(A): def class_name(self): print "B" super(B, self).class_name() # other methods ... class Mixin(object): def class_name(self): print "Mixin" # need to call Grandparent class_name instead of parent's # super(Mixin, self).class_name() class D(Mixin, B): # Here I need to override class_name method from B and call B's super i.e. A's class_name, # It is better if I can able to do this thourgh Mixin class. ( pass class E(B, Mixin): pass </code></pre> <p><br /></p> <pre><code>import inspect print inspect.getmro(D) # returns tuple with (D, Mixin, B, A, object) print inspect.getmro(E) # returns tuple with (E, B, A, Mixin, object) </code></pre> <p>So if you have control and can ensure that you always get <code>Mixin</code> first. You can use <code>getmro()</code> to get the grandparent and execute it's <code>class_name</code> function.</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> <pre><code>page = open('meta.htm', 'r').read() soup = BeautifulSoup(page, "lxml") </code></pre> <p>How do I use <code>soup.prettify()</code> to print out the first and last 1000 lines of the document?</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 4 variables here. I want to plot a parametric variation. The number of points on the parameter is a lot less than the number of points for the horizontal axis. </p> <pre><code>import numpy as np from scipy.interpolate import interpn arr = np.random.random((4,4,4,4)) x1 = np.array([0, 1, 2, 3]) x2 = np.array([0, 10, 20, 30]) x3 = np.array([0, 10, 20, 30]) x4 = np.array([0, .1, .2, .30]) points = (x1, x2, x3, x4) </code></pre> <p>The following works:</p> <pre><code>xi = (0.1, 9, np.transpose(np.linspace(0, 30, 4)), np.linspace(0, 0.3, 4)) result = interpn(points, arr, xi) </code></pre> <p>and so does this:</p> <pre><code>xi = (0.1, 9, 24, np.linspace(0, 0.3, 4)) result = interpn(points, arr, xi) </code></pre> <p>but not this:</p> <pre><code>xi = (0.1, 9, np.transpose(np.linspace(0, 30, 3)), np.linspace(0, 0.3, 4)) result = interpn(points, arr, xi) </code></pre> <p>As you can see, in the last case, the size of the last two arrays in <code>xi</code> is different. Is this kind of functionality not supported by scipy or am I using <code>interpn</code> incorrectly? I need this create a plot where one of the <code>xi</code>'s is a parameter while the other is the horizontal axis.</p>
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.arange(10) x2 = np.arange(10) arr = x1 + x2[:, np.newaxis] # Set up grid for plotting X, Y = np.meshgrid(x1, x2) # Plot the values as a surface plot to depict fig = plt.figure() ax = fig.gca(projection='3d') surf = ax.plot_surface(X, Y, arr, rstride=1, cstride=1, cmap=cm.jet, linewidth=0, alpha=0.8) fig.colorbar(surf, shrink=0.5, aspect=5) </code></pre> <p>This gives us: <a href="http://i.stack.imgur.com/kOAqE.png" rel="nofollow"><img src="http://i.stack.imgur.com/kOAqE.png" alt="surface plot of values"></a></p> <p>Then, let's say you want to interpolate along a line, i.e., one point along the first dimension, but all points along the second dimension. These points are not in the original arrays <code>(x1, x2)</code> obviously. Suppose we want to interpolate to a point <code>x1 = 3.5</code>, which is in between two points on the x1-axis.</p> <pre><code>from scipy.interpolate import interpn interp_x = 3.5 # Only one value on the x1-axis interp_y = np.arange(10) # A range of values on the x2-axis # Note the following two lines that are used to set up the # interpolation points as a 10x2 array! interp_mesh = np.array(np.meshgrid(interp_x, interp_y)) interp_points = np.rollaxis(interp_mesh, 0, 3).reshape((10, 2)) # Perform the interpolation interp_arr = interpn((x1, x2), arr, interp_points) # Plot the result ax.scatter(interp_x * np.ones(interp_y.shape), interp_y, interp_arr, s=20, c='k', depthshade=False) plt.xlabel('x1') plt.ylabel('x2') plt.show() </code></pre> <p>This gives you the result as desired: note that the black points correctly lie on the plane, at an x1 value of <code>3.5</code>. <a href="http://i.stack.imgur.com/AKDzK.png" rel="nofollow"><img src="http://i.stack.imgur.com/AKDzK.png" alt="surface plot of interpolated points"></a></p> <p>Note that most of the "magic", and the answer to your question, lies in these two lines:</p> <pre><code>interp_mesh = np.array(np.meshgrid(interp_x, interp_y)) interp_points = np.rollaxis(interp_mesh, 0, 3).reshape((10, 2)) </code></pre> <p>I have explained the working of this <a href="http://stackoverflow.com/a/27286794/525169">elsewhere</a>. In short, what it does is to create an array of size 10x2, containing the coordinates of the 10 points you want to interpolate <code>arr</code> at. (The only difference between that post and this one is that I've written that explanation for <code>np.mgrid</code>, which is a shortcut to writing <code>np.meshgrid</code> for a bunch of <code>arange</code>s.)</p> <p>For your 4x4x4x4 case, you will probably need something like this:</p> <pre><code>interp_mesh = np.meshgrid([0.1], [9], np.linspace(0, 30, 3), np.linspace(0, 0.3, 4)) interp_points = np.rollaxis(interp_mesh, 0, 5) interp_points = interp_points.reshape((interp_mesh.size // 4, 4)) result = interpn(points, arr, interp_points) </code></pre> <p>Hope that helps!</p>
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('test.csv','r'), delimiter=',', dtype='f8')[1:] poly = PolynomialFeatures(degree=2) train_poly = poly.fit_transform(train) test_poly = poly.fit_transform(test) clf = linear_model.LinearRegression() clf.fit(train_poly, target) savetxt('polyreg_test1.csv', clf.predict(test_poly), delimiter=',', fmt='%f') </code></pre> <p>I wanted to know if there was a way to output a summary of the regression like in Excel ? I explored the attributes/methods of linear_model.LinearRegression() but couldn't find anything.</p> <p><a href="http://i.stack.imgur.com/oJba7.png" rel="nofollow"><img src="http://i.stack.imgur.com/oJba7.png" alt="enter image description here"></a></p>
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 more traditional types of statistical analysis you can use <code>statsmodels</code>, here is an example <a href="http://statsmodels.sourceforge.net/devel/examples/notebooks/generated/ols.html" rel="nofollow">taken from their documentation</a>:</p> <pre><code>import numpy as np import statsmodels.api as sm nsample = 100 x = np.linspace(0, 10, 100) X = np.column_stack((x, x**2)) beta = np.array([1, 0.1, 10]) e = np.random.normal(size=nsample) X = sm.add_constant(X) y = np.dot(X, beta) + e model = sm.OLS(y, X) results = model.fit() print(results.summary()) OLS Regression Results ============================================================================== Dep. Variable: y R-squared: 1.000 Model: OLS Adj. R-squared: 1.000 Method: Least Squares F-statistic: 4.020e+06 Date: Sun, 01 Feb 2015 Prob (F-statistic): 2.83e-239 Time: 09:32:32 Log-Likelihood: -146.51 No. Observations: 100 AIC: 299.0 Df Residuals: 97 BIC: 306.8 Df Model: 2 Covariance Type: nonrobust ============================================================================== coef std err t P&gt;|t| [95.0% Conf. Int.] ------------------------------------------------------------------------------ const 1.3423 0.313 4.292 0.000 0.722 1.963 x1 -0.0402 0.145 -0.278 0.781 -0.327 0.247 x2 10.0103 0.014 715.745 0.000 9.982 10.038 ============================================================================== Omnibus: 2.042 Durbin-Watson: 2.274 Prob(Omnibus): 0.360 Jarque-Bera (JB): 1.875 Skew: 0.234 Prob(JB): 0.392 Kurtosis: 2.519 Cond. No. 144. ============================================================================== </code></pre>
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(0.1) def test_1(): mock = MagicMock(side_effect=f) nb_threads = 100000 threads = [] for _ in range(nb_threads): thread = threading.Thread(target=mock) threads.append(thread) thread.start() for thread in threads: thread.join() assert mock.call_count == nb_threads, mock.call_count test_1() </code></pre> <p>This code produced the following output:</p> <pre><code>Traceback (most recent call last): File "test1.py", line 24, in &lt;module&gt; test_1() File "test1.py", line 21, in test_1 assert mock.call_count == nb_threads, mock.call_count AssertionError: 99994 </code></pre> <p>Is there a way I can use <code>call_count</code> (or similar) within a multithreaded portion of code? I'd like to avoid having to rewrite MagicMock myself...</p>
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(): mock = MagicMock(side_effect=f) nb_threads = 100000 threads = [] for _ in range(nb_threads): thread = threading.Thread(target=mock) threads.append(thread) thread.start() for thread in threads: thread.join() assert f.call_count == nb_threads, f.call_count test_1() </code></pre> <p>Consequently, I'm counting the number of calls of <code>f</code> instead of <code>mock</code>, but the result behaves as expected.</p>
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" # S1 from tinkerforge.ip_connection import IPConnection from tinkerforge.bricklet_ptc import BrickletPTC import numpy as np import serial import matplotlib from matplotlib.ticker import ScalarFormatter, FormatStrFormatter import matplotlib.pyplot as plt from matplotlib import style style.use('ggplot') from drawnow import * # creating arrays to feed the data tempC1 = [] def makeafig(): # creating subplots fig1 = plt.figure(1) a = fig1.add_subplot(111) #setting up axis label, auto formating of axis and title a.set_xlabel('Time [s]', fontsize = 10) a.set_ylabel('Temperature [°C]', fontsize = 10) y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False) a.yaxis.set_major_formatter(y_formatter) title1 = "Current Room Temperature (Side1): " + str(temperature1/100) + " °C" a.set_title(title1, fontsize = 10) #plotting the graph a.plot(tempC1, "#00A3E0") #saving the figure fig1.savefig('RoomTemperature.png', dpi=100) while True: ipcon = IPConnection() # Create IP connection ptc1 = BrickletPTC(UID1, ipcon) # S1 ipcon.connect(HOST, PORT) # Connect to brickd #setting the temperature from PTC bricklet temperature1 = ptc1.get_temperature() #processing data from a temperature sensor to 1st array dataArray1=str(temperature1/100).split(',') temp1 = float(dataArray1[0]) tempC1.append(temp1) #making a live figure drawnow(makeafig) plt.draw() </code></pre> <p>This is the approach I found good on the internet and it is working. The only problem I am facing is It consumes more time if I made more arrays for other sensors and the plot being made lags from the real time when I compare it with a stopwatch.</p> <p>Is there any good and efficient approach for obtaining live graphs that will be efficient with lot of sensors and doen't lag with real time. Or any command to clear up the already plotted array values?</p> <p>I'd be obliged if anyone can help me with this problem.</p>
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 surprisingly, it is actually faster than creating and filling a fixed size <code>numpy.ndarray</code> (but that is probably going to depend on the size of the list/array). </p> <p>I quickly played around with your <code>makeafig()</code> function, placing <code>a = fig1.add_subplot(111)</code> up to (including) <code>a.plot(..)</code> in a simple <code>for i in range(1,5)</code> loop, with <code>a = fig1.add_subplot(2,2,i)</code>; that makes <code>makeafig()</code> about 50% slower, but differences are only about 0.1-0.2 seconds. Is that in line with the lag that you are experiencing?</p> <p>That's about what I can test without the real data, my next step would be to time the part from <code>ipcon=..</code> to <code>temperature1=..</code>. Perhaps the bottleneck is simply the retrieval of the data? I'm sure that there are several examples on SO on how to time parts of Python scripts, for these kind of problems something like the example below should be sufficient:</p> <pre><code>import time t0 = time.time() # do something dt = time.time() - t0 </code></pre>
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_sqlalchemy always tries to create the engine with the pool_size parameter.</p> <p>As far as I understand the parameter pool_size is not allowed as an argument for the DefaultEngineStrategy in SQLAlchemy.</p> <p>Does anyone know a workaround for this issue?</p>
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 project: <a href="https://github.com/mitsuhiko/flask-sqlalchemy/issues/426" rel="nofollow">https://github.com/mitsuhiko/flask-sqlalchemy/issues/426</a></p>
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 statement, mypy complains:</p> <pre><code>Incompatible types in assignment (expression has type "float",variable has type "int") </code></pre> <p>I am using Python 3.5, so it should be a float. What am I missing. Should I somehow hint mypy about the Python version? How exactly?</p>
-2
2016-09-05T13:59:24Z
39,332,387
<p>It depends on your implementation:</p> <pre><code>&gt;&gt;&gt; round(3.5) 4 &gt;&gt;&gt; type(round(3.5)) &lt;class 'int'&gt; &gt;&gt;&gt; round(3.5,1) 3.5 &gt;&gt;&gt; type(round(3.5,1)) &lt;class 'float'&gt; </code></pre> <p>Of course it is trivial to create a float in all cases:</p> <pre><code>&gt;&gt;&gt; float(round(3.5)) 4.0 &gt;&gt;&gt; type(float(round(3.5))) &lt;class 'float'&gt; </code></pre>
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 statement, mypy complains:</p> <pre><code>Incompatible types in assignment (expression has type "float",variable has type "int") </code></pre> <p>I am using Python 3.5, so it should be a float. What am I missing. Should I somehow hint mypy about the Python version? How exactly?</p>
-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>&lt;type 'float'&gt; &lt;type 'float'&gt; </code></pre> <p>But with python 3.5 will be:</p> <pre><code>&lt;class 'int'&gt; &lt;class 'float'&gt; </code></pre> <p>Solution: You should cast explicitly to float when using python 3.5:</p> <pre><code>a_round = float(round(3.5)) </code></pre>
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 statement, mypy complains:</p> <pre><code>Incompatible types in assignment (expression has type "float",variable has type "int") </code></pre> <p>I am using Python 3.5, so it should be a float. What am I missing. Should I somehow hint mypy about the Python version? How exactly?</p>
-2
2016-09-05T13:59:24Z
39,332,594
<p>To fully clarify:</p> <pre><code>type (round (3.5, 0)) # &lt;class 'float'&gt; type (round (3.5)) # &lt;class 'int'&gt; </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 the text of the line do some calculation and replaces that text. For that I have build a simple html:</p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;click demo&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;2016-04-21 09:12:59&lt;/p&gt; &lt;p&gt;Second Paragraph&lt;/p&gt; &lt;p&gt;2016-04-21 09:12:59 bla bla&lt;/p&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; $( "p" ).click(function() { $.getJSON('/background_process', { line: $(this).text(), }, function(data) { $(this).text(data.result); }); return false; }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I also wrote flask code that should be binded once I click some line on my web page:</p> <pre><code>from flask import Flask, jsonify app = Flask(__name__) from flask import render_template import re @app.route("/") def index(): return render_template('index.html') @app.route("/background_process") def background_process(): try: lang = request.args.get('line', 0, type=str) string = lang.split()[0] if re.match(r'\d\d\d\d-\d\d-\d\d',string): return jsonify(result=string) else: return jsonify(result="Doesnt start with a date") except Exception as e: return str(e) if __name__ == "__main__": app.run() </code></pre> <p>The problem is that the function does not work for some reason unless i'm specifying which spot to put the text by id of a slot in my html page, and I cant understand what went wrong.</p>
-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(function() { var this_p = this; $.getJSON('/background_process', { line: $(this_p).text(), }, function(data) { $(this_p).text(data.result); }); return false; }); </code></pre>
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.png" alt="enter image description here"></a></p>
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.png" alt="enter image description here"></a></p>
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.randn(x.shape[0]) yp = np.copy(y) y = y + np.cumsum(np.abs(r)) ax.fill_between(x, yp, y, color=c[i], alpha=0.5) plt.show() </code></pre> <p>Would look like, <a href="http://i.stack.imgur.com/jG9Ch.png" rel="nofollow"><img src="http://i.stack.imgur.com/jG9Ch.png" alt="enter image description here"></a></p>
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 please help me get these verb? Thanks so much</p>
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 data to `faces.</p> <p>The format of the output arrays for <code>verts</code> and <code>faces</code> is of the form <code>(n,3)</code> where n is the number of the vertex/face and the three columns correspond to coordinates.</p> <p>Does anyone know how these output arrays are indexed? What determines the order in which they are registered in the array? Also, why is the <code>faces</code> array needed, as the knowledge of the vertices alone should be enough to construct the isosurface?</p>
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 determined by the position of the smallest x,y,z (in lexicographical order) coordinate in the contour. This is a side-effect of how the input array is traversed, but can be relied upon.</p> </blockquote>
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&lt;74xxx&gt;[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>P.S golang does not have such problem, so does many other languages</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/identifiers.html" rel="nofollow">here</a>:</p> <pre><code>identifier ::= (letter|"_") (letter | digit | "_")* letter ::= lowercase | uppercase lowercase ::= "a"..."z" uppercase ::= "A"..."Z" digit ::= "0"..."9" </code></pre>
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&lt;74xxx&gt;[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>P.S golang does not have such problem, so does many other languages</p>
1
2016-09-05T14:20:08Z
39,333,071
<p>If this is the pattern you are searching <code>r'(?P&lt;74xxx&gt;[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&lt;74xxx&gt;[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 &lt;module&gt;() ----&gt; 1 import scipy C:\Program Files\INRO\Emme\Emme 4\Emme-4.2.7\Python27\lib\site-packages\scipy\__init__.py in &lt;module&gt;() 59 __all__ = ['test'] 60 ---&gt; 61 from numpy._distributor_init import NUMPY_MKL # requires numpy+mkl 62 63 from numpy import show_config as show_numpy_config ImportError: No module named _distributor_init </code></pre> <p>I installed numpy and scipy from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a><br> By checking <code>numpy.show_config()</code> I believe I am indeed using a numpy with Intel MKL.<br> Using Python 2.7.9 in windows 10 .</p>
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"].count() A_sum_a is df.loc[df.B==a,"A"].sum() A_count_all A_sum_all A_count_a A_sum_a 0 5 15 3 8 </code></pre> <p>how can I get this result dataframe?</p>
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.DataFrame({'A_count_all':A_count_all, 'A_sum_all':A_sum_all, 'A_count_a':A_count_a, 'A_sum_a':A_sum_a}, index=[0], columns=['A_count_all','A_sum_all','A_count_a','A_sum_a'])) A_count_all A_sum_all A_count_a A_sum_a 0 5 15 3 8 </code></pre> <p>Thank you <a href="http://stackoverflow.com/questions/39332665/how-to-groupby-with-certain-condition-in-pandas-dataframe/39332727?noredirect=1#comment65997064_39332727"><code>Kris</code></a> for another solution:</p> <pre><code>print (pd.DataFrame(data=[[df.A.count(), df.A.sum(), df.loc[df.B=='a',"A"].count(), df.loc[df.B=='a',"A"].sum()]], columns=['A_count_all','A_sum_all','A_count_a','A_sum_a'])) A_count_all A_sum_all A_count_a A_sum_a 0 5 15 3 8 </code></pre>
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, "fixed") </code></pre> <p>When I do</p> <pre><code>&gt;&gt;&gt; b = B() &gt;&gt;&gt; b.h(3) </code></pre> <p>I get an error:</p> <pre><code>... TypeError: h() takes 3 positional arguments but 4 were given </code></pre> <p>This is consistent with</p> <pre><code>&gt;&gt;&gt; b.h() &lt;class '__main__.A'&gt; &lt;__main__.B object at 0x1034739e8&gt; fixed </code></pre> <p>However, I would expect (and like to have) the following behavior:</p> <pre><code>&gt;&gt;&gt; b.h(4) &lt;class '__main__.B'&gt; fixed 4 </code></pre> <p>I think that <code>functools.partialmethod</code> treats <code>B.h</code> as a normal instance method and passes the actual instance as first argument automatically. But this behavior renders <code>functools.partialmethod</code> useless for freezing arguments in classmethods of inheriting classes.</p>
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(cls, y): return A.h("fixed", y) </code></pre> <hr> <p>It <em>might</em> be possible to do what you want with some invocation of <code>partial</code>, but I was unable to find it. Here are some of my attempts, and why they failed.</p> <p><code>A.h</code> invokes the <code>__get__</code> method of the function object, returning a function where the first argument is already bound to the calling class. <code>partial</code> then applies that function to <code>"fixed"</code>, but then the resulting callable <em>still</em> has a <code>__get__</code> method that tries to insert the calling class into the resulting call. You might try to work around that by defining <code>h</code> to actually be a <em>static</em> method:</p> <pre><code>class B(A): h = staticmethod(partial(A.h, "fixed")) &gt;&gt;&gt; B.h(4) &lt;class '__main__.A'&gt; fixed 4 </code></pre> <p>But as you can see, you already froze the class argument when you call <code>partial</code>. Another attempt is to avoid the descriptor protocol by accessing the argument directly:</p> <pre><code>class B(A): h = staticmethod(partial(A.__dict__["h"], "fixed")) </code></pre> <p>but <code>classmethod</code> objects aren't actually callable; only the return value of their <code>__get__</code> methods is, so the call to <code>partial</code> fails.</p>
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, "fixed") </code></pre> <p>When I do</p> <pre><code>&gt;&gt;&gt; b = B() &gt;&gt;&gt; b.h(3) </code></pre> <p>I get an error:</p> <pre><code>... TypeError: h() takes 3 positional arguments but 4 were given </code></pre> <p>This is consistent with</p> <pre><code>&gt;&gt;&gt; b.h() &lt;class '__main__.A'&gt; &lt;__main__.B object at 0x1034739e8&gt; fixed </code></pre> <p>However, I would expect (and like to have) the following behavior:</p> <pre><code>&gt;&gt;&gt; b.h(4) &lt;class '__main__.B'&gt; fixed 4 </code></pre> <p>I think that <code>functools.partialmethod</code> treats <code>B.h</code> as a normal instance method and passes the actual instance as first argument automatically. But this behavior renders <code>functools.partialmethod</code> useless for freezing arguments in classmethods of inheriting classes.</p>
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) class C(A): def c(self, x): super(C, self).c(x = x, y = 'fixed') b = B() c = C() &gt;&gt;&gt; &gt;&gt;&gt; b.c(4) cls:&lt;class '__main__.B'&gt;, x:fixed, y:4 &gt;&gt;&gt; c.c(4) cls:&lt;class '__main__.C'&gt;, x:4, y:fixed &gt;&gt;&gt; </code></pre> <hr> <p><a href="https://rhettinger.wordpress.com/2011/05/26/super-considered-super/" rel="nofollow">super is super</a></p>
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">question</a> I have switched to using <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.InterpolatedUnivariateSpline.html" rel="nofollow">InterpolatedUnivariateSpline</a>. However, I have noticed that there are some (very) small differences between the resulting functions. My questions therefore are; </p> <p><strong>A.</strong> What causes the difference, as far as I can tell it has to do with the underlying methodology (using FITPACK or not) as per this <a href="http://stackoverflow.com/a/6236482/1093485">answer</a>. However, should the underlying math not be the same?</p> <p><strong>B.</strong> Is it possible to reproduce the interp1d results using InterpolatedUnivariateSpline (altering the smoothing spline degree or boundaries only made the two graphs even more different)?</p> <p>Minimal code to reproduce the slight difference:</p> <pre><code>from scipy.interpolate import interp1d from scipy.interpolate import InterpolatedUnivariateSpline import matplotlib.pyplot as plt import matplotlib import numpy x = [916.03189697265634, 916.0718969726563, 916.11189697265627, 916.15189697265623, 916.1918969726562, 916.23189697265627, 916.27189697265624, 916.31189697265631, 916.35189697265628, 916.39189697265624, 916.4318969726562, 916.47189697265628, 916.51189697265625, 916.55189697265632, 916.59189697265629, 916.63189697265625, 916.67189697265621, 916.71189697265618] y = [893483.0, 2185234.0, 3903053.0, 4264327.0, 3128900.0, 1374942.0, 554350.0, 442512.0, 414232.0, 403098.0, 413778.0, 264185.0, 363063.0, 473762.0, 452284.0, 526806.0, 461402.0, 424270.0] newX = numpy.linspace(x[0],x[-1],2500*(x[-1]-x[0])) f_interp1d = interp1d(x,y, kind='cubic') f_Univariate = InterpolatedUnivariateSpline(x,y) yINTER = f_interp1d(newX) yUNIVAR = f_Univariate(newX) fig = plt.figure() ax = fig.add_subplot(111) plt.plot(x,y,'b*') plt.plot(newX,yINTER,'r--') plt.plot(newX,yUNIVAR,'g--') plt.legend(['Raw Data','Interp1d','Univariate Spline'],loc='best') plt.show() </code></pre> <p>Yielding the following graph (seemingly fine):</p> <p><a href="http://i.stack.imgur.com/UaCUe.png" rel="nofollow"><img src="http://i.stack.imgur.com/UaCUe.png" alt="enter image description here"></a></p> <p>However, a close in view shows that there is a difference:</p> <p><a href="http://i.stack.imgur.com/ZVAZz.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZVAZz.png" alt="enter image description here"></a></p>
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 functions will yield a single solution (instead of a single solution versus two partial solutions if using 5 data points).</p> <p>snippet:</p> <pre><code># Strip top point maxInt = 0 for index,i in enumerate(y): if i &gt; maxInt: maxInt = i x_sub = x[y.index(maxInt)-2:y.index(maxInt)+2] y_sub = y[y.index(maxInt)-2:y.index(maxInt)+2] newX = numpy.linspace(x_sub[0],x_sub[-1],2500*(x_sub[-1]-x_sub[0])) f_interp1d = interp1d(x_sub,y_sub, kind='cubic') f_Univariate = InterpolatedUnivariateSpline(x_sub,y_sub) yINTER = f_interp1d(newX) yUNIVAR = f_Univariate(newX) fig = plt.figure() ax = fig.add_subplot(111) plt.plot(x,y,'b*') plt.plot(newX,yINTER,'r--') plt.plot(newX,yUNIVAR,'g--') plt.legend(['Raw Data','Interp1d','Univariate Spline'],loc='best') plt.show() </code></pre> <p>This yields the following graphs (zoomed out):</p> <p><a href="http://i.stack.imgur.com/wPy1l.png" rel="nofollow"><img src="http://i.stack.imgur.com/wPy1l.png" alt="enter image description here"></a></p> <p>The close-up shows that both functions truly are 'identical':</p> <p><a href="http://i.stack.imgur.com/VaZV2.png" rel="nofollow"><img src="http://i.stack.imgur.com/VaZV2.png" alt="enter image description here"></a></p> <p>However, I am still hoping that there is a better method to force both functions to produce similar behaviour.</p>
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 = 3.1415927 for i in range(len(a)): a[i] = -a[i] if __name__ == '__main__': num = Value('d', 0.0) arr = Array('i', range(10)) p = Process(target=f, args=(num, arr)) p.start() p.join() print(num.value) print(arr[:]) </code></pre>
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 doing things in the main process)</p> <p>You can read the number of CPUs with <a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.cpu_count" rel="nofollow">multiprocessing.cpu_count</a></p>
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('E:/list.txt','r') as target: my_list = json.load(target) </code></pre> <p>How to convert content of my file into list of dictionary ? Thank you </p>
-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('E:/list.txt','r') as target: my_list = json.load(target) </code></pre> <p>How to convert content of my file into list of dictionary ? Thank you </p>
-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('E:/list.txt','r') as target: my_list = json.load(target) </code></pre> <p>How to convert content of my file into list of dictionary ? Thank you </p>
-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('-' * 80) file_content = """[{"uid": 2, "user": 1}, {"uid": 2, "user": 1}, {"uid": 2, "user": 1}]""" print(json.loads(file_content)) </code></pre> <p>The result will be:</p> <pre><code>This is not JSON! -------------------------------------------------------------------------------- [{'user': 1, 'uid': 2}, {'user': 1, 'uid': 2}, {'user': 1, 'uid': 2}] </code></pre> <p>Proving that if if you wrap your dictionary into brackets and separate the items with commas the json will be parsed correctly</p> <p>Of course, If you don't want to tweak your file at all, you can do something like this to create your output:</p> <pre><code>import json file_content = """{"uid": 2, "user": 1} {"uid": 2, "user": 1} {"uid": 2, "user": 1} """ output = [json.loads(line) for line in file_content.split("\n") if line.strip() != ""] print(output) </code></pre>
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 speed. How can I do that, please help me. </p> <pre><code>from netCDF4 import * import matplotlib as mp import numpy as np #import matplotlib.pyplot as plt import pylab as plt #%% file = "/home/vlad/Desktop/task/Untitled Folder/result.nc" ncdata = Dataset(file, 'r') u = np.squeeze(ncdata.variables['u'][:]) v = np.squeeze(ncdata.variables['v'][:]) z = np.squeeze(ncdata.variables['z'][:]) time = ncdata.variables['time'][:]/3600 ncdata.close() u_mean = np.mean(u[0:100,:],0) z_mean = np.mean(z[0:100,:],0) v_mean = np.mean(v[0:100,:],0) u_mean_10 = u[900:1000,:] v_mean_10 = v[900:1000,:] z_10 = np.mean(z[900:1000,:],0) time_10 = time[900:1000] - time[900] T = len(time_10) L = len(z_10) fig = plt.figure(6) plt.pcolormesh(time_10,z_10,u_mean_10.T) plt.xlim([0, time_10[-1]]) fig.suptitle('U_velocity', fontsize=25) plt.xlabel('time', fontsize=20) plt.ylabel('depth(m)', fontsize=20) plt.colorbar() plt.show() shear_u_mean_10 = np.zeros([T,L]) for t in range(T): for i in range(L-1): tmp=(u_mean_10[t, i+1]-u_mean_10[t, i])/(z_10[i+1]-z_10[i]) tmp_depth = 0.5 * (z_10[i+1]+z_10[i]) shear_u_mean_10[t,i] = tmp fig = plt.figure(10) plt.pcolormesh(time_10/3600,z_10, shear_u_mean_10.T) plt.xlim([0, time_10[-1]/3600]) plt.colorbar() #plt.ylim([-30, -25]) fig.suptitle('U_shear velocity', fontsize=25) plt.xlabel('time', fontsize=20) plt.ylabel('depth(m)', fontsize=20) plt.show() shear_v_mean_10 = np.zeros([T,L]) for t in range(T): for i in range(L-1): tmp=(v_mean_10[t, i+1]-v_mean_10[t, i])/(z_10[i+1]-z_10[i]) tmp_depth = 0.5 * (z_10[i+1]+z_10[i]) shear_v_mean_10[t,i] = tmp fig = plt.figure(11) plt.pcolormesh(time_10/3600,z_10, shear_v_mean_10.T) plt.xlim([0, time_10[-1]/3600]) plt.colorbar() #plt.ylim([-30, -25]) fig.suptitle('V_shear velocity', fontsize=25) plt.xlabel('time', fontsize=20) plt.ylabel('depth(m)', fontsize=20) plt.show() fig = plt.figure(7) plt.pcolormesh(time_10,z_10,v_mean_10.T) plt.xlim([0, time_10[-1]]) fig.suptitle('V_velocity', fontsize=25) plt.xlabel('time', fontsize=20) plt.ylabel('depth(m)', fontsize=20) plt.colorbar() plt.show() </code></pre>
-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> <p>To limiting the range of time, you can use array slicing (e.g. <code>time[time&lt;12.5], u[time&lt;12.5]</code>). </p> <p>For your data, surely the speed is just <code>speed = np.sqrt(np.power(u,2) + np.power(v,2)</code></p> <p>Please provide a Minimal, Complete, and Verifiable example if you want further help.</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"}): coLink = link.find("span" , {"class" : "jcn"}) companyName = coLink.find("a").text </code></pre> <p>I am getting error " AttributeError: 'NoneType' object has no attribute 'find'". I know we get this error if object does not find anything. However if when I print(coLink), It gives following link inside every span class</p> <pre><code>&lt;span class="jcn"&gt;&lt;a href="http://xyz/Kolkata/Sunrise-International-&amp;lt;near&amp;gt;-B-R-B-Basu-Road-/033P3001041_BZDET?xid=S29sa2F0YSBUYXBlciBSb2xsZXIgQmVhcmluZyBEZWFsZXJz" onclick="_ct('clntnm', 'lspg');" title="Sunrise International in , Kolkata"&gt;Sunrise International&lt;/a&gt; &lt;/span&gt; &lt;span class="jcn"&gt;&lt;a href="http://xyz/Kolkata/Shree-Shakti-Vyapaar-PVT-LTD/033P6001995_BZDET?xid=S29sa2F0YSBUYXBlciBSb2xsZXIgQmVhcmluZyBEZWFsZXJz" onclick="_ct('clntnm', 'lspg');" title="Shree Shakti Vyapaar PVT LTD in , Kolkata"&gt;Shree Shakti Vyapaar PVT LTD&lt;/a&gt; &lt;/span&gt; </code></pre> <p>Can you please help how to get text of company?</p>
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"): print(link.get_text()) </code></pre> <p>This way you would not get any errors in case there is a <code>span</code> with no <code>a</code> link inside.</p> <p>Note that <code>col-sm-5</code> is a terrible class name to be using to locate elements - it is UI/layout-specific and has a high chance of being changed.</p>
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 line highlighted for the error is <code>class DisconnectedType(theano.gof.type.Type)</code>, within <strong>theano\gradient.py</strong></p> <p>Theano version is 0.8.2, everything installed via pip.</p> <p>Any lights on what may be causing this and how to fix it?</p>
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) class App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.output() </code></pre> <p>Output:</p> <pre><code>def output(self): Heading=StringVar() Heading.set("Please enter student name below") Label(text='Name:').pack(side=LEFT,padx=5,pady=5) self.n = Entry(root, width=10) self.n.pack(side=LEFT,padx=5,pady=5) </code></pre> <p>Text label:</p> <pre><code> Label(text='Grade:').pack(side=LEFT,padx=5,pady=5) self.e = Entry(root, width=10) self.e.pack(side=LEFT,padx=6,pady=6) self.b = Button(root, text='Submit', command=self.writeToFile) self.b.pack(side=RIGHT,padx=5,pady=5) self.b = Button(root, text='Clear', command=self.writeToFile) self.b.pack(side=RIGHT,padx=5,pady=5) </code></pre> <p>Write to grade CSV:</p> <pre><code>def writeToFile(self): with open('Grades.csv', 'a') as f: w=csv.writer(f, quoting=csv.QUOTE_ALL) w.writerow([self.n.get()]) w.writerow([self.e.get()]) if __name__ == "__main__": root=Tk() root.title('grade') root.geometry('380x280') app=App(master=root) app.mainloop() root.mainloop() Delete_button = Button(root, text = 'Clear', command = delete_entries) Delete_button.pack() </code></pre>
-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> <p>Probably, it works well.</p> <p>And then I need to count, for example, number of nouns in each text. I do it like this:</p> <pre><code>for chunk in chunks: for key in tagged.keys(): for noun_tag in noun_tags: if tagged[key] == noun_tag: noun += 1 totalNoun.append(noun) </code></pre> <p>then I use <code>sum()</code> and find percentage. I also tried <code>totalNoun += noun</code> but in both ways I receive smth like 3500% or 2498%. </p> <p>What do I do wrong?</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, you do not set <code>noun</code> equal to 0 after each chunk. That is:</p> <pre><code>for chunk in chunks: ## HERE ## noun = 0 ## HERE ## for key in tagged.keys(): for noun_tag in noun_tags: if tagged[key] == noun_tag: noun += 1 totalNoun.append(noun) </code></pre> <p>Using <code>noun = 0</code> in your <code>for chunk in chunks</code> loop should do the trick.</p>
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;"John";"Bryan";"Johnny";Value;Comedy;Action] </code></pre> <p>So far I coded this </p> <pre><code>resultFile = open("DNA_Movie.csv",'wb') wr = csv.writer(resultFile, dialect='excel') wr.writerows([imdb_id, genre, actors]) </code></pre> <p>But the result is like this: </p> <pre><code>1234 "John","Bryan","Johnny" "Value" "Comedy","Action" </code></pre>
-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;"John";"Bryan";"Johnny";Value;Comedy;Action] </code></pre> <p>So far I coded this </p> <pre><code>resultFile = open("DNA_Movie.csv",'wb') wr = csv.writer(resultFile, dialect='excel') wr.writerows([imdb_id, genre, actors]) </code></pre> <p>But the result is like this: </p> <pre><code>1234 "John","Bryan","Johnny" "Value" "Comedy","Action" </code></pre>
-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 this should function would be extremely helpful, and also if there is an API available that would be great to know.</p> <p>Any advice is appreciated. Thanks.</p>
-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 pandas as pd table = pd.read_excel('sales.xlsx', sheetname = 'Month 1', header = 0, index_col = 0, parse_cols = "A, C, G", convert_float = True) print(table) </code></pre> <h2>Inputting values into browser</h2> <p>Inputting values into the browser can be done quite easily through <a href="http://selenium-python.readthedocs.io/getting-started.html" rel="nofollow">Selenium</a> which is a python library for controlling browsers via code.</p> <p>Also directly from the site:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://www.python.org") assert "Python" in driver.title elem = driver.find_element_by_name("q") elem.clear() elem.send_keys("pycon") elem.send_keys(Keys.RETURN) assert "No results found." not in driver.page_source driver.close() </code></pre> <h2>How to start your project</h2> <p>Now that you have the building blocks, you can put them together. </p> <p>Example steps:</p> <ol> <li>Open file, open browser and other initialization stuff you need to do.</li> <li>Read values from excel document</li> <li>Send values to browser</li> <li>Repeat steps 2 &amp; 3 forever</li> </ol>
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 &lt; 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 &lt; 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 &lt; 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): return max(min(max_value, x), min_value) min_value, max_value = 0, 20 print([clamp(int(random.gammavariate(3, 3)), min_value, max_value) for v in range(1)]) </code></pre> <p>In your example, you were using the index x instead of your random gamma value, I'm assuming that's not what you want</p>
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) </code></pre> <p>but with this list of ids I can't obtain username and number of followers of every id, because the rate limit exceed... How I can complete this code?</p> <p>Thank you all!</p>
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 strictly hit it. Since your problem has something to do with the rate limit, you should put a sleep in your <code>for</code> loop. I'd say a <code>sleep(4)</code> should be enough, but it's mostly a matter of trial and error there, try to change the value and see for yourself.</p> <p>Something like</p> <pre><code>sleeptime = 4 pages = tweepy.Cursor(api.followers, screen_name="username").pages() while True: try: page = next(pages) time.sleep(sleeptime) except tweepy.TweepError: #taking extra care of the "rate limit exceeded" time.sleep(60*15) page = next(pages) except StopIteration: break for user in page: print(user.id_str) print(user.screen_name) print(user.followers_count) </code></pre>
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 = xlrd.open_workbook(file_path) print "Done" except XLRDError: print "Wrong type of file." </code></pre> <p>where <strong>file_path</strong> is the path of my file. </p> <p>This works fine, the problem is the following. First of all I have a valid .xls file, so script prints <em>Done</em>. Now, assume that the valid .xls file is renamed (also extension), for example from test.xls to test.txt.</p> <p>If I run the script, i have the same result (<em>Done</em>). </p> <p>Instead, if I use a "real" .txt file (empty or with some text), the script prints <em>Wrong type of file.</em> </p> <p>This behavior happens because the "structure" of the file is not changed? Am I doing something wrong? There is another type of Exception that I can add to <strong>except</strong> branch?</p> <p>Thanks in advance</p>
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 extention not involved.</p> <p>Signatures for different file types can be found <a href="http://www.garykessler.net/library/file_sigs.html" rel="nofollow">there</a>.</p>
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 try to instantiate the class with </p> <pre><code>w = Window() </code></pre> <p>the shell restarts with a "========== RESTART: Shell ===========" message.</p> <p>These things fix the problem:</p> <ul> <li><p>Rewriting the code so that the Window class has no superclass:</p> <pre><code>from PyQt5.QtWidgets import(QMainWindow) class Window: pass </code></pre></li> <li><p>Running the code outside of IDLE by double-clicking the file when it has an "if <strong>name</strong>=='main':" conditional added</p></li> </ul> <p>These things do <em>not</em> fix the problem:</p> <ul> <li>Changing the name of the class</li> <li>Changing the class used as a super</li> </ul> <p>The clincher is that when I go back and try to import/instantiate similarly subclassed classes from old scripts that worked fine in the past and haven't been touched in awhile, they now exhibit exactly the same problem.</p> <p>So, as far as I can tell, I have an IDLE-specific problem that crashes/restarts the interpreter when it tries to instantiate any subclass, and which arose spontaneously where it wasn't present before.</p> <p>Has anyone seen anything like this before?</p>
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) #if need ascending sorting df = df.sort_index() a 2012-01-05 0 2012-01-06 1 2012-01-07 2 2012-01-08 5 2012-01-09 4 print (df[:'2012-01-07']) a 2012-01-05 0 2012-01-06 1 2012-01-07 2 print (df['2012-01-07':]) a 2012-01-07 2 2012-01-08 5 2012-01-09 4 </code></pre> <hr> <pre><code>df = pd.DataFrame({'a':[0,1,2,5,4]}, index=pd.date_range('2012-01-05', periods=5)) #descending sorting df = df.sort_index(ascending=False) print (df) a 2012-01-09 4 2012-01-08 5 2012-01-07 2 2012-01-06 1 2012-01-05 0 print (df[:'2012-01-07']) a 2012-01-09 4 2012-01-08 5 print (df['2012-01-07':]) a 2012-01-07 2 2012-01-06 1 2012-01-05 0 </code></pre>
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 done using Python?</p>
-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 you can use groupby function:</p> <pre><code>In [10]: df.groupby(df['Classe']).sum() Out[10]: Echantillon Classe 0 2002 1 1912 2 18224 </code></pre>
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 <code>ax.get_projection</code>, <code>ax.properties</code> contains no "projection" key, and a quick google search hasn't turned up anything useful. </p>
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 axesDimensions(ax): if hasattr(ax, 'get_zlim'): return 3 else: return 2 fig = plt.figure() ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212, projection='3d') print "ax1: ", axesDimensions(ax1) print "ax2: ", axesDimensions(ax2) </code></pre> <p>Which prints:</p> <pre><code>ax1: 2 ax2: 3 </code></pre>
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,3): board.append([" "," "," "]) # Fill the board def print_board(): for i in range(0,3): print "| ", for k in range(0,3): print board[i][k], print "|\n" print "The first player to start will be player one with X\n, the second player will be O\n" player_one = "X" player_two = "O" current_player_name = "Player One" current_player = player_one filled_board = False winner = False def check_win_col(the_winner): for i in range(0,3): for j in range(0,3): if board[0][i] == board[j][0] and board[0][i] != " ": the_winner = current_player return the_winner while(filled_board == False): get_row = int(raw_input("Please enter which row you would like to move to " + current_player)) get_col = int(raw_input("Please enter the col you want to move to" + current_player)) board[get_row][get_col] = current_player print_board() check_win_col() if current_player == player_one: current_player = player_two else: current_player = player_one </code></pre> <p><strong>The Error</strong></p> <pre><code>**UnboundLocalError: local variable 'the_winner' referenced before assignment** </code></pre> <p>At first, I did not understand why the line <code>the_winner = current_player</code> gave me an error, then after reading some SO questions like <a href="http://stackoverflow.com/questions/10851906/python-3-unboundlocalerror-local-variable-referenced-before-assignment">Unbound Local Error</a>, I realized my issue.</p> <p>On my own I thought of two solutions. </p> <p><strong>My attempt</strong></p> <p><strong>1.</strong> Make <code>the_winner</code> global. This way I wouldn't have an issue with setting the winner for the winning column to the current player. The reason I don't want to do this, is because I recall people saying during my research on this error, that it is very bad practice to use the keyword <code>global</code>, and thus I do not really want to use it.</p> <p><strong>2</strong>. inside the function add a parameter for <code>the_winner</code>. But the problem with this idea, is that how I would access <code>the_winner</code> outside of the function itself. This would create <code>the_winner</code> inside the <code>check_win_col()</code> local scope, and I would not be able to manipulate this outside of the function, if I for some reason needed to. Plus the idea of adding a parameter to a function for checking the column winner seems odd. It seems like its one of those functions that should just be parameter-less if you will.</p> <p>Is there a better solution I am missing? Sorry if this question seems trivial.</p>
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][i] == board[j][0] and board[0][i] != " ": return current_player # Current player wins, so return it. the_winner = check_win_col() print the_winner </code></pre>
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,3): board.append([" "," "," "]) # Fill the board def print_board(): for i in range(0,3): print "| ", for k in range(0,3): print board[i][k], print "|\n" print "The first player to start will be player one with X\n, the second player will be O\n" player_one = "X" player_two = "O" current_player_name = "Player One" current_player = player_one filled_board = False winner = False def check_win_col(the_winner): for i in range(0,3): for j in range(0,3): if board[0][i] == board[j][0] and board[0][i] != " ": the_winner = current_player return the_winner while(filled_board == False): get_row = int(raw_input("Please enter which row you would like to move to " + current_player)) get_col = int(raw_input("Please enter the col you want to move to" + current_player)) board[get_row][get_col] = current_player print_board() check_win_col() if current_player == player_one: current_player = player_two else: current_player = player_one </code></pre> <p><strong>The Error</strong></p> <pre><code>**UnboundLocalError: local variable 'the_winner' referenced before assignment** </code></pre> <p>At first, I did not understand why the line <code>the_winner = current_player</code> gave me an error, then after reading some SO questions like <a href="http://stackoverflow.com/questions/10851906/python-3-unboundlocalerror-local-variable-referenced-before-assignment">Unbound Local Error</a>, I realized my issue.</p> <p>On my own I thought of two solutions. </p> <p><strong>My attempt</strong></p> <p><strong>1.</strong> Make <code>the_winner</code> global. This way I wouldn't have an issue with setting the winner for the winning column to the current player. The reason I don't want to do this, is because I recall people saying during my research on this error, that it is very bad practice to use the keyword <code>global</code>, and thus I do not really want to use it.</p> <p><strong>2</strong>. inside the function add a parameter for <code>the_winner</code>. But the problem with this idea, is that how I would access <code>the_winner</code> outside of the function itself. This would create <code>the_winner</code> inside the <code>check_win_col()</code> local scope, and I would not be able to manipulate this outside of the function, if I for some reason needed to. Plus the idea of adding a parameter to a function for checking the column winner seems odd. It seems like its one of those functions that should just be parameter-less if you will.</p> <p>Is there a better solution I am missing? Sorry if this question seems trivial.</p>
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 are a few options for how you can deal with that possibility. One might be to initialize the <code>the_winner</code> local variable in the function before starting the loop. <code>None</code> is often a reasonable default value for a variable that may or may not get changed.</p> <pre><code>def check_win_col(): the_winner = None # set a default value for the variable unconditionally for i in range(0,3): for j in range(0,3): if board[0][i] == board[j][0] and board[0][i] != " ": the_winner = current_player # this *may* modify it, if the condition was met return the_winner # this will work always, not only if the loop modified the variable </code></pre> <p>Putting the <code>return</code> statement in the loop (as suggested by Skirrebattie) is almost exactly the same as this, since <code>None</code> is the default return value for functions in Python. If the condition is never met in the code in the other answer, the function will return <code>None</code> after it reaches the end of its code.</p> <p>A final note about the condition you're checking. It doesn't make any sense! Currently you're checking if any value in the first column matches any value in the first row and is not a space. That's not a very relevant condition for winning Tic-Tac-Toe. You probably want something different (though I'm not exactly sure what).</p>
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 develop a mobile application. I can get access_token using curl when sending request for logging in but how do i implement in view so that app sends a post request to 127.0.0.1:8000/o/token asking for the token so that the request contains username, password, client_id and client_secret. The server then receives the credentials and if they are valid it returns the access_token. The rest of the time it should query the server using that token.</p> <p><strong>views.py</strong></p> <pre><code>class UserLoginAPI(APIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): access_token = AccessToken.objects.get(token=request.POST.get('access_token'), expires__gt=timezone.now()) # error is shown here. I get None data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) </code></pre> <p><strong>serializers.py</strong></p> <pre><code>class UserCreateSerializer(ModelSerializer): class Meta: model = User extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): username = validated_data['username'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] email = validated_data['email'] password = validated_data['password'] confirm_password = validated_data['password'] user_obj = User( username = username, first_name = first_name, last_name = last_name, email = email ) user_obj.set_password(password) user_obj.save() if user_obj: expire_seconds = oauth2_settings.user_settings['ACCESS_TOKEN_EXPIRE_SECONDS'] scopes = oauth2_settings.user_settings['SCOPES'] application = Application.objects.get(name="Foodie") expires = datetime.now() + timedelta(seconds=expire_seconds) access_token = AccessToken.objects.create(user=user_obj, application=application, token = generate_token(), expires=expires, scope=scopes) return validated_data class UserLoginSerializer(ModelSerializer): # token = CharField(allow_blank=True, read_only=True) username = CharField() class Meta: model = User fields = [ 'username', 'password', # 'token', ] extra_kwargs = {"password": {"write_only": True} } </code></pre>
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=password) except ObjectDoesNotExist: return HttpResponse("Can't find this user") else: try: access_token = AccessToken.objects.get(user=user) except ObjectDoesNotExist: return HttpResponse("Haven't set any token") else: return HttpResponse(access_token) </code></pre> <p>If you want to use DRF to handle this:</p> <pre><code>@api_view(['POST']) def get_token(request): # get token by query just like above serializer = TokenSerializer(data=access_token.token) #you can pass more parameters to data if you want, but you also have to edit your TokenSerializer if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) </code></pre> <p>Your TokenSerializer:</p> <pre><code>class TokenSerializer(ModelSerializer): class Meta: model = AccessToken field = (token,) </code></pre> <h3>EDIT</h3> <p>It depends</p> <ul> <li>Web, you post your username and password to login api, your browser store session in your cookies.</li> <li>Mobile, you post your username and password to login api, server response the token then you store it in your mobile, maybe keychain when you are developing IOS app.And send it as http header when you want to access the server, <a href="https://stackoverflow.com/questions/3889769/how-can-i-get-all-the-request-headers-in-django">how-can-i-get-all-the-request-headers-in-django</a></li> </ul>
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__ import division a = symbols('a') b = symbols('b') expr = 1/12*b + 1 expr.subs(1/12*b, a) expr.subs(b*1/12, a) </code></pre> <p>The first line gives the expected result (ie. <code>a+1</code>) while in the second one there is no substitution.</p> <p><strong>Problem 2: factorized expressions</strong></p> <p>Some parts of the expression are factorized and when I expand the expression they get simplified, thus making the substitution impossible. For example</p> <pre><code>(((x+1)**2-x).expand()).subs(x**2+2*x, y+1) </code></pre> <p>will give <code>x^2+x+1</code> and what I am looking for is <code>y+2-x</code>.</p> <p><strong>Question</strong></p> <p>Is there a way to solve these problems ? Or maybe I should use another symbolic mathematical tool ? Any suggestions are welcomed.</p>
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)) </code></pre>
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__ import division a = symbols('a') b = symbols('b') expr = 1/12*b + 1 expr.subs(1/12*b, a) expr.subs(b*1/12, a) </code></pre> <p>The first line gives the expected result (ie. <code>a+1</code>) while in the second one there is no substitution.</p> <p><strong>Problem 2: factorized expressions</strong></p> <p>Some parts of the expression are factorized and when I expand the expression they get simplified, thus making the substitution impossible. For example</p> <pre><code>(((x+1)**2-x).expand()).subs(x**2+2*x, y+1) </code></pre> <p>will give <code>x^2+x+1</code> and what I am looking for is <code>y+2-x</code>.</p> <p><strong>Question</strong></p> <p>Is there a way to solve these problems ? Or maybe I should use another symbolic mathematical tool ? Any suggestions are welcomed.</p>
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/12*b</code>, it is not surprising that the second <code>subs</code> does not work. </p> <p>Regarding problem 2, the <code>subs</code> rule you provide is ambiguous. In particular the substitution rule implies that equation <code>x**2+2*x==y+1</code>. However, this equation has many interpretations, e.g, </p> <p><code>x**2 == y + 1 - 2*x</code> (this is the one you consider),</p> <p><code>x**2 + x == y + 1 - x</code>, </p> <p><code>x == (y + 1 - x**2)/2</code>,</p> <p>For this reason, I consider sympy refusing to perform a substitution is actually a correct approach.</p> <p>If it is the first interpretation you want, it is better to explicitly provide it in the <code>subs</code> rule, i.e., </p> <pre><code>(((x+1)**2-x).expand()).subs(x**2, -2*x + y + 1) </code></pre> <blockquote> <p><code>-x + y + 2</code></p> </blockquote>
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__ import division a = symbols('a') b = symbols('b') expr = 1/12*b + 1 expr.subs(1/12*b, a) expr.subs(b*1/12, a) </code></pre> <p>The first line gives the expected result (ie. <code>a+1</code>) while in the second one there is no substitution.</p> <p><strong>Problem 2: factorized expressions</strong></p> <p>Some parts of the expression are factorized and when I expand the expression they get simplified, thus making the substitution impossible. For example</p> <pre><code>(((x+1)**2-x).expand()).subs(x**2+2*x, y+1) </code></pre> <p>will give <code>x^2+x+1</code> and what I am looking for is <code>y+2-x</code>.</p> <p><strong>Question</strong></p> <p>Is there a way to solve these problems ? Or maybe I should use another symbolic mathematical tool ? Any suggestions are welcomed.</p>
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>1/12*b</code> from left to right. <code>1/12</code> is evaluated by Python to give <code>0.08333333333333333</code>, which is then multiplied by <code>b</code>. In the second case, <code>b*1</code> is evaluated as <code>b</code>. Then <code>b/12</code> is evaluated by SymPy (because <code>b</code> is a SymPy object), to give <code>Rational(1, 12)*b</code>. </p> <p>Due to the inexact nature of floating point numbers, SymPy does not see the float <code>0.08333333333333333</code> as equal to the rational <code>1/12</code>. </p> <p>There is some more discussion of this issue <a href="http://docs.sympy.org/latest/tutorial/gotchas.html" rel="nofollow">here</a>. As a workaround, you should avoid direct <code>integer/integer</code> without wrapping it somehow, so that SymPy can create a rational. The following will all create a rational:</p> <pre><code>b/12 Rational(1, 12)*b S(1)/12*b </code></pre> <hr> <p>For <code>(((x+1)**2-x).expand()).subs(x**2+2*x, y+1)</code> the issue is that <code>x**2 + 2*x</code> does not appear exactly in the expression, which is <code>x**2 + x + 1</code>. SymPy generally only replaces things that it sees exactly. </p> <p>It seems you don't mind adding and subtracting an <code>x</code> to make the replacement work. So I would suggest doing instead <code>(((x+1)**2-x).expand()).subs(x**2, y+1 - 2*x)</code>. By only substituting a single term (<code>x**2</code>), the substitution will always work, and the <code>2*x</code> will cancel out to leave whatever <code>x</code> term remains (in this case, <code>-x</code>). </p>
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 Division Error.</p> <pre><code>table[change] = ['{0}%'.format(str(round(100*x,2)) for x in \ (table.ix[:,table.shape[1]-1] - table.ix[:,0]) / table.ix[:,0]] </code></pre> <p>table example:</p> <pre><code> 0 1 2 3 4 5 6 \ numbers 0.0 100.0 120.0 220.0 250.0 300.0 500.0\\ revenues 50.0 100.0 120.0 220.0 250.0 300.0 500.0 </code></pre> <p>where <code>table.ix[:,0]</code> is 0.0.</p> <p>Some of the values at <code>table.ix[:,0]</code> are zero and others are not, hence, try and except in my experience will not work because the script will break once the value divisible is equal to 0.</p> <p>I tried two of the other methods and they did not work for me.</p> <p>Can you be a little more descriptive in your answer? I am struggling to take the approach given.</p> <p>I have another approach which I am trying and it is not working. Do not see yet what the problem is:</p> <pre><code>for index, row in table.iterrows(): if row[0] == 0: table[change] = 'Nan' else: x = (row[-1] - row[0]) / row[0] table[change] = '{0} {1}%'.format( str(round(100 * x, 2))) </code></pre> <p>The 'change' column contains the same values (i.e. the last comparison of the table)</p>
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]) / table.ix[:,0]] except ZeroDivisionError: table[change] = inf </code></pre> <p>In that case, you can just divide the whole Series, and Pandas will do the inf substitution for you. Something like:</p> <pre><code>if df1.ndim == 1: table[change] = inf elif df1.ndim &gt; 1 and df1.shape[0] &gt; 1: table[change] = ['{0}%'.format(str(round(100*x,2)) for x in \ (table.ix[:,table.shape[1]-1] - table.ix[:,0]) / table.ix[:,0]] </code></pre> <p>The fact that your original example only had one row seems to make Pandas fetch the value in that cell for the division. If you do the division with an array with more than one row, it has the behaviour that I think you were originally expecting.</p> <p>EDIT:</p> <p>I've just spotted the generator expression that I completely overlooked. This is much easier than I thought. Performing your normalisation then, if your version of pandas is up to date, then you can call round if you want.</p> <pre><code>table["change"] = 100 * ((table.iloc[:, -1] - table.iloc[:, 0])/ table.iloc[:, 0]) #And if you're running Pandas v 0.17.0 table.round({"change" : 2}) </code></pre>
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 Division Error.</p> <pre><code>table[change] = ['{0}%'.format(str(round(100*x,2)) for x in \ (table.ix[:,table.shape[1]-1] - table.ix[:,0]) / table.ix[:,0]] </code></pre> <p>table example:</p> <pre><code> 0 1 2 3 4 5 6 \ numbers 0.0 100.0 120.0 220.0 250.0 300.0 500.0\\ revenues 50.0 100.0 120.0 220.0 250.0 300.0 500.0 </code></pre> <p>where <code>table.ix[:,0]</code> is 0.0.</p> <p>Some of the values at <code>table.ix[:,0]</code> are zero and others are not, hence, try and except in my experience will not work because the script will break once the value divisible is equal to 0.</p> <p>I tried two of the other methods and they did not work for me.</p> <p>Can you be a little more descriptive in your answer? I am struggling to take the approach given.</p> <p>I have another approach which I am trying and it is not working. Do not see yet what the problem is:</p> <pre><code>for index, row in table.iterrows(): if row[0] == 0: table[change] = 'Nan' else: x = (row[-1] - row[0]) / row[0] table[change] = '{0} {1}%'.format( str(round(100 * x, 2))) </code></pre> <p>The 'change' column contains the same values (i.e. the last comparison of the table)</p>
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 want.</p> <p>Or you can wrap the division calculation in a try/except block as suggested by @Andrew.</p>
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): File "/usr/bin/pip", line 9, in &lt;module&gt; load_entry_point('pip==8.1.2', 'console_scripts', 'pip')() File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 552, i n load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2672, in load_entry_point return ep.load() File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2345, in load return self.resolve() File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2351, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "/usr/lib/python2.7/site-packages/pip/__init__.py", line 16, in &lt;module&gt; from pip.vcs import git, mercurial, subversion, bazaar # noqa File "/usr/lib/python2.7/site-packages/pip/vcs/subversion.py", line 9, in &lt;mod ule&gt; from pip.index import Link File "/usr/lib/python2.7/site-packages/pip/index.py", line 30, in &lt;module&gt; from pip.wheel import Wheel, wheel_ext File "/usr/lib/python2.7/site-packages/pip/wheel.py", line 39, in &lt;module&gt; from pip._vendor.distlib.scripts import ScriptMaker File "/usr/lib/python2.7/site-packages/pip/_vendor/distlib/scripts.py", line 1 4, in &lt;module&gt; from .compat import sysconfig, detect_encoding, ZipFile File "/usr/lib/python2.7/site-packages/pip/_vendor/distlib/compat.py", line 31 , in &lt;module&gt; from urllib2 import (Request, urlopen, URLError, HTTPError, ImportError: cannot import name HTTPSHandler </code></pre>
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-cannot-import-name-httpshandler" rel="nofollow">this</a>.</p>
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. Here is my session code. </p> <pre><code>def dispatch(self): # Get a session store for this request. self.session_store = sessions.get_store(request=self.request) try: # Dispatch the request. webapp2.RequestHandler.dispatch(self) finally: # Save all sessions. self.session_store.save_sessions(self.response) @webapp2.cached_property def session(self): # Returns a session using the default cookie key. return self.session_store.get_session() </code></pre> <p>Config:</p> <pre><code>config = {} config['webapp2_extras.sessions'] = { 'secret_key': 'my-super-secret-key', } </code></pre> <p>Kindly help me.</p>
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 server session identification.</p> <p>Each time the users' web browser interacts with a web server it will pass the cookie information to the web server. Only the cookies stored by the browser that relate to the domain in the requested URL will be sent to the server. This means that cookies that relate to www.example.com will not be sent to www.exampledomain.com.</p> <p>In essence, a cookie is a great way of linking one page to the next for a user's interaction with a web site or web application.</p> </blockquote> <p>.</p> <blockquote> <p>What is a <strong>Session</strong>? A session can be defined as a server-side storage of information that is desired to persist throughout the user's interaction with the web site or web application. </p> <p>Instead of storing large and constantly changing information via cookies in the user's browser, only a unique identifier is stored on the client side (called a "session id"). This session id is passed to the web server every time the browser makes an HTTP request (ie a page link or AJAX request). The web application pairs this session id with it's internal database and retrieves the stored variables for use by the requested page.</p> </blockquote> <p>If you want to implement something like "remember me" you should use cookies because data stored in session isn't persistent.</p> <p>For setting and getting cookies in <code>webapp2</code>:</p> <pre><code>response.headers.add_header('Set-Cookie', 'remember_me=%s' % some_hash) request.cookies.get('remember_me', '') </code></pre> <p>I strongly recommend you to read this <a href="https://www.udacity.com/wiki/cs253/unit-4" rel="nofollow">article</a> that has explained this stuff thoroughly. </p>
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 it, in another ssh session, i just enter python commands :</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities </code></pre> <p>And after that, following the instructions from <a href="http://selenium-python.readthedocs.io/getting-started.html#using-selenium-with-remote-webdriver" rel="nofollow">http://selenium-python.readthedocs.io/getting-started.html#using-selenium-with-remote-webdriver</a>, I enter :</p> <pre><code>driver = webdriver.Remote( command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=DesiredCapabilities.FIREFOX) </code></pre> <p>After 45sec, i have lots of errors in both server window and client window. Here is the main error :</p> <blockquote> <p>Caused by: org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output: Error: GDK_BACKEND does not match available displays</p> </blockquote> <p>I saw some people with the same problem, but even with the latest java and selenium versions, i still got this issue. Thank you in advance for your help</p>
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 any location.</p> <p>Now to run <code>selenium-server-standalone-3.0.0-beta3.jar</code> use below command :-</p> <pre><code>java -jar selenium-server-standalone-3.0.0-beta3.jar -Dwebdriver.gecko.driver = "path/to/downloaded geckodriver" </code></pre> <p>Now you need to set capability with <code>marionette</code> property to <code>true</code> to support latest firefox with <code>selenium 3</code> as below :-</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities caps = DesiredCapabilities.FIREFOX # Tell the Python bindings to use Marionette. caps["marionette"] = True driver = webdriver.Remote(command_executor = 'http://127.0.0.1:4444/wd/hub', desired_capabilities = caps) </code></pre> <p><strong>Note</strong> :- For more <a href="https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver" rel="nofollow">information about <code>marionette</code> follow this <code>Mozilla</code> official page</a></p>
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, e.g. the following rotation matrix:</p> <pre><code>array([[ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00], [ 0.00000000e+00, 1.00000000e+00, 0.00000000e+00], [ -1.00000000e+00, 0.00000000e+00, 0.00000000e+00]]) </code></pre> <p>To do this as efficiently as possible (the real problem has millions of coordinates btw) currently, I am somewhat baffled that I have to do:</p> <p>First apply <code>df.reshape</code> - each row in this example consists of three 3D coordinates as so [(x,y,z),(x,y,z),(x,y,z)]:</p> <pre><code>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>Then in order to get it to <a href="https://en.wikipedia.org/wiki/Rotation_matrix" rel="nofollow">rotate to convention</a>, one must take <code>u_new = R \dot u</code> which means the transpose of the above, so that we can take a column-wise (i.e. coordinate) multiplication with the rotation matrix.</p> <pre><code>array([[0, 1, 0, 1, 1, 0, 0, 1, 1], [1, 1, 1, 0, 1, 0, 0, 0, 1], [0, 1, 1, 1, 1, 1, 0, 0, 0]]) </code></pre> <p>Then we can do the multiplication:</p> <pre><code>pd.DataFrame(dot(rotmat,df)).values array([[ 0.00e+00, 2.22e-16, 0.00e+00, 1.00e+00, 2.22e-16, 2.22e-16, 1.00e+00, 1.00e+00, 2.22e-16], [ 1.00e+00, 0.00e+00, 1.00e+00, 1.00e+00, 1.00e+00, 1.00e+00, 0.00e+00, 0.00e+00, 1.00e+00], [ 0.00e+00, -1.00e+00, 0.00e+00, -1.00e+00, -1.00e+00, -1.00e+00, 2.22e-16, -1.00e+00, -1.00e+00]]) </code></pre> <p>And then reverse the whole process to get this back into the original shape, to be used for other purposes. </p> <p>Surely there must be more efficient ways to do this (hopefully without messing with the rotation matrix)?</p>
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], [ 0.00000000e+00, 1.00000000e+00, 0.00000000e+00], [ -1.00000000e+00, 0.00000000e+00, 0.00000000e+00] ]) a.reshape(3, 3, -1).dot(rotmat).reshape(-1, 9) array([[ 0., 1., 0., -1., 1., 1., -1., 1., 0.], [-1., 0., 1., -1., 1., 1., -1., 0., 0.], [ 0., 0., 0., 0., 0., 1., 0., 1., 1.]]) </code></pre> <hr> <pre><code>df = pd.DataFrame(a.reshape(3, 3, -1).dot(rotmat).reshape(-1, 9)) df </code></pre> <p><a href="http://i.stack.imgur.com/JGP9t.png" rel="nofollow"><img src="http://i.stack.imgur.com/JGP9t.png" alt="enter image description here"></a></p>
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 string starts with "0.":</p> <pre><code>&gt;&gt;&gt; l = ['192.168.1.1', '0.1.2.3', '1.2.3.4', '192.168.1.2', '0.3.4.5', '192.168.1.3'] &gt;&gt;&gt; [item for item in l if not item.startswith('0.')] ['192.168.1.1', '1.2.3.4', '192.168.1.2', '192.168.1.3'] </code></pre> <p>Note that <code>list</code> is not a good variable name - it <em><a href="https://en.wikipedia.org/wiki/Variable_shadowing" rel="nofollow">shadows</a> the built-in <code>list</code></em>.</p> <hr> <p>You can also approach the problem with <a href="https://docs.python.org/3/library/functions.html#filter" rel="nofollow"><code>filter()</code></a> and a filtering function:</p> <pre><code>&gt;&gt;&gt; list(filter(lambda x: not x.startswith("0."), l)) ['192.168.1.1', '1.2.3.4', '192.168.1.2', '192.168.1.3'] </code></pre> <p>Note that in Python 3.x, unlike Python 2.x, <code>filter()</code> returns an <em>iterator</em>, hence, calling <code>list()</code> to demonstrate the result.</p> <hr> <p>And, a "just for fun" option and to demonstrate how can you overcomplicate the problem with different functional programming-style tools:</p> <pre><code>&gt;&gt;&gt; from operator import methodcaller &gt;&gt;&gt; from itertools import filterfalse &gt;&gt;&gt; &gt;&gt;&gt; list(filterfalse(methodcaller('startswith', "0."), l)) ['192.168.1.1', '1.2.3.4', '192.168.1.2', '192.168.1.3'] </code></pre> <p><a href="https://docs.python.org/3/library/itertools.html#itertools.filterfalse" rel="nofollow"><code>itertools.filterfalse()</code></a> and <a href="https://docs.python.org/3/library/operator.html#operator.methodcaller" rel="nofollow"><code>operator.methodcaller()</code></a> were used.</p>
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 function "render_dashboard_page"? I need parameter to be chosen based on "Accept-language" flag of the request, which I can determine only after the method was fired.</p> <p>By the way, the 3rd input of "@register_breadcrumb" is the breadcrumb item title and I want it to be localized based on the "Accept-language" flag.</p> <p>more information about the add-on: <a href="http://flask-breadcrumbs.readthedocs.io/en/latest/" rel="nofollow">http://flask-breadcrumbs.readthedocs.io/en/latest/</a></p> <p>Thanks :)</p>
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/weblogs/viewpost.jsp?thread=240845" rel="nofollow">here</a> - essentially, the decorator is a function that is passed the function below it, and then returns a function that should be inserted into the namespace.</p> <p>Easier to give an example:</p> <pre><code>&gt;&gt;&gt; def add_one(fn): ... print("add_one called") ... def wrap(n): ... print("wrap called") ... return fn(n) + 1 ... return wrap &gt;&gt;&gt; @add_one ... def times_by_two(n): ... print("times_by_two called") ... return n * 2 add_one called &gt;&gt;&gt; times_by_two(21) wrap called times_by_two called 43 </code></pre> <p>I'm not entirely sure how that Flask plugin works, but you might be able to use the <a href="https://flask-breadcrumbs.readthedocs.io/en/latest/#variable-rules" rel="nofollow">variable rules</a> feature to do what you want. It looks like you can define a function to be called which returns text and a URL for the last component of the breadcrumbs, and the <code>request</code> object is accessible from that function; hopefully that's enough to be able to determine the user's language.</p>
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 with element 0). I also want to add a function which will increase the length of the array, i.e. if the method is called the array will increase from size 3 to size 4. How do I go about doing either of these?</p>
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 = 0 self.len = len(self) def append(self, *args, **kwargs): self.len = len(self) if self.len &gt;= self.__size: if self.__wrap_location == self.__size-1: self.__wrap_location = 0 self.__wrap_location += 1 self.pop(self.__wrap_location) return self.insert(self.__wrap_location-1, *args) return list.append(self, *args, **kwargs) def increase_size(self, amount=1): self.__size += 1 </code></pre>
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 with element 0). I also want to add a function which will increase the length of the array, i.e. if the method is called the array will increase from size 3 to size 4. How do I go about doing either of these?</p>
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>&gt; ['monkey', 'banana', 'peanut'] </code></pre> <p>The the list to edit (<code>l</code>), the item to add and the max size (<code>max_len</code>) of the list are arguments.</p> <p>The item will then be added at index 0, while the list is limited to max_len.</p>
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 with element 0). I also want to add a function which will increase the length of the array, i.e. if the method is called the array will increase from size 3 to size 4. How do I go about doing either of these?</p>
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) &lt; 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" ]